@runtypelabs/persona 4.17.0 → 4.18.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 (165) hide show
  1. package/dist/animations/glyph-cycle.d.cts +1 -1
  2. package/dist/animations/glyph-cycle.d.ts +1 -1
  3. package/dist/animations/{types-BpWGm7_6.d.cts → types-DsmTD8TO.d.cts} +12 -0
  4. package/dist/animations/{types-BpWGm7_6.d.ts → types-DsmTD8TO.d.ts} +12 -0
  5. package/dist/animations/wipe.d.cts +1 -1
  6. package/dist/animations/wipe.d.ts +1 -1
  7. package/dist/chunk-3I2S3I5P.js +1 -0
  8. package/dist/chunk-76IELU7F.js +1 -0
  9. package/dist/chunk-EFJBUH5F.js +1 -0
  10. package/dist/chunk-PDPVORUF.js +1 -0
  11. package/dist/chunk-Q735PSZL.js +1 -0
  12. package/dist/chunk-VK6JOIYJ.js +1 -0
  13. package/dist/codegen.cjs +4 -4
  14. package/dist/codegen.js +4 -4
  15. package/dist/{context-mentions-BTSTIBFC.js → context-mentions-MJL6S6P2.js} +1 -1
  16. package/dist/context-mentions.cjs +9 -8
  17. package/dist/context-mentions.d.cts +1224 -14
  18. package/dist/context-mentions.d.ts +1224 -14
  19. package/dist/context-mentions.js +9 -8
  20. package/dist/event-stream-view-4EZ7BGFK.js +1 -0
  21. package/dist/event-stream-view.cjs +129 -0
  22. package/dist/event-stream-view.d.cts +8384 -0
  23. package/dist/event-stream-view.d.ts +8384 -0
  24. package/dist/event-stream-view.js +129 -0
  25. package/dist/history-view-BD6OXLNA.js +898 -0
  26. package/dist/history-view.cjs +898 -0
  27. package/dist/history-view.d.cts +1461 -0
  28. package/dist/history-view.d.ts +1461 -0
  29. package/dist/history-view.js +898 -0
  30. package/dist/index.cjs +77 -77
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.d.cts +2040 -21
  33. package/dist/index.d.ts +2040 -21
  34. package/dist/index.global.js +67 -66
  35. package/dist/index.global.js.map +1 -1
  36. package/dist/index.js +77 -77
  37. package/dist/index.js.map +1 -1
  38. package/dist/launcher.global.js +5 -4
  39. package/dist/launcher.global.js.map +1 -1
  40. package/dist/plugin-kit.cjs +1 -1
  41. package/dist/plugin-kit.d.cts +0 -8
  42. package/dist/plugin-kit.d.ts +0 -8
  43. package/dist/plugin-kit.js +1 -1
  44. package/dist/smart-dom-reader.d.cts +1224 -14
  45. package/dist/smart-dom-reader.d.ts +1224 -14
  46. package/dist/theme-editor-preview.cjs +970 -73
  47. package/dist/theme-editor-preview.d.cts +1343 -15
  48. package/dist/theme-editor-preview.d.ts +1343 -15
  49. package/dist/theme-editor-preview.js +81 -81
  50. package/dist/theme-editor.cjs +7 -7
  51. package/dist/theme-editor.d.cts +1227 -15
  52. package/dist/theme-editor.d.ts +1227 -15
  53. package/dist/theme-editor.js +9 -9
  54. package/dist/theme-reference.cjs +1 -1
  55. package/dist/theme-reference.d.cts +226 -7
  56. package/dist/theme-reference.d.ts +226 -7
  57. package/dist/theme-reference.js +1 -1
  58. package/dist/webmcp-polyfill.js +2 -2
  59. package/dist/widget.css +1 -1
  60. package/package.json +18 -6
  61. package/src/client-history-rest.test.ts +1034 -0
  62. package/src/client-visitor-history.test.ts +596 -0
  63. package/src/client.ts +1040 -24
  64. package/src/components/artifact-inline.ts +8 -1
  65. package/src/components/artifact-pane.test.ts +278 -1
  66. package/src/components/artifact-pane.ts +135 -67
  67. package/src/components/artifact-preview.test.ts +14 -1
  68. package/src/components/artifact-preview.ts +9 -0
  69. package/src/components/header-builder.ts +3 -0
  70. package/src/components/header-layouts.test.ts +171 -7
  71. package/src/components/header-layouts.ts +83 -53
  72. package/src/components/header-parts.test.ts +154 -1
  73. package/src/components/header-parts.ts +266 -138
  74. package/src/components/history-confirm-dialog.ts +177 -0
  75. package/src/components/history-shell-copy.ts +99 -0
  76. package/src/components/history-view/announcer.ts +40 -0
  77. package/src/components/history-view/copy.ts +105 -0
  78. package/src/components/history-view/css.ts +1078 -0
  79. package/src/components/history-view/grouping.test.ts +142 -0
  80. package/src/components/history-view/grouping.ts +142 -0
  81. package/src/components/history-view/icons.ts +73 -0
  82. package/src/components/history-view/rows.ts +341 -0
  83. package/src/components/history-view/state.ts +309 -0
  84. package/src/components/history-view.test.ts +2660 -0
  85. package/src/components/history-view.ts +1891 -0
  86. package/src/components/launcher-surface.test.ts +133 -0
  87. package/src/components/launcher.test.ts +18 -0
  88. package/src/components/launcher.ts +7 -7
  89. package/src/components/panel.ts +17 -7
  90. package/src/components/welcome.ts +72 -2
  91. package/src/defaults.ts +36 -3
  92. package/src/event-stream-view-bundle.test.ts +69 -0
  93. package/src/event-stream-view-entry.ts +19 -0
  94. package/src/event-stream-view-loader.ts +31 -0
  95. package/src/event-stream-view.ts +19 -0
  96. package/src/generated/runtype-openapi-contract.ts +54 -4
  97. package/src/history-render.ts +325 -0
  98. package/src/history-view-bundle.test.ts +78 -0
  99. package/src/history-view-entry.ts +41 -0
  100. package/src/history-view-loader.test.ts +30 -0
  101. package/src/history-view-loader.ts +32 -0
  102. package/src/history-view.ts +28 -0
  103. package/src/index-core.ts +50 -2
  104. package/src/index-global.ts +55 -0
  105. package/src/internal/demo-history-provider.test.ts +402 -0
  106. package/src/internal/demo-history-provider.ts +689 -0
  107. package/src/internal/history-provider-registry.ts +25 -0
  108. package/src/internal/history-provider.ts +150 -0
  109. package/src/internal/runtype-history-provider.test.ts +313 -0
  110. package/src/internal/runtype-history-provider.ts +240 -0
  111. package/src/plugin-kit.test.ts +16 -0
  112. package/src/plugin-kit.ts +13 -5
  113. package/src/plugins/types.ts +177 -1
  114. package/src/session-history.test.ts +1397 -0
  115. package/src/session.ts +1200 -26
  116. package/src/styles/widget-styles.test.ts +133 -0
  117. package/src/styles/widget.css +227 -8
  118. package/src/theme-editor/preview-utils.test.ts +19 -0
  119. package/src/theme-editor/preview-utils.ts +15 -1
  120. package/src/theme-editor/preview.ts +7 -1
  121. package/src/theme-editor/role-mappings.ts +4 -1
  122. package/src/theme-editor/sections.test.ts +168 -1
  123. package/src/theme-editor/sections.ts +136 -7
  124. package/src/theme-editor/webmcp/summary.ts +16 -2
  125. package/src/theme-reference.ts +20 -6
  126. package/src/types/theme.ts +213 -7
  127. package/src/types.ts +927 -7
  128. package/src/ui.artifact-rail-resize.test.ts +235 -0
  129. package/src/ui.attachments-drop.test.ts +1 -0
  130. package/src/ui.header-update-stability.test.ts +2 -2
  131. package/src/ui.history-chunk.test.ts +72 -0
  132. package/src/ui.history-config-provider.test.ts +318 -0
  133. package/src/ui.history-controller.test.ts +711 -0
  134. package/src/ui.history-lifecycle.test.ts +456 -0
  135. package/src/ui.history-render-hooks.test.ts +904 -0
  136. package/src/ui.history-shell.test.ts +1887 -0
  137. package/src/ui.rail-overlay.test.ts +573 -0
  138. package/src/ui.rail-resize.test.ts +284 -0
  139. package/src/ui.rebuild-composer.test.ts +21 -0
  140. package/src/ui.render-welcome.test.ts +42 -0
  141. package/src/ui.shortcuts.test.ts +166 -0
  142. package/src/ui.ts +3071 -240
  143. package/src/utils/__fixtures__/client-conversation-history-wire.json +108 -0
  144. package/src/utils/artifact-file.ts +15 -0
  145. package/src/utils/artifact-gate.test.ts +4 -0
  146. package/src/utils/artifact-gate.ts +13 -17
  147. package/src/utils/artifact-resize.test.ts +28 -0
  148. package/src/utils/artifact-resize.ts +9 -2
  149. package/src/utils/buttons.ts +188 -1
  150. package/src/utils/config-merge.test.ts +91 -0
  151. package/src/utils/dropdown.ts +10 -1
  152. package/src/utils/history-messages.test.ts +284 -0
  153. package/src/utils/history-messages.ts +284 -0
  154. package/src/utils/icons.ts +3 -0
  155. package/src/utils/shortcuts.test.ts +288 -0
  156. package/src/utils/shortcuts.ts +221 -0
  157. package/src/utils/theme.test.ts +501 -4
  158. package/src/utils/theme.ts +42 -3
  159. package/src/utils/tokens.ts +153 -15
  160. package/src/utils/tooltip-timing.ts +4 -0
  161. package/src/utils/tooltip.test.ts +249 -7
  162. package/src/utils/tooltip.ts +146 -4
  163. package/src/utils/visitor-store.test.ts +425 -0
  164. package/src/utils/visitor-store.ts +337 -0
  165. package/dist/chunk-QJ4LV2KW.js +0 -1
@@ -1,14 +1,14 @@
1
- "use strict";var wb=Object.create;var qi=Object.defineProperty;var Cb=Object.getOwnPropertyDescriptor;var Ab=Object.getOwnPropertyNames;var Sb=Object.getPrototypeOf,Mb=Object.prototype.hasOwnProperty;var ht=(t,e)=>()=>(t&&(e=t(t=0)),e);var Tr=(t,e)=>{for(var n in e)qi(t,n,{get:e[n],enumerable:!0})},bu=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ab(e))!Mb.call(t,r)&&r!==n&&qi(t,r,{get:()=>e[r],enumerable:!(o=Cb(e,r))||o.enumerable});return t};var yu=(t,e,n)=>(n=t!=null?wb(Sb(t)):{},bu(e||!t||!t.__esModule?qi(n,"default",{value:t,enumerable:!0}):n,t)),Tb=t=>bu(qi({},"__esModule",{value:!0}),t);var wu={};Tr(wu,{DOMPurify:()=>xu.default,Marked:()=>vu.Marked});var vu,xu,Cu=ht(()=>{"use strict";vu=require("marked"),xu=yu(require("dompurify"),1)});var v,Nu,ye,Bn,Ye=ht(()=>{"use strict";v=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},Nu=()=>document.createDocumentFragment(),ye=(t,e={},...n)=>{let o=document.createElement(t);if(e.className&&(o.className=e.className),e.text!==void 0&&(o.textContent=e.text),e.attrs)for(let[s,i]of Object.entries(e.attrs))o.setAttribute(s,i);if(e.style){let s=o.style,i=e.style;for(let l of Object.keys(i)){let p=i[l];p!=null&&(s[l]=p)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},Bn=(...t)=>t.filter(Boolean).join(" ")});var Or,yc=ht(()=>{"use strict";Or=class{constructor(e=24e3,n={}){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;this.sampleRate=e;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(e*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let n=e;if(this.remainder){let r=new Uint8Array(this.remainder.length+e.length);r.set(this.remainder),r.set(e,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}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 n of e)this.scheduleSamples(n)}scheduleSamples(e){if(e.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,e.length,this.sampleRate);o.getChannelData(0).set(e);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let i=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of i)l()}r.onended=()=>{let i=this.activeSources.indexOf(r);i!==-1&&this.activeSources.splice(i,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 n of e)n()}}pcmToFloat32(e){let n=Math.floor(e.length/2),o=new Float32Array(n),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<n;s++){let i=r.getInt16(s*2,!0);o[s]=i/32768}return o}}});function Fy(t){return t.replace(/\/+$/,"")}async function _y(t){try{let e=await t.json();return e.detail?`${e.error??`Runtype TTS ${t.status}`}: ${e.detail}`:e.error??`Runtype TTS request failed (${t.status})`}catch{return`Runtype TTS request failed (${t.status})`}}var pa,hg=ht(()=>{"use strict";yc();pa=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new Or(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(e=>this.player=e))}speak(e,n){let o=++this.generation;this.run(o,e,n)}async run(e,n,o){try{let r=await this.ensurePlayer();if(e!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.generation&&o.onStart?.()}),r.onFinished(()=>{e===this.generation&&o.onEnd?.()});let s=`${Fy(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,i=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!i.ok||!i.body)throw new Error(await _y(i));let l=i.body.getReader();for(;;){let{done:p,value:c}=await l.read();if(e!==this.generation){await l.cancel().catch(()=>{});return}if(p)break;c&&c.byteLength>0&&r.enqueue(c)}r.markStreamEnd()}catch(r){if(e!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var ua,bg=ht(()=>{"use strict";ua=class{constructor(e,n,o={}){this.primary=e;this.fallback=n;this.options=o;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,n){this.active=this.primary;let o=!1;this.primary.speak(e,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(e,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var yg={};Tr(yg,{FallbackSpeechEngine:()=>ua,RuntypeSpeechEngine:()=>pa});var vg=ht(()=>{"use strict";hg();bg()});var wg={};Tr(wg,{createReconnectController:()=>zy});function zy(t){let e=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let y=n;n=null,y()}},i=()=>{let y=t.getStatus();y!=="resuming"&&y!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||i()},p=()=>{i()},c=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",p),r=!0)},d=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",p),r=!1)},g=y=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},y)}),b=()=>{let y=t.getResumable();t.clearResumable(),t.setReconnecting(!1),e=0,d(),t.setAbortController(null);let C=!1;for(let I of t.getMessages())I.streaming&&(I.streaming=!1,C=!0);let M=t.buildErrorContent("Connection lost and the response could not be resumed.");M?t.appendMessage({id:`reconnect-failed-${y?.executionId??t.nextSequence()}`,role:"assistant",content:M,createdAt:new Date().toISOString(),streaming:!1,sequence:t.nextSequence()}):C&&t.notifyMessagesChanged(),t.setStreaming(!1),t.setStatus("idle"),t.onError(new Error("Durable session reconnect failed."))},f=async()=>{let y=t.config.reconnect?.backoffMs??$y,C=t.config.reconnect?.maxAttempts??y.length,M=t.config.reconnectStream;if(!M){t.setReconnecting(!1);return}for(;t.getResumable()&&e<C;){e+=1,t.setStatus("resuming");let I=t.getResumable(),S=I.lastEventId,E=new AbortController;t.setAbortController(E),t.emitReconnect({phase:"resuming",handle:I,attempt:e});let L=null;try{let D=await M({executionId:I.executionId,after:I.lastEventId,signal:E.signal});D&&D.ok&&D.body&&(L=D.body)}catch{L=null}if(E.signal.aborted)return;if(L){let D=t.getMessages().find($=>$.id===I.assistantMessageId)?.content,z=typeof D=="string"?D:"";try{await t.resumeConnect(L,I.assistantMessageId,z)}catch{}if(E.signal.aborted)return;if(!t.getResumable()){t.setReconnecting(!1),e=0,d(),t.emitReconnect({phase:"resumed",handle:I});return}t.getResumable().lastEventId!==S&&(e=0)}if(t.getResumable()&&e<C&&(t.setStatus("paused"),await g(y[Math.min(e-1,y.length-1)]??1e3),E.signal.aborted))return}t.getResumable()&&b()};return{begin(){e=0,c(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,e=0,d()},wake:s}}var $y,Cg=ht(()=>{"use strict";$y=[1e3,2e3,4e3,8e3,8e3]});function qy(t,e,n,o){if(!Array.isArray(t))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let i=s[0],l=s[1];if(!l)return;let p=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(l).forEach(([c,d])=>{c!=="stroke"&&p.setAttribute(c,String(d))}),r.appendChild(p)}),r}var T,Vy,ie,xt=ht(()=>{"use strict";T=require("lucide"),Vy={activity:T.Activity,"arrow-down":T.ArrowDown,"arrow-up":T.ArrowUp,"arrow-up-right":T.ArrowUpRight,bot:T.Bot,"chevron-down":T.ChevronDown,"chevron-up":T.ChevronUp,"chevron-right":T.ChevronRight,"chevron-left":T.ChevronLeft,check:T.Check,clipboard:T.Clipboard,"clipboard-copy":T.ClipboardCopy,"code-xml":T.CodeXml,copy:T.Copy,file:T.File,"file-code":T.FileCode,"file-spreadsheet":T.FileSpreadsheet,"file-text":T.FileText,"image-plus":T.ImagePlus,loader:T.Loader,"loader-circle":T.LoaderCircle,mic:T.Mic,paperclip:T.Paperclip,"refresh-cw":T.RefreshCw,search:T.Search,send:T.Send,"shield-alert":T.ShieldAlert,"shield-check":T.ShieldCheck,"shield-x":T.ShieldX,square:T.Square,"thumbs-down":T.ThumbsDown,"thumbs-up":T.ThumbsUp,upload:T.Upload,"volume-2":T.Volume2,x:T.X,user:T.User,mail:T.Mail,phone:T.Phone,calendar:T.Calendar,clock:T.Clock,building:T.Building,"map-pin":T.MapPin,lock:T.Lock,key:T.Key,"credit-card":T.CreditCard,"at-sign":T.AtSign,hash:T.Hash,globe:T.Globe,link:T.Link,"circle-check":T.CircleCheck,"circle-x":T.CircleX,"triangle-alert":T.TriangleAlert,info:T.Info,ban:T.Ban,shield:T.Shield,"arrow-left":T.ArrowLeft,"arrow-right":T.ArrowRight,"external-link":T.ExternalLink,ellipsis:T.Ellipsis,"ellipsis-vertical":T.EllipsisVertical,menu:T.Menu,house:T.House,plus:T.Plus,minus:T.Minus,pencil:T.Pencil,"pen-line":T.PenLine,trash:T.Trash,"trash-2":T.Trash2,save:T.Save,download:T.Download,share:T.Share,funnel:T.Funnel,settings:T.Settings,"rotate-cw":T.RotateCw,maximize:T.Maximize,minimize:T.Minimize,"shopping-cart":T.ShoppingCart,"shopping-bag":T.ShoppingBag,package:T.Package,truck:T.Truck,tag:T.Tag,gift:T.Gift,receipt:T.Receipt,wallet:T.Wallet,store:T.Store,"dollar-sign":T.DollarSign,percent:T.Percent,play:T.Play,pause:T.Pause,"volume-x":T.VolumeX,camera:T.Camera,image:T.Image,film:T.Film,headphones:T.Headphones,"message-circle":T.MessageCircle,"message-square":T.MessageSquare,bell:T.Bell,heart:T.Heart,star:T.Star,eye:T.Eye,"eye-off":T.EyeOff,bookmark:T.Bookmark,"calendar-days":T.CalendarDays,history:T.History,timer:T.Timer,folder:T.Folder,"folder-open":T.FolderOpen,files:T.Files,"chart-column":T.ChartColumn,sparkles:T.Sparkles,zap:T.Zap,sun:T.Sun,moon:T.Moon,flag:T.Flag,lightbulb:T.Lightbulb,monitor:T.Monitor,smartphone:T.Smartphone},ie=(t,e=24,n="currentColor",o=2)=>{let r=Vy[t];return r?qy(r,e,n,o):(console.warn(`Lucide icon "${t}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)}});function Qy(t,e,n){if(n==="input-start")return e===0;let o=e>0?t[e-1]:"";return n==="line-start"?o===""||o===`
2
- `:o===""||Mg.test(o)}function Xy(t,e,n="@",o="anywhere",r=!1){if(!n||e<=0||e>t.length)return null;let s=e-1;for(;s>=0;){let i=t[s];if(i===n)return Qy(t,s,o)?{triggerIndex:s,query:t.slice(s+1,e)}:null;if(i===`
3
- `||i==="\uFFFC"||!r&&Mg.test(i))return null;s--}return null}function zs(t,e,n){for(let o of n){let r=Xy(t,e,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Tg(t){return t?t!=="insertFromPaste"&&t!=="insertFromDrop":!0}function Eg(t,e,n){return{value:t.slice(0,e.triggerIndex)+t.slice(n),caret:e.triggerIndex}}var Mg,ma=ht(()=>{"use strict";Mg=/\s/});function ha(t){let e={trigger:t.trigger??"@",position:t.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(t.sources)?t.sources:[],searchPlaceholder:t.searchPlaceholder,showButton:t.showButton!==!1,buttonIconName:t.buttonIconName,buttonTooltipText:t.buttonTooltipText},n=(t.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[e,...n]}var Ac=ht(()=>{"use strict"});function Pg(t){let{ref:e,config:n,onRemove:o}=t;if(n.renderMentionChip){let f="resolving",y,C=n.renderMentionChip({ref:e,status:f,payload:y,remove:o});return{get el(){return C},setStatus:(I,S)=>{if(I===f&&S===y)return;f=I,y=S;let E=n.renderMentionChip({ref:e,status:f,payload:y,remove:o});C.replaceWith(E),C=E}}}let r=e.iconName??n.chipIconName??"at-sign",s=ye("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:e.label}}),i=v("span","persona-mention-chip-icon"),l=f=>{i.replaceChildren();let y=ie(f,13,"currentColor",2);y&&i.appendChild(y)};l(r);let p=v("span","persona-mention-chip-spinner"),c=ye("span",{className:"persona-mention-chip-label",text:e.label}),d=ye("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${e.label} context`}}),g=ie("x",11,"currentColor",2.5);return g?d.appendChild(g):d.textContent="\xD7",d.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),o()}),s.appendChild(p),s.appendChild(c),s.appendChild(d),{el:s,setStatus:f=>{s.setAttribute("data-status",f),f==="resolving"?(p.parentNode!==s&&s.insertBefore(p,c),i.parentNode===s&&i.remove(),s.setAttribute("title",e.label)):(p.parentNode===s&&p.remove(),i.parentNode!==s&&s.insertBefore(i,c),f==="error"?(l("triangle-alert"),s.setAttribute("title",`Couldn't add ${e.label} to context`)):(l(r),s.setAttribute("title",e.label)))}}}var Ig=ht(()=>{"use strict";Ye();xt()});function ev(t){let e=0;for(let n of t.split(`
4
- `)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>e&&(e=o[1].length)}return e}function Ec(t,e){let n="`".repeat(Math.max(3,ev(e)+1));return`${n}${t}
1
+ "use strict";var _x=Object.create;var Gl=Object.defineProperty;var Fx=Object.getOwnPropertyDescriptor;var $x=Object.getOwnPropertyNames;var zx=Object.getPrototypeOf,Vx=Object.prototype.hasOwnProperty;var Ge=(t,e)=>()=>(t&&(e=t(t=0)),e);var lr=(t,e)=>{for(var n in e)Gl(t,n,{get:e[n],enumerable:!0})},ih=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of $x(e))!Vx.call(t,r)&&r!==n&&Gl(t,r,{get:()=>e[r],enumerable:!(o=Fx(e,r))||o.enumerable});return t};var ah=(t,e,n)=>(n=t!=null?_x(zx(t)):{},ih(e||!t||!t.__esModule?Gl(n,"default",{value:t,enumerable:!0}):n,t)),jx=t=>ih(Gl({},"__esModule",{value:!0}),t);var dh={};lr(dh,{DOMPurify:()=>ch.default,Marked:()=>lh.Marked});var lh,ch,ph=Ge(()=>{"use strict";lh=require("marked"),ch=ah(require("dompurify"),1)});var v,Eh,J,zt,Qe=Ge(()=>{"use strict";v=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},Eh=()=>document.createDocumentFragment(),J=(t,e={},...n)=>{let o=document.createElement(t);if(e.className&&(o.className=e.className),e.text!==void 0&&(o.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))o.setAttribute(s,a);if(e.style){let s=o.style,a=e.style;for(let l of Object.keys(a)){let d=a[l];d!=null&&(s[l]=d)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},zt=(...t)=>t.filter(Boolean).join(" ")});function uc(t){return t instanceof xo}var xo,la=Ge(()=>{"use strict";xo=class extends Error{constructor(e,n,o){super(n),this.name="HistoryProviderError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}}});var Vs,au=Ge(()=>{"use strict";Vs=class{constructor(e=24e3,n={}){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;this.sampleRate=e;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(e*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window<"u"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let o=n.AudioContext||n.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let n=e;if(this.remainder){let r=new Uint8Array(this.remainder.length+e.length);r.set(this.remainder),r.set(e,this.remainder.length),n=r,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let o=this.pcmToFloat32(n);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}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 n of e)this.scheduleSamples(n)}scheduleSamples(e){if(e.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,e.length,this.sampleRate);o.getChannelData(0).set(e);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let l of a)l()}r.onended=()=>{let a=this.activeSources.indexOf(r);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 n of e)n()}}pcmToFloat32(e){let n=Math.floor(e.length/2),o=new Float32Array(n),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function aA(t){return t.replace(/\/+$/,"")}async function lA(t){try{let e=await t.json();return e.detail?`${e.error??`Runtype TTS ${t.status}`}: ${e.detail}`:e.error??`Runtype TTS request failed (${t.status})`}catch{return`Runtype TTS request failed (${t.status})`}}var fc,by=Ge(()=>{"use strict";au();fc=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){return this.playerPromise??(this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new Vs(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(e=>this.player=e))}speak(e,n){let o=++this.generation;this.run(o,e,n)}async run(e,n,o){try{let r=await this.ensurePlayer();if(e!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{e===this.generation&&o.onStart?.()}),r.onFinished(()=>{e===this.generation&&o.onEnd?.()});let s=`${aA(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!a.ok||!a.body)throw new Error(await lA(a));let l=a.body.getReader();for(;;){let{done:d,value:p}=await l.read();if(e!==this.generation){await l.cancel().catch(()=>{});return}if(d)break;p&&p.byteLength>0&&r.enqueue(p)}r.markStreamEnd()}catch(r){if(e!==this.generation)return;let s=r instanceof Error?r:new Error(String(r));this.opts.onError?.(s),o.onError?.(s)}}pause(){this.player?.pause()}resume(){this.player?.resume()}stop(){this.generation++,this.player?.flush()}destroy(){this.generation++,this.player?.destroy(),this.player=null,this.playerPromise=null}}});var mc,vy=Ge(()=>{"use strict";mc=class{constructor(e,n,o={}){this.primary=e;this.fallback=n;this.options=o;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,n){this.active=this.primary;let o=!1;this.primary.speak(e,{onStart:()=>{o=!0,n.onStart?.()},onEnd:()=>n.onEnd?.(),onError:r=>{if(o){n.onError?.(r);return}this.options.onFallback?.(r),this.active=this.fallback,this.fallback.speak(e,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var wy={};lr(wy,{FallbackSpeechEngine:()=>mc,RuntypeSpeechEngine:()=>fc});var Cy=Ge(()=>{"use strict";by();vy()});var Sy={};lr(Sy,{createReconnectController:()=>dA});function dA(t){let e=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let y=n;n=null,y()}},a=()=>{let y=t.getStatus();y!=="resuming"&&y!=="paused"||s()},l=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},d=()=>{a()},p=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",l),typeof window<"u"&&window.addEventListener("online",d),r=!0)},u=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",l),typeof window<"u"&&window.removeEventListener("online",d),r=!1)},g=y=>new Promise(w=>{n=w,o=setTimeout(()=>{o=null,n=null,w()},y)}),b=()=>{let y=t.getResumable();t.clearResumable(),t.setReconnecting(!1),e=0,u(),t.setAbortController(null);let w=!1;for(let W of t.getMessages())W.streaming&&(W.streaming=!1,w=!0);let T=t.buildErrorContent("Connection lost and the response could not be resumed.");T?t.appendMessage({id:`reconnect-failed-${y?.executionId??t.nextSequence()}`,role:"assistant",content:T,createdAt:new Date().toISOString(),streaming:!1,sequence:t.nextSequence()}):w&&t.notifyMessagesChanged(),t.setStreaming(!1),t.setStatus("idle"),t.onError(new Error("Durable session reconnect failed."))},m=async()=>{let y=t.config.reconnect?.backoffMs??cA,w=t.config.reconnect?.maxAttempts??y.length,T=t.config.reconnectStream;if(!T){t.setReconnecting(!1);return}for(;t.getResumable()&&e<w;){e+=1,t.setStatus("resuming");let W=t.getResumable(),E=W.lastEventId,k=new AbortController;t.setAbortController(k),t.emitReconnect({phase:"resuming",handle:W,attempt:e});let A=null;try{let D=await T({executionId:W.executionId,after:W.lastEventId,signal:k.signal});D&&D.ok&&D.body&&(A=D.body)}catch{A=null}if(k.signal.aborted)return;if(A){let D=t.getMessages().find(I=>I.id===W.assistantMessageId)?.content,B=typeof D=="string"?D:"";try{await t.resumeConnect(A,W.assistantMessageId,B)}catch{}if(k.signal.aborted)return;if(!t.getResumable()){t.setReconnecting(!1),e=0,u(),t.emitReconnect({phase:"resumed",handle:W});return}t.getResumable().lastEventId!==E&&(e=0)}if(t.getResumable()&&e<w&&(t.setStatus("paused"),await g(y[Math.min(e-1,y.length-1)]??1e3),k.signal.aborted))return}t.getResumable()&&b()};return{begin(){e=0,p(),m()},teardown(){o&&(clearTimeout(o),o=null),n=null,e=0,u()},wake:s}}var cA,Ay=Ge(()=>{"use strict";cA=[1e3,2e3,4e3,8e3,8e3]});function fA(t,e,n,o){if(!Array.isArray(t))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(e)),r.setAttribute("height",String(e)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",n),r.setAttribute("stroke-width",String(o)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),t.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],l=s[1];if(!l)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(l).forEach(([p,u])=>{p!=="stroke"&&d.setAttribute(p,String(u))}),r.appendChild(d)}),r}var H,gA,fe,Rt=Ge(()=>{"use strict";H=require("lucide"),gA={activity:H.Activity,"arrow-down":H.ArrowDown,"arrow-up":H.ArrowUp,"arrow-up-right":H.ArrowUpRight,bot:H.Bot,"chevron-down":H.ChevronDown,"chevron-up":H.ChevronUp,"chevron-right":H.ChevronRight,"chevron-left":H.ChevronLeft,check:H.Check,clipboard:H.Clipboard,"clipboard-copy":H.ClipboardCopy,"code-xml":H.CodeXml,copy:H.Copy,file:H.File,"file-code":H.FileCode,"file-spreadsheet":H.FileSpreadsheet,"file-text":H.FileText,"image-plus":H.ImagePlus,loader:H.Loader,"loader-circle":H.LoaderCircle,mic:H.Mic,paperclip:H.Paperclip,"refresh-cw":H.RefreshCw,search:H.Search,send:H.Send,"shield-alert":H.ShieldAlert,"shield-check":H.ShieldCheck,"shield-x":H.ShieldX,square:H.Square,"thumbs-down":H.ThumbsDown,"thumbs-up":H.ThumbsUp,upload:H.Upload,"volume-2":H.Volume2,x:H.X,user:H.User,mail:H.Mail,phone:H.Phone,calendar:H.Calendar,clock:H.Clock,building:H.Building,"map-pin":H.MapPin,lock:H.Lock,key:H.Key,"credit-card":H.CreditCard,"at-sign":H.AtSign,hash:H.Hash,globe:H.Globe,link:H.Link,"circle-check":H.CircleCheck,"circle-x":H.CircleX,"triangle-alert":H.TriangleAlert,info:H.Info,ban:H.Ban,shield:H.Shield,"arrow-left":H.ArrowLeft,"arrow-right":H.ArrowRight,"external-link":H.ExternalLink,ellipsis:H.Ellipsis,"ellipsis-vertical":H.EllipsisVertical,menu:H.Menu,house:H.House,"panel-left":H.PanelLeft,plus:H.Plus,minus:H.Minus,pencil:H.Pencil,"pen-line":H.PenLine,trash:H.Trash,"trash-2":H.Trash2,save:H.Save,download:H.Download,share:H.Share,funnel:H.Funnel,settings:H.Settings,"rotate-cw":H.RotateCw,maximize:H.Maximize,minimize:H.Minimize,"shopping-cart":H.ShoppingCart,"shopping-bag":H.ShoppingBag,package:H.Package,truck:H.Truck,tag:H.Tag,gift:H.Gift,receipt:H.Receipt,wallet:H.Wallet,store:H.Store,"dollar-sign":H.DollarSign,percent:H.Percent,play:H.Play,pause:H.Pause,"volume-x":H.VolumeX,camera:H.Camera,image:H.Image,film:H.Film,headphones:H.Headphones,"message-circle":H.MessageCircle,"message-square":H.MessageSquare,bell:H.Bell,heart:H.Heart,star:H.Star,eye:H.Eye,"eye-off":H.EyeOff,bookmark:H.Bookmark,"calendar-days":H.CalendarDays,history:H.History,timer:H.Timer,folder:H.Folder,"folder-open":H.FolderOpen,files:H.Files,"chart-column":H.ChartColumn,sparkles:H.Sparkles,zap:H.Zap,sun:H.Sun,moon:H.Moon,flag:H.Flag,lightbulb:H.Lightbulb,monitor:H.Monitor,smartphone:H.Smartphone},fe=(t,e=24,n="currentColor",o=2)=>{let r=gA[t];return r?fA(r,e,n,o):(console.warn(`Lucide icon "${t}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)}});function yA(t,e,n){if(n==="input-start")return e===0;let o=e>0?t[e-1]:"";return n==="line-start"?o===""||o===`
2
+ `:o===""||Ey.test(o)}function bA(t,e,n="@",o="anywhere",r=!1){if(!n||e<=0||e>t.length)return null;let s=e-1;for(;s>=0;){let a=t[s];if(a===n)return yA(t,s,o)?{triggerIndex:s,query:t.slice(s+1,e)}:null;if(a===`
3
+ `||a==="\uFFFC"||!r&&Ey.test(a))return null;s--}return null}function ga(t,e,n){for(let o of n){let r=bA(t,e,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function ky(t){return t?t!=="insertFromPaste"&&t!=="insertFromDrop":!0}function Py(t,e,n){return{value:t.slice(0,e.triggerIndex)+t.slice(n),caret:e.triggerIndex}}var Ey,bc=Ge(()=>{"use strict";Ey=/\s/});function vc(t){let e={trigger:t.trigger??"@",position:t.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(t.sources)?t.sources:[],searchPlaceholder:t.searchPlaceholder,showButton:t.showButton!==!1,buttonIconName:t.buttonIconName,buttonTooltipText:t.buttonTooltipText},n=(t.triggers??[]).map(o=>({trigger:o.trigger,position:o.triggerPosition??"anywhere",allowSpaces:o.allowSpaces??!1,sources:Array.isArray(o.sources)?o.sources:[],searchPlaceholder:o.searchPlaceholder,showButton:o.showButton===!0,buttonIconName:o.buttonIconName,buttonTooltipText:o.buttonTooltipText}));return[e,...n]}var uu=Ge(()=>{"use strict"});function Dy(t){let{ref:e,config:n,onRemove:o}=t;if(n.renderMentionChip){let m="resolving",y,w=n.renderMentionChip({ref:e,status:m,payload:y,remove:o});return{get el(){return w},setStatus:(W,E)=>{if(W===m&&E===y)return;m=W,y=E;let k=n.renderMentionChip({ref:e,status:m,payload:y,remove:o});w.replaceWith(k),w=k}}}let r=e.iconName??n.chipIconName??"at-sign",s=J("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:e.label}}),a=v("span","persona-mention-chip-icon"),l=m=>{a.replaceChildren();let y=fe(m,13,"currentColor",2);y&&a.appendChild(y)};l(r);let d=v("span","persona-mention-chip-spinner"),p=J("span",{className:"persona-mention-chip-label",text:e.label}),u=J("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${e.label} context`}}),g=fe("x",11,"currentColor",2.5);return g?u.appendChild(g):u.textContent="\xD7",u.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),o()}),s.appendChild(d),s.appendChild(p),s.appendChild(u),{el:s,setStatus:m=>{s.setAttribute("data-status",m),m==="resolving"?(d.parentNode!==s&&s.insertBefore(d,p),a.parentNode===s&&a.remove(),s.setAttribute("title",e.label)):(d.parentNode===s&&d.remove(),a.parentNode!==s&&s.insertBefore(a,p),m==="error"?(l("triangle-alert"),s.setAttribute("title",`Couldn't add ${e.label} to context`)):(l(r),s.setAttribute("title",e.label)))}}}var Ny=Ge(()=>{"use strict";Qe();Rt()});function MA(t){let e=0;for(let n of t.split(`
4
+ `)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>e&&(e=o[1].length)}return e}function hu(t,e){let n="`".repeat(Math.max(3,MA(e)+1));return`${n}${t}
5
5
  ${e}
6
- ${n}`}function tv(t,e,n){return e.includes("</document_content>")?Ec(t,e):`<document index="${n+1}">
6
+ ${n}`}function TA(t,e,n){return e.includes("</document_content>")?hu(t,e):`<document index="${n+1}">
7
7
  <source>${t}</source>
8
8
  <document_content>
9
9
  ${e}
10
10
  </document_content>
11
- </document>`}function Rg(t,e,n="fenced"){if(typeof n=="function")try{return n(t,e)}catch(o){return console.warn("[persona] contextMentions.llmFormat threw; falling back to the fenced format for this mention",o),Ec(t.label,t.text)}return n==="document"?tv(t.label,t.text,e):Ec(t.label,t.text)}var Wg=ht(()=>{"use strict"});function ya(t,e){return{sourceId:t.id,itemId:e.id,label:e.label,iconName:e.iconName,color:e.color}}var Hg,va,kc=ht(()=>{"use strict";Ig();Wg();Hg=(t,e)=>`${t}\0${e}`,va=class{constructor(e){this.mentions=[];this.opts=e,this.updateRowVisibility()}get maxMentions(){return this.opts.mentionConfig.maxMentions??8}hasMentions(){return this.mentions.length>0}add(e,n,o=""){let r=Hg(e.id,n.id);if(this.mentions.some(l=>l.key===r))return this.reject(e,n,"duplicate");if(this.atLimit())return this.reject(e,n,"limit");let s=ya(e,n),i={key:r,source:e,item:n,ref:s,status:"resolving",args:o};return i.chip=Pg({ref:s,config:this.opts.mentionConfig,onRemove:()=>this.remove(r)}),this.opts.contextRow.appendChild(i.chip.el),this.startPending(i),this.updateRowVisibility(),!0}atLimit(){return this.mentions.length>=this.maxMentions}admit(e,n){return this.atLimit()?this.reject(e,n,"limit"):!0}track(e,n,o,r="",s){let i={key:e,source:n,item:o,ref:ya(n,o),status:"resolving",args:r,reportStatus:s};this.startPending(i)}reject(e,n,o){return this.opts.mentionConfig.onMentionRejected?.(n,o),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:o}),!1}startPending(e){this.mentions.push(e),e.source.resolveOn==="submit"?(e.status="ready",e.chip?.setStatus("ready"),e.reportStatus?.("resolved")):e.resolvePromise=this.resolvePending(e),this.opts.announce(`Added ${e.ref.label} to context`)}buildResolveContext(e,n,o=this.opts.getComposerText()){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:o,args:n,signal:e}}async resolvePending(e){let n=new AbortController;e.abort=n;try{let o=await e.source.resolve(e.item,this.buildResolveContext(n.signal,e.args));if(n.signal.aborted)return;e.payload=o,e.status="ready",e.chip?.setStatus("ready",o),e.reportStatus?.("resolved")}catch(o){if(n.signal.aborted)return;e.status="error",e.chip?.setStatus("error"),e.reportStatus?.("error"),(this.opts.announceError??this.opts.announce)(`Couldn't attach ${e.ref.label} to context`),this.opts.mentionConfig.onMentionResolveError?.(e.item,o),this.opts.emit?.("resolve-error",{sourceId:e.source.id,itemId:e.item.id})}}remove(e){let n=this.mentions.findIndex(r=>r.key===e);if(n===-1)return;let[o]=this.mentions.splice(n,1);o.abort?.abort(),o.chip?.el.remove(),this.updateRowVisibility(),this.opts.announce(`Removed ${o.ref.label} from context`)}removeLast(){let e=this.mentions[this.mentions.length-1];return e?(this.remove(e.key),!0):!1}clear(){for(let e of this.mentions)e.abort?.abort(),e.chip?.el.remove();this.mentions.length=0,this.updateRowVisibility()}collectForSubmit(){let e=[...this.mentions],n=e.map(s=>s.ref),o=this.opts.getComposerText();for(let s of e)s.chip?.el.remove();return this.mentions.length=0,this.updateRowVisibility(),{refs:n,finalize:async()=>{var d;let s=await Promise.all(e.map(async g=>{try{return g.source.resolveOn==="submit"?await g.source.resolve(g.item,this.buildResolveContext(new AbortController().signal,g.args,o)):(g.resolvePromise&&await g.resolvePromise,g.payload??null)}catch(b){try{this.opts.mentionConfig.onMentionResolveError?.(g.item,b)}catch(f){typeof console<"u"&&console.warn("[Persona] onMentionResolveError callback threw",f)}return this.opts.emit?.("resolve-error",{sourceId:g.source.id,itemId:g.item.id}),null}})),i=[],l=[],p={},c=new Set;for(let g=0;g<e.length;g++){let b=e[g],f=s[g];if(!f)continue;let y=Hg(b.source.id,b.item.id);if(!c.has(y)){if(c.add(y),f.llmAppend&&f.llmAppend.trim())try{i.push(Rg({label:b.ref.label,text:f.llmAppend,ref:b.ref,item:b.item},i.length,this.opts.mentionConfig.llmFormat))}catch(C){typeof console<"u"&&console.warn("[Persona] context-mention llmFormat threw",C)}f.contentParts?.length&&l.push(...f.contentParts),f.context&&((p[d=b.source.id]??(p[d]={}))[b.item.id]=f.context)}}return{blocks:i,contentParts:l,context:p}}}}updateRowVisibility(){this.opts.contextRow.style.display=this.mentions.length>0?"flex":"none"}}});function Bg(t){let e=t.getRootNode?.();return e instanceof ShadowRoot||e instanceof Document?e:t.ownerDocument??document}function xa(t,e,n){let o=t instanceof Document?t.head:t,r=e.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let i=(t instanceof Document?t:t.ownerDocument??document).createElement("style");i.setAttribute("data-persona-plugin-style",e),i.textContent=n,o.appendChild(i)}function Dg(t,e,n){if(t instanceof Document||t instanceof ShadowRoot){xa(t,e,n);return}let o=t;if(o.isConnected){xa(Bg(o),e,n);return}let r=o.ownerDocument??document;xa(r,e,n),queueMicrotask(()=>{let s=Bg(o);s!==r&&xa(s,e,n)})}function nv(t){let e=t.getRootNode?.();return e instanceof ShadowRoot?e:(t.ownerDocument??document).body}function wa(t){let{anchor:e,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:i,verticalOffset:l,zIndex:p=2147483e3,onOpen:c,onDismiss:d}=t,g=t.container??nv(e),b=!1,f=null,y=()=>{if(!b)return;let I=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${I.width}px`),i&&(n.style.maxWidth=`${I.width}px`);let S=n.getBoundingClientRect(),E=l?.()??null,L=E!=null?I.top+E:I.top,D=o==="top-start"||o==="top-end"?L-r-S.height:I.bottom+r,$=o==="bottom-end"||o==="top-end"?I.right-S.width:I.left,F=i?.()??null;if(F!=null){let B=Math.max(I.left,I.right-S.width);$=Math.min(Math.max(I.left+F,I.left),B)}n.style.top=`${D}px`,n.style.left=`${$}px`},C=()=>{b&&(b=!1,f&&(f(),f=null),n.remove())},M=()=>{if(b)return;b=!0,p!=null&&(n.style.zIndex=String(p)),g.appendChild(n),y();let I=(e.ownerDocument??document).defaultView??window,S=e.ownerDocument??document,E=()=>{if(!e.isConnected){C(),d?.("anchor-removed");return}y()},L=z=>{let $=typeof z.composedPath=="function"?z.composedPath():[];$.includes(n)||$.includes(e)||(C(),d?.("outside"))},D=I.setTimeout(()=>{S.addEventListener("pointerdown",L,!0)},0);I.addEventListener("scroll",E,!0),I.addEventListener("resize",E),f=()=>{I.clearTimeout(D),S.removeEventListener("pointerdown",L,!0),I.removeEventListener("scroll",E,!0),I.removeEventListener("resize",E)},c?.()};return{get isOpen(){return b},open:M,close:C,toggle:()=>b?C():M(),reposition:y,destroy:C}}function Og(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Lc=ht(()=>{"use strict"});var Ng,Fg=ht(()=>{"use strict";Ng=`
11
+ </document>`}function Oy(t,e,n="fenced"){if(typeof n=="function")try{return n(t,e)}catch(o){return console.warn("[persona] contextMentions.llmFormat threw; falling back to the fenced format for this mention",o),hu(t.label,t.text)}return n==="document"?TA(t.label,t.text,e):hu(t.label,t.text)}var _y=Ge(()=>{"use strict"});function Cc(t,e){return{sourceId:t.id,itemId:e.id,label:e.label,iconName:e.iconName,color:e.color}}var Fy,xc,yu=Ge(()=>{"use strict";Ny();_y();Fy=(t,e)=>`${t}\0${e}`,xc=class{constructor(e){this.mentions=[];this.opts=e,this.updateRowVisibility()}get maxMentions(){return this.opts.mentionConfig.maxMentions??8}hasMentions(){return this.mentions.length>0}add(e,n,o=""){let r=Fy(e.id,n.id);if(this.mentions.some(l=>l.key===r))return this.reject(e,n,"duplicate");if(this.atLimit())return this.reject(e,n,"limit");let s=Cc(e,n),a={key:r,source:e,item:n,ref:s,status:"resolving",args:o};return a.chip=Dy({ref:s,config:this.opts.mentionConfig,onRemove:()=>this.remove(r)}),this.opts.contextRow.appendChild(a.chip.el),this.startPending(a),this.updateRowVisibility(),!0}atLimit(){return this.mentions.length>=this.maxMentions}admit(e,n){return this.atLimit()?this.reject(e,n,"limit"):!0}track(e,n,o,r="",s){let a={key:e,source:n,item:o,ref:Cc(n,o),status:"resolving",args:r,reportStatus:s};this.startPending(a)}reject(e,n,o){return this.opts.mentionConfig.onMentionRejected?.(n,o),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:o}),!1}startPending(e){this.mentions.push(e),e.source.resolveOn==="submit"?(e.status="ready",e.chip?.setStatus("ready"),e.reportStatus?.("resolved")):e.resolvePromise=this.resolvePending(e),this.opts.announce(`Added ${e.ref.label} to context`)}buildResolveContext(e,n,o=this.opts.getComposerText()){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:o,args:n,signal:e}}async resolvePending(e){let n=new AbortController;e.abort=n;try{let o=await e.source.resolve(e.item,this.buildResolveContext(n.signal,e.args));if(n.signal.aborted)return;e.payload=o,e.status="ready",e.chip?.setStatus("ready",o),e.reportStatus?.("resolved")}catch(o){if(n.signal.aborted)return;e.status="error",e.chip?.setStatus("error"),e.reportStatus?.("error"),(this.opts.announceError??this.opts.announce)(`Couldn't attach ${e.ref.label} to context`),this.opts.mentionConfig.onMentionResolveError?.(e.item,o),this.opts.emit?.("resolve-error",{sourceId:e.source.id,itemId:e.item.id})}}remove(e){let n=this.mentions.findIndex(r=>r.key===e);if(n===-1)return;let[o]=this.mentions.splice(n,1);o.abort?.abort(),o.chip?.el.remove(),this.updateRowVisibility(),this.opts.announce(`Removed ${o.ref.label} from context`)}removeLast(){let e=this.mentions[this.mentions.length-1];return e?(this.remove(e.key),!0):!1}clear(){for(let e of this.mentions)e.abort?.abort(),e.chip?.el.remove();this.mentions.length=0,this.updateRowVisibility()}collectForSubmit(){let e=[...this.mentions],n=e.map(s=>s.ref),o=this.opts.getComposerText();for(let s of e)s.chip?.el.remove();return this.mentions.length=0,this.updateRowVisibility(),{refs:n,finalize:async()=>{var u;let s=await Promise.all(e.map(async g=>{try{return g.source.resolveOn==="submit"?await g.source.resolve(g.item,this.buildResolveContext(new AbortController().signal,g.args,o)):(g.resolvePromise&&await g.resolvePromise,g.payload??null)}catch(b){try{this.opts.mentionConfig.onMentionResolveError?.(g.item,b)}catch(m){typeof console<"u"&&console.warn("[Persona] onMentionResolveError callback threw",m)}return this.opts.emit?.("resolve-error",{sourceId:g.source.id,itemId:g.item.id}),null}})),a=[],l=[],d={},p=new Set;for(let g=0;g<e.length;g++){let b=e[g],m=s[g];if(!m)continue;let y=Fy(b.source.id,b.item.id);if(!p.has(y)){if(p.add(y),m.llmAppend&&m.llmAppend.trim())try{a.push(Oy({label:b.ref.label,text:m.llmAppend,ref:b.ref,item:b.item},a.length,this.opts.mentionConfig.llmFormat))}catch(w){typeof console<"u"&&console.warn("[Persona] context-mention llmFormat threw",w)}m.contentParts?.length&&l.push(...m.contentParts),m.context&&((d[u=b.source.id]??(d[u]={}))[b.item.id]=m.context)}}return{blocks:a,contentParts:l,context:d}}}}updateRowVisibility(){this.opts.contextRow.style.display=this.mentions.length>0?"flex":"none"}}});function $y(t){let e=t.getRootNode?.();return e&&zy(e)||e&&Ac(e)?e:t.ownerDocument??document}function Sc(t,e,n){let o=Ac(t)?t.head:t,r=e.replace(/["\\]/g,"\\$&");if(o.querySelector(`style[data-persona-plugin-style="${r}"]`))return;let a=(Ac(t)?t:t.ownerDocument??document).createElement("style");a.setAttribute("data-persona-plugin-style",e),a.textContent=n,o.appendChild(a)}function Mc(t,e,n){if(Ac(t)||zy(t)){Sc(t,e,n);return}let o=t;if(o.isConnected){Sc($y(o),e,n);return}let r=o.ownerDocument??document;Sc(r,e,n),queueMicrotask(()=>{let s=$y(o);s!==r&&Sc(s,e,n)})}function EA(t){let e=t.getRootNode?.();return e instanceof ShadowRoot?e:(t.ownerDocument??document).body}function Tc(t){let{anchor:e,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:l,zIndex:d=2147483e3,onOpen:p,onDismiss:u}=t,g=t.container??EA(e),b=!1,m=null,y=()=>{if(!b)return;let W=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${W.width}px`),a&&(n.style.maxWidth=`${W.width}px`);let E=n.getBoundingClientRect(),k=l?.()??null,A=k!=null?W.top+k:W.top,D=o==="top-start"||o==="top-end"?A-r-E.height:W.bottom+r,I=o==="bottom-end"||o==="top-end"?W.right-E.width:W.left,N=a?.()??null;if(N!=null){let _=Math.max(W.left,W.right-E.width);I=Math.min(Math.max(W.left+N,W.left),_)}n.style.top=`${D}px`,n.style.left=`${I}px`},w=()=>{b&&(b=!1,m&&(m(),m=null),n.remove())},T=()=>{if(b)return;b=!0,d!=null&&(n.style.zIndex=String(d)),g.appendChild(n),y();let W=(e.ownerDocument??document).defaultView??window,E=e.ownerDocument??document,k=()=>{if(!e.isConnected){w(),u?.("anchor-removed");return}y()},A=B=>{let I=typeof B.composedPath=="function"?B.composedPath():[];I.includes(n)||I.includes(e)||(w(),u?.("outside"))},D=W.setTimeout(()=>{E.addEventListener("pointerdown",A,!0)},0);W.addEventListener("scroll",k,!0),W.addEventListener("resize",k),m=()=>{W.clearTimeout(D),E.removeEventListener("pointerdown",A,!0),W.removeEventListener("scroll",k,!0),W.removeEventListener("resize",k)},p?.()};return{get isOpen(){return b},open:T,close:w,toggle:()=>b?w():T(),reposition:y,destroy:w}}function Vy(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Ac,zy,Ec=Ge(()=>{"use strict";Ac=t=>t.nodeType===Node.DOCUMENT_NODE,zy=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&t.host!==void 0});var jy,qy=Ge(()=>{"use strict";jy=`
12
12
  .persona-mention-menu {
13
13
  box-sizing: border-box;
14
14
  display: flex;
@@ -166,57 +166,954 @@ ${e}
166
166
  min-height: 36px;
167
167
  }
168
168
  }
169
- `});function Ca(t){let e=t.replace(/^\s+/,""),n=e.search(/\s/);return n===-1?{name:e,args:""}:{name:e.slice(0,n),args:e.slice(n+1).trim()}}var _g=ht(()=>{"use strict"});function zg(t){let{config:e,listboxId:n}=t,o=ye("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=ye("div",{className:"persona-mention-search",style:{display:"none"}}),s=v("span","persona-mention-search-icon"),i=ie("search",15,"currentColor",2);i&&s.appendChild(i);let l=ye("input",{className:"persona-mention-search-input",attrs:{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-controls":n,"aria-label":e.searchPlaceholder??"Search context",placeholder:e.searchPlaceholder??"Search context\u2026",autocomplete:"off",autocapitalize:"off",spellcheck:"false"}});r.append(s,l),l.addEventListener("input",()=>t.onSearchInput?.(l.value)),l.addEventListener("keydown",H=>t.onSearchKeydown?.(H));let p=ye("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,p);let c=[],d=[],g=-1,b=new Map,f=(H,w)=>`${H}\0${w}`,y=H=>`${n}-opt-${H}`,C=H=>`${n}-grp-${H}`,M=(H,w)=>{let N=c[H];N&&(w?N.setAttribute("data-active","true"):N.removeAttribute("data-active"),N.setAttribute("aria-selected",w?"true":"false"),d[H]?.(w))},I=(H,w=!0)=>{g>=0&&g!==H&&M(g,!1),g=H;let N=c[H];N?(M(H,!0),w&&N.scrollIntoView?.({block:"nearest"}),p.setAttribute("aria-activedescendant",N.id),l.setAttribute("aria-activedescendant",N.id)):(p.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},S=(H,w)=>{let N=C(w),K=ye("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":N}});return K.appendChild(ye("div",{className:"persona-mention-group-header",attrs:{id:N},text:H})),K},E=()=>{let H=ye("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),w=v("span","persona-mention-option-icon");H.appendChild(w);let N="",K=v("span","persona-mention-option-text"),te=v("span","persona-mention-option-labelline"),Q=v("span","persona-mention-option-label");te.appendChild(Q),K.appendChild(te),H.appendChild(K);let se=null,J=null,oe={el:H,index:0,update:(Y,pe,ne)=>{oe.index=pe,H.id=y(pe),H.setAttribute("aria-setsize",String(ne)),H.setAttribute("aria-posinset",String(pe+1)),H.removeAttribute("data-active"),H.setAttribute("aria-selected","false");let me=Y.iconName??e.chipIconName??"at-sign";if(me!==N){N=me;let be=ov(me,15,2);w.replaceChildren(...be?[be]:[])}Q.textContent!==Y.label&&(Q.textContent=Y.label);let ve=Y.commandArgsPlaceholder?`\u2039${Y.commandArgsPlaceholder}\u203A`:null;ve?(se||(se=v("span","persona-mention-option-arghint"),te.appendChild(se)),se.textContent!==ve&&(se.textContent=ve)):se&&(se.remove(),se=null),Y.description?(J||(J=v("span","persona-mention-option-desc"),K.appendChild(J)),J.textContent!==Y.description&&(J.textContent=Y.description)):J&&(J.remove(),J=null)}};return H.addEventListener("mousedown",Y=>{Y.button===0&&(Y.preventDefault(),t.onSelectIndex(oe.index))}),H.addEventListener("mouseenter",()=>t.onHoverIndex(oe.index)),oe},L=(H,w,N,K,te)=>{let Q=ye("div",{className:"persona-mention-option",attrs:{role:"option",id:y(K),"aria-selected":"false","aria-setsize":String(te),"aria-posinset":String(K+1)}}),se=J=>{Q.replaceChildren(e.renderMentionItem({item:H,source:w,query:N,active:J,index:K}))};return se(!1),Q.addEventListener("mousedown",J=>{J.button===0&&(J.preventDefault(),t.onSelectIndex(K))}),Q.addEventListener("mouseenter",()=>t.onHoverIndex(K)),{el:Q,paint:se}},D=H=>{let w=ye("div",{className:"persona-mention-status persona-mention-error"});if(w.appendChild(ye("span",{className:"persona-mention-error-text",text:`Couldn't load ${H.label}`})),t.onRetry){let N=ye("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});N.addEventListener("mousedown",K=>K.preventDefault()),N.addEventListener("click",K=>{K.preventDefault(),t.onRetry(H.id)}),w.appendChild(N)}return w};return{el:o,render:H=>{p.replaceChildren(),c=[],d=[],g=-1;let w=new Set,N=0,K=0,te=0,Q=0,se=0,J=H.groups.reduce((oe,Y)=>Y.status==="ready"?oe+Y.items.length:oe,0);for(let oe of H.groups)if(oe.status==="loading"){te++;let Y=S(oe.source.label,se++);Y.appendChild(ye("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),p.appendChild(Y)}else if(oe.status==="error"){Q++;let Y=S(oe.source.label,se++);Y.appendChild(D(oe.source)),p.appendChild(Y)}else if(oe.status==="ready"&&oe.items.length>0){let Y=new Map;for(let ne of oe.items){let me=ne.group??oe.source.label,ve=Y.get(me);ve?ve.push(ne):Y.set(me,[ne])}let pe=Array.from(Y.entries());pe.forEach(([ne,me],ve)=>{let be=S(ne,se++);for(let Te of me){let ze=N++,Oe;if(e.renderMentionItem){let Ne=L(Te,oe.source,H.query,ze,J);Oe=Ne.el,d.push(Ne.paint)}else{let Ne=f(oe.source.id,Te.id),Be=w.has(Ne)?void 0:b.get(Ne);Be||(Be=E(),w.has(Ne)||b.set(Ne,Be)),w.add(Ne),Be.update(Te,ze,J),Oe=Be.el,d.push(null)}c.push(Oe),be.appendChild(Oe),K++}oe.truncated&&ve===pe.length-1&&be.appendChild(ye("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),p.appendChild(be)})}for(let oe of b.keys())w.has(oe)||b.delete(oe);K===0&&te===0&&Q===0&&p.appendChild(ye("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),c.length>0?I(Math.min(Math.max(0,H.activeIndex),c.length-1)):(p.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:I,destroy:()=>{p.replaceChildren(),c=[],b.clear(),o.remove()},showSearch:(H,w)=>{l.value=H,w&&(l.placeholder=w),r.style.display="",l.setAttribute("aria-expanded","true"),l.focus(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{r.style.display!=="none"&&l.focus()})},hideSearch:()=>{r.style.display="none",l.value="",l.setAttribute("aria-expanded","false"),l.removeAttribute("aria-activedescendant")}}}var $g,ov,Ug=ht(()=>{"use strict";Ye();xt();$g=new Map,ov=(t,e,n)=>{let o=`${t}|${e}|${n}`,r=$g.get(o);return r===void 0&&(r=ie(t,e,"currentColor",n),$g.set(o,r)),r?r.cloneNode(!0):null}});var rv,sv,Aa,jg=ht(()=>{"use strict";Lc();Fg();ma();Ac();_g();Ug();kc();rv=t=>!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function",sv=0,Aa=class{constructor(e){this.popover=null;this.resizeObserver=null;this.isOpenState=!1;this.query="";this.triggerMatch=null;this.activeIndex=0;this.activeKey=null;this.pickerMode=!1;this.pickerTrigger=null;this.groups=[];this.flat=[];this.searchToken=0;this.searchAbort=null;this.debounceTimer=null;this.knownAsync=new Set;this.invokedForToken=new Set;this.lastAnnouncedCount=-1;this.triggerAnchorOffset=null;this.measuredTriggerIndex=null;this.opts=e;let n=e.mentionConfig,o=ha(n),r=o.filter(i=>i.sources.length>0);this.channels=r.length>0?r:[o[0]],this.activeChannel=this.channels[0],this.maxPerGroup=n.maxItemsPerGroup??6,this.debounceMs=n.searchDebounceMs??150,this.listboxId=`persona-mention-listbox-${++sv}`,this.menu=e.mentionConfig.renderMentionMenu?this.createHostMenu():zg({config:e.mentionConfig,listboxId:this.listboxId,onSelectIndex:i=>this.selectIndex(i),onHoverIndex:i=>this.setActiveIndex(i,!1),onRetry:i=>this.retrySource(i),onSearchInput:i=>this.setQuery(i),onSearchKeydown:i=>{this.handleKeydown(i)}});let s=e.composerInput.element;s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",this.listboxId)}get input(){return this.opts.composerInput}createHostMenu(){let e=document.createElement("div");e.setAttribute("data-persona-mention-menu",""),e.setAttribute("role","listbox"),e.id=this.listboxId;let n=()=>{let o=this.opts.mentionConfig.renderMentionMenu({query:this.query,groups:this.groups.map(r=>({source:r.source,items:r.items})),status:Object.fromEntries(this.groups.map(r=>[r.source.id,r.status])),activeIndex:this.activeIndex,select:r=>{let s=this.groups.find(i=>i.items.includes(r));s&&this.commit(s.source,r)},close:()=>this.close()});e.replaceChildren(o)};return{el:e,render:n,setActiveIndex:n,destroy:()=>e.remove()}}isOpen(){return this.isOpenState}openFromButton(e){let n=e&&this.channels.find(i=>i.trigger===e)||this.channels[0],o=this.input.getSelection().start,r=zs(this.input.getLogicalText(),o,[n]);if(r){this.pickerMode=!1,this.triggerMatch=r.match,this.isOpenState?(this.switchChannel(n),this.setQuery(r.match.query)):this.open(r.match.query,n),this.input.focus();return}let s=this.pickerTrigger;this.pickerMode=!0,this.pickerTrigger=n.trigger,this.triggerMatch=null,this.isOpenState?(s&&s!==n.trigger&&this.opts.onPickerOpenChange?.(!1,s,this.listboxId),this.switchChannel(n),this.setQuery("")):this.open("",n),this.menu.showSearch?this.menu.showSearch("",n.searchPlaceholder):this.input.focus(),this.opts.onPickerOpenChange?.(!0,n.trigger,this.listboxId)}onInput(){let e=this.input.getSelection().start,n=zs(this.input.getLogicalText(),e,this.channels);if(!n){this.isOpenState&&this.close();return}if(this.isInlineArgTail(n.channel,n.match.query)){this.triggerMatch=null,this.isOpenState&&this.close(!1);return}this.triggerMatch=n.match,this.isOpenState?(this.switchChannel(n.channel),this.measuredTriggerIndex!==n.match.triggerIndex&&this.updateTriggerAnchor(),this.setQuery(n.match.query)):this.open(n.match.query,n.channel)}switchChannel(e){e!==this.activeChannel&&(this.activeChannel=e,this.groups=[],this.activeIndex=0)}open(e,n){if(this.isOpenState=!0,this.activeChannel=n,this.groups=[],this.activeIndex=0,this.lastAnnouncedCount=-1,!this.popover){let o=this.canAnchorMenu();if(this.popover=wa({anchor:this.opts.anchor,content:this.menu.el,placement:"top-start",matchAnchorWidth:!o,offset:6,container:this.opts.popoverContainer,horizontalOffset:o?()=>this.triggerAnchorOffset?.x??null:void 0,verticalOffset:o?()=>this.triggerAnchorOffset?.y??null:void 0,onDismiss:()=>this.close(!1)}),o){let r=this.opts.anchor.getBoundingClientRect().width;this.menu.el.style.minWidth=`${Math.min(220,r)}px`}}this.updateTriggerAnchor(),this.popover.open(),Dg(this.menu.el,"persona-mention-menu",Ng),this.observeComposerResize(),this.opts.emit?.("opened",{trigger:n.trigger}),this.setQuery(e)}observeComposerResize(){typeof ResizeObserver>"u"||this.resizeObserver||(this.resizeObserver=new ResizeObserver(()=>{this.isOpenState&&(this.updateTriggerAnchor(),this.popover?.reposition())}),this.resizeObserver.observe(this.opts.anchor))}disconnectComposerResize(){this.resizeObserver?.disconnect(),this.resizeObserver=null}canAnchorMenu(){return this.isInlineDisplay()&&!!this.input.getLogicalRangeRect}updateTriggerAnchor(){let e=this.triggerMatch,n=this.input.getLogicalRangeRect;if(this.measuredTriggerIndex=e?.triggerIndex??null,this.triggerAnchorOffset=null,!e||!n)return;let o=n(e.triggerIndex,e.triggerIndex+1);if(!o)return;let r=this.opts.anchor.getBoundingClientRect(),s=o.top-r.top,i=this.input.element,l=typeof getComputedStyle=="function"&&getComputedStyle(i).direction==="rtl";this.triggerAnchorOffset={x:l?null:o.left-r.left,y:s}}close(e=!0){this.isOpenState&&(this.isOpenState=!1,this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.searchToken++,this.popover?.close(),this.input.element.removeAttribute("aria-activedescendant"),this.pickerMode&&(this.pickerMode=!1,this.menu.hideSearch?.(),this.opts.onPickerOpenChange?.(!1,this.pickerTrigger??this.activeChannel.trigger,this.listboxId),this.pickerTrigger=null,e&&this.input.focus()))}setQuery(e){this.query=e,this.activeIndex=0,this.activeKey=null;let n=++this.searchToken;this.invokedForToken.clear(),this.searchAbort?.abort(),this.searchAbort=new AbortController;for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)?this.setGroupStatus(o.id,"loading"):(this.invokedForToken.add(o.id),this.invokeSource(o,n));this.render(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{if(n===this.searchToken)for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)&&!this.invokedForToken.has(o.id)&&this.invokeSource(o,n)},this.debounceMs)}invokeSource(e,n){let o={messages:this.opts.getMessages(),config:this.opts.getConfig(),signal:this.searchAbort.signal},r;try{r=e.search(this.query,o)}catch{this.setGroupStatus(e.id,"error"),this.render();return}rv(r)?(this.knownAsync.add(e.id),this.setGroupStatus(e.id,"loading"),r.then(s=>{n===this.searchToken&&(this.setGroupItems(e.id,s),this.render())}).catch(()=>{n===this.searchToken&&(this.setGroupStatus(e.id,"error"),this.render())})):this.setGroupItems(e.id,r)}getOrCreateGroup(e){let n=this.groups.find(o=>o.source.id===e.id);if(!n){n={source:e,items:[],status:"loading",truncated:!1};let o=this.activeChannel.sources;this.groups.push(n),this.groups.sort((r,s)=>o.findIndex(i=>i.id===r.source.id)-o.findIndex(i=>i.id===s.source.id))}return n}setGroupStatus(e,n){let o=this.activeChannel.sources.find(r=>r.id===e);o&&(this.getOrCreateGroup(o).status=n)}setGroupItems(e,n){let o=this.activeChannel.sources.find(s=>s.id===e);if(!o)return;let r=this.getOrCreateGroup(o);r.truncated=n.length>this.maxPerGroup,r.items=n.slice(0,this.maxPerGroup),r.status=r.items.length===0?"empty":"ready"}keyOf(e){return JSON.stringify([e.source.id,e.item.id])}rebuildFlat(){this.flat=[];for(let e of this.groups)if(e.status==="ready")for(let n of e.items)this.flat.push({source:e.source,item:n});if(this.activeKey){let e=this.flat.findIndex(n=>this.keyOf(n)===this.activeKey);this.activeIndex=e>=0?e:Math.min(this.activeIndex,Math.max(0,this.flat.length-1))}else this.activeIndex>=this.flat.length&&(this.activeIndex=Math.max(0,this.flat.length-1))}viewModel(){return{query:this.query,groups:this.groups,activeIndex:this.activeIndex}}render(){this.rebuildFlat(),this.menu.render(this.viewModel()),this.syncActiveDescendant(),this.popover?.reposition();let e=this.groups.some(n=>n.status==="loading");this.flat.length===0&&e||this.flat.length!==this.lastAnnouncedCount&&(this.lastAnnouncedCount=this.flat.length,this.opts.announce(this.flat.length===0?"No matches":this.flat.length===1?"1 result":`${this.flat.length} results`),this.opts.emit?.("searched",{query:this.query,results:this.flat.length}))}setActiveIndex(e,n=!0){e<0||e>=this.flat.length||(this.activeIndex=e,this.activeKey=this.keyOf(this.flat[e]),this.menu.setActiveIndex(e,n),this.syncActiveDescendant())}syncActiveDescendant(){this.isOpenState&&!this.pickerMode&&this.activeIndex>=0&&this.activeIndex<this.flat.length?this.input.element.setAttribute("aria-activedescendant",`${this.listboxId}-opt-${this.activeIndex}`):this.input.element.removeAttribute("aria-activedescendant")}retrySource(e){let n=this.activeChannel.sources.find(o=>o.id===e);!n||!this.searchAbort||(this.setGroupStatus(e,"loading"),this.render(),this.invokeSource(n,this.searchToken),this.render())}handleKeydown(e){if(!this.isOpenState)return!1;switch(e.key){case"ArrowDown":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex+1)%this.flat.length)),!0;case"ArrowUp":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex-1+this.flat.length)%this.flat.length)),!0;case"Home":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(0)),!0;case"End":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(this.flat.length-1)),!0;case"Enter":case"Tab":return this.flat.length===0?(this.close(),!1):(e.preventDefault(),this.selectIndex(this.activeIndex),!0);case"Escape":return e.preventDefault(),this.close(),!0;case"Backspace":return this.query.length===0&&this.close(),!1;default:return!1}}selectIndex(e){let n=this.flat[e];n&&this.commit(n.source,n.item)}deriveArgs(e){return Ca(e).args}isInlineCommand(e){return e.command==="server"||e.commandArgsPlaceholder!=null}commit(e,n){let o=n.command;if(this.isInlineCommand(n)){this.completeCommandInline(e,n);return}if(o==="action"){let s=this.deriveArgs(this.query);this.stripQuery(),this.close(),this.runAction(n,s),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"action",args:s}),this.input.focus();return}if(o==="prompt"){let s=this.deriveArgs(this.query),i=this.captureStripTarget();this.close(),this.runPromptMacro(e,n,s,i),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"prompt",args:s});return}if(this.isInlineDisplay()){this.commitInlineMention(e,n);return}this.opts.onSelect(e,n,"")&&(this.stripQuery(),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})),this.close(),this.input.focus()}isInlineDisplay(){return this.opts.mentionConfig.display==="inline"&&!!this.opts.onInsertMention&&!!this.input.insertMentionAtTrigger}commitInlineMention(e,n){if(this.opts.admitMention&&!this.opts.admitMention(e,n)){this.close(),this.input.focus();return}let o=ya(e,n),r=this.triggerMatch?this.input.insertMentionAtTrigger(o,this.triggerMatch):this.input.insertMentionAtSelection?.(o)??null;r?(this.opts.onInsertMention(r,e,n,""),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})):(this.opts.mentionConfig.onMentionRejected?.(n,"stale"),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:"stale"})),this.triggerMatch=null,this.close(),this.input.focus()}completeCommandInline(e,n){let o=`${this.activeChannel.trigger}${n.label} `,r=this.input.getSelection().start,s=this.triggerMatch?this.triggerMatch.triggerIndex:r;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(s,r,o);else{let i=this.input.getValue();this.input.setValueWithCaret(i.slice(0,s)+o+i.slice(r),s+o.length)}this.triggerMatch=null,this.close(),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:n.command??"prompt",phase:"armed"}),this.input.dispatchInput(),this.input.focus()}isInlineArgTail(e,n){let{name:o}=Ca(n);return!o||n.length<=o.length?!1:e.sources.some(r=>{let s=r.matchCommand?.(o);return!!s&&this.isInlineCommand(s)})}matchInlineCommand(e){for(let n of this.channels){if(!n.trigger)continue;let o=n.position==="anywhere"?[e]:n.position==="line-start"?e.split(`
169
+ `});function kc(t){let e=t.replace(/^\s+/,""),n=e.search(/\s/);return n===-1?{name:e,args:""}:{name:e.slice(0,n),args:e.slice(n+1).trim()}}var Uy=Ge(()=>{"use strict"});function Gy(t){let{config:e,listboxId:n}=t,o=J("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=J("div",{className:"persona-mention-search",style:{display:"none"}}),s=v("span","persona-mention-search-icon"),a=fe("search",15,"currentColor",2);a&&s.appendChild(a);let l=J("input",{className:"persona-mention-search-input",attrs:{type:"text",role:"combobox","aria-autocomplete":"list","aria-expanded":"false","aria-controls":n,"aria-label":e.searchPlaceholder??"Search context",placeholder:e.searchPlaceholder??"Search context\u2026",autocomplete:"off",autocapitalize:"off",spellcheck:"false"}});r.append(s,l),l.addEventListener("input",()=>t.onSearchInput?.(l.value)),l.addEventListener("keydown",F=>t.onSearchKeydown?.(F));let d=J("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,d);let p=[],u=[],g=-1,b=new Map,m=(F,P)=>`${F}\0${P}`,y=F=>`${n}-opt-${F}`,w=F=>`${n}-grp-${F}`,T=(F,P)=>{let V=p[F];V&&(P?V.setAttribute("data-active","true"):V.removeAttribute("data-active"),V.setAttribute("aria-selected",P?"true":"false"),u[F]?.(P))},W=(F,P=!0)=>{g>=0&&g!==F&&T(g,!1),g=F;let V=p[F];V?(T(F,!0),P&&V.scrollIntoView?.({block:"nearest"}),d.setAttribute("aria-activedescendant",V.id),l.setAttribute("aria-activedescendant",V.id)):(d.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},E=(F,P)=>{let V=w(P),se=J("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":V}});return se.appendChild(J("div",{className:"persona-mention-group-header",attrs:{id:V},text:F})),se},k=()=>{let F=J("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),P=v("span","persona-mention-option-icon");F.appendChild(P);let V="",se=v("span","persona-mention-option-text"),ve=v("span","persona-mention-option-labelline"),he=v("span","persona-mention-option-label");ve.appendChild(he),se.appendChild(ve),F.appendChild(se);let ge=null,re=null,oe={el:F,index:0,update:(ee,M,te)=>{oe.index=M,F.id=y(M),F.setAttribute("aria-setsize",String(te)),F.setAttribute("aria-posinset",String(M+1)),F.removeAttribute("data-active"),F.setAttribute("aria-selected","false");let pe=ee.iconName??e.chipIconName??"at-sign";if(pe!==V){V=pe;let xe=kA(pe,15,2);P.replaceChildren(...xe?[xe]:[])}he.textContent!==ee.label&&(he.textContent=ee.label);let Se=ee.commandArgsPlaceholder?`\u2039${ee.commandArgsPlaceholder}\u203A`:null;Se?(ge||(ge=v("span","persona-mention-option-arghint"),ve.appendChild(ge)),ge.textContent!==Se&&(ge.textContent=Se)):ge&&(ge.remove(),ge=null),ee.description?(re||(re=v("span","persona-mention-option-desc"),se.appendChild(re)),re.textContent!==ee.description&&(re.textContent=ee.description)):re&&(re.remove(),re=null)}};return F.addEventListener("mousedown",ee=>{ee.button===0&&(ee.preventDefault(),t.onSelectIndex(oe.index))}),F.addEventListener("mouseenter",()=>t.onHoverIndex(oe.index)),oe},A=(F,P,V,se,ve)=>{let he=J("div",{className:"persona-mention-option",attrs:{role:"option",id:y(se),"aria-selected":"false","aria-setsize":String(ve),"aria-posinset":String(se+1)}}),ge=re=>{he.replaceChildren(e.renderMentionItem({item:F,source:P,query:V,active:re,index:se}))};return ge(!1),he.addEventListener("mousedown",re=>{re.button===0&&(re.preventDefault(),t.onSelectIndex(se))}),he.addEventListener("mouseenter",()=>t.onHoverIndex(se)),{el:he,paint:ge}},D=F=>{let P=J("div",{className:"persona-mention-status persona-mention-error"});if(P.appendChild(J("span",{className:"persona-mention-error-text",text:`Couldn't load ${F.label}`})),t.onRetry){let V=J("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});V.addEventListener("mousedown",se=>se.preventDefault()),V.addEventListener("click",se=>{se.preventDefault(),t.onRetry(F.id)}),P.appendChild(V)}return P};return{el:o,render:F=>{d.replaceChildren(),p=[],u=[],g=-1;let P=new Set,V=0,se=0,ve=0,he=0,ge=0,re=F.groups.reduce((oe,ee)=>ee.status==="ready"?oe+ee.items.length:oe,0);for(let oe of F.groups)if(oe.status==="loading"){ve++;let ee=E(oe.source.label,ge++);ee.appendChild(J("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),d.appendChild(ee)}else if(oe.status==="error"){he++;let ee=E(oe.source.label,ge++);ee.appendChild(D(oe.source)),d.appendChild(ee)}else if(oe.status==="ready"&&oe.items.length>0){let ee=new Map;for(let te of oe.items){let pe=te.group??oe.source.label,Se=ee.get(pe);Se?Se.push(te):ee.set(pe,[te])}let M=Array.from(ee.entries());M.forEach(([te,pe],Se)=>{let xe=E(te,ge++);for(let Ce of pe){let Me=V++,ke;if(e.renderMentionItem){let Oe=A(Ce,oe.source,F.query,Me,re);ke=Oe.el,u.push(Oe.paint)}else{let Oe=m(oe.source.id,Ce.id),ze=P.has(Oe)?void 0:b.get(Oe);ze||(ze=k(),P.has(Oe)||b.set(Oe,ze)),P.add(Oe),ze.update(Ce,Me,re),ke=ze.el,u.push(null)}p.push(ke),xe.appendChild(ke),se++}oe.truncated&&Se===M.length-1&&xe.appendChild(J("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),d.appendChild(xe)})}for(let oe of b.keys())P.has(oe)||b.delete(oe);se===0&&ve===0&&he===0&&d.appendChild(J("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),p.length>0?W(Math.min(Math.max(0,F.activeIndex),p.length-1)):(d.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:W,destroy:()=>{d.replaceChildren(),p=[],b.clear(),o.remove()},showSearch:(F,P)=>{l.value=F,P&&(l.placeholder=P),r.style.display="",l.setAttribute("aria-expanded","true"),l.focus(),typeof requestAnimationFrame=="function"&&requestAnimationFrame(()=>{r.style.display!=="none"&&l.focus()})},hideSearch:()=>{r.style.display="none",l.value="",l.setAttribute("aria-expanded","false"),l.removeAttribute("aria-activedescendant")}}}var Ky,kA,Yy=Ge(()=>{"use strict";Qe();Rt();Ky=new Map,kA=(t,e,n)=>{let o=`${t}|${e}|${n}`,r=Ky.get(o);return r===void 0&&(r=fe(t,e,"currentColor",n),Ky.set(o,r)),r?r.cloneNode(!0):null}});var PA,LA,Pc,Xy=Ge(()=>{"use strict";Ec();qy();bc();uu();Uy();Yy();yu();PA=t=>!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function",LA=0,Pc=class{constructor(e){this.popover=null;this.resizeObserver=null;this.isOpenState=!1;this.query="";this.triggerMatch=null;this.activeIndex=0;this.activeKey=null;this.pickerMode=!1;this.pickerTrigger=null;this.groups=[];this.flat=[];this.searchToken=0;this.searchAbort=null;this.debounceTimer=null;this.knownAsync=new Set;this.invokedForToken=new Set;this.lastAnnouncedCount=-1;this.triggerAnchorOffset=null;this.measuredTriggerIndex=null;this.opts=e;let n=e.mentionConfig,o=vc(n),r=o.filter(a=>a.sources.length>0);this.channels=r.length>0?r:[o[0]],this.activeChannel=this.channels[0],this.maxPerGroup=n.maxItemsPerGroup??6,this.debounceMs=n.searchDebounceMs??150,this.listboxId=`persona-mention-listbox-${++LA}`,this.menu=e.mentionConfig.renderMentionMenu?this.createHostMenu():Gy({config:e.mentionConfig,listboxId:this.listboxId,onSelectIndex:a=>this.selectIndex(a),onHoverIndex:a=>this.setActiveIndex(a,!1),onRetry:a=>this.retrySource(a),onSearchInput:a=>this.setQuery(a),onSearchKeydown:a=>{this.handleKeydown(a)}});let s=e.composerInput.element;s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",this.listboxId)}get input(){return this.opts.composerInput}createHostMenu(){let e=document.createElement("div");e.setAttribute("data-persona-mention-menu",""),e.setAttribute("role","listbox"),e.id=this.listboxId;let n=()=>{let o=this.opts.mentionConfig.renderMentionMenu({query:this.query,groups:this.groups.map(r=>({source:r.source,items:r.items})),status:Object.fromEntries(this.groups.map(r=>[r.source.id,r.status])),activeIndex:this.activeIndex,select:r=>{let s=this.groups.find(a=>a.items.includes(r));s&&this.commit(s.source,r)},close:()=>this.close()});e.replaceChildren(o)};return{el:e,render:n,setActiveIndex:n,destroy:()=>e.remove()}}isOpen(){return this.isOpenState}openFromButton(e){let n=e&&this.channels.find(a=>a.trigger===e)||this.channels[0],o=this.input.getSelection().start,r=ga(this.input.getLogicalText(),o,[n]);if(r){this.pickerMode=!1,this.triggerMatch=r.match,this.isOpenState?(this.switchChannel(n),this.setQuery(r.match.query)):this.open(r.match.query,n),this.input.focus();return}let s=this.pickerTrigger;this.pickerMode=!0,this.pickerTrigger=n.trigger,this.triggerMatch=null,this.isOpenState?(s&&s!==n.trigger&&this.opts.onPickerOpenChange?.(!1,s,this.listboxId),this.switchChannel(n),this.setQuery("")):this.open("",n),this.menu.showSearch?this.menu.showSearch("",n.searchPlaceholder):this.input.focus(),this.opts.onPickerOpenChange?.(!0,n.trigger,this.listboxId)}onInput(){let e=this.input.getSelection().start,n=ga(this.input.getLogicalText(),e,this.channels);if(!n){this.isOpenState&&this.close();return}if(this.isInlineArgTail(n.channel,n.match.query)){this.triggerMatch=null,this.isOpenState&&this.close(!1);return}this.triggerMatch=n.match,this.isOpenState?(this.switchChannel(n.channel),this.measuredTriggerIndex!==n.match.triggerIndex&&this.updateTriggerAnchor(),this.setQuery(n.match.query)):this.open(n.match.query,n.channel)}switchChannel(e){e!==this.activeChannel&&(this.activeChannel=e,this.groups=[],this.activeIndex=0)}open(e,n){if(this.isOpenState=!0,this.activeChannel=n,this.groups=[],this.activeIndex=0,this.lastAnnouncedCount=-1,!this.popover){let o=this.canAnchorMenu();if(this.popover=Tc({anchor:this.opts.anchor,content:this.menu.el,placement:"top-start",matchAnchorWidth:!o,offset:6,container:this.opts.popoverContainer,horizontalOffset:o?()=>this.triggerAnchorOffset?.x??null:void 0,verticalOffset:o?()=>this.triggerAnchorOffset?.y??null:void 0,onDismiss:()=>this.close(!1)}),o){let r=this.opts.anchor.getBoundingClientRect().width;this.menu.el.style.minWidth=`${Math.min(220,r)}px`}}this.updateTriggerAnchor(),this.popover.open(),Mc(this.menu.el,"persona-mention-menu",jy),this.observeComposerResize(),this.opts.emit?.("opened",{trigger:n.trigger}),this.setQuery(e)}observeComposerResize(){typeof ResizeObserver>"u"||this.resizeObserver||(this.resizeObserver=new ResizeObserver(()=>{this.isOpenState&&(this.updateTriggerAnchor(),this.popover?.reposition())}),this.resizeObserver.observe(this.opts.anchor))}disconnectComposerResize(){this.resizeObserver?.disconnect(),this.resizeObserver=null}canAnchorMenu(){return this.isInlineDisplay()&&!!this.input.getLogicalRangeRect}updateTriggerAnchor(){let e=this.triggerMatch,n=this.input.getLogicalRangeRect;if(this.measuredTriggerIndex=e?.triggerIndex??null,this.triggerAnchorOffset=null,!e||!n)return;let o=n(e.triggerIndex,e.triggerIndex+1);if(!o)return;let r=this.opts.anchor.getBoundingClientRect(),s=o.top-r.top,a=this.input.element,l=typeof getComputedStyle=="function"&&getComputedStyle(a).direction==="rtl";this.triggerAnchorOffset={x:l?null:o.left-r.left,y:s}}close(e=!0){this.isOpenState&&(this.isOpenState=!1,this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.searchToken++,this.popover?.close(),this.input.element.removeAttribute("aria-activedescendant"),this.pickerMode&&(this.pickerMode=!1,this.menu.hideSearch?.(),this.opts.onPickerOpenChange?.(!1,this.pickerTrigger??this.activeChannel.trigger,this.listboxId),this.pickerTrigger=null,e&&this.input.focus()))}setQuery(e){this.query=e,this.activeIndex=0,this.activeKey=null;let n=++this.searchToken;this.invokedForToken.clear(),this.searchAbort?.abort(),this.searchAbort=new AbortController;for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)?this.setGroupStatus(o.id,"loading"):(this.invokedForToken.add(o.id),this.invokeSource(o,n));this.render(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout(()=>{if(n===this.searchToken)for(let o of this.activeChannel.sources)this.knownAsync.has(o.id)&&!this.invokedForToken.has(o.id)&&this.invokeSource(o,n)},this.debounceMs)}invokeSource(e,n){let o={messages:this.opts.getMessages(),config:this.opts.getConfig(),signal:this.searchAbort.signal},r;try{r=e.search(this.query,o)}catch{this.setGroupStatus(e.id,"error"),this.render();return}PA(r)?(this.knownAsync.add(e.id),this.setGroupStatus(e.id,"loading"),r.then(s=>{n===this.searchToken&&(this.setGroupItems(e.id,s),this.render())}).catch(()=>{n===this.searchToken&&(this.setGroupStatus(e.id,"error"),this.render())})):this.setGroupItems(e.id,r)}getOrCreateGroup(e){let n=this.groups.find(o=>o.source.id===e.id);if(!n){n={source:e,items:[],status:"loading",truncated:!1};let o=this.activeChannel.sources;this.groups.push(n),this.groups.sort((r,s)=>o.findIndex(a=>a.id===r.source.id)-o.findIndex(a=>a.id===s.source.id))}return n}setGroupStatus(e,n){let o=this.activeChannel.sources.find(r=>r.id===e);o&&(this.getOrCreateGroup(o).status=n)}setGroupItems(e,n){let o=this.activeChannel.sources.find(s=>s.id===e);if(!o)return;let r=this.getOrCreateGroup(o);r.truncated=n.length>this.maxPerGroup,r.items=n.slice(0,this.maxPerGroup),r.status=r.items.length===0?"empty":"ready"}keyOf(e){return JSON.stringify([e.source.id,e.item.id])}rebuildFlat(){this.flat=[];for(let e of this.groups)if(e.status==="ready")for(let n of e.items)this.flat.push({source:e.source,item:n});if(this.activeKey){let e=this.flat.findIndex(n=>this.keyOf(n)===this.activeKey);this.activeIndex=e>=0?e:Math.min(this.activeIndex,Math.max(0,this.flat.length-1))}else this.activeIndex>=this.flat.length&&(this.activeIndex=Math.max(0,this.flat.length-1))}viewModel(){return{query:this.query,groups:this.groups,activeIndex:this.activeIndex}}render(){this.rebuildFlat(),this.menu.render(this.viewModel()),this.syncActiveDescendant(),this.popover?.reposition();let e=this.groups.some(n=>n.status==="loading");this.flat.length===0&&e||this.flat.length!==this.lastAnnouncedCount&&(this.lastAnnouncedCount=this.flat.length,this.opts.announce(this.flat.length===0?"No matches":this.flat.length===1?"1 result":`${this.flat.length} results`),this.opts.emit?.("searched",{query:this.query,results:this.flat.length}))}setActiveIndex(e,n=!0){e<0||e>=this.flat.length||(this.activeIndex=e,this.activeKey=this.keyOf(this.flat[e]),this.menu.setActiveIndex(e,n),this.syncActiveDescendant())}syncActiveDescendant(){this.isOpenState&&!this.pickerMode&&this.activeIndex>=0&&this.activeIndex<this.flat.length?this.input.element.setAttribute("aria-activedescendant",`${this.listboxId}-opt-${this.activeIndex}`):this.input.element.removeAttribute("aria-activedescendant")}retrySource(e){let n=this.activeChannel.sources.find(o=>o.id===e);!n||!this.searchAbort||(this.setGroupStatus(e,"loading"),this.render(),this.invokeSource(n,this.searchToken),this.render())}handleKeydown(e){if(!this.isOpenState)return!1;switch(e.key){case"ArrowDown":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex+1)%this.flat.length)),!0;case"ArrowUp":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex((this.activeIndex-1+this.flat.length)%this.flat.length)),!0;case"Home":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(0)),!0;case"End":return this.flat.length===0||(e.preventDefault(),this.setActiveIndex(this.flat.length-1)),!0;case"Enter":case"Tab":return this.flat.length===0?(this.close(),!1):(e.preventDefault(),this.selectIndex(this.activeIndex),!0);case"Escape":return e.preventDefault(),this.close(),!0;case"Backspace":return this.query.length===0&&this.close(),!1;default:return!1}}selectIndex(e){let n=this.flat[e];n&&this.commit(n.source,n.item)}deriveArgs(e){return kc(e).args}isInlineCommand(e){return e.command==="server"||e.commandArgsPlaceholder!=null}commit(e,n){let o=n.command;if(this.isInlineCommand(n)){this.completeCommandInline(e,n);return}if(o==="action"){let s=this.deriveArgs(this.query);this.stripQuery(),this.close(),this.runAction(n,s),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"action",args:s}),this.input.focus();return}if(o==="prompt"){let s=this.deriveArgs(this.query),a=this.captureStripTarget();this.close(),this.runPromptMacro(e,n,s,a),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:"prompt",args:s});return}if(this.isInlineDisplay()){this.commitInlineMention(e,n);return}this.opts.onSelect(e,n,"")&&(this.stripQuery(),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})),this.close(),this.input.focus()}isInlineDisplay(){return this.opts.mentionConfig.display==="inline"&&!!this.opts.onInsertMention&&!!this.input.insertMentionAtTrigger}commitInlineMention(e,n){if(this.opts.admitMention&&!this.opts.admitMention(e,n)){this.close(),this.input.focus();return}let o=Cc(e,n),r=this.triggerMatch?this.input.insertMentionAtTrigger(o,this.triggerMatch):this.input.insertMentionAtSelection?.(o)??null;r?(this.opts.onInsertMention(r,e,n,""),this.opts.emit?.("selected",{sourceId:e.id,itemId:n.id,label:n.label})):(this.opts.mentionConfig.onMentionRejected?.(n,"stale"),this.opts.emit?.("rejected",{sourceId:e.id,itemId:n.id,reason:"stale"})),this.triggerMatch=null,this.close(),this.input.focus()}completeCommandInline(e,n){let o=`${this.activeChannel.trigger}${n.label} `,r=this.input.getSelection().start,s=this.triggerMatch?this.triggerMatch.triggerIndex:r;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(s,r,o);else{let a=this.input.getValue();this.input.setValueWithCaret(a.slice(0,s)+o+a.slice(r),s+o.length)}this.triggerMatch=null,this.close(),this.opts.emit?.("command",{sourceId:e.id,itemId:n.id,kind:n.command??"prompt",phase:"armed"}),this.input.dispatchInput(),this.input.focus()}isInlineArgTail(e,n){let{name:o}=kc(n);return!o||n.length<=o.length?!1:e.sources.some(r=>{let s=r.matchCommand?.(o);return!!s&&this.isInlineCommand(s)})}matchInlineCommand(e){for(let n of this.channels){if(!n.trigger)continue;let o=n.position==="anywhere"?[e]:n.position==="line-start"?e.split(`
170
170
  `):[e.split(`
171
- `)[0]];for(let r of o){if(!r.startsWith(n.trigger))continue;let{name:s,args:i}=Ca(r.slice(n.trigger.length));if(s)for(let l of n.sources){let p=l.matchCommand?.(s);if(p&&this.isInlineCommand(p))return{source:l,item:p,args:i}}}}return null}async dispatchInlineCommand(e){let n=this.matchInlineCommand(e);if(!n)return null;let{source:o,item:r,args:s}=n,i=r.command??"prompt";if(this.opts.emit?.("command",{sourceId:o.id,itemId:r.id,kind:i,args:s}),i==="action")return this.runAction(r,s),{kind:"action"};if(i==="prompt"){let p;try{p=await o.resolve(r,this.resolveContext(s,e))}catch(c){return typeof console<"u"&&console.warn("[Persona] inline prompt command resolve failed",c),null}return{kind:"prompt",sendText:p.insertText??p.llmAppend??e}}return{kind:"server",mentions:{refs:[],finalize:async()=>{let p=await o.resolve(r,this.resolveContext(s,e)),c={};return p.context&&(c[o.id]={[r.id]:p.context}),{blocks:[],contentParts:p.contentParts??[],context:c}}}}}resolveContext(e,n){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:n,args:e,signal:new AbortController().signal}}runAction(e,n){if(e.action)try{Promise.resolve(e.action({args:n,config:this.opts.getConfig(),messages:this.opts.getMessages(),composer:this.input})).catch(o=>{typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)})}catch(o){typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)}}captureStripTarget(){return this.triggerMatch?{value:this.input.getValue(),start:this.triggerMatch.triggerIndex,end:this.input.getSelection().start}:null}async runPromptMacro(e,n,o,r){let s=this.input,i;try{i=await e.resolve(n,{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:s.getValue(),args:o,signal:new AbortController().signal})}catch(p){typeof console<"u"&&console.warn("[Persona] context-mention prompt resolve failed",p);return}let l=i.insertText??i.llmAppend??"";n.insertMode==="insert-at-caret"&&r?s.replaceLogicalRange?(s.replaceLogicalRange(r.start,r.end,l),s.dispatchInput()):s.setValue(r.value.slice(0,r.start)+l+r.value.slice(r.end)):s.setValue(l),n.submitOnSelect&&s.submit()}stripQuery(){if(!this.triggerMatch)return;let e=this.input.getSelection().start;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(this.triggerMatch.triggerIndex,e,"");else{let n=Eg(this.input.getValue(),this.triggerMatch,e);this.input.setValueWithCaret(n.value,n.caret)}this.input.dispatchInput(),this.triggerMatch=null}destroy(){this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.popover?.destroy(),this.menu.destroy();let e=this.input.element;e.removeAttribute("aria-haspopup"),e.removeAttribute("aria-controls"),e.removeAttribute("aria-activedescendant")}}});function Pc(t){t&&(typeof t.requestSubmit=="function"?t.requestSubmit():t.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function Vg(t){let e=()=>{t.dispatchEvent(new Event("input",{bubbles:!0}))};return{element:t,getValue:()=>t.value,getLogicalText:()=>t.value,getSelection:()=>({start:t.selectionStart??0,end:t.selectionEnd??0}),setSelection:(n,o=n)=>{t.setSelectionRange(n,o)},setValueWithCaret:(n,o)=>{t.value=n,t.setSelectionRange(o,o)},setValue:n=>{t.value=n,t.setSelectionRange(n.length,n.length),e(),t.focus()},submit:()=>Pc(t.form),dispatchInput:e,focus:()=>t.focus()}}var Ic=ht(()=>{"use strict"});function Rc(t,e){let n=document.createElement("div");n.className="persona-sr-only",n.setAttribute("aria-live",t),n.setAttribute("aria-atomic","true"),n.setAttribute("role",t==="assertive"?"alert":"status"),n.setAttribute("data-persona-mention-live-region","");let o=e.getRootNode();typeof ShadowRoot<"u"&&o instanceof ShadowRoot?(Object.assign(n.style,iv),document.body.appendChild(n)):e.appendChild(n);let s;return{announce:i=>{s!==void 0&&clearTimeout(s),n.textContent="",s=setTimeout(()=>{s=void 0,n.textContent=i},0)},destroy:()=>{s!==void 0&&clearTimeout(s),n.remove()}}}var iv,qg=ht(()=>{"use strict";iv={position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}});function Kg(t){let e=t.composerInput??Vg(t.textarea),n=Rc("polite",t.liveRegionHost),o=Rc("assertive",t.liveRegionHost),r=c=>n.announce(c),s=c=>o.announce(c),i=new va({mentionConfig:t.mentionConfig,contextRow:t.contextRow,getMessages:t.getMessages,getConfig:t.getConfig,getComposerText:()=>e.getValue(),announce:r,announceError:s,emit:t.emit}),l=()=>new Aa({mentionConfig:t.mentionConfig,composerInput:e,anchor:t.anchor,getMessages:t.getMessages,getConfig:t.getConfig,onSelect:(c,d,g)=>i.add(c,d,g),onInsertMention:(c,d,g,b)=>i.track(c,d,g,b,f=>e.setMentionStatus?.(c,f)),admitMention:(c,d)=>i.admit(c,d),announce:r,popoverContainer:t.popoverContainer,onPickerOpenChange:t.onPickerOpenChange,emit:t.emit}),p=l();return{openMenu:c=>p.openFromButton(c),isMenuOpen:()=>p.isOpen(),handleInput:()=>p.onInput(),handleKeydown:c=>p.handleKeydown(c),hasMentions:()=>i.hasMentions(),removeLastChip:()=>i.removeLast(),dispatchInlineCommand:c=>p.dispatchInlineCommand(c),collectForSubmit:()=>i.hasMentions()?i.collectForSubmit():null,untrackMention:c=>i.remove(c),rebindComposer:c=>{c!==e&&(p.destroy(),e=c,p=l())},clear:()=>i.clear(),destroy:()=>{p.destroy(),i.clear(),n.destroy(),o.destroy()}}}var Gg=ht(()=>{"use strict";kc();jg();Ic();qg()});var Qg={};Tr(Qg,{mountContextMentions:()=>Kg});var Xg=ht(()=>{"use strict";Gg()});function Bc(t){return t.kind==="text"?t.value.length:1}function Dc(t){let e=[],n=r=>{let s=e[e.length-1];s&&s.kind==="text"?s.value+=r:e.push({kind:"text",value:r})};(t.length===0||t[0].kind!=="text")&&e.push({kind:"text",value:""});for(let r of t){if(r.kind==="text"){n(r.value);continue}let s=e[e.length-1];(!s||s.kind!=="text")&&e.push({kind:"text",value:""}),e.push({kind:"mention",id:r.id,ref:r.ref}),e.push({kind:"text",value:""})}let o=e[e.length-1];return(!o||o.kind!=="text")&&e.push({kind:"text",value:""}),e}function Yg(){return{blocks:[{kind:"text",value:""}]}}function Oc(t){return{blocks:[{kind:"text",value:t}]}}function Nc(t){return t.blocks.map(e=>e.kind==="text"?e.value:`${lv}${e.ref.label}`).join("")}function Ma(t){return t.blocks.map(e=>e.kind==="text"?e.value:"\uFFFC").join("")}function Ta(t){return t.blocks.reduce((e,n)=>e+Bc(n),0)}function cv(t){let e=[];for(let n of t.blocks)n.kind==="mention"&&e.push({id:n.id,ref:n.ref});return e}function Sa(t,e){let n=[],o=[],r=0;for(let s of t){let i=Bc(s),l=r+i;if(l<=e)n.push(s);else if(r>=e)o.push(s);else if(s.kind==="text"){let p=e-r;p>0&&n.push({kind:"text",value:s.value.slice(0,p)}),p<i&&o.push({kind:"text",value:s.value.slice(p)})}else o.push(s);r=l}return{left:n,right:o}}function Fc(t,e,n,o){let r=Sa(t.blocks,e.start).left,s=Sa(t.blocks,e.end).right,i=s[0],l=i?.kind==="text"?i.value.charAt(0):"",p=l!==" "&&l!==" "&&l!==`
172
- `,c=Dc([...r,{kind:"mention",id:o,ref:n},...p?[{kind:"text",value:" "}]:[],...s]),d=e.start+1+(l===`
173
- `?0:1);return{doc:{blocks:c},caret:d}}function Jg(t,e){let n=0,o=0,r=!1;for(let i of t.blocks)i.kind==="mention"&&i.id===e&&(n=o,r=!0),o+=Bc(i);return r?{doc:{blocks:Dc(t.blocks.filter(i=>!(i.kind==="mention"&&i.id===e)))},caret:n}:{doc:t,caret:o}}function Ea(t,e,n,o){let r=Ta(t),s=Math.max(0,Math.min(e,n,r)),i=Math.min(r,Math.max(e,n,0)),l=Sa(t.blocks,s).left,p=Sa(t.blocks,i).right;return{doc:{blocks:Dc([...l,{kind:"text",value:o},...p])},caret:s+o.length}}function Zg(t){let e=[];for(let n of t.blocks)n.kind==="text"?n.value.length>0&&e.push({kind:"text",text:n.value}):e.push({kind:"mention",ref:n.ref});return{content:Nc(t),contextMentions:cv(t).map(n=>n.ref),contentSegments:e}}var lv,_c=ht(()=>{"use strict";ma();lv="@"});function qs(t){return t.nodeType===1&&t.hasAttribute(Vs)}function nf(t){return t.nodeType===1&&t.tagName==="BR"}function ka(t){return t.nodeType===3?t.data.length:qs(t)||nf(t)?1:t.textContent?.length??0}function ef(t,e,n){let o=0;for(let r of Array.from(t.childNodes)){if(r===e)return r.nodeType===3?o+n:o+(n>0?ka(r):0);if(r.contains(e))return qs(r)?o+1:o+pv(r,e,n);o+=ka(r)}if(e===t){let r=0,s=Array.from(t.childNodes);for(let i=0;i<Math.min(n,s.length);i++)r+=ka(s[i]);return r}return o}function pv(t,e,n){let o=0,r=s=>{if(s===e)return o+=s.nodeType===3?n:0,!0;if(s.nodeType===3)return o+=s.data.length,!1;for(let i of Array.from(s.childNodes))if(r(i))return!0;return!1};return r(t),o}function js(t,e){let n=0,o=Array.from(t.childNodes);for(let r=0;r<o.length;r++){let s=o[r],i=ka(s);if(e<=n+i)return s.nodeType===3?{node:s,offset:e-n}:{node:t,offset:e<=n?r:r+1};n+=i}return{node:t,offset:o.length}}function uv(t,e){let n=[];for(let o of Array.from(t.childNodes))if(qs(o)){let r=o.getAttribute(Vs),s=e.get(r);s&&n.push({kind:"mention",id:r,ref:s})}else if(nf(o))n.push({kind:"text",value:tf});else if(o.nodeType===3)n.push({kind:"text",value:o.data});else{let r=o.textContent??"";r&&n.push({kind:"text",value:r})}return n.length===0&&n.push({kind:"text",value:""}),{blocks:n}}function of(t){let e=t.renderToken,n=new Map,o=t.element??document.createElement("div");o.setAttribute("contenteditable","true"),o.setAttribute("data-persona-composer-input",""),o.setAttribute("role","textbox"),o.setAttribute("aria-multiline","true"),o.classList.add("persona-composer-contenteditable"),t.placeholder!=null&&o.setAttribute("data-placeholder",t.placeholder);let r=!1,s=0,i=()=>uv(o,n),l=F=>{o.replaceChildren();for(let B of F.blocks)if(B.kind==="text")B.value.length>0&&o.appendChild(document.createTextNode(B.value));else{n.set(B.id,B.ref);let H=e(B.ref);H.setAttribute("contenteditable","false"),H.setAttribute(Vs,B.id),o.appendChild(H)}},p=()=>{let B=o.getRootNode().activeElement;return B===o||B!=null&&o.contains(B)},c=(F,B)=>{if(s=F,!B?.focus&&!p())return;let H=typeof window<"u"?window.getSelection():null;if(!H)return;let w=js(o,F);try{let N=document.createRange();N.setStart(w.node,w.offset),N.collapse(!0),H.removeAllRanges(),H.addRange(N)}catch{}},d=()=>{o.dispatchEvent(new Event("input",{bubbles:!0}))},g=()=>{let F={start:s,end:s},B=typeof window<"u"?window.getSelection():null;if(!B||B.rangeCount===0)return F;let H=B.getRangeAt(0);if(!o.contains(H.startContainer))return F;let w=ef(o,H.startContainer,H.startOffset),N=H.collapsed?w:ef(o,H.endContainer,H.endOffset);return{start:Math.min(w,N),end:Math.max(w,N)}},b=()=>{let F=new Set;for(let B of Array.from(o.childNodes))qs(B)&&F.add(B.getAttribute(Vs));for(let B of Array.from(n.keys()))F.has(B)||(n.delete(B),t.onMentionRemoved?.(B))},f=()=>{r||n.size!==0&&b()},y=()=>{r=!0},C=()=>{r=!1,b()},M=F=>{F.preventDefault();let B=F.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,B);else{let{start:H,end:w}=g(),N=Ea(i(),H,w,B);l(N.doc),c(N.caret,{focus:!0}),b()}d()},I=F=>{if(r)return;let B=F.inputType;if(B==="insertParagraph"){F.preventDefault();let{start:oe,end:Y}=g(),pe=Ea(i(),oe,Y,tf);l(pe.doc),c(pe.caret,{focus:!0}),n.size>0&&b(),d();return}if(B!=="deleteContentBackward"&&B!=="deleteContentForward"||n.size===0)return;let{start:H,end:w}=g();if(H!==w)return;let N=i(),K=Ma(N),te=B==="deleteContentBackward"?H-1:H;if(te<0||te>=K.length||K[te]!=="\uFFFC")return;let Q=0,se=null;for(let oe of N.blocks){let Y=oe.kind==="text"?oe.value.length:1;if(oe.kind==="mention"&&te>=Q&&te<Q+Y){se=oe.id;break}Q+=Y}if(!se)return;F.preventDefault();let J=Jg(N,se);l(J.doc),c(J.caret,{focus:!0}),b(),d()},S=(F,B)=>{l(Oc(F)),c(B)},E=(F,B)=>{if(!Number.isFinite(F)||!Number.isFinite(B)||B<=F)return null;try{let H=js(o,F),w=js(o,B),N=document.createRange();N.setStart(H.node,H.offset),N.setEnd(w.node,w.offset);let K=N.getBoundingClientRect();return K.width===0&&K.height===0?null:K}catch{return null}},L=(F,B,H)=>{let w=Ea(i(),F,B,H);l(w.doc),c(w.caret,{focus:!0})},D=(F,B)=>{let H=i(),w=Ma(H),N=B.triggerIndex,K=B.triggerIndex+1+B.query.length;if(N<0||K>w.length||w.slice(N+1,K)!==B.query)return null;let te=t.generateId(),Q=Fc(H,{start:N,end:K},F,te);return l(Q.doc),c(Q.caret,{focus:!0}),t.onMentionInserted?.(te,F),d(),te},z=F=>{let B=i(),H=g(),N=typeof window<"u"&&!!window.getSelection()?.rangeCount&&o.contains(window.getSelection().getRangeAt(0).startContainer)?{start:H.start,end:H.end}:{start:Ta(B),end:Ta(B)},K=t.generateId(),te=Fc(B,N,F,K);return l(te.doc),c(te.caret,{focus:!0}),t.onMentionInserted?.(K,F),d(),K},$=(F,B)=>{for(let H of Array.from(o.childNodes))if(qs(H)&&H.getAttribute(Vs)===F){let w=B==="error";if(H.classList.toggle(dv,w),w){H.hasAttribute(Us)||(H.setAttribute(Us,H.getAttribute("aria-label")??""),H.setAttribute($c,H.getAttribute("title")??""));let N=n.get(F)?.label??"";H.setAttribute("title",`${N}: failed to attach context`),H.setAttribute("aria-label",`${N}, failed to attach context`)}else if(H.hasAttribute(Us)){let N=H.getAttribute(Us),K=H.getAttribute($c);N?H.setAttribute("aria-label",N):H.removeAttribute("aria-label"),K?H.setAttribute("title",K):H.removeAttribute("title"),H.removeAttribute(Us),H.removeAttribute($c)}return}};return o.addEventListener("input",f),o.addEventListener("compositionstart",y),o.addEventListener("compositionend",C),o.addEventListener("paste",M),o.addEventListener("beforeinput",I),l(Yg()),{element:o,getValue:()=>Nc(i()),getLogicalText:()=>Ma(i()),getDocument:i,getSelection:g,setSelection:(F,B=F)=>{let H=typeof window<"u"?window.getSelection():null;if(H)try{let w=js(o,F),N=js(o,B),K=document.createRange();K.setStart(w.node,w.offset),K.setEnd(N.node,N.offset),H.removeAllRanges(),H.addRange(K)}catch{}},setValueWithCaret:S,getLogicalRangeRect:E,setValue:F=>{l(Oc(F)),o.focus(),c(F.length,{focus:!0}),d()},replaceLogicalRange:L,insertMentionAtTrigger:D,insertMentionAtSelection:z,setMentionStatus:$,submit:()=>Pc(o.closest("form")),dispatchInput:d,focus:()=>o.focus(),destroy:()=>{o.removeEventListener("input",f),o.removeEventListener("compositionstart",y),o.removeEventListener("compositionend",C),o.removeEventListener("paste",M),o.removeEventListener("beforeinput",I)}}}var dv,Vs,Us,$c,tf,rf=ht(()=>{"use strict";_c();Ic();dv="persona-mention-token-error",Vs="data-mention-id",Us="data-mention-prev-label",$c="data-mention-prev-title",tf=`
174
- `});function mv(t,e){e.className=`${t.className} persona-composer-contenteditable`.trim();for(let r=0;r<t.style.length;r++){let s=t.style.item(r);s!=="height"&&e.style.setProperty(s,t.style.getPropertyValue(s),t.style.getPropertyPriority(s))}let n=t.getAttribute("placeholder");n&&(e.setAttribute("data-placeholder",n),e.setAttribute("aria-placeholder",n));let o=t.getAttribute("aria-label")??n;o&&e.setAttribute("aria-label",o)}function hv(t,e,n){Object.defineProperty(t,"value",{configurable:!0,get:()=>e.getValue(),set:o=>{e.setValueWithCaret(o,o.length),e.dispatchInput()}}),Object.defineProperty(t,"placeholder",{configurable:!0,get:()=>t.getAttribute("data-placeholder")??"",set:o=>{o?(t.setAttribute("data-placeholder",o),t.setAttribute("aria-placeholder",o),n||t.setAttribute("aria-label",o)):(t.removeAttribute("data-placeholder"),t.removeAttribute("aria-placeholder"),n||t.removeAttribute("aria-label"))}}),Object.defineProperty(t,"selectionStart",{configurable:!0,get:()=>e.getSelection().start}),Object.defineProperty(t,"selectionEnd",{configurable:!0,get:()=>e.getSelection().end}),t.setSelectionRange=(o,r)=>e.setSelection(o??0,r??o??0)}function sf(t){let{textarea:e}=t,n={generateId:fv,renderToken:t.renderToken,onMentionRemoved:t.onMentionRemoved,placeholder:e.getAttribute("placeholder")??void 0},o=of(n),r=o.element,s=e.getAttribute("aria-label")!=null;mv(e,r),hv(r,o,s),r.getInlineMessageFields=()=>Zg(o.getDocument?.()??{blocks:[]});let i=e.selectionStart??e.value.length;return o.setValueWithCaret(e.value,i),{input:o,element:r,destroy:o.destroy}}var gv,fv,af=ht(()=>{"use strict";rf();_c();gv=0,fv=()=>`pmention-${++gv}`});var lf={};Tr(lf,{mountInlineComposer:()=>sf});var cf=ht(()=>{"use strict";af()});var FC={};Tr(FC,{createThemePreview:()=>bh});module.exports=Tb(FC);var Er=t=>{let{fallbackImport:e,resetOnSetLoader:n=!1}=t,o=null,r=null,s=null;return{setLoader:d=>{o=d,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??e)().then(g=>(r=g,g)).catch(g=>{throw s=null,g}),s),provide:d=>{r=d},getSync:()=>r}};var{setLoader:qC,load:Eb,provide:KC,getSync:rc}=Er({fallbackImport:()=>Promise.resolve().then(()=>(Cu(),wu))}),Ki=new Set,kb=()=>{let t=[...Ki];Ki.clear();for(let e of t)try{e()}catch{}};var Lb=()=>{let t=rc();return t?Promise.resolve(t):Eb().then(e=>(kb(),e))},Gi=t=>rc()?()=>{}:(Ki.add(t),Lb().catch(()=>{}),()=>{Ki.delete(t)});var Jn=rc;var Pb=t=>{if(t)return t},sc=t=>{let e=null;return n=>{let o=Jn();if(!o)return vo(n);if(!e){let{Marked:r}=o,s=t?.markedOptions;e=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let i=Pb(t?.renderer);i&&e.use({renderer:i})}return e.parse(n)}},Qi=t=>t?sc({markedOptions:t.options,renderer:t.renderer}):sc(),XC=sc();var vo=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var Ib={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"]},Rb=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Wb=()=>{let t=null;return e=>{let n=Jn();if(!n)return vo(e);if(!t){let{DOMPurify:o}=n;t=o(typeof window<"u"?window:void 0),t.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let i=s.attrValue;i.toLowerCase().startsWith("data:")&&!Rb.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,Ib)}},Xi=t=>t===!1?null:typeof t=="function"?t:Wb();var Au=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Su=t=>t.includes("|"),Mu=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},Hb=t=>`| ${t.join(" | ")} |`,Bb=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,Db=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),Tu=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
175
- `),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!Su(r)||Au.test(r)||!Au.test(s))continue;let i=Mu(r).length;if(i<1)continue;let l=Bb(i);e[o+1]!==l&&(e[o+1]=l,n=!0);let p=o+2;for(;p<e.length;p++){let c=e[p];if(c.trim()===""||!Su(c))break;let d=Hb(Db(Mu(c),i));e[p]!==d&&(e[p]=d,n=!0)}o=p-1}return n?e.join(`
176
- `):t};var Eu="var(--persona-md-table-scroll-fade, 24px)",ku=new WeakSet;function Pu(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function Lu(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,r=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":Eu),t.style.setProperty("--persona-fade-r",r<=1?"0px":Eu)}function ic(t){ku.has(t)||(ku.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&Lu(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(Lu)}var Zn="webmcp:",ac=new Map,Iu=t=>{ac.clear();for(let e of t){let n=e.title?.trim();n&&ac.set(e.name,n)}},ks=t=>ac.get(Bu(t)),Yi={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},Ru=null;function Hu(t){if(t.length===0)return"0:empty";let e=t.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${t.length}:${Ob(e.join(""))}`}function Wu(t,e){let n=3735928559^e,o=1103547991^e;for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function Ob(t){let e=Wu(t,0).toString(36),n=Wu(t,2654435761).toString(36);return`${e}.${n}`}var Ji=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=e.onConfirm??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 n;try{n=await e.getTools()}catch(r){return Yi.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}Iu(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},i=Fb(r.inputSchema);return i&&(s.parametersSchema=i),s})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Hn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let y=typeof document<"u"&&!!document.modelContext;return Hn(y?"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=Bu(e),i;try{i=await r.getTools()}catch(y){let C=y instanceof Error?y.message:String(y);return Hn(`Failed to read WebMCP registry: ${C}`)}Iu(i);let l=i.find(y=>y.name===s);if(!l)return Hn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Hn(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Hn("Aborted by cancel()");let p=ks(s),c={toolName:s,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(c))return Hn("User declined the tool call.");if(o?.aborted)return Hn("Aborted by cancel()");let d=new AbortController,g=!1,b=setTimeout(()=>{g=!0,d.abort()},this.timeoutMs),f=()=>d.abort();o&&(o.aborted?d.abort():o.addEventListener("abort",f,{once:!0}));try{let y=await r.executeTool(l,Ub(n),{signal:d.signal});return _b(y)}catch(y){if(g)return Hn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Hn("Aborted by cancel()");let C=y instanceof Error?y.message:String(y);return Hn(C)}finally{clearTimeout(b),o&&o.removeEventListener("abort",f)}}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}(Ru?await Ru():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Yi.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let n=e;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Yi.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){let n=this.confirmHandler??$b;try{return await n(e)}catch(o){return Yi.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>Nb(e,o))}},Bu=t=>t.startsWith(Zn)?t.slice(Zn.length):t,kr=t=>t.startsWith(Zn),Nb=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},Fb=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},_b=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:jb(e)}]}},Hn=t=>({isError:!0,content:[{type:"text",text:t}]}),$b=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=zb(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
171
+ `)[0]];for(let r of o){if(!r.startsWith(n.trigger))continue;let{name:s,args:a}=kc(r.slice(n.trigger.length));if(s)for(let l of n.sources){let d=l.matchCommand?.(s);if(d&&this.isInlineCommand(d))return{source:l,item:d,args:a}}}}return null}async dispatchInlineCommand(e){let n=this.matchInlineCommand(e);if(!n)return null;let{source:o,item:r,args:s}=n,a=r.command??"prompt";if(this.opts.emit?.("command",{sourceId:o.id,itemId:r.id,kind:a,args:s}),a==="action")return this.runAction(r,s),{kind:"action"};if(a==="prompt"){let d;try{d=await o.resolve(r,this.resolveContext(s,e))}catch(p){return typeof console<"u"&&console.warn("[Persona] inline prompt command resolve failed",p),null}return{kind:"prompt",sendText:d.insertText??d.llmAppend??e}}return{kind:"server",mentions:{refs:[],finalize:async()=>{let d=await o.resolve(r,this.resolveContext(s,e)),p={};return d.context&&(p[o.id]={[r.id]:d.context}),{blocks:[],contentParts:d.contentParts??[],context:p}}}}}resolveContext(e,n){return{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:n,args:e,signal:new AbortController().signal}}runAction(e,n){if(e.action)try{Promise.resolve(e.action({args:n,config:this.opts.getConfig(),messages:this.opts.getMessages(),composer:this.input})).catch(o=>{typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)})}catch(o){typeof console<"u"&&console.warn("[Persona] context-mention command action failed",o)}}captureStripTarget(){return this.triggerMatch?{value:this.input.getValue(),start:this.triggerMatch.triggerIndex,end:this.input.getSelection().start}:null}async runPromptMacro(e,n,o,r){let s=this.input,a;try{a=await e.resolve(n,{messages:this.opts.getMessages(),config:this.opts.getConfig(),composerText:s.getValue(),args:o,signal:new AbortController().signal})}catch(d){typeof console<"u"&&console.warn("[Persona] context-mention prompt resolve failed",d);return}let l=a.insertText??a.llmAppend??"";n.insertMode==="insert-at-caret"&&r?s.replaceLogicalRange?(s.replaceLogicalRange(r.start,r.end,l),s.dispatchInput()):s.setValue(r.value.slice(0,r.start)+l+r.value.slice(r.end)):s.setValue(l),n.submitOnSelect&&s.submit()}stripQuery(){if(!this.triggerMatch)return;let e=this.input.getSelection().start;if(this.input.replaceLogicalRange)this.input.replaceLogicalRange(this.triggerMatch.triggerIndex,e,"");else{let n=Py(this.input.getValue(),this.triggerMatch,e);this.input.setValueWithCaret(n.value,n.caret)}this.input.dispatchInput(),this.triggerMatch=null}destroy(){this.disconnectComposerResize(),this.debounceTimer&&clearTimeout(this.debounceTimer),this.searchAbort?.abort(),this.popover?.destroy(),this.menu.destroy();let e=this.input.element;e.removeAttribute("aria-haspopup"),e.removeAttribute("aria-controls"),e.removeAttribute("aria-activedescendant")}}});function bu(t){t&&(typeof t.requestSubmit=="function"?t.requestSubmit():t.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function Qy(t){let e=()=>{t.dispatchEvent(new Event("input",{bubbles:!0}))};return{element:t,getValue:()=>t.value,getLogicalText:()=>t.value,getSelection:()=>({start:t.selectionStart??0,end:t.selectionEnd??0}),setSelection:(n,o=n)=>{t.setSelectionRange(n,o)},setValueWithCaret:(n,o)=>{t.value=n,t.setSelectionRange(o,o)},setValue:n=>{t.value=n,t.setSelectionRange(n.length,n.length),e(),t.focus()},submit:()=>bu(t.form),dispatchInput:e,focus:()=>t.focus()}}var vu=Ge(()=>{"use strict"});function wu(t,e){let n=document.createElement("div");n.className="persona-sr-only",n.setAttribute("aria-live",t),n.setAttribute("aria-atomic","true"),n.setAttribute("role",t==="assertive"?"alert":"status"),n.setAttribute("data-persona-mention-live-region","");let o=e.getRootNode();typeof ShadowRoot<"u"&&o instanceof ShadowRoot?(Object.assign(n.style,IA),document.body.appendChild(n)):e.appendChild(n);let s;return{announce:a=>{s!==void 0&&clearTimeout(s),n.textContent="",s=setTimeout(()=>{s=void 0,n.textContent=a},0)},destroy:()=>{s!==void 0&&clearTimeout(s),n.remove()}}}var IA,Jy=Ge(()=>{"use strict";IA={position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}});function Zy(t){let e=t.composerInput??Qy(t.textarea),n=wu("polite",t.liveRegionHost),o=wu("assertive",t.liveRegionHost),r=p=>n.announce(p),s=p=>o.announce(p),a=new xc({mentionConfig:t.mentionConfig,contextRow:t.contextRow,getMessages:t.getMessages,getConfig:t.getConfig,getComposerText:()=>e.getValue(),announce:r,announceError:s,emit:t.emit}),l=()=>new Pc({mentionConfig:t.mentionConfig,composerInput:e,anchor:t.anchor,getMessages:t.getMessages,getConfig:t.getConfig,onSelect:(p,u,g)=>a.add(p,u,g),onInsertMention:(p,u,g,b)=>a.track(p,u,g,b,m=>e.setMentionStatus?.(p,m)),admitMention:(p,u)=>a.admit(p,u),announce:r,popoverContainer:t.popoverContainer,onPickerOpenChange:t.onPickerOpenChange,emit:t.emit}),d=l();return{openMenu:p=>d.openFromButton(p),isMenuOpen:()=>d.isOpen(),handleInput:()=>d.onInput(),handleKeydown:p=>d.handleKeydown(p),hasMentions:()=>a.hasMentions(),removeLastChip:()=>a.removeLast(),dispatchInlineCommand:p=>d.dispatchInlineCommand(p),collectForSubmit:()=>a.hasMentions()?a.collectForSubmit():null,untrackMention:p=>a.remove(p),rebindComposer:p=>{p!==e&&(d.destroy(),e=p,d=l())},clear:()=>a.clear(),destroy:()=>{d.destroy(),a.clear(),n.destroy(),o.destroy()}}}var eb=Ge(()=>{"use strict";yu();Xy();vu();Jy()});var tb={};lr(tb,{mountContextMentions:()=>Zy});var nb=Ge(()=>{"use strict";eb()});function Su(t){return t.kind==="text"?t.value.length:1}function Au(t){let e=[],n=r=>{let s=e[e.length-1];s&&s.kind==="text"?s.value+=r:e.push({kind:"text",value:r})};(t.length===0||t[0].kind!=="text")&&e.push({kind:"text",value:""});for(let r of t){if(r.kind==="text"){n(r.value);continue}let s=e[e.length-1];(!s||s.kind!=="text")&&e.push({kind:"text",value:""}),e.push({kind:"mention",id:r.id,ref:r.ref}),e.push({kind:"text",value:""})}let o=e[e.length-1];return(!o||o.kind!=="text")&&e.push({kind:"text",value:""}),e}function ob(){return{blocks:[{kind:"text",value:""}]}}function Mu(t){return{blocks:[{kind:"text",value:t}]}}function Tu(t){return t.blocks.map(e=>e.kind==="text"?e.value:`${RA}${e.ref.label}`).join("")}function Ic(t){return t.blocks.map(e=>e.kind==="text"?e.value:"\uFFFC").join("")}function Hc(t){return t.blocks.reduce((e,n)=>e+Su(n),0)}function WA(t){let e=[];for(let n of t.blocks)n.kind==="mention"&&e.push({id:n.id,ref:n.ref});return e}function Lc(t,e){let n=[],o=[],r=0;for(let s of t){let a=Su(s),l=r+a;if(l<=e)n.push(s);else if(r>=e)o.push(s);else if(s.kind==="text"){let d=e-r;d>0&&n.push({kind:"text",value:s.value.slice(0,d)}),d<a&&o.push({kind:"text",value:s.value.slice(d)})}else o.push(s);r=l}return{left:n,right:o}}function Eu(t,e,n,o){let r=Lc(t.blocks,e.start).left,s=Lc(t.blocks,e.end).right,a=s[0],l=a?.kind==="text"?a.value.charAt(0):"",d=l!==" "&&l!==" "&&l!==`
172
+ `,p=Au([...r,{kind:"mention",id:o,ref:n},...d?[{kind:"text",value:" "}]:[],...s]),u=e.start+1+(l===`
173
+ `?0:1);return{doc:{blocks:p},caret:u}}function rb(t,e){let n=0,o=0,r=!1;for(let a of t.blocks)a.kind==="mention"&&a.id===e&&(n=o,r=!0),o+=Su(a);return r?{doc:{blocks:Au(t.blocks.filter(a=>!(a.kind==="mention"&&a.id===e)))},caret:n}:{doc:t,caret:o}}function Rc(t,e,n,o){let r=Hc(t),s=Math.max(0,Math.min(e,n,r)),a=Math.min(r,Math.max(e,n,0)),l=Lc(t.blocks,s).left,d=Lc(t.blocks,a).right;return{doc:{blocks:Au([...l,{kind:"text",value:o},...d])},caret:s+o.length}}function sb(t){let e=[];for(let n of t.blocks)n.kind==="text"?n.value.length>0&&e.push({kind:"text",text:n.value}):e.push({kind:"mention",ref:n.ref});return{content:Tu(t),contextMentions:WA(t).map(n=>n.ref),contentSegments:e}}var RA,ku=Ge(()=>{"use strict";bc();RA="@"});function va(t){return t.nodeType===1&&t.hasAttribute(ba)}function lb(t){return t.nodeType===1&&t.tagName==="BR"}function Wc(t){return t.nodeType===3?t.data.length:va(t)||lb(t)?1:t.textContent?.length??0}function ib(t,e,n){let o=0;for(let r of Array.from(t.childNodes)){if(r===e)return r.nodeType===3?o+n:o+(n>0?Wc(r):0);if(r.contains(e))return va(r)?o+1:o+DA(r,e,n);o+=Wc(r)}if(e===t){let r=0,s=Array.from(t.childNodes);for(let a=0;a<Math.min(n,s.length);a++)r+=Wc(s[a]);return r}return o}function DA(t,e,n){let o=0,r=s=>{if(s===e)return o+=s.nodeType===3?n:0,!0;if(s.nodeType===3)return o+=s.data.length,!1;for(let a of Array.from(s.childNodes))if(r(a))return!0;return!1};return r(t),o}function ya(t,e){let n=0,o=Array.from(t.childNodes);for(let r=0;r<o.length;r++){let s=o[r],a=Wc(s);if(e<=n+a)return s.nodeType===3?{node:s,offset:e-n}:{node:t,offset:e<=n?r:r+1};n+=a}return{node:t,offset:o.length}}function NA(t,e){let n=[];for(let o of Array.from(t.childNodes))if(va(o)){let r=o.getAttribute(ba),s=e.get(r);s&&n.push({kind:"mention",id:r,ref:s})}else if(lb(o))n.push({kind:"text",value:ab});else if(o.nodeType===3)n.push({kind:"text",value:o.data});else{let r=o.textContent??"";r&&n.push({kind:"text",value:r})}return n.length===0&&n.push({kind:"text",value:""}),{blocks:n}}function cb(t){let e=t.renderToken,n=new Map,o=t.element??document.createElement("div");o.setAttribute("contenteditable","true"),o.setAttribute("data-persona-composer-input",""),o.setAttribute("role","textbox"),o.setAttribute("aria-multiline","true"),o.classList.add("persona-composer-contenteditable"),t.placeholder!=null&&o.setAttribute("data-placeholder",t.placeholder);let r=!1,s=0,a=()=>NA(o,n),l=N=>{o.replaceChildren();for(let _ of N.blocks)if(_.kind==="text")_.value.length>0&&o.appendChild(document.createTextNode(_.value));else{n.set(_.id,_.ref);let F=e(_.ref);F.setAttribute("contenteditable","false"),F.setAttribute(ba,_.id),o.appendChild(F)}},d=()=>{let _=o.getRootNode().activeElement;return _===o||_!=null&&o.contains(_)},p=(N,_)=>{if(s=N,!_?.focus&&!d())return;let F=typeof window<"u"?window.getSelection():null;if(!F)return;let P=ya(o,N);try{let V=document.createRange();V.setStart(P.node,P.offset),V.collapse(!0),F.removeAllRanges(),F.addRange(V)}catch{}},u=()=>{o.dispatchEvent(new Event("input",{bubbles:!0}))},g=()=>{let N={start:s,end:s},_=typeof window<"u"?window.getSelection():null;if(!_||_.rangeCount===0)return N;let F=_.getRangeAt(0);if(!o.contains(F.startContainer))return N;let P=ib(o,F.startContainer,F.startOffset),V=F.collapsed?P:ib(o,F.endContainer,F.endOffset);return{start:Math.min(P,V),end:Math.max(P,V)}},b=()=>{let N=new Set;for(let _ of Array.from(o.childNodes))va(_)&&N.add(_.getAttribute(ba));for(let _ of Array.from(n.keys()))N.has(_)||(n.delete(_),t.onMentionRemoved?.(_))},m=()=>{r||n.size!==0&&b()},y=()=>{r=!0},w=()=>{r=!1,b()},T=N=>{N.preventDefault();let _=N.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,_);else{let{start:F,end:P}=g(),V=Rc(a(),F,P,_);l(V.doc),p(V.caret,{focus:!0}),b()}u()},W=N=>{if(r)return;let _=N.inputType;if(_==="insertParagraph"){N.preventDefault();let{start:oe,end:ee}=g(),M=Rc(a(),oe,ee,ab);l(M.doc),p(M.caret,{focus:!0}),n.size>0&&b(),u();return}if(_!=="deleteContentBackward"&&_!=="deleteContentForward"||n.size===0)return;let{start:F,end:P}=g();if(F!==P)return;let V=a(),se=Ic(V),ve=_==="deleteContentBackward"?F-1:F;if(ve<0||ve>=se.length||se[ve]!=="\uFFFC")return;let he=0,ge=null;for(let oe of V.blocks){let ee=oe.kind==="text"?oe.value.length:1;if(oe.kind==="mention"&&ve>=he&&ve<he+ee){ge=oe.id;break}he+=ee}if(!ge)return;N.preventDefault();let re=rb(V,ge);l(re.doc),p(re.caret,{focus:!0}),b(),u()},E=(N,_)=>{l(Mu(N)),p(_)},k=(N,_)=>{if(!Number.isFinite(N)||!Number.isFinite(_)||_<=N)return null;try{let F=ya(o,N),P=ya(o,_),V=document.createRange();V.setStart(F.node,F.offset),V.setEnd(P.node,P.offset);let se=V.getBoundingClientRect();return se.width===0&&se.height===0?null:se}catch{return null}},A=(N,_,F)=>{let P=Rc(a(),N,_,F);l(P.doc),p(P.caret,{focus:!0})},D=(N,_)=>{let F=a(),P=Ic(F),V=_.triggerIndex,se=_.triggerIndex+1+_.query.length;if(V<0||se>P.length||P.slice(V+1,se)!==_.query)return null;let ve=t.generateId(),he=Eu(F,{start:V,end:se},N,ve);return l(he.doc),p(he.caret,{focus:!0}),t.onMentionInserted?.(ve,N),u(),ve},B=N=>{let _=a(),F=g(),V=typeof window<"u"&&!!window.getSelection()?.rangeCount&&o.contains(window.getSelection().getRangeAt(0).startContainer)?{start:F.start,end:F.end}:{start:Hc(_),end:Hc(_)},se=t.generateId(),ve=Eu(_,V,N,se);return l(ve.doc),p(ve.caret,{focus:!0}),t.onMentionInserted?.(se,N),u(),se},I=(N,_)=>{for(let F of Array.from(o.childNodes))if(va(F)&&F.getAttribute(ba)===N){let P=_==="error";if(F.classList.toggle(BA,P),P){F.hasAttribute(ha)||(F.setAttribute(ha,F.getAttribute("aria-label")??""),F.setAttribute(Pu,F.getAttribute("title")??""));let V=n.get(N)?.label??"";F.setAttribute("title",`${V}: failed to attach context`),F.setAttribute("aria-label",`${V}, failed to attach context`)}else if(F.hasAttribute(ha)){let V=F.getAttribute(ha),se=F.getAttribute(Pu);V?F.setAttribute("aria-label",V):F.removeAttribute("aria-label"),se?F.setAttribute("title",se):F.removeAttribute("title"),F.removeAttribute(ha),F.removeAttribute(Pu)}return}};return o.addEventListener("input",m),o.addEventListener("compositionstart",y),o.addEventListener("compositionend",w),o.addEventListener("paste",T),o.addEventListener("beforeinput",W),l(ob()),{element:o,getValue:()=>Tu(a()),getLogicalText:()=>Ic(a()),getDocument:a,getSelection:g,setSelection:(N,_=N)=>{let F=typeof window<"u"?window.getSelection():null;if(F)try{let P=ya(o,N),V=ya(o,_),se=document.createRange();se.setStart(P.node,P.offset),se.setEnd(V.node,V.offset),F.removeAllRanges(),F.addRange(se)}catch{}},setValueWithCaret:E,getLogicalRangeRect:k,setValue:N=>{l(Mu(N)),o.focus(),p(N.length,{focus:!0}),u()},replaceLogicalRange:A,insertMentionAtTrigger:D,insertMentionAtSelection:B,setMentionStatus:I,submit:()=>bu(o.closest("form")),dispatchInput:u,focus:()=>o.focus(),destroy:()=>{o.removeEventListener("input",m),o.removeEventListener("compositionstart",y),o.removeEventListener("compositionend",w),o.removeEventListener("paste",T),o.removeEventListener("beforeinput",W)}}}var BA,ba,ha,Pu,ab,db=Ge(()=>{"use strict";ku();vu();BA="persona-mention-token-error",ba="data-mention-id",ha="data-mention-prev-label",Pu="data-mention-prev-title",ab=`
174
+ `});function FA(t,e){e.className=`${t.className} persona-composer-contenteditable`.trim();for(let r=0;r<t.style.length;r++){let s=t.style.item(r);s!=="height"&&e.style.setProperty(s,t.style.getPropertyValue(s),t.style.getPropertyPriority(s))}let n=t.getAttribute("placeholder");n&&(e.setAttribute("data-placeholder",n),e.setAttribute("aria-placeholder",n));let o=t.getAttribute("aria-label")??n;o&&e.setAttribute("aria-label",o)}function $A(t,e,n){Object.defineProperty(t,"value",{configurable:!0,get:()=>e.getValue(),set:o=>{e.setValueWithCaret(o,o.length),e.dispatchInput()}}),Object.defineProperty(t,"placeholder",{configurable:!0,get:()=>t.getAttribute("data-placeholder")??"",set:o=>{o?(t.setAttribute("data-placeholder",o),t.setAttribute("aria-placeholder",o),n||t.setAttribute("aria-label",o)):(t.removeAttribute("data-placeholder"),t.removeAttribute("aria-placeholder"),n||t.removeAttribute("aria-label"))}}),Object.defineProperty(t,"selectionStart",{configurable:!0,get:()=>e.getSelection().start}),Object.defineProperty(t,"selectionEnd",{configurable:!0,get:()=>e.getSelection().end}),t.setSelectionRange=(o,r)=>e.setSelection(o??0,r??o??0)}function pb(t){let{textarea:e}=t,n={generateId:_A,renderToken:t.renderToken,onMentionRemoved:t.onMentionRemoved,placeholder:e.getAttribute("placeholder")??void 0},o=cb(n),r=o.element,s=e.getAttribute("aria-label")!=null;FA(e,r),$A(r,o,s),r.getInlineMessageFields=()=>sb(o.getDocument?.()??{blocks:[]});let a=e.selectionStart??e.value.length;return o.setValueWithCaret(e.value,a),{input:o,element:r,destroy:o.destroy}}var OA,_A,ub=Ge(()=>{"use strict";db();ku();OA=0,_A=()=>`pmention-${++OA}`});var gb={};lr(gb,{mountInlineComposer:()=>pb});var fb=Ge(()=>{"use strict";ub()});function tv(t){return t.role!=="assistant"||t.variant==="tool"||t.variant==="reasoning"?!1:t.variant==="approval"?!0:!!(t.content?.trim()||t.rawContent?.trim()||t.contentParts?.length)}function Jc(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Mo(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function Go(t,e){return Mo(t)-t.scrollTop<=e}function Zc(t){let{following:e,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:p=!1}=t,u=n-o;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!e&&r&&(!p||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:e&&l&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:e&&d&&!r?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function ed(t){let{following:e,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=t;return e&&n<0?"pause":!e&&r&&n>0&&o?"resume":"none"}function nv(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function Fu(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight+(t.slack??0));return{targetScrollTop:e,spacerHeight:n}}function ov(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var $u=Ge(()=>{"use strict"});function ii(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}function gE(t,e){let n={...cE,...e};if(n[t])return n[t];for(let o of Object.keys(n))if(o.endsWith("_")&&t.startsWith(o))return n[o];return dE}function fE(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function mE(t){let e=new Date(t),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),r=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function hE(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return null;for(let o of e){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function yE(t){return navigator.clipboard?.writeText?navigator.clipboard.writeText(t):new Promise(e=>{let n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),e()})}function bE(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function vE(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function wE(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function CE(t,e,n){let o,r;try{r=JSON.parse(t.payload),o=JSON.stringify(r,null,2)}catch{r=t.payload,o=t.payload}let s=e.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:t,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(l)return l}return a();function a(){let l=v("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=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=o,l.appendChild(d),l}}function ug(t,e,n,o,r,s,a,l){let d=r.has(t.id),p=v("div","persona-border-b persona-border-persona-divider persona-text-xs");ii(p,o.classNames?.eventRow);let u=a.find(b=>b.renderEventStreamRow);if(u?.renderEventStreamRow&&l){let b=u.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>g(),isExpanded:d,onToggleExpand:()=>s(t.id)});if(b)return p.appendChild(b),p}return p.appendChild(g()),p;function g(){let b=v("div",""),m=v("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");m.setAttribute("data-event-id",t.id);let y=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),w=fe(d?"chevron-down":"chevron-right","14px","currentColor",2);w&&y.appendChild(w);let T=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),W=o.timestampFormat??"relative";T.textContent=W==="relative"?fE(t.timestamp,n):mE(t.timestamp);let E=null;o.showSequenceNumbers!==!1&&(E=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),E.textContent=String(e+1));let k=gE(t.type,o.badgeColors),A=v("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");A.style.backgroundColor=k.bg,A.style.color=k.text,A.style.borderColor=k.text+"50",A.textContent=t.type;let D=o.descriptionFields??pE,B=hE(t.payload,D),I=null;B&&(I=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),I.textContent=B);let N=v("div","persona-flex-1 persona-min-w-0"),_=v("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"),F=fe("clipboard","12px","currentColor",1.5);return F&&_.appendChild(F),_.addEventListener("click",async P=>{P.stopPropagation(),await yE(bE(t)),_.innerHTML="";let V=fe("check","12px","currentColor",1.5);V&&_.appendChild(V),setTimeout(()=>{_.innerHTML="";let se=fe("clipboard","12px","currentColor",1.5);se&&_.appendChild(se)},1500)}),m.appendChild(y),m.appendChild(T),E&&m.appendChild(E),m.appendChild(A),I&&m.appendChild(I),m.appendChild(N),m.appendChild(_),b.appendChild(m),d&&b.appendChild(CE(t,a,l)),b}}function gg(t){let{buffer:e,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=t,l=r?.features?.scrollToBottom,d=l?.enabled!==!1,p=l?.iconName??"arrow-down",u=l?.label??"",g=r?.features?.eventStream??{},b=s.find(y=>y.renderEventStreamView);if(b?.renderEventStreamView&&r){let y=b.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>m().element,onClose:o});if(y)return{element:y,update:()=>{},destroy:()=>{}}}return m();function m(){let y=g.classNames,w=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");ii(w,y?.panel);let T=[],W="",E="",k=null,A=[],D={},B=0,I=Jc(),N=0,_=0,F=!1,P=null,V=!1,se=0,ve=new Set,he=new Map,ge="",re="",oe=null,ee,M,te,pe,Se=null,xe=null,Ce=null;function Me(){let K=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Y=v("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");if(ii(Y,y?.headerBar),a){xe=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),xe.style.cursor="help",Se=v("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"),Se.textContent="-- tok/s",Ce=v("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"),Ce.style.display="none",Ce.style.pointerEvents="none";let _e=xe,Bt=Ce,ln=()=>{if(!Bt.textContent)return;let cn=_e.getBoundingClientRect(),ls=K.getBoundingClientRect();Bt.style.left=`${cn.left-ls.left}px`,Bt.style.top=`${cn.bottom-ls.top+4}px`,Bt.style.display="block"},pi=()=>{Bt.style.display="none"};xe.addEventListener("mouseenter",ln),xe.addEventListener("mouseleave",pi),xe.appendChild(Se)}let Q=v("div","persona-flex-1");ee=v("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 Z=v("option","");Z.value="",Z.textContent="All events (0)",ee.appendChild(Z),M=v("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"),M.type="button",M.title="Copy All";let et=fe("clipboard-copy","12px","currentColor",1.5);et&&M.appendChild(et);let Ye=v("span","persona-event-copy-all persona-text-xs");Ye.textContent="Copy All",M.appendChild(Ye),xe&&Y.appendChild(xe),Y.appendChild(Q),Y.appendChild(ee),Y.appendChild(M);let Be=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");ii(Be,y?.searchBar);let ye=fe("search","14px","var(--persona-muted, #9ca3af)",1.5),we=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");ye&&we.appendChild(ye),te=v("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"),ii(te,y?.searchInput),te.type="text",te.placeholder="Search event payloads...",pe=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),pe.type="button",pe.style.display="none";let ct=fe("x","12px","currentColor",2);return ct&&pe.appendChild(ct),Be.appendChild(we),Be.appendChild(te),Be.appendChild(pe),K.appendChild(Y),K.appendChild(Be),Ce&&K.appendChild(Ce),K}let ke,Oe=s.find(K=>K.renderEventStreamToolbar);Oe?.renderEventStreamToolbar&&r?ke=Oe.renderEventStreamToolbar({config:r,defaultRenderer:()=>Me(),eventCount:e.getSize(),filteredCount:0,onFilterChange:Y=>{W=Y,Wt(),lt()},onSearchChange:Y=>{E=Y,Wt(),lt()}})??Me():ke=Me();let ze=v("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");ze.style.display="none";function qe(){if(!a||!Se||!xe)return;let K=a(),Y=vE(K);Se.textContent=Y;let Q=wE(K);Ce&&(Ce.textContent=Q,Q||(Ce.style.display="none")),xe.setAttribute("aria-label",Q?`Throughput: ${Y}, ${Q}`:`Throughput: ${Y}`)}let nt=v("div","persona-flex-1 persona-min-h-0 persona-relative"),De=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");De.style.height="100%";let Ue=v("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");ii(Ue,y?.scrollIndicator),Ue.style.display="none",Ue.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let an=fe(p,"14px","currentColor",2);an&&Ue.appendChild(an);let Ee=v("span","");Ee.textContent=u,Ue.appendChild(Ee);let $e=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");$e.style.display="none",nt.appendChild(De),nt.appendChild($e),nt.appendChild(Ue),w.setAttribute("tabindex","0"),w.appendChild(ke),w.appendChild(ze),w.appendChild(nt);function mt(){let K=e.getAll(),Y={};for(let Be of K)Y[Be.type]=(Y[Be.type]||0)+1;let Q=Object.keys(Y).sort(),Z=Q.length!==A.length||!Q.every((Be,ye)=>Be===A[ye]),ue=!Z&&Q.some(Be=>Y[Be]!==D[Be]),et=K.length!==Object.values(D).reduce((Be,ye)=>Be+ye,0);if(!Z&&!ue&&!et||(A=Q,D=Y,!ee))return;let Ye=ee.value;if(ee.options[0].textContent=`All events (${K.length})`,Z){for(;ee.options.length>1;)ee.remove(1);for(let Be of Q){let ye=v("option","");ye.value=Be,ye.textContent=`${Be} (${Y[Be]||0})`,ee.appendChild(ye)}Ye&&Q.includes(Ye)?ee.value=Ye:Ye&&(ee.value="",W="")}else for(let Be=1;Be<ee.options.length;Be++){let ye=ee.options[Be];ye.textContent=`${ye.value} (${Y[ye.value]||0})`}}function At(){let K=e.getAll();if(W&&(K=K.filter(Y=>Y.type===W)),E){let Y=E.toLowerCase();K=K.filter(Q=>Q.type.toLowerCase().includes(Y)||Q.payload.toLowerCase().includes(Y))}return K}function yt(){return W!==""||E!==""}function Wt(){B=0,N=0,I.resume(),Ue.style.display="none"}function Te(K){ve.has(K)?ve.delete(K):ve.add(K),oe=K;let Y=De.scrollTop,Q=I.isFollowing();V=!0,I.pause(),lt(),De.scrollTop=Y,Q&&I.resume(),V=!1}function ot(){return Go(De,50)}function lt(){_=Date.now(),F=!1,qe(),mt();let K=e.getEvictedCount();K>0?(ze.textContent=`${K.toLocaleString()} older events truncated`,ze.style.display=""):ze.style.display="none",T=At();let Y=T.length,Q=e.getSize()>0;Y===0&&Q&&yt()?($e.textContent=E?`No events matching '${E}'`:"No events matching filter",$e.style.display="",De.style.display="none"):($e.style.display="none",De.style.display=""),M&&(M.title=yt()?`Copy Filtered (${Y})`:"Copy All"),d&&!I.isFollowing()&&Y>B&&(N+=Y-B,Ee.textContent=u?`${u}${N>0?` (${N})`:""}`:"",Ue.style.display=""),B=Y;let Z=e.getAll(),ue=Z.length>0?Z[0].timestamp:0,et=new Set(T.map(ye=>ye.id));for(let ye of ve)et.has(ye)||ve.delete(ye);let Ye=W!==ge||E!==re,Be=he.size===0&&T.length>0;if(Ye||Be||T.length===0){De.innerHTML="",he.clear();let ye=document.createDocumentFragment();for(let we=0;we<T.length;we++){let ct=ug(T[we],we,ue,g,ve,Te,s,r);he.set(T[we].id,ct),ye.appendChild(ct)}De.appendChild(ye),ge=W,re=E,oe=null}else{if(oe!==null){let we=he.get(oe);if(we&&we.parentNode===De){let ct=T.findIndex(_e=>_e.id===oe);if(ct>=0){let _e=ug(T[ct],ct,ue,g,ve,Te,s,r);De.insertBefore(_e,we),we.remove(),he.set(oe,_e)}}oe=null}let ye=new Set(T.map(we=>we.id));for(let[we,ct]of he)ye.has(we)||(ct.remove(),he.delete(we));for(let we=0;we<T.length;we++){let ct=T[we];if(!he.has(ct.id)){let _e=ug(ct,we,ue,g,ve,Te,s,r);he.set(ct.id,_e),De.appendChild(_e)}}}I.isFollowing()&&(De.scrollTop=De.scrollHeight)}function kt(){if(Date.now()-_>=uE){P!==null&&(cancelAnimationFrame(P),P=null),lt();return}F||(F=!0,P=requestAnimationFrame(()=>{P=null,lt()}))}let wn=(K,Y)=>{if(!M)return;M.innerHTML="";let Q=fe(K,"12px","currentColor",1.5);Q&&M.appendChild(Q);let Z=v("span","persona-text-xs");Z.textContent="Copy All",M.appendChild(Z),setTimeout(()=>{M.innerHTML="";let ue=fe("clipboard-copy","12px","currentColor",1.5);ue&&M.appendChild(ue);let et=v("span","persona-text-xs");et.textContent="Copy All",M.appendChild(et),M.disabled=!1},Y)},Ct=async()=>{if(M){M.disabled=!0;try{let K;yt()?K=T:n?(K=await n(),K.length===0&&(K=e.getAll())):K=e.getAll();let Y=K.map(Q=>{try{return JSON.parse(Q.payload)}catch{return Q.payload}});await navigator.clipboard.writeText(JSON.stringify(Y,null,2)),wn("check",1500)}catch{wn("x",1500)}}},Ln=()=>{ee&&(W=ee.value,Wt(),lt())},Gn=()=>{!te||!pe||(pe.style.display=te.value?"":"none",k&&clearTimeout(k),k=setTimeout(()=>{E=te.value,Wt(),lt()},150))},j=()=>{!te||!pe||(te.value="",E="",pe.style.display="none",k&&clearTimeout(k),Wt(),lt())},ae=()=>{if(V)return;let K=De.scrollTop,{action:Y,nextLastScrollTop:Q}=Zc({following:I.isFollowing(),currentScrollTop:K,lastScrollTop:se,nearBottom:ot(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});se=Q,Y==="resume"?(I.resume(),N=0,Ue.style.display="none"):Y==="pause"&&(I.pause(),d&&(Ee.textContent=u,Ue.style.display=""))},x=K=>{let Y=ed({following:I.isFollowing(),deltaY:K.deltaY,nearBottom:ot(),resumeWhenNearBottom:!0});Y==="pause"?(I.pause(),d&&(Ee.textContent=u,Ue.style.display="")):Y==="resume"&&(I.resume(),N=0,Ue.style.display="none")},S=()=>{d&&(De.scrollTop=De.scrollHeight,I.resume(),N=0,Ue.style.display="none")},O=K=>{let Y=K.target;if(!Y||Y.closest("button"))return;let Q=Y.closest("[data-event-id]");if(!Q)return;let Z=Q.getAttribute("data-event-id");Z&&Te(Z)},R=K=>{if((K.metaKey||K.ctrlKey)&&K.key==="f"){K.preventDefault(),te?.focus(),te?.select();return}K.key==="Escape"&&(te&&document.activeElement===te?(j(),te.blur(),w.focus()):o&&o())};M&&M.addEventListener("click",Ct),ee&&ee.addEventListener("change",Ln),te&&te.addEventListener("input",Gn),pe&&pe.addEventListener("click",j),De.addEventListener("scroll",ae),De.addEventListener("wheel",x,{passive:!0}),De.addEventListener("click",O),Ue.addEventListener("click",S),w.addEventListener("keydown",R);function $(){k&&clearTimeout(k),P!==null&&(cancelAnimationFrame(P),P=null),F=!1,he.clear(),M&&M.removeEventListener("click",Ct),ee&&ee.removeEventListener("change",Ln),te&&te.removeEventListener("input",Gn),pe&&pe.removeEventListener("click",j),De.removeEventListener("scroll",ae),De.removeEventListener("wheel",x),De.removeEventListener("click",O),Ue.removeEventListener("click",S),w.removeEventListener("keydown",R)}return{element:w,update:kt,destroy:$}}}var cE,dE,pE,uE,Fv=Ge(()=>{"use strict";Qe();Rt();$u();cE={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)"}},dE={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},pE=["flowName","stepName","reasoningText","text","name","tool","toolName"],uE=100});var $v=Ge(()=>{"use strict";Fv()});var zv={};lr(zv,{createEventStreamView:()=>gg});var Vv=Ge(()=>{"use strict";$v()});function pw(){let t=document.createElement("div");t.className="persona-history-sr-only",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true"),t.setAttribute("data-persona-history-live-region","");let e;return{element:t,announce(n){e!==void 0&&clearTimeout(e),t.textContent="",e=setTimeout(()=>{e=void 0,t.textContent=n},0)},destroy(){e!==void 0&&clearTimeout(e),t.remove()}}}var uw=Ge(()=>{"use strict"});var gw,fw=Ge(()=>{"use strict";gw=`
175
+ .persona-history-view {
176
+ --persona-history-surface-bg: var(--persona-surface, #ffffff);
177
+ --persona-history-topbar-bg: var(--persona-header-bg, var(--persona-surface, #ffffff));
178
+ --persona-history-border: var(--persona-divider, var(--persona-border, #e5e7eb));
179
+ --persona-history-row-hover-bg: var(--persona-button-ghost-hover-bg, rgba(0, 0, 0, 0.04));
180
+ --persona-history-row-avatar-bg: var(--persona-header-icon-bg, var(--persona-primary, #2563eb));
181
+ --persona-history-row-active-bg: var(--persona-divider, var(--persona-border, #e5e7eb));
182
+ --persona-history-skeleton-bg: var(--persona-divider, var(--persona-border, #e5e7eb));
183
+ --persona-history-focus-ring: var(--persona-primary, #2563eb);
184
+ --persona-history-slide: 20px;
185
+ --persona-history-row-min-height: 60px;
186
+ --persona-history-topbar-min-height: 56px;
187
+ box-sizing: border-box;
188
+ display: flex;
189
+ flex-direction: column;
190
+ width: 100%;
191
+ max-width: 100%;
192
+ min-width: 0;
193
+ height: 100%;
194
+ overflow: hidden;
195
+ background: var(--persona-history-surface-bg);
196
+ color: var(--persona-text, #111827);
197
+ font-family: var(--persona-font-family, inherit);
198
+ font-size: 14px;
199
+ line-height: 1.45;
200
+ opacity: 1;
201
+ }
202
+ .persona-history-view *,
203
+ .persona-history-view *::before,
204
+ .persona-history-view *::after {
205
+ box-sizing: border-box;
206
+ }
207
+ .persona-history-view--enter .persona-history-body {
208
+ animation: persona-history-enter-body var(--persona-history-enter-ms, 180ms)
209
+ var(--persona-history-enter-easing, cubic-bezier(0, 0, 0.2, 1)) both;
210
+ }
211
+ @keyframes persona-history-enter-body {
212
+ from { opacity: 0; transform: translateX(var(--persona-history-slide)); }
213
+ to { opacity: 1; transform: none; }
214
+ }
215
+ .persona-history-view .persona-history-sr-only,
216
+ .persona-history-view--panel .persona-history-group-heading,
217
+ .persona-history-view--panel .persona-history-conversations-title,
218
+ .persona-history-view .persona-history-scope-alert[data-persona-history-scope-tone="ambient"] {
219
+ position: absolute;
220
+ width: 1px;
221
+ height: 1px;
222
+ margin: -1px;
223
+ padding: 0;
224
+ overflow: hidden;
225
+ clip: rect(0 0 0 0);
226
+ clip-path: inset(50%);
227
+ white-space: nowrap;
228
+ border: 0;
229
+ }
230
+
231
+ .persona-history-view .persona-history-topbar,
232
+ .persona-history-topbar.persona-history-topbar--shell {
233
+ display: grid;
234
+ grid-template-columns: 44px minmax(0, 1fr) 44px;
235
+ align-items: center;
236
+ gap: 4px;
237
+ }
238
+ .persona-history-view .persona-history-topbar {
239
+ min-height: var(--persona-history-topbar-min-height);
240
+ padding: 6px 8px;
241
+ background: var(--persona-history-topbar-bg);
242
+ border-bottom: 1px solid var(--persona-history-border);
243
+ }
244
+ .persona-history-view .persona-history-heading-group,
245
+ .persona-history-topbar--shell .persona-history-heading-group {
246
+ min-width: 0;
247
+ text-align: center;
248
+ }
249
+ .persona-history-view .persona-history-title,
250
+ .persona-history-topbar--shell .persona-history-title {
251
+ margin: 0;
252
+ padding: 0;
253
+ font-family: var(--persona-components-header-title-fontFamily, inherit);
254
+ font-size: var(--persona-components-header-title-fontSize, 1rem);
255
+ font-weight: var(--persona-components-header-title-fontWeight, 600);
256
+ line-height: var(--persona-components-header-title-lineHeight, 1.5rem);
257
+ color: var(--persona-header-title-fg, var(--persona-primary, #0f0f0f));
258
+ overflow: hidden;
259
+ text-overflow: ellipsis;
260
+ white-space: nowrap;
261
+ }
262
+ .persona-history-view .persona-history-caption {
263
+ position: relative;
264
+ display: flex;
265
+ align-items: center;
266
+ gap: 8px;
267
+ padding: 0 4px;
268
+ }
269
+ .persona-history-view .persona-history-scope {
270
+ flex: 1 1 auto;
271
+ margin: 0;
272
+ font-size: 12px;
273
+ line-height: 1.35;
274
+ color: var(--persona-text-muted, #6b7280);
275
+ overflow-wrap: anywhere;
276
+ }
277
+ .persona-history-view .persona-history-conversations-title {
278
+ margin: 0;
279
+ font-family: var(--persona-components-history-listHeading-fontFamily, inherit);
280
+ font-size: var(--persona-components-history-listHeading-fontSize, 14px);
281
+ font-weight: var(--persona-components-history-listHeading-fontWeight, 600);
282
+ line-height: var(--persona-components-history-listHeading-lineHeight, 20px);
283
+ letter-spacing: var(--persona-components-history-listHeading-letterSpacing, normal);
284
+ color: var(--persona-components-history-listHeading-color, var(--persona-text, #111827));
285
+ overflow: hidden;
286
+ text-overflow: ellipsis;
287
+ white-space: nowrap;
288
+ }
289
+ .persona-history-view .persona-history-scope-icon {
290
+ display: none;
291
+ }
292
+ .persona-history-view .persona-history-scope-description {
293
+ display: block;
294
+ }
295
+ .persona-history-view .persona-history-scope-alert {
296
+ display: flex;
297
+ flex-direction: column;
298
+ align-items: flex-start;
299
+ gap: 8px;
300
+ margin: 0;
301
+ padding: 10px 12px;
302
+ border: 1px solid var(--persona-history-border);
303
+ border-radius: var(--persona-radius-md, 8px);
304
+ font-size: 12px;
305
+ color: var(--persona-text-muted, #6b7280);
306
+ }
307
+ .persona-history-view .persona-history-scope-alert-title {
308
+ display: block;
309
+ font-weight: 600;
310
+ color: var(--persona-text, #111827);
311
+ }
312
+
313
+ .persona-history-view button.persona-history-icon-button,
314
+ .persona-history-topbar--shell button.persona-history-icon-button {
315
+ display: inline-flex;
316
+ align-items: center;
317
+ justify-content: center;
318
+ width: 44px;
319
+ height: 44px;
320
+ min-width: 44px;
321
+ min-height: 44px;
322
+ padding: 0;
323
+ margin: 0;
324
+ border: 0;
325
+ border-radius: var(--persona-button-ghost-radius, var(--persona-radius-md, 8px));
326
+ background: transparent;
327
+ color: var(--persona-header-action-icon-fg, var(--persona-text-muted, #6b7280));
328
+ cursor: pointer;
329
+ }
330
+ .persona-history-view button.persona-history-icon-button:hover:not(:disabled),
331
+ .persona-history-topbar--shell button.persona-history-icon-button:hover:not(:disabled) {
332
+ background: var(--persona-button-ghost-hover-bg, rgba(0, 0, 0, 0.04));
333
+ }
334
+ .persona-history-view button:focus-visible,
335
+ .persona-history-view [role="menuitem"]:focus-visible,
336
+ .persona-history-topbar--shell button:focus-visible {
337
+ outline: 2px solid var(--persona-history-focus-ring, var(--persona-primary, #2563eb));
338
+ outline-offset: 2px;
339
+ }
340
+ .persona-history-view button:disabled {
341
+ opacity: 0.55;
342
+ cursor: default;
343
+ }
344
+ .persona-history-view button.persona-history-list-options {
345
+ width: 28px;
346
+ height: 28px;
347
+ min-width: 28px;
348
+ min-height: 28px;
349
+ margin-left: auto;
350
+ }
351
+ .persona-history-view button.persona-history-list-options[aria-expanded="true"] {
352
+ background: var(--persona-button-ghost-hover-bg, rgba(0, 0, 0, 0.04));
353
+ color: var(--persona-text, #111827);
354
+ }
355
+
356
+ .persona-history-view .persona-history-body {
357
+ flex: 1 1 auto;
358
+ min-height: 0;
359
+ overflow-y: auto;
360
+ overflow-x: hidden;
361
+ padding: 12px 16px 16px;
362
+ display: flex;
363
+ flex-direction: column;
364
+ gap: 16px;
365
+ }
366
+ .persona-history-view button.persona-history-new {
367
+ display: inline-flex;
368
+ align-items: center;
369
+ gap: 8px;
370
+ max-width: 100%;
371
+ border: 1px solid transparent;
372
+ border-radius: var(--persona-button-radius, var(--persona-radius-lg, 10px));
373
+ font: inherit;
374
+ font-size: 14px;
375
+ line-height: 20px;
376
+ text-align: left;
377
+ cursor: pointer;
378
+ }
379
+ .persona-history-view button.persona-history-new span {
380
+ min-width: 0;
381
+ overflow-wrap: anywhere;
382
+ }
383
+ .persona-history-view .persona-history-list-region {
384
+ display: flex;
385
+ flex-direction: column;
386
+ gap: 16px;
387
+ min-width: 0;
388
+ }
389
+
390
+ .persona-history-view .persona-history-group-heading {
391
+ margin: 0 0 4px;
392
+ padding: 0 4px;
393
+ font-family: var(--persona-components-history-groupHeading-fontFamily, inherit);
394
+ font-size: var(--persona-components-history-groupHeading-fontSize, 12px);
395
+ font-weight: var(--persona-components-history-groupHeading-fontWeight, 600);
396
+ line-height: var(--persona-components-history-groupHeading-lineHeight, 1.35);
397
+ letter-spacing: var(--persona-components-history-groupHeading-letterSpacing, normal);
398
+ color: var(--persona-components-history-groupHeading-color, var(--persona-text-muted, #6b7280));
399
+ }
400
+ .persona-history-view ul.persona-history-list {
401
+ list-style: none;
402
+ margin: 0;
403
+ padding: 0;
404
+ }
405
+ .persona-history-view li.persona-history-item {
406
+ position: relative;
407
+ margin: 0;
408
+ padding: 0;
409
+ list-style: none;
410
+ }
411
+ .persona-history-view button.persona-history-row {
412
+ display: flex;
413
+ align-items: center;
414
+ gap: 8px;
415
+ width: 100%;
416
+ min-height: var(--persona-history-row-min-height);
417
+ padding: 10px 16px;
418
+ margin: 0;
419
+ border: 0;
420
+ border-radius: 0;
421
+ background: transparent;
422
+ color: inherit;
423
+ font: inherit;
424
+ text-align: left;
425
+ cursor: pointer;
426
+ }
427
+ .persona-history-view li.persona-history-item:hover button.persona-history-row:not(:disabled),
428
+ .persona-history-view button.persona-history-row:hover:not(:disabled) {
429
+ background: var(--persona-history-row-hover-bg);
430
+ }
431
+ .persona-history-view button.persona-history-row[aria-current="page"] {
432
+ background: var(--persona-history-row-active-bg);
433
+ }
434
+ .persona-history-view .persona-history-row-avatar {
435
+ display: flex;
436
+ flex: 0 0 auto;
437
+ align-items: center;
438
+ justify-content: center;
439
+ width: 40px;
440
+ height: 40px;
441
+ overflow: hidden;
442
+ border-radius: 16.7%;
443
+ background: var(--persona-history-row-avatar-bg);
444
+ color: var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff));
445
+ font-size: 20px;
446
+ line-height: 1;
447
+ }
448
+ .persona-history-view .persona-history-row-avatar img {
449
+ width: 100%;
450
+ height: 100%;
451
+ object-fit: cover;
452
+ }
453
+ .persona-history-view .persona-history-row-body {
454
+ flex: 1 1 auto;
455
+ min-width: 0;
456
+ line-height: 21px;
457
+ }
458
+ .persona-history-view .persona-history-row-head {
459
+ display: flex;
460
+ align-items: baseline;
461
+ gap: 8px;
462
+ min-width: 0;
463
+ }
464
+ .persona-history-view .persona-history-row-title {
465
+ flex: 1 1 auto;
466
+ min-width: 0;
467
+ font-size: 14px;
468
+ font-weight: 600;
469
+ color: var(--persona-text, #111827);
470
+ }
471
+ .persona-history-view .persona-history-truncate {
472
+ display: block;
473
+ overflow: hidden;
474
+ text-overflow: ellipsis;
475
+ white-space: nowrap;
476
+ }
477
+ .persona-history-view time.persona-history-row-time {
478
+ flex: 0 0 auto;
479
+ white-space: nowrap;
480
+ font-size: 14px;
481
+ font-weight: 400;
482
+ font-variant-numeric: tabular-nums;
483
+ color: var(--persona-text-muted, #6b7280);
484
+ }
485
+ .persona-history-view .persona-history-row-star {
486
+ flex: 0 0 auto;
487
+ display: inline-flex;
488
+ align-self: center;
489
+ color: var(--persona-text-muted, #6b7280);
490
+ }
491
+ .persona-history-view .persona-history-row-preview {
492
+ font-size: 14px;
493
+ color: var(--persona-text-muted, #6b7280);
494
+ }
495
+ .persona-history-view button.persona-history-row-menu-button {
496
+ position: absolute;
497
+ top: 50%;
498
+ right: 6px;
499
+ transform: translateY(-50%);
500
+ color: var(--persona-text-muted, #6b7280);
501
+ }
502
+ @media (hover: hover) {
503
+ .persona-history-view button.persona-history-row-menu-button {
504
+ opacity: 0;
505
+ transition: opacity 120ms ease;
506
+ }
507
+ .persona-history-view li.persona-history-item:hover time.persona-history-row-time,
508
+ .persona-history-view li.persona-history-item:focus-within time.persona-history-row-time {
509
+ opacity: 0;
510
+ }
511
+ .persona-history-view li.persona-history-item:hover button.persona-history-row-menu-button,
512
+ .persona-history-view li.persona-history-item:focus-within button.persona-history-row-menu-button {
513
+ opacity: 1;
514
+ }
515
+ }
516
+ .persona-history-view button.persona-history-row-menu-button[aria-expanded="true"] {
517
+ opacity: 1;
518
+ }
519
+ .persona-history-view button.persona-history-row-menu-button:hover:not(:disabled),
520
+ .persona-history-view button.persona-history-row-menu-button[aria-expanded="true"] {
521
+ background: linear-gradient(var(--persona-history-row-hover-bg), var(--persona-history-row-hover-bg)),
522
+ linear-gradient(var(--persona-history-row-hover-bg), var(--persona-history-row-hover-bg)),
523
+ var(--persona-history-surface-bg);
524
+ color: var(--persona-text, #111827);
525
+ }
526
+ @media (hover: hover) {
527
+ .persona-history-view li.persona-history-item:hover .persona-history-row-preview,
528
+ .persona-history-view li.persona-history-item:focus-within .persona-history-row-preview,
529
+ .persona-history-view li.persona-history-item:has(button[aria-expanded="true"]) .persona-history-row-preview {
530
+ -webkit-mask-image: linear-gradient(to right, #000 calc(100% - 84px), transparent calc(100% - 36px));
531
+ mask-image: linear-gradient(to right, #000 calc(100% - 84px), transparent calc(100% - 36px));
532
+ }
533
+ }
534
+ .persona-history-view li.persona-history-item--no-menu:hover time.persona-history-row-time,
535
+ .persona-history-view li.persona-history-item--no-menu:focus-within time.persona-history-row-time {
536
+ opacity: 1;
537
+ }
538
+ .persona-history-view li.persona-history-item--no-menu:hover .persona-history-row-preview,
539
+ .persona-history-view li.persona-history-item--no-menu:focus-within .persona-history-row-preview,
540
+ .persona-history-view li.persona-history-item--no-menu .persona-history-row-preview {
541
+ -webkit-mask-image: none;
542
+ mask-image: none;
543
+ }
544
+ .persona-history-view .persona-history-menu {
545
+ position: absolute;
546
+ top: calc(50% + 20px);
547
+ right: 8px;
548
+ z-index: 2;
549
+ min-width: 160px;
550
+ max-width: calc(100% - 16px);
551
+ padding: 4px;
552
+ border: 1px solid var(--persona-history-border);
553
+ border-radius: var(--persona-history-menu-radius, 12px);
554
+ background: var(--persona-history-surface-bg);
555
+ background: var(--persona-history-menu-bg, color-mix(in srgb, var(--persona-history-surface-bg) 92%, #fff));
556
+ box-shadow: 0 8px 28px rgba(0, 0, 0, 0.12);
557
+ }
558
+ .persona-history-view .persona-history-caption .persona-history-menu {
559
+ top: calc(100% - 2px);
560
+ right: 4px;
561
+ }
562
+ .persona-history-view--rail .persona-history-caption .persona-history-menu {
563
+ grid-row: 1 / 2;
564
+ grid-column: 1 / -1;
565
+ top: calc(100% + 2px);
566
+ right: 0;
567
+ }
568
+ .persona-history-view button.persona-history-menu-item {
569
+ display: block;
570
+ width: 100%;
571
+ min-height: 32px;
572
+ padding: 6px 10px;
573
+ border: 0;
574
+ border-radius: 8px;
575
+ background: transparent;
576
+ color: var(--persona-text, #111827);
577
+ font: inherit;
578
+ text-align: left;
579
+ cursor: pointer;
580
+ }
581
+ .persona-history-view button.persona-history-menu-item--danger {
582
+ color: var(--persona-history-danger-fg, var(--persona-palette-colors-error-600, #b91c1c));
583
+ }
584
+ .persona-history-view button.persona-history-menu-item:hover:not(:disabled) {
585
+ background: var(--persona-history-row-hover-bg);
586
+ }
587
+ .persona-history-view .persona-history-row-error {
588
+ display: flex;
589
+ flex-wrap: wrap;
590
+ align-items: center;
591
+ gap: 8px;
592
+ padding: 8px 16px 12px;
593
+ font-size: 13px;
594
+ color: var(--persona-history-danger-fg, var(--persona-palette-colors-error-600, #b91c1c));
595
+ }
596
+
597
+ .persona-history-view button.persona-history-secondary {
598
+ display: inline-flex;
599
+ align-items: center;
600
+ justify-content: center;
601
+ gap: 8px;
602
+ width: 100%;
603
+ min-height: 44px;
604
+ padding: 10px 16px;
605
+ margin: 0;
606
+ border: 1px solid var(--persona-history-border);
607
+ border-radius: var(--persona-button-radius, var(--persona-radius-lg, 10px));
608
+ background: transparent;
609
+ color: var(--persona-text, #111827);
610
+ font: inherit;
611
+ font-weight: 500;
612
+ cursor: pointer;
613
+ }
614
+ .persona-history-view button.persona-history-secondary:hover:not(:disabled) {
615
+ background: var(--persona-history-row-hover-bg);
616
+ }
617
+ .persona-history-view .persona-history-state {
618
+ display: flex;
619
+ flex-direction: column;
620
+ align-items: flex-start;
621
+ gap: 8px;
622
+ padding: 8px 4px;
623
+ }
624
+ .persona-history-view .persona-history-state-title {
625
+ margin: 0;
626
+ font-size: 14px;
627
+ font-weight: 600;
628
+ color: var(--persona-text, #111827);
629
+ }
630
+ .persona-history-view .persona-history-state-description {
631
+ margin: 0;
632
+ font-size: 13px;
633
+ color: var(--persona-text-muted, #6b7280);
634
+ overflow-wrap: anywhere;
635
+ }
636
+ .persona-history-view button.persona-history-state-action {
637
+ width: auto;
638
+ min-width: 44px;
639
+ }
640
+ .persona-history-view .persona-history-view-loading {
641
+ display: flex;
642
+ flex-direction: column;
643
+ animation: persona-history-skeleton-in 120ms ease-out 250ms both;
644
+ }
645
+ @keyframes persona-history-skeleton-in {
646
+ from { opacity: 0; }
647
+ to { opacity: 1; }
648
+ }
649
+ .persona-history-view .persona-history-skeleton-row {
650
+ display: flex;
651
+ flex-direction: column;
652
+ justify-content: center;
653
+ gap: 9px;
654
+ min-height: var(--persona-history-row-min-height);
655
+ padding: 10px 16px;
656
+ }
657
+ .persona-history-view .persona-history-skeleton-head {
658
+ display: flex;
659
+ align-items: center;
660
+ justify-content: space-between;
661
+ gap: 8px;
662
+ }
663
+ .persona-history-view .persona-history-skeleton-bar {
664
+ height: 12px;
665
+ border-radius: 999px;
666
+ background: var(--persona-history-skeleton-bg);
667
+ animation: persona-history-pulse 1400ms ease-in-out infinite;
668
+ }
669
+ .persona-history-view .persona-history-skeleton-bar--time {
670
+ flex: 0 0 auto;
671
+ width: 22px;
672
+ }
673
+ .persona-history-view .persona-history-skeleton-bar--preview {
674
+ width: 88%;
675
+ }
676
+ @keyframes persona-history-pulse {
677
+ 0%, 100% { opacity: 1; }
678
+ 50% { opacity: 0.55; }
679
+ }
680
+
681
+ .persona-history-view--panel .persona-history-list-region {
682
+ gap: 0;
683
+ }
684
+ .persona-history-view--panel .persona-history-group {
685
+ margin: 0 -16px;
686
+ }
687
+ .persona-history-view--panel button.persona-history-load-more {
688
+ margin-top: 12px;
689
+ }
690
+ .persona-history-view--panel button.persona-history-new {
691
+ order: 1;
692
+ position: sticky;
693
+ bottom: 12px;
694
+ z-index: 1;
695
+ align-self: center;
696
+ width: auto;
697
+ min-height: 40px;
698
+ padding: 10px 16px;
699
+ margin: auto 0 0;
700
+ background: var(--persona-button-primary-bg, var(--persona-primary, #2563eb));
701
+ color: var(--persona-button-primary-fg, var(--persona-text-inverse, #ffffff));
702
+ font-weight: 600;
703
+ box-shadow: 0 4px 20px rgba(0, 0, 0, 0.18);
704
+ }
705
+
706
+ .persona-history-view--rail {
707
+ --persona-history-slide: 12px;
708
+ --persona-history-surface-bg: var(--persona-container, #f7f7f8);
709
+ --persona-history-topbar-bg: transparent;
710
+ --persona-history-topbar-min-height: 48px;
711
+ --persona-history-row-min-height: 36px;
712
+ }
713
+ .persona-history-view--rail .persona-history-topbar {
714
+ grid-template-columns: minmax(0, 1fr) auto;
715
+ min-height: var(
716
+ --persona-history-rail-header-min-height,
717
+ var(--persona-header-min-height, 56px)
718
+ );
719
+ padding: 2px 6px;
720
+ background: var(
721
+ --persona-history-rail-header-bg,
722
+ var(--persona-history-surface-bg)
723
+ );
724
+ border-bottom: var(--persona-history-rail-header-border, 0);
725
+ }
726
+ .persona-history-view--rail .persona-history-heading-group {
727
+ text-align: left;
728
+ padding-left: 10px;
729
+ }
730
+ .persona-history-view--rail-right .persona-history-topbar {
731
+ grid-template-columns: auto minmax(0, 1fr);
732
+ }
733
+ .persona-history-view--rail-right .persona-history-heading-group {
734
+ padding: 0 10px 0 0;
735
+ }
736
+ .persona-history-view--rail .persona-history-topbar button.persona-history-icon-button {
737
+ width: 36px;
738
+ height: 36px;
739
+ min-width: 36px;
740
+ min-height: 36px;
741
+ color: var(--persona-text-muted, #6b7280);
742
+ }
743
+ @media (pointer: coarse) {
744
+ .persona-history-view--rail .persona-history-topbar button.persona-history-icon-button {
745
+ width: 44px;
746
+ height: 44px;
747
+ min-width: 44px;
748
+ min-height: 44px;
749
+ }
750
+ .persona-history-view button.persona-history-menu-item {
751
+ min-height: 44px;
752
+ padding: 10px 12px;
753
+ }
754
+ .persona-history-view .persona-history-row-preview {
755
+ -webkit-mask-image: linear-gradient(to right, #000 calc(100% - 84px), transparent calc(100% - 36px));
756
+ mask-image: linear-gradient(to right, #000 calc(100% - 84px), transparent calc(100% - 36px));
757
+ }
758
+ .persona-history-view button.persona-history-list-options {
759
+ width: 40px;
760
+ height: 40px;
761
+ min-width: 40px;
762
+ min-height: 40px;
763
+ }
764
+ }
765
+ .persona-history-view--rail .persona-history-title {
766
+ font-family: var(--persona-components-history-railHeader-title-fontFamily, inherit);
767
+ font-size: var(--persona-components-history-railHeader-title-fontSize, 14px);
768
+ font-weight: var(--persona-components-history-railHeader-title-fontWeight, 600);
769
+ line-height: var(--persona-components-history-railHeader-title-lineHeight, inherit);
770
+ letter-spacing: var(--persona-components-history-railHeader-title-letterSpacing, normal);
771
+ color: var(
772
+ --persona-components-history-railHeader-title-color,
773
+ var(--persona-text, #111827)
774
+ );
775
+ }
776
+ .persona-history-view .persona-history-heading-brand {
777
+ display: flex;
778
+ align-items: center;
779
+ gap: 8px;
780
+ min-width: 0;
781
+ }
782
+ .persona-history-view .persona-history-brand-mark {
783
+ display: flex;
784
+ flex: none;
785
+ align-items: center;
786
+ justify-content: center;
787
+ }
788
+ .persona-history-view .persona-history-brand-mark > img,
789
+ .persona-history-view .persona-history-brand-mark > svg {
790
+ width: 20px;
791
+ height: 20px;
792
+ object-fit: contain;
793
+ }
794
+ .persona-history-view .persona-history-wordmark {
795
+ min-width: 0;
796
+ overflow: hidden;
797
+ color: var(--persona-text, #111827);
798
+ font-size: 14px;
799
+ font-weight: 600;
800
+ text-overflow: ellipsis;
801
+ white-space: nowrap;
802
+ }
803
+ .persona-history-view .persona-history-toggle-brand {
804
+ display: none;
805
+ }
806
+ .persona-history-view--rail-collapsed .persona-history-back--branded .persona-history-toggle-brand {
807
+ display: flex;
808
+ }
809
+ .persona-history-view--rail-collapsed .persona-history-back--branded > svg {
810
+ display: none;
811
+ }
812
+ .persona-history-view--rail-collapsed .persona-history-back--branded:hover .persona-history-toggle-brand,
813
+ .persona-history-view--rail-collapsed .persona-history-back--branded:focus-visible .persona-history-toggle-brand {
814
+ display: none;
815
+ }
816
+ .persona-history-view--rail-collapsed .persona-history-back--branded:hover > svg,
817
+ .persona-history-view--rail-collapsed .persona-history-back--branded:focus-visible > svg {
818
+ display: block;
819
+ }
820
+ @media (pointer: coarse) {
821
+ .persona-history-view--rail-collapsed .persona-history-back--branded .persona-history-toggle-brand {
822
+ display: none;
823
+ }
824
+ .persona-history-view--rail-collapsed .persona-history-back--branded > svg {
825
+ display: block;
826
+ }
827
+ }
828
+ .persona-history-view--rail .persona-history-body {
829
+ gap: 8px;
830
+ padding: 4px 0 12px;
831
+ }
832
+ .persona-history-view--rail .persona-history-caption,
833
+ .persona-history-view--rail .persona-history-scope-alert,
834
+ .persona-history-view--rail .persona-history-state {
835
+ padding-right: 16px;
836
+ padding-left: 16px;
837
+ }
838
+ .persona-history-view--rail .persona-history-caption {
839
+ display: grid;
840
+ grid-template-columns: minmax(0, 1fr) auto;
841
+ /* Explicit rows: the abspos menu is grid-placed into row 1, and abspos
842
+ grid placement only resolves against explicit lines (implicit/auto ends
843
+ fall back to the padding-box edge, i.e. below the scope line). */
844
+ grid-template-rows: auto auto;
845
+ align-items: center;
846
+ row-gap: 2px;
847
+ }
848
+ .persona-history-view--rail .persona-history-conversations-title {
849
+ grid-row: 1;
850
+ grid-column: 1;
851
+ }
852
+ .persona-history-view--rail .persona-history-caption button.persona-history-list-options {
853
+ grid-row: 1;
854
+ grid-column: 2;
855
+ margin-left: 0;
856
+ }
857
+ .persona-history-view--rail .persona-history-scope {
858
+ grid-row: 2;
859
+ grid-column: 1 / -1;
860
+ display: flex;
861
+ align-items: center;
862
+ gap: 6px;
863
+ }
864
+ .persona-history-view--rail .persona-history-scope[hidden] {
865
+ display: none;
866
+ }
867
+ .persona-history-view--rail .persona-history-scope-title {
868
+ min-width: 0;
869
+ overflow: hidden;
870
+ text-overflow: ellipsis;
871
+ white-space: nowrap;
872
+ }
873
+ .persona-history-view--rail .persona-history-scope[data-persona-history-identity="browser_only"] .persona-history-scope-icon {
874
+ display: flex;
875
+ flex: none;
876
+ align-items: center;
877
+ }
878
+ .persona-history-view--rail.persona-history-view--has-nav .persona-history-caption {
879
+ margin-top: 4px;
880
+ padding-top: 12px;
881
+ border-top: 1px solid var(--persona-history-border);
882
+ }
883
+ .persona-history-view--rail button.persona-history-new {
884
+ width: calc(100% - 12px);
885
+ min-height: 36px;
886
+ padding: 6px 10px;
887
+ margin: 0 6px;
888
+ border-radius: 10px;
889
+ background: transparent;
890
+ color: inherit;
891
+ font-weight: 500;
892
+ }
893
+ .persona-history-view--rail button.persona-history-new:hover:not(:disabled) {
894
+ background: var(--persona-history-row-hover-bg);
895
+ }
896
+ .persona-history-view--rail .persona-history-list-region {
897
+ gap: 24px;
898
+ }
899
+ .persona-history-view .persona-history-nav {
900
+ display: flex;
901
+ flex-direction: column;
902
+ gap: 2px;
903
+ }
904
+ .persona-history-view .persona-history-nav--footer {
905
+ margin-top: auto;
906
+ }
907
+ .persona-history-view .persona-history-nav[hidden] {
908
+ display: none;
909
+ }
910
+ .persona-history-view button.persona-history-nav-item {
911
+ display: flex;
912
+ align-items: center;
913
+ gap: 8px;
914
+ width: calc(100% - 12px);
915
+ min-height: 36px;
916
+ padding: 6px 10px;
917
+ margin: 0 6px;
918
+ border: 0;
919
+ border-radius: 10px;
920
+ background: transparent;
921
+ color: inherit;
922
+ font: inherit;
923
+ text-align: left;
924
+ cursor: pointer;
925
+ }
926
+ .persona-history-view button.persona-history-nav-item:hover:not(:disabled) {
927
+ background: var(--persona-history-row-hover-bg);
928
+ }
929
+ .persona-history-view .persona-history-nav-icon {
930
+ display: flex;
931
+ flex: none;
932
+ align-items: center;
933
+ justify-content: center;
934
+ width: 20px;
935
+ height: 20px;
936
+ color: var(--persona-text-muted, #6b7280);
937
+ }
938
+ .persona-history-view .persona-history-nav-icon > * {
939
+ width: 20px;
940
+ height: 20px;
941
+ object-fit: contain;
942
+ }
943
+ .persona-history-view .persona-history-nav-label {
944
+ flex: 1 1 auto;
945
+ min-width: 0;
946
+ }
947
+ .persona-history-view .persona-history-nav-badge {
948
+ flex: none;
949
+ padding: 0 6px;
950
+ border-radius: 999px;
951
+ background: var(--persona-history-row-hover-bg);
952
+ color: var(--persona-text-muted, #6b7280);
953
+ font-size: 11px;
954
+ line-height: 18px;
955
+ }
956
+ .persona-history-view--rail .persona-history-group-heading {
957
+ margin: 0 0 6px;
958
+ padding: 0 16px;
959
+ font-size: var(--persona-components-history-groupHeading-fontSize, 13px);
960
+ font-weight: var(--persona-components-history-groupHeading-fontWeight, 500);
961
+ line-height: var(--persona-components-history-groupHeading-lineHeight, 20px);
962
+ }
963
+ .persona-history-view--rail .persona-history-row-avatar,
964
+ .persona-history-view--rail .persona-history-row-preview,
965
+ .persona-history-view--rail time.persona-history-row-time {
966
+ display: none;
967
+ }
968
+ .persona-history-view--rail button.persona-history-row {
969
+ min-height: 36px;
970
+ padding: 6px 10px;
971
+ margin: 0 6px;
972
+ width: calc(100% - 12px);
973
+ border-radius: 10px;
974
+ }
975
+ .persona-history-view--rail .persona-history-row-title {
976
+ font-weight: 400;
977
+ }
978
+ .persona-history-view--rail button.persona-history-row-menu-button {
979
+ right: 10px;
980
+ width: 28px;
981
+ height: 28px;
982
+ min-width: 28px;
983
+ min-height: 28px;
984
+ }
985
+ .persona-history-view--rail .persona-history-skeleton-row {
986
+ padding: 6px 16px;
987
+ }
988
+ .persona-history-view--rail .persona-history-skeleton-bar--preview,
989
+ .persona-history-view--rail .persona-history-skeleton-bar--time {
990
+ display: none;
991
+ }
992
+ .persona-history-view--rail-collapsed .persona-history-topbar {
993
+ grid-template-columns: minmax(0, 1fr);
994
+ justify-items: center;
995
+ padding: 2px;
996
+ }
997
+ .persona-history-view--rail-collapsed .persona-history-heading-group,
998
+ .persona-history-view--rail-collapsed .persona-history-body > :not(.persona-history-new):not(.persona-history-nav) {
999
+ display: none;
1000
+ }
1001
+ .persona-history-view--rail-collapsed button.persona-history-new {
1002
+ width: 36px;
1003
+ padding: 0;
1004
+ margin: 0 auto;
1005
+ justify-content: center;
1006
+ }
1007
+ .persona-history-view--rail-collapsed button.persona-history-new span {
1008
+ display: none;
1009
+ }
1010
+ .persona-history-view--rail-collapsed .persona-history-nav .persona-history-group-heading,
1011
+ .persona-history-view--rail-collapsed button.persona-history-nav-item:not(.persona-history-nav-item--icon),
1012
+ .persona-history-view--rail-collapsed .persona-history-nav-label,
1013
+ .persona-history-view--rail-collapsed .persona-history-nav-badge {
1014
+ display: none;
1015
+ }
1016
+ .persona-history-view--rail-collapsed button.persona-history-nav-item {
1017
+ width: 36px;
1018
+ padding: 0;
1019
+ margin: 0 auto;
1020
+ justify-content: center;
1021
+ }
1022
+
1023
+ [data-persona-history-suppressed] { display: none !important; }
1024
+ .persona-history-header-host {
1025
+ display: flex;
1026
+ flex: 1 1 auto;
1027
+ align-self: stretch;
1028
+ align-items: center;
1029
+ min-width: 0;
1030
+ }
1031
+ .persona-history-rail-host {
1032
+ transition: flex-basis 180ms cubic-bezier(0, 0, 0.2, 1);
1033
+ }
1034
+ .persona-history-topbar.persona-history-topbar--shell {
1035
+ flex: 1 1 auto;
1036
+ min-width: 0;
1037
+ grid-template-columns: var(--persona-header-control-size, 44px) minmax(0, 1fr) var(--persona-header-control-size, 44px);
1038
+ }
1039
+ .persona-history-topbar--shell button.persona-history-icon-button {
1040
+ width: var(--persona-header-control-size, 44px);
1041
+ height: var(--persona-header-control-size, 44px);
1042
+ min-width: var(--persona-header-control-size, 44px);
1043
+ min-height: var(--persona-header-control-size, 44px);
1044
+ }
1045
+ .persona-history-topbar--shell button.persona-history-icon-button svg {
1046
+ width: var(--persona-header-control-icon-size, 20px);
1047
+ height: var(--persona-header-control-icon-size, 20px);
1048
+ }
1049
+ @media (pointer: coarse) {
1050
+ .persona-history-topbar--shell button.persona-history-icon-button {
1051
+ min-width: 40px;
1052
+ min-height: 40px;
1053
+ }
1054
+ }
1055
+ .persona-history-topbar--shell.persona-history-topbar--shell-enter {
1056
+ animation: persona-history-header-fade 120ms cubic-bezier(0, 0, 0.2, 1) both;
1057
+ }
1058
+ @keyframes persona-history-header-fade {
1059
+ from { opacity: 0; }
1060
+ to { opacity: 1; }
1061
+ }
1062
+
1063
+ @media (prefers-reduced-motion: reduce) {
1064
+ .persona-history-view--enter .persona-history-body { animation: none; }
1065
+ .persona-history-topbar--shell.persona-history-topbar--shell-enter {
1066
+ animation: none;
1067
+ }
1068
+ .persona-history-view .persona-history-skeleton-bar { animation: none; }
1069
+ .persona-history-rail-host { transition: none; }
1070
+ }
1071
+ `});function Mg(t){if(!t)return xd;let e={...xd};for(let n of GE){let o=t[n];typeof o=="string"&&o.length>0&&(e[n]=o)}return e}var GE,xd,Tg=Ge(()=>{"use strict";GE=["viewTitle","openHistoryLabel","openHistoryBusyLabel","newConversationLabel","expandLabel","collapseLabel","resizeLabel","showEarlierMessagesLabel","openConversationLoadingLabel","openConversationErrorTitle","openConversationRetryLabel","openConversationBackLabel","confirmCancelLabel","deleteConversationConfirmTitle","deleteConversationConfirm","deleteConversationConfirmLabel","clearHistoryConfirmTitle","clearHistoryConfirm","clearHistoryVerifiedConfirm","clearHistoryConfirmLabel","resetIdentityConfirmTitle","resetIdentityConfirm","resetIdentityConfirmLabel","conversationDeletedNotice","identityResetNotice","identityResetUnconfirmedNotice"],xd={viewTitle:"Messages",openHistoryLabel:"Messages",openHistoryBusyLabel:"Messages, available once the reply finishes",newConversationLabel:"New conversation",expandLabel:"Expand conversation list",collapseLabel:"Collapse conversation list",resizeLabel:"Resize conversation list",showEarlierMessagesLabel:"Show earlier messages",openConversationLoadingLabel:"Loading conversation",openConversationErrorTitle:"Could not open the conversation.",openConversationRetryLabel:"Try again",openConversationBackLabel:"Back to messages",confirmCancelLabel:"Cancel",deleteConversationConfirmTitle:"Delete conversation",deleteConversationConfirm:"Delete this conversation? This cannot be undone.",deleteConversationConfirmLabel:"Delete",clearHistoryConfirmTitle:"Delete all conversations",clearHistoryConfirm:"Delete all conversations for this assistant on this browser? This cannot be undone.",clearHistoryVerifiedConfirm:"Delete all conversations for this assistant and signed-in user? This cannot be undone.",clearHistoryConfirmLabel:"Delete all",resetIdentityConfirmTitle:"Forget this device",resetIdentityConfirm:"Forget this device? All Persona data stored in this browser is cleared. Records are not deleted elsewhere.",resetIdentityConfirmLabel:"Forget this device",conversationDeletedNotice:"That conversation was deleted. You are now in a new conversation.",identityResetNotice:"This device was forgotten.",identityResetUnconfirmedNotice:"This device was cleared here, but the server could not confirm it."}});function qa(t){if(!t)return ja;let e={...ja};for(let[n,o]of Object.entries(t))typeof o=="string"&&o.length>0&&(e[n]=o);return e}function Eo(t,e){return t.replace(/\{(\w+)\}/g,(n,o)=>o in e?String(e[o]):n)}var ja,Ua=Ge(()=>{"use strict";Tg();ja={...xd,emptyTitle:"No conversations yet",emptyDescription:"Start a conversation and it will show up here.",errorTitle:"Could not load conversations",errorDescription:"Something went wrong. Please try again.",retryLabel:"Retry",rateLimitedTitle:"Too many requests",rateLimitedDescription:"Please wait a moment before trying again.",groupStarred:"Starred",groupToday:"Today",groupYesterday:"Yesterday",groupPrevious7Days:"Previous 7 days",groupPrevious30Days:"Previous 30 days",groupMonthYear:"{month} {year}",browserOnlyTitle:"On this device",browserOnlyDescription:"Another browser or device keeps its own separate history.",verifyingTitle:"Checking your account",verifyingDescription:"Looking for messages linked to your account.",verifiedTitle:"Available across signed-in devices",verifiedDescription:"This list refreshes when the chat opens rather than syncing live.",authenticationRequiredTitle:"Sign in to see your messages",authenticationRequiredDescription:"Your session expired. Sign in again to load account history.",identityProviderFailedTitle:"Account history is unavailable",identityProviderFailedDescription:"We could not verify your account, so account history is not shown here.",proofNotAdmittedTitle:"Account history is unavailable",proofNotAdmittedDescription:"This assistant is not set up to accept your account identity.",retryIdentityLabel:"Try again",backLabel:"Back to conversation",closeLabel:"Close conversation list",loadingLabel:"Loading conversations",loadMoreLabel:"Load more",loadingMoreLabel:"Loading more conversations",conversationsTitle:"Conversations",rowActionsLabel:"Conversation options",listOptionsLabel:"Conversation options",deleteConversationLabel:"Delete",clearHistoryLabel:"Delete all conversations",resetIdentityLabel:"Forget this device",messageCountLabel:"{count} messages",messageCountLabelOne:"1 message",conversationRemovedNotice:"Conversation deleted.",historyClearedNotice:"All conversations were deleted.",unavailableTitle:"Conversation history is unavailable",unavailableDescription:"Try again later.",newConversationRequiredTitle:"Start a new conversation",newConversationRequiredDescription:"The previous conversation is gone. Start a new one to keep chatting.",rateLimitedWaitDescription:"You can try again in {seconds} seconds.",openFailedLabel:"Could not open that conversation.",deleteFailedLabel:"Could not delete that conversation.",relativeNow:"now",relativeMinutes:"{value}m",relativeHours:"{value}h",relativeDays:"{value}d",relativeWeeks:"{value}w",relativeYears:"{value}y"}});function YE(t){let e=new Date(t);return e.setHours(0,0,0,0),e.getTime()}function kg(t,e){let n=Date.parse(t);return Number.isFinite(n)?n:e}function XE(t,e){let n=kg(t,e),o=YE(e);if(n>=o)return"today";if(n>=o-Eg)return"yesterday";if(n>=o-7*Eg)return"previous-7-days";if(n>=o-30*Eg)return"previous-30-days";let r=new Date(n);return`month:${r.getFullYear()}-${r.getMonth()}`}function QE(t,e,n,o){if(t==="today")return o.groupToday;if(t==="yesterday")return o.groupYesterday;if(t==="previous-7-days")return o.groupPrevious7Days;if(t==="previous-30-days")return o.groupPrevious30Days;let r=new Date(kg(e,n));return Eo(o.groupMonthYear,{month:r.toLocaleString(void 0,{month:"long"}),year:r.getFullYear()})}function mw(t,e,n,o="time"){let r=t.filter(a=>a.starred),s=r.length>0?[{key:"starred",label:n.groupStarred,items:r}]:[];if(o==="none"){let a=t.filter(l=>!l.starred);return a.length>0&&s.push({key:"recent",label:n.conversationsTitle,items:a}),s}for(let a of t){if(a.starred)continue;let l=XE(a.updatedAt,e),d=s[s.length-1];if(d&&d.key===l){d.items.push(a);continue}s.push({key:l,label:QE(l,a.updatedAt,e,n),items:[a]})}return s}function hw(t,e,n){let o=Math.max(0,e-kg(t,e)),r=Math.floor(o/6e4);if(r<1)return n.relativeNow;if(r<60)return Eo(n.relativeMinutes,{value:r});let s=Math.floor(r/60);if(s<24)return Eo(n.relativeHours,{value:s});let a=Math.floor(s/24);if(a<7)return Eo(n.relativeDays,{value:a});let l=Math.floor(a/7);return a<365?Eo(n.relativeWeeks,{value:l}):Eo(n.relativeYears,{value:Math.floor(a/365)})}function yw(t,e){return t===1?e.messageCountLabelOne:Eo(e.messageCountLabel,{count:t})}var Eg,Pg=Ge(()=>{"use strict";Ua();Eg=864e5});function xr(t,e=20){let n=document.createElementNS(Sd,"svg");if(n.setAttribute("width",String(e)),n.setAttribute("height",String(e)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","2"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),t==="ellipsis"){for(let r of[12,19,5]){let s=document.createElementNS(Sd,"circle");s.setAttribute("cx",String(r)),s.setAttribute("cy","12"),s.setAttribute("r","1"),n.appendChild(s)}return n}let o=ZE[t];if(o){let r=document.createElementNS(Sd,"rect");r.setAttribute("x",String(o[0])),r.setAttribute("y",String(o[1])),r.setAttribute("width",String(o[2])),r.setAttribute("height",String(o[3])),r.setAttribute("rx","2"),n.appendChild(r)}for(let r of JE[t]){let s=document.createElementNS(Sd,"path");s.setAttribute("d",r),n.appendChild(s)}return n}var Sd,JE,ZE,Lg=Ge(()=>{"use strict";Sd="http://www.w3.org/2000/svg",JE={"arrow-left":["m12 19-7-7 7-7","M19 12H5"],plus:["M5 12h14","M12 5v14"],star:["m12 2 2.9 6.2 6.8.7-5.1 4.5 1.4 6.6-6-3.4-6 3.4 1.4-6.6-5.1-4.5 6.8-.7z"],x:["M18 6 6 18","m6 6 12 12"],"panel-left":["M9 3v18"],monitor:["M8 21h8","M12 17v4"],ellipsis:[]},ZE={"panel-left":[3,3,18,18],monitor:[2,3,20,14]}});function tk(t){let e=J("span",{className:"persona-history-row-avatar",attrs:{"aria-hidden":"true"}});return ek.test(t)?e.appendChild(J("img",{attrs:{src:t,alt:"",loading:"lazy"}})):e.textContent=t,e}function bw(t){let{conversation:e,copy:n,busy:o,pending:r}=t,s=o||r!==null,a=e.title.trim().length>0,l=e.starred?(()=>{let m=xr("star",11);return m.setAttribute("fill","currentColor"),m.setAttribute("stroke-width","1"),J("span",{className:"persona-history-row-star"},m,J("span",{className:"persona-history-sr-only",text:n.groupStarred}))})():null,d=J("div",{className:"persona-history-row-head"},J("span",{className:"persona-history-row-title persona-history-truncate",text:a?e.title:e.preview??""}),l,J("time",{className:"persona-history-row-time",attrs:{datetime:e.updatedAt},text:hw(e.updatedAt,t.nowMs,n)})),p=a&&e.preview?J("span",{className:"persona-history-row-preview persona-history-truncate",text:e.preview}):null,u=J("button",{className:zt("persona-history-row",t.active&&"persona-history-row--active",r&&`persona-history-row--${r}`),attrs:{type:"button","data-persona-history-focus":nk(e.id),"data-persona-history-conversation":e.id,...t.active?{"aria-current":"page"}:{},...s?{"aria-disabled":"true"}:{},...r?{"aria-busy":"true"}:{}}},t.avatar?tk(t.avatar):null,J("div",{className:"persona-history-row-body"},d,p,J("span",{className:"persona-history-row-count persona-history-sr-only",text:yw(e.messageCount,n)})));u.addEventListener("click",()=>{s||t.onOpen()});let g=t.showDelete?Ig({className:"persona-history-row-menu-button",label:`${n.rowActionsLabel}: ${e.title}`,focusKey:ok(e.id),open:t.menuOpen,inert:s,onToggle:t.onToggleMenu}):null;return J("li",{className:zt("persona-history-item",!t.showDelete&&"persona-history-item--no-menu"),attrs:{"data-persona-history-item":e.id}},u,g,t.menuOpen&&t.showDelete?rk(t):null,t.error?sk(t.error,n,e.id):null)}function rk(t){let{conversation:e,copy:n}=t;return Hg({label:`${n.rowActionsLabel}: ${e.title}`,items:[{label:n.deleteConversationLabel,focusKey:Ka(e.id),danger:!0,onSelect:t.onDelete}],onCloseMenu:t.onCloseMenu})}function Ig(t){let e=J("button",{className:zt("persona-history-icon-button",t.className),attrs:{type:"button","aria-label":t.label,"aria-haspopup":"menu","aria-expanded":t.open?"true":"false","data-persona-history-focus":t.focusKey,...t.inert?{"aria-disabled":"true"}:{}}});e.appendChild(xr("ellipsis",t.iconSize));let n=()=>e.getAttribute("aria-disabled")==="true";return e.addEventListener("click",o=>{o.stopPropagation(),!n()&&t.onToggle()}),e.addEventListener("keydown",o=>{o.key!=="ArrowDown"&&o.key!=="ArrowUp"||(o.preventDefault(),!(n()||e.getAttribute("aria-expanded")==="true")&&t.onToggle())}),e}function Hg(t){let e=J("div",{className:"persona-history-menu",attrs:{role:"menu","aria-label":t.label}});for(let n of t.items){let o=J("button",{className:zt("persona-history-menu-item",n.danger&&"persona-history-menu-item--danger"),text:n.label,attrs:{type:"button",role:"menuitem",tabindex:"0","data-persona-history-focus":n.focusKey}});o.addEventListener("click",()=>{t.onCloseMenu(),n.onSelect()}),e.appendChild(o)}return e.addEventListener("keydown",n=>{let o=Array.from(e.querySelectorAll('[role="menuitem"]'));if(o.length===0)return;let r=o.indexOf(document.activeElement);if(n.key==="Tab"){t.onCloseMenu({restoreFocus:!0});return}if(n.key==="ArrowDown"){n.preventDefault(),o[(r+1+o.length)%o.length]?.focus();return}if(n.key==="ArrowUp"){n.preventDefault(),o[(r-1+o.length)%o.length]?.focus();return}if(n.key==="Home"){n.preventDefault(),o[0]?.focus();return}n.key==="End"&&(n.preventDefault(),o[o.length-1]?.focus())}),e}function sk(t,e,n){let o=J("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryLabel,attrs:{type:"button","data-persona-history-focus":`row-retry:${n}`}});return o.addEventListener("click",t.retry),J("div",{className:"persona-history-row-error",attrs:{role:"alert"}},J("span",{text:t.message}),o)}var ek,nk,ok,Ka,vw=Ge(()=>{"use strict";Qe();Lg();Pg();ek=/^(https?:|\/|data:)/i;nk=t=>`row:${t}`,ok=t=>`menu:${t}`,Ka=t=>`menu-item:${t}`});function ik(t){switch(t){case"authentication_failed":case"authentication_required":case"identity_provider_failed":case"proof_not_admitted":case"unsupported_scope":case"unavailable":return t;default:return"unknown"}}function ww(t){if(uc(t)){if(t.code==="rate_limited")return{kind:"rate_limited",retryAfterSeconds:t.retryAfterSeconds??0};let e=ik(t.code);return{kind:"error",reason:e,retryable:e!=="unsupported_scope"}}return{kind:"error",reason:"unknown",retryable:!0}}function ak(t,e){switch(t.state){case"authentication_required":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription};case"configuration_error":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription};default:return null}}function lk(t,e){switch(t){case"authentication_required":case"authentication_failed":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription};case"proof_not_admitted":case"unsupported_scope":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription};case"unavailable":return{title:e.unavailableTitle,description:e.unavailableDescription};default:return{title:e.errorTitle,description:e.errorDescription}}}function Ad(t,e,n,o){let r=J("button",{className:"persona-history-secondary persona-history-state-action",text:t,attrs:{type:"button","data-persona-history-focus":e,...n?{"aria-disabled":"true"}:{}}});return r.addEventListener("click",()=>{n||o()}),r}function Ga(t,e,n,o,r){return J("div",{className:"persona-history-state",attrs:{"data-persona-history-state":t,...r?{role:"alert"}:{role:"status"}}},J("p",{className:"persona-history-state-title",text:e}),J("p",{className:"persona-history-state-description",text:n}),o)}function ck(t){let e=["42%","58%","34%"],n=["94%","78%","88%"],o=[0,1,2].map(r=>J("div",{className:"persona-history-skeleton-row",attrs:{"aria-hidden":"true"}},J("div",{className:"persona-history-skeleton-head"},J("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--title",style:{width:e[r]}}),J("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--time"})),J("div",{className:"persona-history-skeleton-bar persona-history-skeleton-bar--preview",style:{width:n[r]}})));return J("div",{className:"persona-history-view-loading",attrs:{"data-persona-history-state":"loading",role:"status","aria-label":t.loadingLabel}},...o)}function Cw(t){let{state:e,copy:n,busy:o}=t;if(e.kind==="loading")return ck(n);if(e.kind==="empty"){let l=ak(t.identityStatus,n);return l?Ga("identity",l.title,l.description,t.onRetry?Ad(n.retryIdentityLabel,"state-retry",o,t.onRetry):null,!0):Ga("empty",n.emptyTitle,n.emptyDescription,null,!1)}if(e.kind==="rate_limited"){let l=e.retryAfterSeconds>0?Eo(n.rateLimitedWaitDescription,{seconds:e.retryAfterSeconds}):n.rateLimitedDescription;return Ga("rate_limited",n.rateLimitedTitle,l,t.onRetry?Ad(n.retryLabel,"state-retry",o,t.onRetry):null,!1)}if(e.kind==="new_conversation_required")return Ga("new_conversation_required",n.newConversationRequiredTitle,n.newConversationRequiredDescription,t.onStartNew?Ad(n.newConversationLabel,"state-retry",o,t.onStartNew):null,!0);let{title:r,description:s}=lk(e.reason,n),a=e.reason==="authentication_required"||e.reason==="authentication_failed"||e.reason==="identity_provider_failed"?n.retryIdentityLabel:n.retryLabel;return Ga("error",r,s,e.retryable&&t.onRetry?Ad(a,"state-retry",o,t.onRetry):null,!0)}var xw=Ge(()=>{"use strict";Qe();Ua();la()});function Md(t){return`${t.state}:${"reason"in t?t.reason:""}`}function Aw(t,e){switch(t.state){case"verified":return{title:e.verifiedTitle,description:e.verifiedDescription,pending:!1};case"verifying":case"resetting":return{title:e.verifyingTitle,description:e.verifyingDescription,pending:!0};case"authentication_required":return{title:e.authenticationRequiredTitle,description:e.authenticationRequiredDescription,pending:!1};case"identity_provider_failed":return{title:e.identityProviderFailedTitle,description:e.identityProviderFailedDescription,pending:!1};case"configuration_error":return{title:e.proofNotAdmittedTitle,description:e.proofNotAdmittedDescription,pending:!1};case"unavailable":return{title:e.unavailableTitle,description:e.unavailableDescription,pending:!1};default:return{title:e.browserOnlyTitle,description:e.browserOnlyDescription,pending:!1}}}function yk(t){return t.state==="verified"||t.state==="browser_only"}function bk(t){return t.state==="authentication_required"||t.state==="identity_provider_failed"||t.state==="configuration_error"}function Rg(t){let e=qa(t.copy),n=t.now??(()=>Date.now()),o=t.pageSize??dk,r=`persona-history-title-${Math.random().toString(36).slice(2,8)}`,s=[],a=null,l={kind:"loading",phase:"initial"},d=null,p=t.activeConversationId,u=t.provider.getIdentityStatus(),g=Md(u),b=null,m=!1,y=!1,w=0,T=t.presentation,W=t.collapsible!==!1,E=t.collapsed===!0,k=t.railSide==="right",A=t.renderDom!==!1,D=new Map,B=null,I=pw(),N=q=>{!A&&t.onAnnounce?t.onAnnounce(q):I.announce(q)},_=()=>d!==null,F=`${r}-body`,P=J("button",{className:"persona-history-icon-button persona-history-back",attrs:{type:"button"}}),V=()=>T==="rail"&&W,se,ve=()=>{if(t.railBrand){if(!V()){P.classList.remove("persona-history-back--branded");return}if(se===void 0){let q=t.railBrand(!0);se=q?J("span",{className:"persona-history-brand-mark persona-history-toggle-brand",attrs:{"aria-hidden":"true"}},q):null}se&&(P.classList.add("persona-history-back--branded"),P.appendChild(se))}},he=()=>{let q=V(),ce=T==="rail";P.setAttribute("data-persona-history-focus",q?"collapse":"close"),P.setAttribute("aria-label",q?E?e.expandLabel:e.collapseLabel:ce?e.closeLabel:e.backLabel),q?(P.setAttribute("aria-expanded",E?"false":"true"),P.setAttribute("aria-controls",F),t.collapseShortcut?.aria&&P.setAttribute("aria-keyshortcuts",t.collapseShortcut.aria)):(P.removeAttribute("aria-expanded"),P.removeAttribute("aria-controls"),P.removeAttribute("aria-keyshortcuts")),P.replaceChildren(xr(q?"panel-left":ce?"x":"arrow-left")),ve()};he(),P.addEventListener("click",()=>{V()?t.onToggleCollapse?.():t.onClose()});let ge=J("h2",{className:"persona-history-title",text:e.viewTitle,attrs:{id:r}}),re=J("span",{className:"persona-history-scope-title"}),oe=J("p",{className:"persona-history-scope"},J("span",{className:"persona-history-scope-icon",attrs:{"aria-hidden":"true"}},xr("monitor",14)),re),ee=J("div",{className:"persona-history-heading-group"},ge),M=!1,te,pe=()=>{let q=T==="rail",ce=q?t.renderRailHeader:void 0,He=null,Xe=ce!==void 0;if(ce)try{He=ce({collapsed:E,defaultTitle:e.viewTitle})}catch(Le){Xe=!1,M||(M=!0,console.warn("[persona] history rail renderHeader threw",Le))}if(!Xe&&q&&t.railBrand){if(te===void 0){let Le=t.railBrand(!1);te=Le?J("span",{className:"persona-history-heading-brand",attrs:{"aria-hidden":"true"}},J("span",{className:"persona-history-brand-mark"},Le),J("span",{className:"persona-history-wordmark",text:e.viewTitle})):null}te&&(Xe=!0,He=te)}ge.classList.toggle("persona-history-sr-only",Xe),ee.replaceChildren(ge),He&&ee.appendChild(He)};pe();let Se=J("button",{className:"persona-history-icon-button persona-history-new-icon",attrs:{type:"button","data-persona-history-focus":"new-icon","aria-label":e.newConversationLabel}});Se.appendChild(xr("plus")),Se.addEventListener("click",()=>{de()});let xe=[P,Se].map(q=>t.attachTooltip?.({anchor:q,text:()=>q.getAttribute("aria-label")??"",...q===P&&t.collapseShortcut?{hint:()=>V()?t.collapseShortcut.hint:""}:{}})),Ce=J("div",{className:"persona-history-topbar"}),Me=null,ke=()=>{let q=T==="rail",ce=q?k?"rail-right":"rail":"panel";ce!==Me&&(Me=ce,ce==="rail"?Ce.append(ee,P):Ce.append(P,ee),q?Se.remove():Ce.appendChild(Se),Te.classList.toggle("persona-history-view--rail-right",ce==="rail-right"))},Oe=J("div",{className:"persona-history-scope-alert"}),ze=`${r}-scope`,qe=xr("plus",18),nt=J("button",{className:"persona-history-new",attrs:{type:"button","data-persona-history-focus":"new"}},qe,J("span",{text:e.newConversationLabel}));nt.addEventListener("click",()=>{de()});let De=J("div",{className:"persona-history-list-region"}),Ue=t.showDeleteAll!==!1,an=!!t.provider.resetDevice,Ee=t.listActions??[],$e=Ue||an||Ee.length>0?Ig({className:"persona-history-list-options",label:e.listOptionsLabel,focusKey:`menu:${as}`,open:!1,inert:!0,iconSize:16,onToggle:()=>fo(as)}):null,mt=J("h3",{className:"persona-history-conversations-title",text:e.conversationsTitle}),At=J("div",{className:"persona-history-caption",attrs:{"data-persona-history-item":as}},mt,t.showScopeStatus?oe:null,$e),yt=J("div",{className:"persona-history-body",attrs:{id:F}},t.showScopeStatus?Oe:null,nt,At,De),Wt=t.headerPlacement??"inline";Wt==="external"&&Ce.classList.add("persona-history-topbar--shell","persona-history-topbar--shell-enter");let Te=J("div",{className:zt("persona-history-view",`persona-history-view--${t.presentation}`,"persona-history-view--enter"),attrs:{role:"region","aria-labelledby":r,"data-persona-history-presentation":t.presentation}},I.element,Wt==="inline"?Ce:null,yt),ot=()=>{Te.classList.toggle("persona-history-view--rail-collapsed",E&&V())};ot(),ke();let lt=(q,ce)=>{let He=`${r}-s${ce}`,Xe=J("div",{className:zt("persona-history-nav",q.placement==="footer"&&"persona-history-nav--footer"),attrs:{role:"group","data-persona-rail-section":q.id,...q.title?{"aria-labelledby":He}:{"aria-label":q.id}}});q.title&&Xe.appendChild(J("h3",{className:"persona-history-group-heading",text:q.title,attrs:{id:He}}));for(let Le of q.items){let Nt=Le.iconNode?.()??null,In=J("button",{className:zt("persona-history-nav-item",Nt&&"persona-history-nav-item--icon"),attrs:{type:"button","aria-label":Le.label,"data-persona-rail-item":Le.id}},Nt?J("span",{className:"persona-history-nav-icon"},Nt):null,J("span",{className:"persona-history-nav-label persona-history-truncate",text:Le.label}),Le.badge?J("span",{className:"persona-history-nav-badge",text:Le.badge}):null);In.addEventListener("click",()=>Le.onSelect()),Xe.appendChild(In)}return Xe},kt=null,wn=null,Ct=()=>{!kt||!A||T!=="rail"||E===wn||(wn=E,t.railSections.forEach((q,ce)=>{if(!q.render)return;let He=kt[ce],Xe=q.title?He.firstElementChild:null,Le=null;try{Le=q.render(E)}catch(Nt){q.render=void 0,console.warn("[persona] history rail section threw",q.id,Nt)}He.replaceChildren(...Xe?[Xe]:[],...Le?[Le]:[]),He.hidden=!Le}))},Ln=()=>{let q=t.railSections;if(Te.classList.toggle("persona-history-view--has-nav",T==="rail"&&!!q?.some(ce=>ce.placement==="above-conversations")),!!q?.length){if(T!=="rail"){kt?.forEach(ce=>ce.remove());return}kt??(kt=q.map(lt));for(let ce of["above-conversations","below-conversations","footer"]){let He=ce==="above-conversations"?At.parentNode===yt?At:De:null;q.forEach((Xe,Le)=>{Xe.placement===ce&&yt.insertBefore(kt[Le],He)})}Ct()}};Ln(),Mc(Te,"persona-history-view",gw);let Gn=(q,ce)=>{let He=Te.ownerDocument.defaultView?.getComputedStyle(Te).getPropertyValue(q),Xe=Number.parseFloat(He??"");return Number.isFinite(Xe)&&Xe>=0?Xe:ce},j=(q,ce)=>Te.ownerDocument.defaultView?.getComputedStyle(Te).getPropertyValue(q).trim()||ce,ae=null,x=()=>{ae!==null&&(clearTimeout(ae),ae=null),Te.removeEventListener("animationend",x),Te.classList.remove("persona-history-view--enter")};Te.addEventListener("animationend",x),ae=setTimeout(()=>{ae=setTimeout(x,Gn("--persona-history-enter-ms",pk)+60)},0);let S=null,O=()=>{S!==null&&(clearTimeout(S),S=null),Ce.classList.remove("persona-history-topbar--shell-enter")},R=()=>{O(),Ce.classList.add("persona-history-topbar--shell-enter"),S=setTimeout(O,Sw+60)};Wt==="external"&&(S=setTimeout(O,Sw+60));let $=[],K=null,Y=()=>{if(K)return K;if(y||mk()||typeof Te.animate!="function")return x(),null;let q=Te.ownerDocument.defaultView?.getComputedStyle(yt).opacity||"1";x(),Te.style.pointerEvents="none",Z.style.pointerEvents="none";let ce={duration:Gn("--persona-history-exit-ms",uk),easing:j("--persona-history-exit-easing",gk),fill:"forwards"},He=fk[T];return $=[yt.animate([{opacity:q,transform:"none"},{opacity:0,transform:`translateX(${He}px)`}],ce)],K=Promise.all($.map(hk)).then(()=>{}),K},Q=(q,ce)=>{q&&(ce?q.setAttribute("aria-disabled","true"):q.removeAttribute("aria-disabled"))},Z=Ce,ue=null,et=()=>{let q=t.slots?.header;if(!q)return;let ce=`${T}|${Md(u)}|${d?`${d.kind}:${"conversationId"in d?d.conversationId:""}`:""}`;if(ce===ue)return;ue=ce;let He=q({identityStatus:u,pendingAction:d,copy:e,defaultRenderer:()=>Ce})??Ce;He!==Z&&(Z.replaceWith(He),Z=He)},Ye=null,Be=()=>{if(!t.showScopeStatus)return;let q=Md(u);if(q===Ye)return;Ye=q;let ce=Aw(u,e);re.textContent=ce.title;let He=yk(u);if(oe.hidden=!He,Oe.replaceChildren(...He?[]:[J("span",{className:"persona-history-scope-alert-title",text:ce.title})],J("span",{className:"persona-history-scope-description",text:ce.description,attrs:{id:ze}})),Oe.setAttribute("data-persona-history-scope-tone",He?"ambient":"attention"),He?oe.setAttribute("aria-describedby",ze):oe.removeAttribute("aria-describedby"),ce.pending?Oe.setAttribute("role","status"):Oe.removeAttribute("role"),Oe.setAttribute("data-persona-history-identity",u.state),oe.setAttribute("data-persona-history-identity",u.state),bk(u)){let Xe=J("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryIdentityLabel,attrs:{type:"button","data-persona-history-focus":"identity-retry"}});Xe.addEventListener("click",()=>{_()||io("refresh")}),Oe.appendChild(Xe)}},ye=q=>d?d.kind==="open"&&d.conversationId===q?"opening":d.kind==="delete"&&d.conversationId===q?"deleting":null:null,we=()=>{let q=document.activeElement;return!(q instanceof HTMLElement)||!Te.contains(q)?null:q.getAttribute("data-persona-history-focus")},ct=q=>{if(m&&b){m=!1;let ce=Te.querySelector(`[data-persona-history-focus="${Ka(b)}"]`);if(ce){ce.focus();return}}q&&Te.querySelector(`[data-persona-history-focus="${q}"]`)?.focus()},_e=()=>{if(!B)return null;let q=J("button",{className:"persona-history-secondary persona-history-state-action",text:e.retryLabel,attrs:{type:"button","data-persona-history-focus":"action-retry"}}),ce=B;return q.addEventListener("click",()=>{_()||ce.retry()}),J("div",{className:"persona-history-row-error",attrs:{role:"alert"}},J("span",{text:ce.message}),q)},Bt=()=>mw(s,n(),e,t.grouping).map((q,ce)=>{let He=`${r}-g${ce}`,Xe=J("ul",{className:"persona-history-list",attrs:{"aria-labelledby":He}});for(let Le of q.items){let Nt=()=>bw({conversation:Le,active:Le.id===p,pending:ye(Le.id),busy:_(),menuOpen:b===Le.id,error:D.get(Le.id)??null,avatar:t.rowAvatar,showDelete:t.showDelete!==!1,nowMs:n(),copy:e,onOpen:()=>{ao(Le.id)},onToggleMenu:()=>fo(Le.id),onCloseMenu:cs=>tn(cs),onDelete:()=>{Sr(Le.id)}}),Qo=t.slots?.conversation?.({conversation:Le,active:Le.id===p,pending:ye(Le.id),open:()=>ao(Le.id),requestDelete:()=>Sr(Le.id),defaultRenderer:Nt})??Nt();Xe.appendChild(Qo instanceof HTMLLIElement?Qo:J("li",{className:"persona-history-item"},Qo))}return J("div",{className:"persona-history-group",attrs:{"data-persona-history-group":q.key}},J("h3",{className:zt("persona-history-group-heading",q.key==="recent"&&"persona-history-sr-only"),text:q.label,attrs:{id:He}}),Xe)}),ln=()=>{if(!a)return null;let q=d?.kind==="load-more"||l.kind==="loading"&&l.phase==="load-more",ce=J("button",{className:"persona-history-secondary persona-history-load-more",text:q?e.loadingMoreLabel:e.loadMoreLabel,attrs:{type:"button","data-persona-history-focus":"load-more",...q?{"aria-busy":"true","aria-disabled":"true"}:{},..._()&&!q?{"aria-disabled":"true"}:{}}});return ce.addEventListener("click",()=>{_()||io("load-more")}),ce},pi=()=>{let q=we(),ce=[_e()],He=s.length>0;if(He&&(ce.push(...Bt()),ce.push(ln())),l.kind!=="ready"&&!(l.kind==="loading"&&l.phase!=="initial"&&He)){let Le=l,Nt=Le.kind==="loading"?void 0:()=>io("refresh"),In=Le.kind==="new_conversation_required"?()=>de():void 0,Qo=()=>Cw({state:Le,copy:e,identityStatus:u,busy:_(),...Nt?{onRetry:()=>{Nt()}}:{},...In?{onStartNew:()=>{In()}}:{}}),cs=t.slots?.state?.({state:Le,identityStatus:u,copy:e,...Nt?{retry:Nt}:{},...In?{startNewConversation:In}:{},defaultRenderer:Qo});ce.push(cs??Qo())}De.replaceChildren(...ce.filter(Le=>!!Le)),ct(q)},cn=()=>{let q=l.kind==="loading"&&s.length===0,ce=[],He=()=>ce.length===0?Ka(as):`${Ka(as)}-${ce.length}`;if(!q)for(let Xe of Ee)ce.push({label:Xe.label,focusKey:He(),danger:Xe.danger===!0,onSelect:()=>{Xe.onSelect({conversations:[...s]})}});return Ue&&!(s.length===0&&(l.kind==="empty"||q))&&ce.push({label:e.clearHistoryLabel,focusKey:He(),danger:!0,onSelect:()=>{Nn()}}),an&&!q&&ce.push({label:e.resetIdentityLabel,focusKey:He(),danger:!0,onSelect:()=>{yn()}}),ce},ls=()=>{if(Q(nt,_()),Q(Se,_()),$e){let q=cn(),ce=l.kind==="loading"&&s.length===0;$e.hidden=q.length===0&&!ce,Q($e,_()||q.length===0),$e.setAttribute("aria-expanded",b===as?"true":"false");let He=At.querySelector(".persona-history-menu");if(b!==as||q.length===0)He?.remove();else{let Xe=Hg({label:e.listOptionsLabel,items:q,onCloseMenu:Le=>tn(Le)});He?He.replaceWith(Xe):At.appendChild(Xe)}}At.hidden=T!=="rail"&&(!$e||$e.hidden)&&(!t.showScopeStatus||oe.hidden)},Xa,Ke=()=>{let q=t.onActiveConversationChange;if(!q)return;let ce=s.find(Xe=>Xe.id===p)??null,He=ce?`${ce.id}\0${ce.title}\0${ce.starred?1:0}`:"";He!==Xa&&(Xa=He,q(ce))},Fe=()=>{if(!y){if(Ke(),!A){t.onModelChange?.();return}et(),Be(),ls(),pi(),Ct()}},tn=q=>{if(!b)return;let ce=b;b=null,m=!1,Fe(),q?.restoreFocus&&Te.querySelector(`[data-persona-history-focus="menu:${ce}"]`)?.focus()},fo=q=>{if(b===q){tn({restoreFocus:!0});return}b=q,m=!0,Fe()},Pe=q=>{if(!b)return;let ce=q.target;ce instanceof Node&&Te.contains(ce)&&ce.closest?.(`[data-persona-history-item="${b}"]`)||tn()};document.addEventListener("pointerdown",Pe,!0);let Je=q=>{q.key!=="Escape"||!b||(q.stopPropagation(),tn({restoreFocus:!0}))};Te.addEventListener("keydown",Je);async function io(q){if(y)return;let ce=++w,He=q==="load-more"?a:null;if(!(q==="load-more"&&!He)){d={kind:q==="load-more"?"load-more":"refresh"},l={kind:"loading",phase:q},q!=="load-more"&&(D.clear(),B=null),tn(),Fe();try{let Xe=await t.provider.list({limit:o,context:t.context,...He?{cursor:He}:{},...t.targetId?{targetId:t.targetId}:{}});if(y||ce!==w)return;s=He?[...s,...Xe.items]:Xe.items,a=Xe.nextCursor,l=s.length===0?{kind:"empty"}:{kind:"ready"}}catch(Xe){if(y||ce!==w)return;l=ww(Xe)}finally{!y&&ce===w&&(d=null,Fe())}}}let ui=q=>{s=s.filter(ce=>ce.id!==q),D.delete(q),p===q&&(p=null),s.length===0&&!a&&(l={kind:"empty"})};async function ao(q){if(!(_()||y)){D.delete(q),tn(),d={kind:"open",conversationId:q},Fe();try{if(await t.onSelect(q),y)return;p=q}catch{if(y)return;D.set(q,{message:e.openFailedLabel,retry:()=>{ao(q)}})}finally{y||(d=null,Fe())}}}async function Sr(q){if(_()||y)return"cancelled";D.delete(q),d={kind:"delete",conversationId:q},Fe();try{let ce=await t.onRequestDeleteConversation(q);return y||ce==="deleted"&&(ui(q),N(e.conversationRemovedNotice)),ce}catch(ce){return y||(uc(ce)&&ce.code==="not_found"?ui(q):D.set(q,{message:e.deleteFailedLabel,retry:()=>{Sr(q)}})),"cancelled"}finally{y||(d=null,Fe())}}async function de(){if(!(_()||y)){B=null,tn(),d={kind:"start-new"},Fe();try{if(await t.onStartNew(),y)return;l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"})}catch{if(y)return;B={message:e.errorDescription,retry:()=>{de()}}}finally{y||(d=null,Fe())}}}async function Nn(){if(_()||y)return"cancelled";B=null,tn(),d={kind:"clear"},Fe();try{let q=await t.onRequestClearHistory();return y||q==="cleared"&&(s=[],a=null,p=null,l={kind:"empty"},N(e.historyClearedNotice)),q}catch{return y||(B={message:e.errorDescription,retry:()=>{Nn()}}),"cancelled"}finally{y||(d=null,Fe())}}let vt={outcome:"cancelled"};async function yn(){if(_()||y||!t.onRequestResetIdentity)return vt;B=null,tn(),d={kind:"reset"},Fe();try{let q=await t.onRequestResetIdentity();return y||q.outcome==="reset"&&(N(q.remoteRevocationConfirmed?e.identityResetNotice:e.identityResetUnconfirmedNotice),d=null,await io("refresh")),q}catch{return y||(B={message:e.errorDescription,retry:()=>{yn()}}),vt}finally{!y&&d?.kind==="reset"&&(d=null,Fe())}}let Dt=t.provider.subscribeIdentityStatus(q=>{if(y)return;let ce=Md(q),He=ce!==g;u=q,g=ce,Fe(),He&&q.state!=="verifying"&&N(Aw(q,e).title)}),On=t.provider.subscribeAvailability?.(q=>{if(!y){if(q){io("refresh");return}s=[],a=null,l={kind:"error",reason:"unavailable",retryable:!1},Fe()}});return Fe(),io("initial"),{element:Te,copy:e,getModel:()=>({conversations:s,activeConversationId:p,state:l,pendingAction:d,identityStatus:u,nextCursor:a}),operations:{refresh:async()=>{_()||await io("refresh")},loadMore:async()=>{_()||await io("load-more")},openConversation:q=>ao(q),startNewConversation:()=>de(),requestDeleteConversation:q=>Sr(q),requestClearConversationHistory:()=>Nn(),requestResetHistoryIdentity:()=>yn()},setDomRenderEnabled:q=>{q!==A&&(A=q,q&&Fe())},refresh:()=>{io("refresh")},setPresentation:q=>{if(q===T)return;x(),T=q,ue=null;let ce=q==="rail";Te.classList.toggle("persona-history-view--panel",!ce),Te.classList.toggle("persona-history-view--rail",ce),Te.setAttribute("data-persona-history-presentation",q),he(),ot(),ke(),pe(),Ln(),Fe()},setCollapsed:q=>{q!==E&&(E=q,ot(),he(),pe(),Ct())},setRailSide:q=>{k=q==="right",ke()},getHeaderElement:()=>Z,setHeaderPlacement:q=>{if(q===Wt)return;Wt=q;let ce=q==="external";if(Ce.classList.toggle("persona-history-topbar--shell",ce),ce){R(),Z.remove();return}O(),Te.insertBefore(Z,yt)},setActiveConversationId:q=>{p!==q&&(p=q,Fe())},applyConversationSummary:q=>{let ce=s.findIndex(He=>He.id===q.id);ce!==-1&&(s[ce]=q,Fe())},removeConversationSummary:q=>{s.some(ce=>ce.id===q)&&(ui(q),Fe())},setNewConversationRequired:q=>{q?l={kind:"new_conversation_required"}:l.kind==="new_conversation_required"&&(l=s.length===0?{kind:"empty"}:{kind:"ready"}),Fe()},playExit:Y,destroy:()=>{y=!0,w+=1,x(),O(),xe.forEach(q=>q?.destroy()),Z.remove(),$.forEach(q=>q.cancel()),$=[],Dt(),On?.(),document.removeEventListener("pointerdown",Pe,!0),Te.removeEventListener("keydown",Je),I.destroy(),Te.remove(),Te.replaceChildren()}}}var dk,as,pk,Sw,uk,gk,fk,mk,hk,Mw=Ge(()=>{"use strict";Ec();Qe();uw();fw();Ua();Pg();Lg();vw();xw();la();dk=25,as="persona:list-options",pk=180,Sw=120,uk=160,gk="cubic-bezier(0.4, 0, 1, 1)",fk={panel:20,rail:12},mk=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,hk=t=>t.finished?t.finished.then(()=>{},()=>{}):Promise.resolve()});var Wg=Ge(()=>{"use strict";Mw();Ua()});var Tw={};lr(Tw,{HISTORY_VIEW_COPY_DEFAULTS:()=>ja,createHistoryView:()=>Rg,resolveHistoryViewCopy:()=>qa});var Ew=Ge(()=>{"use strict";Wg();Wg()});var t0={};lr(t0,{createThemePreview:()=>Zw});module.exports=jx(t0);var Co=t=>{let{fallbackImport:e,resetOnSetLoader:n=!1}=t,o=null,r=null,s=null;return{setLoader:u=>{o=u,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??e)().then(g=>(r=g,g)).catch(g=>{throw s=null,g}),s),provide:u=>{r=u},getSync:()=>r}};var{setLoader:c0,load:qx,provide:d0,getSync:Up}=Co({fallbackImport:()=>Promise.resolve().then(()=>(ph(),dh))}),Yl=new Set,Ux=()=>{let t=[...Yl];Yl.clear();for(let e of t)try{e()}catch{}};var Kx=()=>{let t=Up();return t?Promise.resolve(t):qx().then(e=>(Ux(),e))},Xl=t=>Up()?()=>{}:(Yl.add(t),Kx().catch(()=>{}),()=>{Yl.delete(t)});var zo=Up;var Gx=t=>{if(t)return t},Kp=t=>{let e=null;return n=>{let o=zo();if(!o)return cr(n);if(!e){let{Marked:r}=o,s=t?.markedOptions;e=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=Gx(t?.renderer);a&&e.use({renderer:a})}return e.parse(n)}},Ql=t=>t?Kp({markedOptions:t.options,renderer:t.renderer}):Kp(),g0=Kp();var cr=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var Yx={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"]},Xx=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Qx=()=>{let t=null;return e=>{let n=zo();if(!n)return cr(e);if(!t){let{DOMPurify:o}=n;t=o(typeof window<"u"?window:void 0),t.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!Xx.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,Yx)}},Jl=t=>t===!1?null:typeof t=="function"?t:Qx();var uh=/^\s*\|?[\s:|-]*-[\s:|-]*$/,gh=t=>t.includes("|"),fh=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},Jx=t=>`| ${t.join(" | ")} |`,Zx=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,eS=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),mh=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
1072
+ `),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!gh(r)||uh.test(r)||!uh.test(s))continue;let a=fh(r).length;if(a<1)continue;let l=Zx(a);e[o+1]!==l&&(e[o+1]=l,n=!0);let d=o+2;for(;d<e.length;d++){let p=e[d];if(p.trim()===""||!gh(p))break;let u=Jx(eS(fh(p),a));e[d]!==u&&(e[d]=u,n=!0)}o=d-1}return n?e.join(`
1073
+ `):t};var hh="var(--persona-md-table-scroll-fade, 24px)",yh=new WeakSet;function vh(t){t.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function bh(t){let e=t.scrollWidth-t.clientWidth;if(e<=1){t.removeAttribute("data-persona-scroll-x");return}t.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(t).direction==="rtl"?e+t.scrollLeft:t.scrollLeft,r=e-o;t.style.setProperty("--persona-fade-l",o<=1?"0px":hh),t.style.setProperty("--persona-fade-r",r<=1?"0px":hh)}function Gp(t){yh.has(t)||(yh.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&bh(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(bh)}var Vo="webmcp:",Yp=new Map,wh=t=>{Yp.clear();for(let e of t){let n=e.title?.trim();n&&Yp.set(e.name,n)}},Qi=t=>Yp.get(Ah(t)),Zl={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},Ch=null;function Sh(t){if(t.length===0)return"0:empty";let e=t.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${t.length}:${tS(e.join(""))}`}function xh(t,e){let n=3735928559^e,o=1103547991^e;for(let r=0;r<t.length;r++){let s=t.charCodeAt(r);n=Math.imul(n^s,2654435761),o=Math.imul(o^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(o^o>>>13,3266489909),o=Math.imul(o^o>>>16,2246822507),o^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&o)+(n>>>0)}function tS(t){let e=xh(t,0).toString(36),n=xh(t,2654435761).toString(36);return`${e}.${n}`}var ec=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=e.onConfirm??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 n;try{n=await e.getTools()}catch(r){return Zl.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}wh(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=oS(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return go("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let y=typeof document<"u"&&!!document.modelContext;return go(y?"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=Ah(e),a;try{a=await r.getTools()}catch(y){let w=y instanceof Error?y.message:String(y);return go(`Failed to read WebMCP registry: ${w}`)}wh(a);let l=a.find(y=>y.name===s);if(!l)return go(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return go(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return go("Aborted by cancel()");let d=Qi(s),p={toolName:s,args:n,description:l.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(p))return go("User declined the tool call.");if(o?.aborted)return go("Aborted by cancel()");let u=new AbortController,g=!1,b=setTimeout(()=>{g=!0,u.abort()},this.timeoutMs),m=()=>u.abort();o&&(o.aborted?u.abort():o.addEventListener("abort",m,{once:!0}));try{let y=await r.executeTool(l,aS(n),{signal:u.signal});return rS(y)}catch(y){if(g)return go(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return go("Aborted by cancel()");let w=y instanceof Error?y.message:String(y);return go(w)}finally{clearTimeout(b),o&&o.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Ch?await Ch():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Zl.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let n=e;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Zl.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){let n=this.confirmHandler??sS;try{return await n(e)}catch(o){return Zl.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>nS(e,o))}},Ah=t=>t.startsWith(Vo)?t.slice(Vo.length):t,Rs=t=>t.startsWith(Vo),nS=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},oS=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},rS=t=>{if(t==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(t)}catch{return{content:[{type:"text",text:t}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:lS(e)}]}},go=t=>({isError:!0,content:[{type:"text",text:t}]}),sS=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=iS(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
177
1074
 
178
1075
  Arguments:
179
1076
  ${e}`:"")+(t.description?`
180
1077
 
181
- ${t.description}`:"");return window.confirm(n)},zb=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},Ub=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},jb=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};function wn(t){return t==="card"?"collapsed":t}function Lr(t){return t.split(";",1)[0].trim().toLowerCase()}function Vb(t,e){if(!t)return;let n=Object.entries(t);for(let[r,s]of n)if(Lr(r)===e)return{mode:wn(s),selector:Lr(r)};let o=`${e.split("/",1)[0]}/*`;for(let[r,s]of n)if(Lr(r)===o)return{mode:wn(s),selector:o}}function qb(t,e){let n=t?.display,o=typeof n=="string"?{default:n}:n??{};if(e.file&&o.files){if(typeof o.files=="string")return{mode:wn(o.files),matchedBy:{type:"files"}};let l=e.file.mimeType?Lr(e.file.mimeType):void 0,p=l?Vb(o.files.byMediaType,l):void 0;if(l&&p)return{mode:p.mode,matchedBy:{type:"mediaType",mediaType:l,selector:p.selector}};if(o.files.default)return{mode:wn(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[e.artifactType];if(r)return{mode:wn(r),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let s=o.byType?.[e.artifactType];if(s)return{mode:wn(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let i=e.presentation?.preferredMode;return i?{mode:wn(i),matchedBy:{type:"preferredMode"}}:o.default?{mode:wn(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function xo(t,e){return qb(t,e).mode}function Ls(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var Kb="agent_",Gb="flow_";function Du(t){return t.startsWith(Kb)?{kind:"agentId",agentId:t}:t.startsWith(Gb)?{kind:"flowId",flowId:t}:null}function Ou(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let i=n.slice(0,o),l=n.slice(o+1);if(i==="runtype"){let c=Du(l);if(c)return c;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let p=e?.[i];if(!p)throw new Error(`[Persona] No target provider registered for "${i}". Add a \`targetProviders.${i}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(l).payload}}let r=Du(n);if(r)return r;let s=e?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var wo=require("partial-json");Ye();var lc="ask_user_question",Ps=8,Pr="data-persona-ask-sheet-for",Qb="Other",Xb="Other\u2026",_u="Type your own answer here",$u="Send",Yb="Next",Jb="Back",Zb="Submit all",ey="Skip",ty=3,cc="data-ask-current-index",dc="data-ask-question-count",zu="data-ask-answers",pc="data-ask-grouped",Uu="data-ask-layout",ny=t=>t.layout==="pills"?"pills":"rows",oy=t=>t.getAttribute(Uu)==="pills"?"pills":"rows",Fu=!1,ju=t=>t.replace(/["\\]/g,"\\$&"),Yo=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===lc,uc=t=>t?.features?.askUserQuestion??{},Ir=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,wo.parse)(r,wo.STR|wo.OBJ|wo.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Is=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>Ps&&!Fu&&(Fu=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Ps}.`)),e.slice(0,Ps)},ry=t=>Is(t)[0]??null,sy=(t,e)=>Is(t)[e]??null,iy=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Vu=(t,e,n)=>{if(t!=="rows")return null;let o=v("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=v("span","persona-ask-row-check");o.appendChild(r)}else{let r=v("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},ay=(t,e,n,o)=>{let s=v("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let i=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=t.label,i.appendChild(l),t.description){let c=v("span","persona-ask-row-description");c.textContent=t.description,i.appendChild(c)}s.appendChild(i);let p=Vu(n,o,e);p&&s.appendChild(p)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},ly=t=>{let n=v("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},cy=(t,e,n,o)=>{let s=v("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let i=!!t?.multiSelect,p=(Array.isArray(t?.options)?t.options:[]).filter(d=>d&&typeof d.label=="string"&&d.label.length>0);if(p.length===0&&!n){for(let d=0;d<ty;d++)s.appendChild(ly(o));return s}if(p.forEach((d,g)=>{s.appendChild(ay(d,g,o,i))}),t?.allowFreeText!==!1){let d=o==="rows"?Qb:Xb;if(o==="rows"){let g=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");g.setAttribute("data-ask-user-action","focus-free-text"),g.setAttribute("data-option-index",String(p.length)),g.setAttribute("data-ask-other-row","true");let b=v("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=e.freeTextPlaceholder??_u,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",e.freeTextLabel??d),b.appendChild(f),g.appendChild(b);let y=Vu(o,i,p.length);y&&g.appendChild(y),s.appendChild(g)}else{let g=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");g.type="button",g.setAttribute("data-ask-user-action","open-free-text"),g.textContent=e.freeTextLabel??d,s.appendChild(g)}}return s},qu=(t,e)=>{let o=v("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=t.freeTextPlaceholder??_u,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=v("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??$u,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},dy=t=>{let e=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=v("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??$u,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},py=(t,e,n)=>{let o=v("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=v("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Jb,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=v("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=n.skipLabel??ey,i.setAttribute("data-ask-user-action","skip"),s.appendChild(i);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=t===e-1;return l.textContent=p?n.submitAllLabel??Zb:n.nextLabel??Yb,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Jo=t=>{let e=t.getAttribute(zu);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},Ku=(t,e)=>{t.setAttribute(zu,JSON.stringify(e))},Cn=t=>{let e=Number(t.getAttribute(cc)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},uy=(t,e)=>{t.setAttribute(cc,String(Math.max(0,Math.floor(e))))},Rr=t=>{let e=Number(t.getAttribute(dc)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},Co=t=>t.getAttribute(pc)==="true",gy=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((r,s)=>{let i=typeof r?.question=="string"?r.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let l=n[i];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},fy=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},Zi=(t,e)=>{let{payload:n}=Ir(e),o=Is(n),r=Jo(t),s={},i=new Set;return o.forEach((l,p)=>{let c=typeof l?.question=="string"?l.question:"";c&&(i.has(c)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),i.add(c),Object.prototype.hasOwnProperty.call(r,p)&&(s[c]=r[p]))}),s},Gu=t=>{let e=Jo(t),n=Cn(t),o=e[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let c=p.getAttribute("data-option-label")??"",d=r.has(c);p.setAttribute("aria-pressed",d?"true":"false"),p.classList.toggle("persona-ask-pill-selected",d)});let i=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),l=t.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!i.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},Qu=t=>{if(!Co(t))return;let e=Jo(t),n=Cn(t),o=e[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let i=t.querySelector('[data-ask-user-action="submit-multi"]');if(i){let l=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));i.disabled=l.length===0}},gc=(t,e,n)=>{let o=uc(n),r=oy(t),{payload:s,complete:i}=Ir(e),l=Co(t),p=Cn(t),c=Rr(t),d=l?sy(s,p):ry(s),g=!!d?.multiSelect,b=t.querySelector('[data-ask-step-inline="true"]');b&&(b.textContent=l?`${p+1}/${c}`:"");let f=t.querySelector('[data-ask-stepper="true"]');f&&f.remove();let y=t.querySelector('[data-ask-question="true"]');if(y){let S=typeof d?.question=="string"?d.question:"";y.textContent=S,y.classList.toggle("persona-ask-question-skeleton",!S&&!i)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let S=cy(d,o,i,r);C.replaceWith(S)}if(r!=="rows"){let S=t.querySelector('[data-ask-free-text-row="true"]');S&&S.replaceWith(qu(o,r))}let M=t.querySelector('[data-ask-multi-actions="true"]');!l&&g&&!M?t.appendChild(dy(o)):(!g||l)&&M&&M.remove(),t.setAttribute("data-multi-select",g?"true":"false");let I=t.querySelector('[data-ask-nav-row="true"]');if(l){let S=py(p,c,o);I?I.replaceWith(S):t.appendChild(S)}else I&&I.remove();Gu(t),Qu(t)},my=(t,e,n)=>{let o=uc(e),r=ny(o),s=t.toolCall.id,i=Is(n),l=Math.max(1,i.length),p=l>1,c=gy(t,i),d=p?fy(t,l):0,g=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(Pr,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",t.id),g.setAttribute(dc,String(l)),g.setAttribute(cc,String(d)),g.setAttribute(pc,p?"true":"false"),g.setAttribute(Uu,r),Ku(g,c),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),iy(g,o);let b=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=v("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",b.appendChild(f);let y=v("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",b.appendChild(y),g.appendChild(b);let M=v("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),g.appendChild(M),r!=="rows"&&g.appendChild(qu(o,r)),gc(g,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},hy=(t,e,n)=>{let{payload:o}=Ir(e),r=Math.max(1,Is(o).length);r>Rr(t)&&(t.setAttribute(dc,String(r)),r>1&&!Co(t)&&t.setAttribute(pc,"true")),gc(t,e,n)};var ea=(t,e,n)=>{if(!n||!Yo(t)||uc(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${Pr}]`).forEach(c=>{c.getAttribute(Pr)!==r&&c.remove()});let i=n.querySelector(`[${Pr}="${ju(r)}"]`);if(i){hy(i,t,e);return}let{payload:l}=Ir(t),p=my(t,e,l);n.appendChild(p)},Wr=(t,e)=>{if(!t)return;let n=e?`[${Pr}="${ju(e)}"]`:`[${Pr}]`;t.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},fc=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),Ao=(t,e)=>{let n=Jo(t),o=Cn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,Ku(t,n),Gu(t),Qu(t)},ta=(t,e,n,o)=>{let r=Rr(t),s=Math.max(0,Math.min(r-1,o));uy(t,s),gc(t,e,n)};var eo="suggest_replies";var by={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},Yu={name:eo,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:by,origin:"sdk",annotations:{readOnlyHint:!0}},mc=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Rs=t=>t.variant==="tool"&&t.toolCall?.name===eo,yy=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let i={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(i.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(i.description=s.description.trim()),[i]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},Ju=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!Rs(n))continue;let o=yy(n.toolCall?.args);return o.length>0?o:null}return null},Xu=new Set,vy=(t,e,n)=>{let o=`${t}:${e}:${n}`;Xu.has(o)||(Xu.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},So=t=>{let e=t?.suggestions?.followUps,n=t?.features?.suggestReplies,o=i=>{let l=e?.[i],p=n?.[i];l===void 0||p===void 0||l!==p&&vy(i,p,l)};t&&(o("enabled"),o("expose"));let r=e?.enabled??n?.enabled??!0,s=r?e?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var xy={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Ps,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},wy={name:lc,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:xy,origin:"sdk",annotations:{readOnlyHint:!0}},na=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(wy),So(t).expose&&e.push(Yu),e};var Hr=require("partial-json"),Zu=t=>t.replace(/\\n/g,`
182
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Mo=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},Cy=t=>{let e=t.completedAt??Date.now(),n=t.startedAt??e,r=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},eg=t=>t.status==="complete"?Cy(t):t.status==="pending"?"Waiting":"",Ay=t=>{let n=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var tg=t=>t.status==="complete"?Ay(t):"Using tool...",oa=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Hs=t=>{let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return oa(e)},ra=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return oa(e)},hc=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=Hs(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},sa=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,i;for(;(i=r.exec(n))!==null;)i.index>s&&Ws(o,n.slice(s,i.index),[]),i[1]!==void 0?Ws(o,i[1],["bold"]):i[2]!==void 0?Ws(o,i[2],["italic"]):i[3]!==void 0&&Ws(o,i[3],["dim"]),s=i.index+i[0].length;return s<n.length&&Ws(o,n.slice(s),[]),o},Ws=(t,e,n)=>{let o=e.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&t.push({text:o[r],styles:n}),r<o.length-1&&t.push({text:"{duration}",styles:n,isDuration:!0})},Sy=()=>{let t=null,e=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
183
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(i);if(l&&l[1])try{return l[1].replace(/\\n/g,`
184
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>t,processChunk:async o=>{if(o.length<=e)return t!==null?{text:t,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(t=s),e=o.length,t!==null?{text:t,raw:o}:null},close:async()=>{}}},Bs=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},ng=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},og=()=>{let t=Sy();return{processChunk:async e=>{let n=e.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(e)},getExtractedText:t.getExtractedText.bind(t),close:t.close?.bind(t)}},rg=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let r=(0,Hr.parse)(n,Hr.STR|Hr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?Zu(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=Zu(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var sg=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let o=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(t=o[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var ig="4.17.0";var Ds=ig;var Ty="https://api.runtype.com/v1/dispatch",ia="https://api.runtype.com";function Ey(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let r=e.indexOf("/");if(r>0){let s=e.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var bc=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function ky(t){switch(t){case"json":return rg;case"regex-json":return og;case"xml":return sg;default:return ng}}var ag=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function Ly(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let r=ag(n);if(!ag(o))return t;if(!r||o===n||o.startsWith(n))return e;let i=Bs(t);return Bs(e)!==null&&i===null?e:t}var Os=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??Ty,this.headers={"Content-Type":"application/json","X-Persona-Version":Ds,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??ky(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=e.webmcp?.enabled===!0?new Ji(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:e,flowId:n};let s=Ou(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(e){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ia}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let e=await this.sessionInitPromise;return this.clientSession=e,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){let e=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ds},body:JSON.stringify(r)});if(!s.ok){let l=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${l.hint||l.error}`):s.status===403?new Error(`Origin not allowed: ${l.hint||l.error}`):new Error(l.error||"Failed to initialize session")}let i=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(i.sessionId),{sessionId:i.sessionId,expiresAt:new Date(i.expiresAt),flow:i.flow,config:{welcomeMessage:i.config.welcomeMessage,placeholder:i.config.placeholder,theme:i.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ia}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ds},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}async dispatch(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let c=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:c}),c}let r=await this.buildPayload(e.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([c])=>c!=="sessionId"&&c!=="session_id")):void 0,i={sessionId:o.sessionId,messages:e.messages.filter(bc).map(c=>({id:c.id,role:c.role,content:c.contentParts??c.llmContent??c.rawContent??c.content})),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:l,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,c=>{let d={...i,...c};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Ds},body:JSON.stringify(d),signal:e.signal})});if(!l.ok){let c=await l.json().catch(()=>({error:"Chat request failed"}));if(l.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let g=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:g}),g}if(l.status===429){let g=new Error(c.hint||"Message limit reached for this session.");throw n({type:"error",error:g}),g}let d=new Error(c.error||"Failed to send message");throw n({type:"error",error:d}),d}if(!l.body){let c=new Error("No response body received");throw n({type:"error",error:c}),c}p(),n({type:"status",status:"connected"});try{await this.streamResponse(l.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();r={...r,...i}}catch(i){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(i){let l=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||ia}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(r,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,r){let s=!!(n&&n.length>0),i=s?Hu(n):void 0,l=this.clientToolsFingerprintSessionId===e,p=s&&l&&this.lastSentClientToolsFingerprint===i,c=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,d=!1,g;for(let b=0;;b++){if(g=await o({...s&&(d||!p)&&n?{clientTools:n}:{},...c?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),g.status===409&&b===0&&s&&(await g.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){d=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=i??null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:c&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||ia}/resume`,i;r&&(i=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let p={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(i&&(p.sessionId=i),r&&i){let c=[...na(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:d,commit:g}=await this.sendWithClientToolsDiff(i,c,b=>{let f={...p,...b};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(s,{method:"POST",headers:l,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return d.ok&&g(),d}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:e,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(e){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=e.slice().filter(bc).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let c=new Date(l.createdAt).getTime(),d=new Date(p.createdAt).getTime();return c-d}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...na(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let i=await this.buildContextAggregate(e);return i&&(r.context=i),r}async buildPayload(e){let n=e.slice().filter(bc).sort((l,p)=>{let c=new Date(l.createdAt).getTime(),d=new Date(p.createdAt).getTime();return c-d}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,p]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=p);let s=[...na(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let i=await this.buildContextAggregate(e);if(i&&(r.context=i),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let p=l;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(e,n,o,r,s,i){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);if(l===null)return!1;let p=d=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...d!==void 0&&{partId:d}};return o.current=g,r(g),g},c=d=>o.current?o.current:p(d);if(l.text!==void 0){l.partId!==void 0&&i.current!==null&&l.partId!==i.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(l.partId)),l.partId!==void 0&&(i.current=l.partId);let d=c(l.partId);l.partId!==void 0&&!d.partId&&(d.partId=l.partId),d.content+=l.text,r(d)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),i.current=null,n({type:"status",status:"idle"})),l.error&&(i.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(e,n,o,r){let s=e.getReader(),i=new TextDecoder,l="",p=Date.now(),c=0,d=()=>p+c++,g=k=>{let W=k.reasoning?{...k.reasoning,chunks:[...k.reasoning.chunks]}:void 0,h=k.toolCall?{...k.toolCall,chunks:k.toolCall.chunks?[...k.toolCall.chunks]:void 0}:void 0,O=k.tools?k.tools.map(R=>({...R,chunks:R.chunks?[...R.chunks]:void 0})):void 0;return{...k,reasoning:W,toolCall:h,tools:O}},b=k=>{if(k.role!=="assistant"||k.variant)return!0;let W=Array.isArray(k.contentParts)&&k.contentParts.length>0,h=typeof k.rawContent=="string"&&k.rawContent.trim()!=="";return typeof k.content=="string"&&k.content.trim()!==""||W||h||!!k.stopReason},f=k=>{b(k)&&n({type:"message",message:g(k)})},y=null,C=null,M={current:null},I={current:null},S=null,E="",L=new Map,D=new Map,z=new Map,$=new Map,F=new Map,B={lastId:null,byStep:new Map},H={lastId:null,byCall:new Map},w=k=>{if(k==null)return null;try{return String(k)}catch{return null}},N=k=>w(k.stepId??k.step_id??k.step??k.parentId??k.flowStepId??k.flow_step_id),K=k=>w(k.callId??k.call_id??k.requestId??k.request_id??k.toolCallId??k.tool_call_id??k.stepId??k.step_id),te=o,Q=!1,se=()=>{if(y)return y;let k,W="",h=S;return!Q&&te?(k=te,Q=!0,W=r??""):te&&h?k=`${te}_${h}`:k=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:k,role:"assistant",content:W,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},f(y),y},J=(k,W)=>{B.lastId=W,k&&B.byStep.set(k,W)},oe=(k,W)=>{let h=k.reasoningId??k.id,O=N(k);if(h){let _=String(h);return J(O,_),_}if(O){let _=B.byStep.get(O);if(_)return B.lastId=_,_}if(B.lastId&&!W)return B.lastId;if(!W)return null;let R=`reason-${d()}`;return J(O,R),R},Y=k=>{let W=$.get(k);if(W)return W;let h={id:`reason-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:k,status:"streaming",chunks:[]}};return $.set(k,h),f(h),h},pe=(k,W)=>{H.lastId=W,k&&H.byCall.set(k,W)},ne=new Set,me=new Map,ve=new Set,be=new Map,Te=k=>{if(!k)return!1;let W=k.replace(/_+/g,"_").replace(/^_|_$/g,"");return W==="emit_artifact_markdown"||W==="emit_artifact_component"},ze=(k,W)=>{let h=k.toolId??k.id,O=K(k);if(h){let _=String(h);return pe(O,_),_}if(O){let _=H.byCall.get(O);if(_)return H.lastId=_,_}if(H.lastId&&!W)return H.lastId;if(!W)return null;let R=`tool-${d()}`;return pe(O,R),R},Oe=k=>{let W=F.get(k);if(W)return W;let h={id:`tool-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:k,status:"pending"}};return F.set(k,h),f(h),h},Ne=k=>{if(typeof k=="number"&&Number.isFinite(k))return k;if(typeof k=="string"){let W=Number(k);if(!Number.isNaN(W)&&Number.isFinite(W))return W;let h=Date.parse(k);if(!Number.isNaN(h))return h}return Date.now()},Be=k=>{if(typeof k=="string")return k;if(k==null)return"";try{return JSON.stringify(k)}catch{return String(k)}},Ue=new Map,Me=new Map,Ee=new Map,Ve=(k,W,h)=>{let O=Ee.get(k);O||(O=[],Ee.set(k,O));let R=0,_=O.length;for(;R<_;){let q=R+_>>>1;O[q].seq<W?R=q+1:_=q}O[R]?.seq===W?O[R]={seq:W,text:h}:O.splice(R,0,{seq:W,text:h});let Z="";for(let q=0;q<O.length;q++)Z+=O[q].text;return Z},Jt=(k,W)=>{let h=Be(W),O=Me.get(k.id),R=Ly(O,h);k.rawContent=R;let _=Ue.get(k.id),Z=fe=>{let Ie=k.content??"";fe.trim()!==""&&(Ie.trim().length===0||fe.startsWith(Ie)||fe.trimStart().startsWith(Ie.trim()))&&(k.content=fe)},q=()=>{if(_){let fe=_.close?.();fe instanceof Promise&&fe.catch(()=>{})}Ue.delete(k.id),Me.delete(k.id),k.streaming=!1,f(k)};if(!_){Z(h),q();return}let ee=Bs(R);if(ee!==null&&ee.trim()!==""){Z(ee),q();return}let ge=fe=>{let Ie=typeof fe=="string"?fe:fe?.text??null;if(Ie!==null&&Ie.trim()!=="")return Ie;let Ke=_.getExtractedText();return Ke!==null&&Ke.trim()!==""?Ke:h},qe;try{qe=_.processChunk(R)}catch{Z(h),q();return}if(qe instanceof Promise){qe.then(fe=>{Z(ge(fe)),q()}).catch(()=>{Z(h),q()});return}Z(ge(qe)),q()},bt=null,Nt=(k,W,h,O)=>{k.rawContent=W,Ue.has(k.id)||Ue.set(k.id,this.createStreamParser());let R=Ue.get(k.id),_=W.trim().startsWith("{")||W.trim().startsWith("[");if(_&&Me.set(k.id,W),R.__isPlainTextParser===!0){k.content=O!==void 0?W:k.content+h,Me.delete(k.id),Ue.delete(k.id),k.rawContent=void 0,f(k);return}let q=R.processChunk(W);if(q instanceof Promise)q.then(ee=>{let ge=typeof ee=="string"?ee:ee?.text??null;ge!==null&&ge.trim()!==""?(k.content=ge,f(k)):!_&&!W.trim().startsWith("<")&&(k.content=O!==void 0?W:k.content+h,Me.delete(k.id),Ue.delete(k.id),k.rawContent=void 0,f(k))}).catch(()=>{k.content=O!==void 0?W:k.content+h,Me.delete(k.id),Ue.delete(k.id),k.rawContent=void 0,f(k)});else{let ee=typeof q=="string"?q:q?.text??null;ee!==null&&ee.trim()!==""?(k.content=ee,f(k)):!_&&!W.trim().startsWith("<")&&(k.content=O!==void 0?W:k.content+h,Me.delete(k.id),Ue.delete(k.id),k.rawContent=void 0,f(k))}},Mn=(k,W)=>{let h=W??k.content;if(h==null||h===""){k.streaming=!1,f(k);return}let R=Me.get(k.id)??Be(h);k.rawContent=R;let _=Ue.get(k.id),Z=null,q=!1;if(_&&(Z=_.getExtractedText(),Z===null&&(Z=Bs(R)),Z===null)){let ee=_.processChunk(R);ee instanceof Promise?(q=!0,ee.then(ge=>{let qe=typeof ge=="string"?ge:ge?.text??null;qe!==null&&(k.content=qe,k.streaming=!1,Ue.delete(k.id),Me.delete(k.id),f(k))}).catch(()=>{})):Z=typeof ee=="string"?ee:ee?.text??null}if(!q){Z!==null&&Z.trim()!==""?k.content=Z:Me.has(k.id)||(k.content=Be(h));let ee=Ue.get(k.id);if(ee){let ge=ee.close?.();ge instanceof Promise&&ge.catch(()=>{}),Ue.delete(k.id)}Me.delete(k.id),k.streaming=!1,f(k)}},Tn=(k,W,h)=>{let O=D.get(k);if(O)return O;let R={id:`nested-${W}-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...h?{variant:h}:{},...h==="reasoning"?{reasoning:{id:k,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:W}};return D.set(k,R),f(R),R},nt=[],Pe,xe=new Map,ot=0,ke="agent",Ce=!1,ce=null,Ae=null,En=new Map,ae=this.config.iterationDisplay??"separate";for(Pe=()=>{for(let k=0;k<nt.length;k++){let W=nt[k].payloadType,h=nt[k].payload;if(!Ce&&ke!=="flow"&&typeof h.stepType=="string"&&(ke="flow"),W==="reasoning_start"){let O=typeof h.id=="string"?h.id:null,R=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(O&&R){L.set(O,R),Tn(O,R,"reasoning");continue}let _=oe(h,!0)??`reason-${d()}`,Z=Y(_);Z.reasoning=Z.reasoning??{id:_,status:"streaming",chunks:[]},Z.reasoning.startedAt=Z.reasoning.startedAt??Ne(h.startedAt??h.timestamp),Z.reasoning.completedAt=void 0,Z.reasoning.durationMs=void 0,(h.scope==="loop"||h.scope==="turn")&&(Z.reasoning.scope=h.scope),Z.streaming=!0,Z.reasoning.status="streaming",f(Z)}else if(W==="reasoning_delta"){let O=typeof h.id=="string"?h.id:null;if(O&&L.has(O)&&D.has(O)){let q=D.get(O),ee=h.reasoningText??h.text??h.delta??"";ee&&h.hidden!==!0&&q.reasoning&&(q.reasoning.chunks.push(String(ee)),f(q));continue}let R=oe(h,!1)??oe(h,!0)??`reason-${d()}`,_=Y(R);_.reasoning=_.reasoning??{id:R,status:"streaming",chunks:[]},_.reasoning.startedAt=_.reasoning.startedAt??Ne(h.startedAt??h.timestamp);let Z=h.reasoningText??h.text??h.delta??"";if(Z&&h.hidden!==!0){let q=typeof h.sequenceIndex=="number"?h.sequenceIndex:void 0;if(q!==void 0){let ee=Ve(R,q,String(Z));_.reasoning.chunks=[ee]}else _.reasoning.chunks.push(String(Z))}if(_.reasoning.status=h.done?"complete":"streaming",h.done){_.reasoning.completedAt=Ne(h.completedAt??h.timestamp);let q=_.reasoning.startedAt??Date.now();_.reasoning.durationMs=Math.max(0,(_.reasoning.completedAt??Date.now())-q)}_.streaming=_.reasoning.status!=="complete",f(_)}else if(W==="reasoning_complete"){let O=typeof h.id=="string"?h.id:null;if(O&&L.has(O)&&D.has(O)){let ee=D.get(O);if(ee.reasoning){let ge=typeof h.text=="string"?h.text:"";ge&&ee.reasoning.chunks.length===0&&ee.reasoning.chunks.push(ge),ee.reasoning.status="complete",ee.streaming=!1,f(ee)}L.delete(O),D.delete(O);continue}let R=oe(h,!1)??oe(h,!0)??`reason-${d()}`,_=typeof h.text=="string"?h.text:"";!$.get(R)&&(_||h.scope==="loop")&&Y(R);let Z=$.get(R);if(Z?.reasoning){(h.scope==="loop"||h.scope==="turn")&&(Z.reasoning.scope=h.scope),_&&Z.reasoning.chunks.length===0&&Z.reasoning.chunks.push(_),Z.reasoning.status="complete",Z.reasoning.completedAt=Ne(h.completedAt??h.timestamp);let ee=Z.reasoning.startedAt??Date.now();Z.reasoning.durationMs=Math.max(0,(Z.reasoning.completedAt??Date.now())-ee),Z.streaming=!1,f(Z)}let q=N(h);q&&B.byStep.delete(q)}else if(W==="tool_start"){y&&(y.streaming=!1,f(y),y=null),typeof h.iteration=="number"&&(ot=h.iteration);let O=(typeof h.toolCallId=="string"?h.toolCallId:void 0)??ze(h,!0)??`tool-${d()}`,R=h.toolName??h.name;if(Te(R)){ne.add(O);continue}pe(K(h),O);let _=Oe(O),Z=_.toolCall??{id:O,status:"pending"};Z.name=R??Z.name,Z.status="running",h.parameters!==void 0?Z.args=h.parameters:h.args!==void 0&&(Z.args=h.args),Z.startedAt=Z.startedAt??Ne(h.startedAt??h.timestamp),Z.completedAt=void 0,Z.durationMs=void 0,_.toolCall=Z,_.streaming=!0,h.executionId&&(_.agentMetadata={executionId:h.executionId,iteration:h.iteration}),f(_)}else if(W==="tool_output_delta"){let O=ze(h,!1)??ze(h,!0)??`tool-${d()}`;if(ne.has(O))continue;let R=Oe(O),_=R.toolCall??{id:O,status:"running"};_.startedAt=_.startedAt??Ne(h.startedAt??h.timestamp);let Z=h.text??h.delta??h.message??"";Z&&(_.chunks=_.chunks??[],_.chunks.push(String(Z))),_.status="running",R.toolCall=_,R.streaming=!0;let q=h.agentContext;(q||h.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:q?.executionId??h.executionId,iteration:q?.iteration??h.iteration}),f(R)}else if(W==="tool_complete"){let O=ze(h,!1)??ze(h,!0)??`tool-${d()}`;if(ne.has(O)){ne.delete(O);continue}let R=Oe(O),_=R.toolCall??{id:O,status:"running"};_.status="complete",h.result!==void 0&&(_.result=h.result),typeof h.duration=="number"&&(_.duration=h.duration),_.completedAt=Ne(h.completedAt??h.timestamp);let Z=h.duration??h.executionTime;if(typeof Z=="number")_.durationMs=Z;else{let ge=_.startedAt??Date.now();_.durationMs=Math.max(0,(_.completedAt??Date.now())-ge)}R.toolCall=_,R.streaming=!1;let q=h.agentContext;(q||h.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:q?.executionId??h.executionId,iteration:q?.iteration??h.iteration}),f(R);let ee=K(h);ee&&H.byCall.delete(ee)}else if(W==="await"&&h.toolName){let O=typeof h.toolCallId=="string"&&h.toolCallId.length>0?h.toolCallId:void 0,R=O??h.toolId??`local-${d()}`,_=Oe(R),Z=h.toolName,q=h.origin==="webmcp"&&!kr(Z)?`webmcp:${Z}`:Z,ee=kr(q),ge=_.toolCall??{id:R,status:"pending"};ge.name=q,ge.args=h.parameters,ge.status=ee?"running":"complete",ge.chunks=ge.chunks??[],ge.startedAt=ge.startedAt??Ne(h.startedAt??h.timestamp??h.awaitedAt),ee?(ge.completedAt=void 0,ge.duration=void 0,ge.durationMs=void 0):ge.completedAt=ge.completedAt??ge.startedAt,_.toolCall=ge,_.streaming=!1,_.agentMetadata={..._.agentMetadata,executionId:h.executionId??_.agentMetadata?.executionId,awaitingLocalTool:!0,...O?{webMcpToolCallId:O}:{}},f(_)}else if(W==="text_start"){let O=typeof h.id=="string"?h.id:null,R=typeof h.parentToolCallId=="string"&&h.parentToolCallId?h.parentToolCallId:null;if(O&&R){L.set(O,R);continue}let _=y;_&&(ke==="flow"?(Mn(_),bt=_):(_.streaming=!1,f(_)),y=null),S=typeof h.id=="string"?h.id:S,E=""}else if(W==="text_delta"){let O=typeof h.id=="string"?h.id:null,R=O?L.get(O):void 0;if(O&&R){let Z=typeof h.delta=="string"?h.delta:"",q=(z.get(O)??"")+Z;if(z.set(O,q),q.trim()==="")continue;let ee=Tn(O,R);ee.agentMetadata={...ee.agentMetadata,executionId:h.executionId,parentToolId:R},Nt(ee,q,Z,void 0);continue}if(S=typeof h.id=="string"?h.id:S,ke==="flow"){let Z=typeof h.delta=="string"?h.delta:"";if(E+=Z,E.trim()==="")continue;let q=se();q.agentMetadata={executionId:h.executionId,iteration:h.iteration},Nt(q,E,Z,void 0),C=q;continue}let _=se();_.content+=h.delta??"",_.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:ce??void 0,agentName:Ae?.agentName},C=_,f(_)}else if(W==="text_complete"){let O=typeof h.id=="string"?h.id:null;if(O&&L.has(O)){let _=D.get(O);_&&Mn(_),L.delete(O),z.delete(O),D.delete(O);continue}let R=y;R&&(ke==="flow"?(Mn(R),bt=R):((R.content??"")===""&&typeof h.text=="string"&&(R.content=h.text),R.streaming=!1,f(R)),y=null),S=null,E=""}else if(W==="step_complete"){let O=h.stepType,R=h.executionType;if(O==="tool"||R==="context")continue;if(h.success===!1){let _=h.error,Z=typeof _=="string"&&_!==""?_:_!=null&&typeof _=="object"&&Reflect.has(_,"message")?String(_.message??"Step failed"):"Step failed";n({type:"error",error:new Error(Z)});let q=y;q&&q.streaming&&(q.streaming=!1,f(q)),n({type:"status",status:"idle"});continue}{let _=bt;bt=null;let Z=h.stopReason,q=h.result?.response;if(_)Z&&(_.stopReason=Z),q!=null?Jt(_,q):_.streaming!==!1&&(Ue.delete(_.id),Me.delete(_.id),_.streaming=!1,f(_));else{let ee=q!=null&&q!=="";if(ee||Z){let ge=se();Z&&(ge.stopReason=Z),ee?Mn(ge,q):(ge.streaming=!1,f(ge))}}continue}}else if(W==="execution_start")ke=h.kind==="flow"?"flow":"agent",Ce=!0,ke==="agent"&&(Ae={executionId:h.executionId,agentId:h.agentId??"virtual",agentName:h.agentName??"",status:"running",currentIteration:0,maxTurns:h.maxTurns??1,startedAt:Ne(h.startedAt)});else if(W==="turn_start"){let O=typeof h.iteration=="number"?h.iteration:ot;if(O!==ot){if(Ae&&(Ae.currentIteration=O),ae==="separate"&&O>1){let R=y;R&&(R.streaming=!1,f(R),En.set(O-1,R),y=null)}ot=O}ce=typeof h.id=="string"?h.id:null,C=null}else if(W==="tool_input_delta"){let O=h.toolCallId??H.lastId;if(O){let R=F.get(O);R?.toolCall&&(R.toolCall.chunks=R.toolCall.chunks??[],R.toolCall.chunks.push(h.delta??""),f(R))}}else{if(W==="tool_input_complete")continue;if(W==="turn_complete"){let O=h.stopReason,R=y??C;if(O&&R!==null){let _=h.id;(!_||R.agentMetadata?.turnId===_)&&(R.stopReason=O,f(R))}ce===h.id&&(ce=null)}else if(W==="media_start"){let O=String(h.id);xe.set(O,{mediaType:typeof h.mediaType=="string"?h.mediaType:void 0,role:typeof h.role=="string"?h.role:void 0,toolCallId:h.toolCallId,parts:[]})}else if(W==="media_delta"){let O=xe.get(String(h.id));O&&typeof h.delta=="string"&&O.parts.push(h.delta)}else if(W==="media_complete"){let O=String(h.id),R=xe.get(O);xe.delete(O);let _=(typeof h.mediaType=="string"?h.mediaType:void 0)??R?.mediaType??"application/octet-stream",Z=typeof h.data=="string"?h.data:void 0,q=typeof h.url=="string"?h.url:R&&R.parts.length>0?R.parts.join(""):void 0,ee=null;if(Z)ee={type:"media",data:Z,mediaType:_};else if(q){let Ie=_.toLowerCase();ee={type:Ie==="image"||Ie.startsWith("image/")?"image-url":"file-url",url:q,mediaType:_}}let ge=h.toolCallId??R?.toolCallId,qe=ee?[ee]:[],fe=[];for(let Ie of qe){if(!Ie||typeof Ie!="object")continue;let Ke=Ie,je=typeof Ke.type=="string"?Ke.type:void 0,He=typeof Ke.mediaType=="string"?Ke.mediaType.toLowerCase():"",Se=null,rt="";if(je==="media"){let Mt=typeof Ke.data=="string"?Ke.data:void 0;if(!Mt)continue;rt=He.length>0?He:"application/octet-stream",Se=`data:${rt};base64,${Mt}`}else if(je==="image-url"){let Mt=typeof Ke.url=="string"?Ke.url:void 0;if(!Mt)continue;rt=He,Se=Mt}else if(je==="file-url"){let Mt=typeof Ke.url=="string"?Ke.url:void 0;if(!Mt)continue;rt=He,Se=Mt}else continue;if(Se)if(je==="image-url"||rt.startsWith("image/"))fe.push({type:"image",image:Se,...rt.includes("/")?{mimeType:rt}:{}});else if(rt.startsWith("audio/"))fe.push({type:"audio",audio:Se,mimeType:rt});else if(rt.startsWith("video/"))fe.push({type:"video",video:Se,mimeType:rt});else{let Mt=rt||"application/octet-stream";fe.push({type:"file",data:Se,mimeType:Mt,filename:Ey(Mt)})}}if(fe.length>0){let Ie=d(),Ke=ge,He={id:`agent-media-${typeof Ke=="string"&&Ke.length>0?`${Ke}-${Ie}`:String(Ie)}`,role:"assistant",content:"",contentParts:fe,createdAt:new Date().toISOString(),streaming:!1,sequence:Ie,agentMetadata:{executionId:h.executionId,iteration:typeof h.iteration=="number"?h.iteration:ot}};f(He);let Se=y;Se&&(Se.streaming=!1,f(Se)),y=null,M.current=null}}else if(W==="execution_complete"){let O=h.kind??ke;O==="agent"&&Ae&&(Ae.status=h.success?"complete":"error",Ae.completedAt=Ne(h.completedAt),Ae.stopReason=h.stopReason);let R=y;R&&(O==="flow"&&R.streaming!==!1?Mn(R):(R.streaming=!1,f(R)),y=null),S=null,E="",bt=null,n({type:"status",status:"idle",terminal:!0})}else if(W==="execution_error"){let O=typeof h.error=="string"?h.error:h.error?.message??"Execution error";n({type:"error",error:new Error(O)})}else if(W!=="ping"){if(W==="approval_start"){let O=h.approvalId??`approval-${d()}`,R={id:`approval-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:O,status:"pending",agentId:Ae?.agentId??"virtual",executionId:h.executionId??Ae?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};f(R)}else if(W==="step_await"&&h.awaitReason==="approval_required"){let O=h.approvalId??`approval-${d()}`,R={id:`approval-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:O,status:"pending",agentId:Ae?.agentId??"virtual",executionId:h.executionId??Ae?.executionId??"",toolName:h.toolName??"",toolType:h.toolType,description:h.description??`Execute ${h.toolName??"tool"}`,...typeof h.reason=="string"&&h.reason?{reason:h.reason}:{},parameters:h.parameters}};f(R)}else if(W==="approval_complete"){let O=h.approvalId;if(O){let _={id:`approval-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:O,status:h.decision??"approved",agentId:Ae?.agentId??"virtual",executionId:h.executionId??Ae?.executionId??"",toolName:h.toolName??"",description:h.description??"",resolvedAt:Date.now()}};f(_)}}else if(W==="artifact_start"||W==="artifact_delta"||W==="artifact_update"||W==="artifact_complete"){if(W==="artifact_start"){let O=h.artifactType,R=String(h.id),_=typeof h.title=="string"?h.title:void 0,Z=h.file,q;Z&&typeof Z=="object"&&!Array.isArray(Z)&&typeof Z.path=="string"&&typeof Z.mimeType=="string"&&(q={path:Z.path,mimeType:Z.mimeType,...typeof Z.language=="string"?{language:Z.language}:{}}),n({type:"artifact_start",id:R,artifactType:O,title:_,component:typeof h.component=="string"?h.component:void 0,...q?{file:q}:{}});let ee=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?{...h.props}:void 0;if(be.set(R,{markdown:"",title:_,file:q,...ee?{props:ee}:{}}),!ve.has(R)){ve.add(R);let ge=xo(this.config.features?.artifacts,{artifactType:O,...q?{file:q}:{}}),qe=typeof h.component=="string"?h.component:void 0,fe={id:`artifact-ref-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:Ls(ge,{artifactId:R,title:_,artifactType:O,status:"streaming",...q?{file:q}:{},...qe?{component:qe}:{}})};me.set(R,fe),f(fe)}}else if(W==="artifact_delta"){let O=String(h.id),R=typeof h.delta=="string"?h.delta:String(h.delta??"");n({type:"artifact_delta",id:O,artDelta:R});let _=be.get(O);_&&(_.markdown+=R)}else if(W==="artifact_update"){let O=h.props&&typeof h.props=="object"&&!Array.isArray(h.props)?h.props:{};n({type:"artifact_update",id:String(h.id),props:O,component:typeof h.component=="string"?h.component:void 0});let R=be.get(String(h.id));R&&(R.props={...R.props??{},...O})}else if(W==="artifact_complete"){let O=String(h.id);n({type:"artifact_complete",id:O});let R=me.get(O);if(R){R.streaming=!1;try{let _=JSON.parse(R.rawContent??"{}");if(_.props){_.props.status="complete";let Z=be.get(O);Z?.markdown&&(_.props.markdown=Z.markdown),Z?.file&&(_.props.file=Z.file),_.component==="PersonaArtifactInline"&&Z?.props&&Object.keys(Z.props).length>0&&(_.props.componentProps=Z.props)}R.rawContent=JSON.stringify(_)}catch{}be.delete(O),f(R),me.delete(O)}}}else if(W==="transcript_insert"){let O=h.message;if(!O||typeof O!="object")continue;let R=String(O.id??`msg-${d()}`),_=O.role,q={id:R,role:_==="user"?"user":_==="system"?"system":"assistant",content:typeof O.content=="string"?O.content:"",rawContent:typeof O.rawContent=="string"?O.rawContent:void 0,createdAt:typeof O.createdAt=="string"?O.createdAt:new Date().toISOString(),streaming:O.streaming===!0,...typeof O.variant=="string"?{variant:O.variant}:{},sequence:d()};if(f(q),q.rawContent)try{let ge=JSON.parse(q.rawContent)?.props?.artifactId;typeof ge=="string"&&ve.add(ge)}catch{}y=null,M.current=null,Ue.delete(R),Me.delete(R)}else if(W==="error"){if(h.recoverable===!1&&h.error!=null&&h.error!==""){let O=typeof h.error=="string"?h.error:h.error?.message!=null?String(h.error.message):"Execution error";n({type:"error",error:new Error(O)});let R=y;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}else if(W==="step_error"||W==="dispatch_error"||W==="flow_error"){let O=null;if(h.error instanceof Error)O=h.error;else if(W==="dispatch_error"){let R=h.message??h.error;R!=null&&R!==""&&(O=new Error(String(R)))}else{let R=h.error;typeof R=="string"&&R!==""?O=new Error(R):R!=null&&typeof R=="object"&&Reflect.has(R,"message")&&(O=new Error(String(R.message??R)))}if(O){n({type:"error",error:O});let R=y;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}}}}nt.length=0};;){let{done:k,value:W}=await s.read();if(k)break;l+=i.decode(W,{stream:!0});let h=l.split(`
1078
+ ${t.description}`:"");return window.confirm(n)},iS=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},aS=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},lS=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};function no(t){return t==="card"?"collapsed":t}function Ws(t){return t.split(";",1)[0].trim().toLowerCase()}function cS(t,e){if(!t)return;let n=Object.entries(t);for(let[r,s]of n)if(Ws(r)===e)return{mode:no(s),selector:Ws(r)};let o=`${e.split("/",1)[0]}/*`;for(let[r,s]of n)if(Ws(r)===o)return{mode:no(s),selector:o}}function dS(t,e){let n=t?.display,o=typeof n=="string"?{default:n}:n??{};if(e.file&&o.files){if(typeof o.files=="string")return{mode:no(o.files),matchedBy:{type:"files"}};let l=e.file.mimeType?Ws(e.file.mimeType):void 0,d=l?cS(o.files.byMediaType,l):void 0;if(l&&d)return{mode:d.mode,matchedBy:{type:"mediaType",mediaType:l,selector:d.selector}};if(o.files.default)return{mode:no(o.files.default),matchedBy:{type:"files"}}}let r=o.byKind?.[e.artifactType];if(r)return{mode:no(r),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byKind"}};let s=o.byType?.[e.artifactType];if(s)return{mode:no(s),matchedBy:{type:"kind",kind:e.artifactType,configuredBy:"byType"}};let a=e.presentation?.preferredMode;return a?{mode:no(a),matchedBy:{type:"preferredMode"}}:o.default?{mode:no(o.default),matchedBy:{type:"default"}}:{mode:"panel",matchedBy:{type:"personaDefault"}}}function dr(t,e){return dS(t,e).mode}function Ji(t,e){return JSON.stringify({component:t==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:e.artifactId,title:e.title,artifactType:e.artifactType,status:e.status,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var pS="agent_",uS="flow_";function Mh(t){return t.startsWith(pS)?{kind:"agentId",agentId:t}:t.startsWith(uS)?{kind:"flowId",flowId:t}:null}function Th(t,e){let n=t.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),l=n.slice(o+1);if(a==="runtype"){let p=Mh(l);if(p)return p;throw new Error(`[Persona] target "runtype:${l}" is not a valid Runtype agent_/flow_ id.`)}let d=e?.[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(l).payload}}let r=Mh(n);if(r)return r;let s=e?.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var pr=require("partial-json");Qe();var Xp="ask_user_question",Zi=8,Bs="data-persona-ask-sheet-for",gS="Other",fS="Other\u2026",Ph="Type your own answer here",Lh="Send",mS="Next",hS="Back",yS="Submit all",bS="Skip",vS=3,Qp="data-ask-current-index",Jp="data-ask-question-count",Ih="data-ask-answers",Zp="data-ask-grouped",Hh="data-ask-layout",wS=t=>t.layout==="pills"?"pills":"rows",CS=t=>t.getAttribute(Hh)==="pills"?"pills":"rows",kh=!1,Rh=t=>t.replace(/["\\]/g,"\\$&"),Kr=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===Xp,eu=t=>t?.features?.askUserQuestion??{},Ds=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,pr.parse)(r,pr.STR|pr.OBJ|pr.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ea=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>Zi&&!kh&&(kh=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Zi}.`)),e.slice(0,Zi)},xS=t=>ea(t)[0]??null,SS=(t,e)=>ea(t)[e]??null,AS=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Wh=(t,e,n)=>{if(t!=="rows")return null;let o=v("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=v("span","persona-ask-row-check");o.appendChild(r)}else{let r=v("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},MS=(t,e,n,o)=>{let s=v("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",o?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let a=v("span","persona-ask-row-content"),l=v("span","persona-ask-row-label");if(l.textContent=t.label,a.appendChild(l),t.description){let p=v("span","persona-ask-row-description");p.textContent=t.description,a.appendChild(p)}s.appendChild(a);let d=Wh(n,o,e);d&&s.appendChild(d)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},TS=t=>{let n=v("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},ES=(t,e,n,o)=>{let s=v("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!t?.multiSelect,d=(Array.isArray(t?.options)?t.options:[]).filter(u=>u&&typeof u.label=="string"&&u.label.length>0);if(d.length===0&&!n){for(let u=0;u<vS;u++)s.appendChild(TS(o));return s}if(d.forEach((u,g)=>{s.appendChild(MS(u,g,o,a))}),t?.allowFreeText!==!1){let u=o==="rows"?gS:fS;if(o==="rows"){let g=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");g.setAttribute("data-ask-user-action","focus-free-text"),g.setAttribute("data-option-index",String(d.length)),g.setAttribute("data-ask-other-row","true");let b=v("span","persona-ask-row-content"),m=document.createElement("input");m.type="text",m.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",m.placeholder=e.freeTextPlaceholder??Ph,m.setAttribute("data-ask-free-text-input","true"),m.setAttribute("aria-label",e.freeTextLabel??u),b.appendChild(m),g.appendChild(b);let y=Wh(o,a,d.length);y&&g.appendChild(y),s.appendChild(g)}else{let g=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");g.type="button",g.setAttribute("data-ask-user-action","open-free-text"),g.textContent=e.freeTextLabel??u,s.appendChild(g)}}return s},Bh=(t,e)=>{let o=v("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let r=document.createElement("input");if(r.type="text",r.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",r.placeholder=t.freeTextPlaceholder??Ph,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=v("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??Lh,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},kS=t=>{let e=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=v("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??Lh,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},PS=(t,e,n)=>{let o=v("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let r=v("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??hS,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=v("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??bS,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let l=v("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let d=t===e-1;return l.textContent=d?n.submitAllLabel??yS:n.nextLabel??mS,l.setAttribute("data-ask-user-action",d?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Gr=t=>{let e=t.getAttribute(Ih);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},Dh=(t,e)=>{t.setAttribute(Ih,JSON.stringify(e))},oo=t=>{let e=Number(t.getAttribute(Qp)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},LS=(t,e)=>{t.setAttribute(Qp,String(Math.max(0,Math.floor(e))))},Ns=t=>{let e=Number(t.getAttribute(Jp)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},ur=t=>t.getAttribute(Zp)==="true",IS=(t,e)=>{let n=t.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return e.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let l=n[a];(typeof l=="string"||Array.isArray(l))&&(o[s]=l)}}),o},HS=(t,e)=>{let n=t.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},tc=(t,e)=>{let{payload:n}=Ds(e),o=ea(n),r=Gr(t),s={},a=new Set;return o.forEach((l,d)=>{let p=typeof l?.question=="string"?l.question:"";p&&(a.has(p)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${p}"; later answer wins.`),a.add(p),Object.prototype.hasOwnProperty.call(r,d)&&(s[p]=r[d]))}),s},Nh=t=>{let e=Gr(t),n=oo(t),o=e[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(d=>r.add(d));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{let p=d.getAttribute("data-option-label")??"",u=r.has(p);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>d.getAttribute("data-option-label")??"")),l=t.querySelector('[data-ask-free-text-input="true"]');l&&(typeof o=="string"&&o.length>0&&!a.has(o)?(l.value=o,l.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):l.value="")},Oh=t=>{if(!ur(t))return;let e=Gr(t),n=oo(t),o=e[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let l=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=l.length===0}},tu=(t,e,n)=>{let o=eu(n),r=CS(t),{payload:s,complete:a}=Ds(e),l=ur(t),d=oo(t),p=Ns(t),u=l?SS(s,d):xS(s),g=!!u?.multiSelect,b=t.querySelector('[data-ask-step-inline="true"]');b&&(b.textContent=l?`${d+1}/${p}`:"");let m=t.querySelector('[data-ask-stepper="true"]');m&&m.remove();let y=t.querySelector('[data-ask-question="true"]');if(y){let E=typeof u?.question=="string"?u.question:"";y.textContent=E,y.classList.toggle("persona-ask-question-skeleton",!E&&!a)}let w=t.querySelector('[data-ask-pill-list="true"]');if(w){let E=ES(u,o,a,r);w.replaceWith(E)}if(r!=="rows"){let E=t.querySelector('[data-ask-free-text-row="true"]');E&&E.replaceWith(Bh(o,r))}let T=t.querySelector('[data-ask-multi-actions="true"]');!l&&g&&!T?t.appendChild(kS(o)):(!g||l)&&T&&T.remove(),t.setAttribute("data-multi-select",g?"true":"false");let W=t.querySelector('[data-ask-nav-row="true"]');if(l){let E=PS(d,p,o);W?W.replaceWith(E):t.appendChild(E)}else W&&W.remove();Nh(t),Oh(t)},RS=(t,e,n)=>{let o=eu(e),r=wS(o),s=t.toolCall.id,a=ea(n),l=Math.max(1,a.length),d=l>1,p=IS(t,a),u=d?HS(t,l):0,g=v("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(Bs,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",t.id),g.setAttribute(Jp,String(l)),g.setAttribute(Qp,String(u)),g.setAttribute(Zp,d?"true":"false"),g.setAttribute(Hh,r),Dh(g,p),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),AS(g,o);let b=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=v("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",b.appendChild(m);let y=v("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",b.appendChild(y),g.appendChild(b);let T=v("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),g.appendChild(T),r!=="rows"&&g.appendChild(Bh(o,r)),tu(g,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},WS=(t,e,n)=>{let{payload:o}=Ds(e),r=Math.max(1,ea(o).length);r>Ns(t)&&(t.setAttribute(Jp,String(r)),r>1&&!ur(t)&&t.setAttribute(Zp,"true")),tu(t,e,n)};var nc=(t,e,n)=>{if(!n||!Kr(t)||eu(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${Bs}]`).forEach(p=>{p.getAttribute(Bs)!==r&&p.remove()});let a=n.querySelector(`[${Bs}="${Rh(r)}"]`);if(a){WS(a,t,e);return}let{payload:l}=Ds(t),d=RS(t,e,l);n.appendChild(d)},Os=(t,e)=>{if(!t)return;let n=e?`[${Bs}="${Rh(e)}"]`:`[${Bs}]`;t.querySelectorAll(n).forEach(r=>{r.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(r).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>r.remove(),Number.isFinite(s)?s:180)})},nu=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),gr=(t,e)=>{let n=Gr(t),o=oo(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,Dh(t,n),Nh(t),Oh(t)},oc=(t,e,n,o)=>{let r=Ns(t),s=Math.max(0,Math.min(r-1,o));LS(t,s),tu(t,e,n)};var jo="suggest_replies";var BS={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"object",properties:{label:{type:"string",minLength:1,maxLength:80},prompt:{type:"string",minLength:1,maxLength:500},description:{type:"string",minLength:1,maxLength:160}},required:["label"],additionalProperties:!1}}},required:["suggestions"],additionalProperties:!1},Fh={name:jo,description:"Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the last action after your reply text is complete. Give each suggestion a `label` with the short visible text, an optional `prompt` with the fuller text placed as the user's message (defaults to the label), and an optional `description` with one line of supporting copy. Suggestions are sent as the user's next message, so phrase prompts in the user's voice (e.g. \"Tell me more about pricing\"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.",parametersSchema:BS,origin:"sdk",annotations:{readOnlyHint:!0}},ou=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ta=t=>t.variant==="tool"&&t.toolCall?.name===jo,DS=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e?.suggestions;if(!Array.isArray(n))return[];let o=n.flatMap(r=>{if(typeof r=="string"){let l=r.trim();return l?[l]:[]}if(!r||typeof r!="object")return[];let s=r;if(typeof s.label!="string"||!s.label.trim())return[];let a={label:s.label.trim()};return typeof s.prompt=="string"&&s.prompt.trim()&&(a.prompt=s.prompt.trim()),typeof s.description=="string"&&s.description.trim()&&(a.description=s.description.trim()),[a]});return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},$h=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!ta(n))continue;let o=DS(n.toolCall?.args);return o.length>0?o:null}return null},_h=new Set,NS=(t,e,n)=>{let o=`${t}:${e}:${n}`;_h.has(o)||(_h.add(o),console.warn(`[persona] suggestions.followUps.${t} and features.suggestReplies.${t} disagree; suggestions.followUps.${t} wins.`))},fr=t=>{let e=t?.suggestions?.followUps,n=t?.features?.suggestReplies,o=a=>{let l=e?.[a],d=n?.[a];l===void 0||d===void 0||l!==d&&NS(a,d,l)};t&&(o("enabled"),o("expose"));let r=e?.enabled??n?.enabled??!0,s=r?e?.expose??n?.expose??!1:!1;return{enabled:r,expose:s}};var OS={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Zi,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},_S={name:Xp,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:OS,origin:"sdk",annotations:{readOnlyHint:!0}},rc=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(_S),fr(t).expose&&e.push(Fh),e};var _s=require("partial-json"),zh=t=>t.replace(/\\n/g,`
1079
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),mr=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},FS=t=>{let e=t.completedAt??Date.now(),n=t.startedAt??e,r=(t.durationMs!==void 0?t.durationMs:Math.max(0,e-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Vh=t=>t.status==="complete"?FS(t):t.status==="pending"?"Waiting":"",$S=t=>{let n=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var jh=t=>t.status==="complete"?$S(t):"Using tool...",sc=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},oa=t=>{let e=typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return sc(e)},ic=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return sc(e)},ru=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=oa(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},ac=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&na(o,n.slice(s,a.index),[]),a[1]!==void 0?na(o,a[1],["bold"]):a[2]!==void 0?na(o,a[2],["italic"]):a[3]!==void 0&&na(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&na(o,n.slice(s),[]),o},na=(t,e,n)=>{let o=e.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&t.push({text:o[r],styles:n}),r<o.length-1&&t.push({text:"{duration}",styles:n,isDuration:!0})},zS=()=>{let t=null,e=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
1080
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,l=o.match(a);if(l&&l[1])try{return l[1].replace(/\\n/g,`
1081
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return l[1]}return null};return{getExtractedText:()=>t,processChunk:async o=>{if(o.length<=e)return t!==null?{text:t,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(t=s),e=o.length,t!==null?{text:t,raw:o}:null},close:async()=>{}}},ra=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},qh=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},Uh=()=>{let t=zS();return{processChunk:async e=>{let n=e.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:t.processChunk(e)},getExtractedText:t.getExtractedText.bind(t),close:t.close?.bind(t)}},Kh=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let r=(0,_s.parse)(n,_s.STR|_s.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?zh(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=zh(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var Gh=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let o=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(t=o[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var Yh="4.18.0";var Fs=Yh;var $s="[Image]";function Xh(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join("")}function lc(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function hr(t){return{type:"text",text:t}}function Qh(t,e){return{type:"image",image:t,...e?.mimeType&&{mimeType:e.mimeType},...e?.alt&&{alt:e.alt}}}var Jh=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],jS=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],qo=[...Jh,...jS];function qS(t){return Jh.includes(t)||t.startsWith("image/")}function cc(t){return qS(t.type)}function Zh(t,e,n){return{type:"file",data:t,mimeType:e,filename:n}}async function ey(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;cc(t)?e({type:"image",image:r,mimeType:t.type,alt:t.name}):e({type:"file",data:r,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function ty(t,e=qo,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function US(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function ny(t,e){let n=US(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[t]||n||"FILE"}var KS=["user","assistant","system"],GS=0;function oy(t){if(typeof t!="string"||t==="")return null;let e=Date.parse(t);return Number.isNaN(e)?null:e}function dc(t){return typeof t=="string"?t:void 0}function YS(t){if(typeof t!="object"||t===null)return null;let e=t;switch(e.type){case"text":return typeof e.text=="string"?hr(e.text):null;case"image":return typeof e.image=="string"?Qh(e.image,{mimeType:dc(e.mimeType),alt:dc(e.alt)}):null;case"file":return typeof e.data=="string"&&typeof e.mimeType=="string"&&typeof e.filename=="string"?Zh(e.data,e.mimeType,e.filename):null;case"audio":return typeof e.audio=="string"?{type:"audio",audio:e.audio,...dc(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;case"video":return typeof e.video=="string"?{type:"video",video:e.video,...dc(e.mimeType)!==void 0&&{mimeType:e.mimeType}}:null;default:return null}}function XS(t,e){let n=oy(e),o=t.map(a=>oy(a.timestamp)),r=new Array(t.length),s=0;for(;s<o.length;){let a=o[s];if(a!==null){r[s]=a,s+=1;continue}let l=s;for(;l+1<o.length&&o[l+1]===null;)l+=1;let d=l-s+1,p=s>0?r[s-1]:null,u=l+1<o.length?o[l+1]:null,g=u!==null&&n!==null?Math.min(u,n):u??n;for(let b=0;b<d;b+=1)r[s+b]=g!==null?g-(d-b):p!==null?p+b+1:GS+b;s=l+1}return r.map(a=>new Date(a).toISOString())}function ry(t,e){let n=XS(t,e?.beforeCreatedAt),o=[];return t.forEach((r,s)=>{if(typeof r?.id!="string"||r.id===""||!KS.includes(r.role))return;let a=r.role,l=n[s];if(r.displayAvailable===!1){let d={historyDisplayUnavailable:!0};o.push({id:r.id,role:a,content:"",createdAt:l,agentMetadata:d});return}if(typeof r.displayContent=="string"){o.push({id:r.id,role:a,content:r.displayContent,createdAt:l});return}if(typeof r.content=="string"){o.push({id:r.id,role:a,content:r.content,createdAt:l});return}if(Array.isArray(r.content)){let d=r.content.map(YS).filter(u=>u!==null),p=Xh(d);o.push({id:r.id,role:a,content:p||(lc(d)?$s:""),createdAt:l,...d.length>0&&{contentParts:d}});return}o.push({id:r.id,role:a,content:"",createdAt:l})}),o}function sa(t){let e=t.content;if(typeof e!="string"||e==="")return;let n=t.contentParts??t.llmContent??t.rawContent??e;if(!(typeof n=="string"&&n===e))return e}function ia(t,e){let n=new Map;for(let o of t)n.set(o.id,o);for(let o of e)n.set(o.id,o);return[...n.values()].sort((o,r)=>{let s=new Date(o.createdAt).getTime(),a=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(a)&&s!==a)return s-a;let l=o.sequence??0,d=r.sequence??0;return l!==d?l-d:o.id.localeCompare(r.id)})}var QS="https://api.runtype.com/v1/dispatch",sy="https://api.runtype.com",Ze=class extends Error{constructor(e,n,o){super(n),this.name="HistoryClientError",this.code=e,o?.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=o.retryAfterSeconds)}},iy=32768,su=49152,ay=t=>{let e=t??{},n=typeof e.targetId=="string"?e.targetId:typeof e.flowId=="string"?e.flowId:null;return{id:typeof e.id=="string"?e.id:"",title:typeof e.title=="string"?e.title:"",targetId:n,preview:typeof e.preview=="string"?e.preview:null,messageCount:typeof e.messageCount=="number"?e.messageCount:0,createdAt:typeof e.createdAt=="string"?e.createdAt:"",updatedAt:typeof e.updatedAt=="string"?e.updatedAt:""}},ly=t=>"reason"in t?t.reason:void 0,cy="The identity proof was not admitted; account history is unavailable",dy="The identity proof was rejected",py="The request carried no visitor credential",uy="The stored visitor belongs to a different signed-in user",gy=(t,e)=>t instanceof Ze&&t.code===e;function JS(t){let e=t.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(o)return`attachment.${o}`;let r=e.indexOf("/");if(r>0){let s=e.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var iu=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function ZS(t){switch(t){case"json":return Kh;case"regex-json":return Uh;case"xml":return Gh;default:return qh}}var fy=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function eA(t,e){if(!t)return e;let n=t.trim(),o=e.trim();if(n.length===0)return e;if(o.length===0)return t;let r=fy(n);if(!fy(o))return t;if(!r||o===n||o.startsWith(n))return e;let a=ra(t);return ra(e)!==null&&a===null?e:t}var aa=class{constructor(e={},n={}){this.config=e;this.historyInternals=n;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;this.historyUnavailable=!1;this.historyUnavailableWarned=!1;this.claimInFlight=!1;this.historyIdentityStatus=null;this.historyIdentitySubscribers=new Set;this.historyAvailabilitySubscribers=new Set;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=e.apiUrl??QS,this.headers={"Content-Type":"application/json","X-Persona-Version":Fs,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??ZS(e.parserType),this.contextProviders=e.contextProviders??[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=e.webmcp?.enabled===!0?new ec(e.webmcp):null}updateConfig(e){this.config=e}setHistoryInternals(e){this.historyInternals=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){this.webMcpBridge?.setConfirmHandler(e)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(e,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:e,flowId:n};let s=Th(o,r);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}clientApiBase(){return this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||sy}getClientApiUrl(e){return`${this.clientApiBase()}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let e=await this.sessionInitPromise;return this.clientSession=e,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(e),e}finally{this.sessionInitPromise=null}}isHistoryCapable(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()&&!this.historyUnavailable}async readVisitorToken(){let e=this.historyInternals.visitorStore;return e?(await e.ready,await e.get()??null):null}markHistoryUnavailable(){if(!this.historyUnavailable){this.setHistoryIdentityStatus({state:"unavailable",reason:"history_disabled"}),this.historyUnavailable=!0,!this.historyUnavailableWarned&&typeof console<"u"&&(this.historyUnavailableWarned=!0,console.warn("[Persona] Visitor history is disabled for this surface; continuing without it.")),this.historyInternals.onHistoryAvailabilityChanged?.(!1);for(let e of[...this.historyAvailabilitySubscribers])e(!1)}}getHistoryIdentityStatus(){return this.historyIdentityStatus??this.restingIdentityStatus()}subscribeHistoryIdentityStatus(e){return this.historyIdentitySubscribers.add(e),()=>{this.historyIdentitySubscribers.delete(e)}}subscribeHistoryAvailability(e){return this.historyAvailabilitySubscribers.add(e),this.historyUnavailable&&e(!1),()=>{this.historyAvailabilitySubscribers.delete(e)}}restingIdentityStatus(){return this.isClientTokenMode()?this.config.features?.history?.enabled!==!0||this.historyUnavailable?{state:"unavailable",reason:"history_disabled"}:this.browserOnlyStatus():{state:"unavailable",reason:"ineligible_mode"}}browserOnlyStatus(){let e=this.historyIdentityStatus;return e?.state==="browser_only"?e:this.derivedBrowserOnly()}derivedBrowserOnly(){return this.config.features?.history?.scope==="browser"?{state:"browser_only",reason:"configured_browser_scope"}:this.config.getIdentityProof?{state:"browser_only",reason:"proof_unavailable_before_binding"}:{state:"browser_only",reason:"no_identity_provider"}}setHistoryIdentityStatus(e){let n=this.getHistoryIdentityStatus(),o=n.state===e.state&&ly(n)===ly(e);if(this.historyIdentityStatus=e,!o){this.historyInternals.onHistoryIdentityStatusChanged?.(e);for(let r of[...this.historyIdentitySubscribers])r(e)}}async createClientSession(e){let n=this.isHistoryCapable()&&!e.omitVisitorFields,o=null;n&&(await this.historyInternals.historyBootstrapReady,o=await this.readVisitorToken());let r=this.routing(),s=r.agentId??r.flowId,a=n?e.conversationId:void 0,l={token:this.config.clientToken,...s&&{flowId:s},...n&&{visitorHistory:!0},...n&&o?{visitorToken:o}:{},...n&&e.identityProof?{identityProof:e.identityProof}:{},...a?{conversationId:a}:e.storedSessionId?{sessionId:e.storedSessionId}:{}},d=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Fs},body:JSON.stringify(l)});if(!d.ok){let u=await d.json().catch(()=>({error:"Session initialization failed"}));if(n&&d.status===403&&u.error==="visitor_history_disabled"){if(this.markHistoryUnavailable(),a)throw new Ze("history_disabled","Visitor history is disabled for this surface");return this.createClientSession({...e,omitVisitorFields:!0})}throw n&&d.status===401&&u.error==="visitor_required"?new Ze("visitor_required","Visitor credential no longer resolves"):a&&d.status===404?new Ze("not_found","Conversation not found"):d.status===401?new Error(`Invalid client token: ${u.hint||u.error}`):d.status===403?new Error(`Origin not allowed: ${u.hint||u.error}`):new Error(u.error||"Failed to initialize session")}let p=await d.json();return p.visitor?.token&&await this.historyInternals.visitorStore?.set(p.visitor.token),{sessionId:p.sessionId,expiresAt:new Date(p.expiresAt),flow:p.flow,...p.conversationId?{conversationId:p.conversationId}:{},...p.targetId??p.flow?.id?{targetId:p.targetId??p.flow?.id}:{},...p.conversationRevision?{conversationRevision:p.conversationRevision}:{},...p.visitor?{visitor:p.visitor}:{},config:{welcomeMessage:p.config.welcomeMessage,placeholder:p.config.placeholder,theme:p.config.theme}}}async _doInitSession(){if(!this.isHistoryCapable()){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o});return this.config.setStoredSessionId?.(r.sessionId),r}await this.historyInternals.historyBootstrapReady;let e=this.config.getStoredConversationId?.()||null,n=await this.readVisitorToken();if(e&&n)try{let o=await this.createClientSession({conversationId:e});return this.finishInit(o,e,!1)}catch(o){if(!gy(o,"not_found")&&!gy(o,"visitor_required"))throw o;return this.ordinaryInit(e,!0)}return this.ordinaryInit(e,!1)}async ordinaryInit(e,n){let o=this.historyInternals.visitorStore;return o&&this.isHistoryCapable()&&!await this.readVisitorToken()?o.withFirstInitLock(()=>this.doOrdinaryInit(e,n)):this.doOrdinaryInit(e,n)}async doOrdinaryInit(e,n){let o=this.config.getStoredSessionId?.()||null,r=await this.createClientSession({storedSessionId:o}),s=await this.claimFirstConversation(r);return this.finishInit(s,e,n)}async reinitWithProof(e){let n=this.config.getStoredSessionId?.()||null,o=this.config.getStoredConversationId?.()||null,r=await this.createClientSession({storedSessionId:n,identityProof:e}),s=this.finishInit(r,o,!1);return this.clientSession=s,this.sessionInitPromise=null,this.resetClientToolsFingerprint(),s}async claimFirstConversation(e){if(!e.visitor?.token||this.claimInFlight||!this.isHistoryCapable())return e;this.claimInFlight=!0;try{return await this.createClientSession({storedSessionId:e.sessionId})}catch{return e}finally{this.claimInFlight=!1}}finishInit(e,n,o){let r=e.conversationId;return r&&n&&(o||r!==n)&&this.historyInternals.onHistoryContinuityChanged?.({previousConversationId:n,conversationId:r}),this.config.setStoredSessionId?.(e.sessionId),r&&(this.config.setStoredConversationId?.(r),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),e}prepared(e){let n=!1;return{session:e,commit:()=>{n||(n=!0,this.clientSession=e,this.resetClientToolsFingerprint())},discard:()=>{n=!0}}}async prepareConversationSession(e,n){if(!this.isClientTokenMode())throw new Error("prepareConversationSession() only available in client token mode");if(!this.isHistoryCapable())throw new Ze("history_disabled","Visitor history is disabled for this surface");await this.historyInternals.historyBootstrapReady;let o=n?.proof??null;if(!await this.readVisitorToken()&&!o)throw new Ze("conversation_credential_missing","Reopening a conversation requires a stored visitor token or an identity proof");let s=await this.createClientSession({conversationId:e,identityProof:o});return this.prepared(s)}async prepareNewConversationSession(){if(!this.isClientTokenMode())throw new Error("prepareNewConversationSession() only available in client token mode");await this.historyInternals.historyBootstrapReady;let e=await this.createClientSession({});return this.prepared(e)}handleExternalCredentialChange(){this.clearClientSession(),this.isHistoryCapable()&&this.setHistoryIdentityStatus(this.derivedBrowserOnly())}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null,this.sentNonEmptyClientToolsSessionId=null}getFeedbackApiUrl(){return`${this.clientApiBase()}/v1/client/feedback`}async sendFeedback(e){if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let r={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Fs},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:e,comment:n})}async submitNPSFeedback(e,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:e,comment:n})}historyUrl(e,n){let o=new URLSearchParams;for(let[s,a]of Object.entries(n))a===void 0||a===""||o.set(s,String(a));let r=o.toString();return`${this.clientApiBase()}/v1/client/${e}${r?`?${r}`:""}`}resolveHistoryScope(e){if(e)return e;let n=this.config.features?.history?.scope;return n||(this.config.getIdentityProof?"verified-user":"browser")}async resolveIdentityProof(e,n){let o=this.config.getIdentityProof;if(!o)return n&&this.setHistoryIdentityStatus(this.browserOnlyStatus()),null;n&&this.setHistoryIdentityStatus({state:"verifying"});let r;try{r=await o()??null}catch{throw n&&this.setHistoryIdentityStatus({state:"identity_provider_failed"}),new Ze("identity_provider_failed","The identity proof provider failed")}if(r)return r;if(e.visitor?.endUserId!=null)throw n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Ze("authentication_required","This browser is bound to a signed-in user and needs a fresh identity proof");return n&&this.setHistoryIdentityStatus({state:"browser_only",reason:"proof_unavailable_before_binding"}),null}async bindIdentity(e,n,o){if(e.visitor?.endUserId!=null)return e;let r=await this.reinitWithProof(n);if(!(r.visitor?.identityStatus==="admitted"&&r.visitor?.endUserId!=null))throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Ze("proof_not_admitted",cy);return r}async readErrorCode(e){let n=await e.json().catch(()=>({}));return typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:""}async recoverFromUnauthorized(e,n,o){let r=e.toLowerCase();if(r.includes("invalid_identity_proof"))throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Ze("invalid_identity_proof",dy);if(r.includes("visitor token required"))throw new Ze("visitor_token_missing",py);if(r.includes("visitor_identity_mismatch")){if(!n)throw o&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"proof_unavailable_after_binding"}),new Ze("visitor_identity_mismatch",uy);return this.reinitWithProof(n)}if(r.includes("expired")||r.includes("not found"))return this.clearClientSession(),this.initSession();throw new Ze("unauthorized",e||"History request was not authorized")}async historyErrorFor(e,n){let o=await this.readErrorCode(e);if(e.status===404)return new Ze("not_found","Conversation not found");if(e.status===429){let r=Number.parseInt(e.headers.get("Retry-After")??"",10);return new Ze("rate_limited","Too many history requests",{...Number.isFinite(r)?{retryAfterSeconds:r}:{}})}if(e.status===503&&o.includes("identity_proof_not_admitted"))return n&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),new Ze("proof_not_admitted",cy);if(e.status===401){let r=o.toLowerCase();return r.includes("invalid_identity_proof")?(n&&this.setHistoryIdentityStatus({state:"authentication_required",reason:"invalid_identity_proof"}),new Ze("invalid_identity_proof",dy)):r.includes("visitor token required")?new Ze("visitor_token_missing",py):r.includes("visitor_identity_mismatch")?new Ze("visitor_identity_mismatch",uy):new Ze("unauthorized",o||"History request was not authorized")}return new Ze("request_failed",o||`History request failed (${e.status})`)}commitIdentityAcknowledgement(e,n,o){let r=e?.toLowerCase()??null;if(n){if(r==="admitted"){o&&this.setHistoryIdentityStatus({state:"verified"});return}throw o&&this.setHistoryIdentityStatus({state:"configuration_error",reason:"proof_not_admitted"}),r==="ignored"?new Ze("identity_contract_violation","Server reported an ignored identity proof on a success response"):new Ze("proof_not_admitted","The response did not acknowledge the identity proof this request sent")}if(r==="admitted")throw new Ze("identity_contract_violation","Server admitted an identity proof that was never sent");o&&this.setHistoryIdentityStatus(this.browserOnlyStatus())}async historyFetch(e,n){this.assertHistoryUsable();let o=n.trackIdentity!==!1,r=await this.initSession(),s=null;this.resolveHistoryScope(n.scope)==="verified-user"&&(s=await this.resolveIdentityProof(r,o),s&&(r=await this.bindIdentity(r,s,o)));let a=this.historyInternals.visitorStore,l=!1;for(;;){let d=a?.revision()??0,p=await this.readVisitorToken();if(!p&&!n.visitorTokenOptional)throw new Ze("visitor_token_missing","No visitor credential is stored for this browser");let u=await fetch(this.historyUrl(e,{...n.query,sessionId:r.sessionId}),{method:n.method,headers:{"X-Persona-Version":Fs,...p?{"X-Visitor-Token":p}:{},...s?{"X-Identity-Proof":s}:{},...n.body!==void 0?{"Content-Type":"application/json"}:{}},...n.body!==void 0?{body:JSON.stringify(n.body)}:{},...n.keepalive?{keepalive:!0}:{}});if(u.status===401&&!l){l=!0,r=await this.recoverFromUnauthorized(await this.readErrorCode(u),s,o);continue}if(!u.ok)throw await this.historyErrorFor(u,o);let g=u.headers.get("X-History-Identity-Status"),b=await u.json().catch(()=>{});if(a&&a.revision()!==d)throw new Ze("credential_changed","The visitor credential changed while the request was in flight");return this.commitIdentityAcknowledgement(g,s!==null,o),b}}assertHistoryUsable(){if(!this.isClientTokenMode())throw new Error("Conversation history is only available in client token mode");if(!this.isHistoryCapable())throw new Ze("history_disabled","Visitor history is disabled for this surface")}async listConversations(e){let n=await this.historyFetch("conversations",{method:"GET",query:{...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{data:(Array.isArray(n?.data)?n.data:[]).map(ay),nextCursor:typeof n?.nextCursor=="string"?n.nextCursor:null}}async getConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"GET",query:{...n?.messageCursor?{messageCursor:n.messageCursor}:{}},...n?.scope?{scope:n.scope}:{}}),r=o&&typeof o.conversation=="object"&&o.conversation!==null?o.conversation:o;return{summary:ay(r),messages:Array.isArray(o?.messages)?o.messages:[],nextMessageCursor:typeof o?.nextMessageCursor=="string"?o.nextMessageCursor:null,conversationRevision:typeof o?.conversationRevision=="string"?o.conversationRevision:null}}async finalizeDisplayProjections(e,n){this.assertHistoryUsable();let o=0;for(let d of n){let p=d.displayContent.length;if(p>iy)throw new Ze("payload_too_large",`displayContent exceeds the ${iy} character limit`);o+=p}if(o>su)throw new Ze("payload_too_large",`Display projection batch exceeds the ${su} character limit`);await this.initSession();let r=this.historyInternals.visitorStore,s=r?.revision()??0,a=await this.historyFetch(`conversations/${encodeURIComponent(e)}/display-projections`,{method:"PATCH",body:{messages:n},scope:"browser",keepalive:o<=su,trackIdentity:!1}),l=typeof a?.conversationRevision=="string"?a.conversationRevision:null;return l&&this.clientSession?.conversationId===e&&(r?.revision()??0)===s&&this.historyInternals.setStoredConversationRevision?.(l),{conversationRevision:l}}async deleteConversation(e,n){let o=await this.historyFetch(`conversations/${encodeURIComponent(e)}`,{method:"DELETE",...n?.scope?{scope:n.scope}:{}});return{deleted:typeof o?.deleted=="number"?o.deleted:0}}async deleteAllConversations(e){let n=await this.historyFetch("conversations",{method:"DELETE",query:{...e?.targetId!==void 0?{targetId:e.targetId}:{}},...e?.scope?{scope:e.scope}:{}});return{deleted:typeof n?.deleted=="number"?n.deleted:0}}async resetVisitor(){this.assertHistoryUsable(),this.setHistoryIdentityStatus({state:"resetting"});try{await this.historyFetch("visitor/reset",{method:"POST",scope:"browser",visitorTokenOptional:!0})}finally{await this.historyInternals.visitorStore?.clear(),this.setHistoryIdentityStatus(this.derivedBrowserOnly())}return{reset:!0}}async dispatch(e,n){return e.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){n({type:"status",status:"connecting"});try{let o=await this.initSession();if(new Date>=new Date(o.expiresAt.getTime()-6e4)){this.clearClientSession(),this.config.onSessionExpired?.();let u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}let r=await this.buildPayload(e.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([u])=>u!=="sessionId"&&u!=="session_id")):void 0,a=this.isHistoryCapable(),l={sessionId:o.sessionId,messages:e.messages.filter(iu).map(u=>{let g=a?sa(u):void 0;return{id:u.id,role:u.role,content:u.contentParts??u.llmContent??u.rawContent??u.content,...g!==void 0&&{displayContent:g}}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...s&&Object.keys(s).length>0&&{metadata:s},...r.inputs&&Object.keys(r.inputs).length>0&&{inputs:r.inputs},...r.context&&{context:r.context}},{response:d,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,u=>{let g={...l,...u};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",g),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Fs},body:JSON.stringify(g),signal:e.signal})});if(!d.ok){let u=await d.json().catch(()=>({error:"Chat request failed"}));if(d.status===401){this.clearClientSession(),this.config.onSessionExpired?.();let b=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:b}),b}if(d.status===429){let b=new Error(u.hint||"Message limit reached for this session.");throw n({type:"error",error:b}),b}if(d.status===410&&u.error==="conversation_deleted"){let b=new Ze("conversation_deleted","This conversation was deleted");throw n({type:"error",error:b}),b}let g=new Error(u.error||"Failed to send message");throw n({type:"error",error:g}),g}if(!d.body){let u=new Error("No response body received");throw n({type:"error",error:u}),u}p(),n({type:"status",status:"connected"});try{await this.streamResponse(d.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(o){let r=o instanceof Error?o:new Error(String(o));throw!(r instanceof Ze)&&!r.message.includes("Session expired")&&!r.message.includes("Message limit")&&n({type:"error",error:r}),r}}async dispatchProxy(e,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(e,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let l=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:l}),l}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:e.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){let o=`${this.clientApiBase()}/v1/agents/${e.agentId}/approve`,r={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(r,await this.getHeaders()),fetch(o,{method:"POST",headers:r,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(e,n,o,r){let s=!!(n&&n.length>0),a=s?Sh(n):void 0,l=this.clientToolsFingerprintSessionId===e,d=s&&l&&this.lastSentClientToolsFingerprint===a,p=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,u=!1,g;for(let b=0;;b++){if(g=await o({...s&&(u||!d)&&n?{clientTools:n}:{},...p?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),g.status===409&&b===0&&s&&(await g.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){u=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:g,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=e,s?this.sentNonEmptyClientToolsSessionId=e:p&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(e,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||sy}/resume`,a;r&&(a=(await this.initSession()).sessionId);let l={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(l,await this.getHeaders());let d={executionId:e,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(d.sessionId=a),r&&a){let p=[...rc(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:u,commit:g}=await this.sendWithClientToolsDiff(a,p,b=>{let m={...d,...b};return this.debug&&console.debug("[AgentWidgetClient] client token resume",m),fetch(s,{method:"POST",headers:l,body:JSON.stringify(m),signal:o?.signal})},{emptyMeansReplace:!0});return u.ok&&g(),u}return fetch(s,{method:"POST",headers:l,body:JSON.stringify(d),signal:o?.signal})}latestMentionContext(e){for(let n=e.length-1;n>=0;n--){let o=e[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(e){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:e,config:this.config});s&&typeof s=="object"&&Object.assign(n,s)}catch(s){typeof console<"u"&&console.warn("[AgentWidget] Context provider failed:",s)}}));let o=this.latestMentionContext(e);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(e){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=e.slice().filter(iu).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,d)=>{let p=new Date(l.createdAt).getTime(),u=new Date(d.createdAt).getTime();return p-u}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...rc(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(e);return a&&(r.context=a),r}async buildPayload(e){let n=e.slice().filter(iu).sort((l,d)=>{let p=new Date(l.createdAt).getTime(),u=new Date(d.createdAt).getTime();return p-u}).map(l=>({role:l.role,content:l.contentParts??l.llmContent??l.rawContent??l.content,createdAt:l.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[l,d]of Object.entries(o.targetPayload))l!=="messages"&&(r[l]=d);let s=[...rc(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(e);if(a&&(r.context=a),this.requestMiddleware)try{let l=await this.requestMiddleware({payload:{...r},config:this.config});if(l&&typeof l=="object"){let d=l;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",l)}return r}async handleCustomSSEEvent(e,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let l=await this.parseSSEEvent(e);if(l===null)return!1;let d=u=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return o.current=g,r(g),g},p=u=>o.current?o.current:d(u);if(l.text!==void 0){l.partId!==void 0&&a.current!==null&&l.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),d(l.partId)),l.partId!==void 0&&(a.current=l.partId);let u=p(l.partId);l.partId!==void 0&&!u.partId&&(u.partId=l.partId),u.content+=l.text,r(u)}return l.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),l.error&&(a.current=null,n({type:"error",error:new Error(l.error)})),!0}catch(l){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",l),!1}}async streamResponse(e,n,o,r){let s=e.getReader(),a=new TextDecoder,l="",d=Date.now(),p=0,u=()=>d+p++,g=j=>{let ae=j.reasoning?{...j.reasoning,chunks:[...j.reasoning.chunks]}:void 0,x=j.toolCall?{...j.toolCall,chunks:j.toolCall.chunks?[...j.toolCall.chunks]:void 0}:void 0,S=j.tools?j.tools.map(O=>({...O,chunks:O.chunks?[...O.chunks]:void 0})):void 0;return{...j,reasoning:ae,toolCall:x,tools:S}},b=j=>{if(j.role!=="assistant"||j.variant)return!0;let ae=Array.isArray(j.contentParts)&&j.contentParts.length>0,x=typeof j.rawContent=="string"&&j.rawContent.trim()!=="";return typeof j.content=="string"&&j.content.trim()!==""||ae||x||!!j.stopReason},m=j=>{b(j)&&n({type:"message",message:g(j)})},y=null,w=null,T={current:null},W={current:null},E=null,k="",A=new Map,D=new Map,B=new Map,I=new Map,N=new Map,_={lastId:null,byStep:new Map},F={lastId:null,byCall:new Map},P=j=>{if(j==null)return null;try{return String(j)}catch{return null}},V=j=>P(j.stepId??j.step_id??j.step??j.parentId??j.flowStepId??j.flow_step_id),se=j=>P(j.callId??j.call_id??j.requestId??j.request_id??j.toolCallId??j.tool_call_id??j.stepId??j.step_id),ve=o,he=!1,ge=()=>{if(y)return y;let j,ae="",x=E;return!he&&ve?(j=ve,he=!0,ae=r??""):ve&&x?j=`${ve}_${x}`:j=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:j,role:"assistant",content:ae,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},m(y),y},re=(j,ae)=>{_.lastId=ae,j&&_.byStep.set(j,ae)},oe=(j,ae)=>{let x=j.reasoningId??j.id,S=V(j);if(x){let R=String(x);return re(S,R),R}if(S){let R=_.byStep.get(S);if(R)return _.lastId=R,R}if(_.lastId&&!ae)return _.lastId;if(!ae)return null;let O=`reason-${u()}`;return re(S,O),O},ee=j=>{let ae=I.get(j);if(ae)return ae;let x={id:`reason-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:j,status:"streaming",chunks:[]}};return I.set(j,x),m(x),x},M=(j,ae)=>{F.lastId=ae,j&&F.byCall.set(j,ae)},te=new Set,pe=new Map,Se=new Set,xe=new Map,Ce=j=>{if(!j)return!1;let ae=j.replace(/_+/g,"_").replace(/^_|_$/g,"");return ae==="emit_artifact_markdown"||ae==="emit_artifact_component"},Me=(j,ae)=>{let x=j.toolId??j.id,S=se(j);if(x){let R=String(x);return M(S,R),R}if(S){let R=F.byCall.get(S);if(R)return F.lastId=R,R}if(F.lastId&&!ae)return F.lastId;if(!ae)return null;let O=`tool-${u()}`;return M(S,O),O},ke=j=>{let ae=N.get(j);if(ae)return ae;let x={id:`tool-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:j,status:"pending"}};return N.set(j,x),m(x),x},Oe=j=>{if(typeof j=="number"&&Number.isFinite(j))return j;if(typeof j=="string"){let ae=Number(j);if(!Number.isNaN(ae)&&Number.isFinite(ae))return ae;let x=Date.parse(j);if(!Number.isNaN(x))return x}return Date.now()},ze=j=>{if(typeof j=="string")return j;if(j==null)return"";try{return JSON.stringify(j)}catch{return String(j)}},qe=new Map,nt=new Map,De=new Map,Ue=(j,ae,x)=>{let S=De.get(j);S||(S=[],De.set(j,S));let O=0,R=S.length;for(;O<R;){let K=O+R>>>1;S[K].seq<ae?O=K+1:R=K}S[O]?.seq===ae?S[O]={seq:ae,text:x}:S.splice(O,0,{seq:ae,text:x});let $="";for(let K=0;K<S.length;K++)$+=S[K].text;return $},an=(j,ae)=>{let x=ze(ae),S=nt.get(j.id),O=eA(S,x);j.rawContent=O;let R=qe.get(j.id),$=ue=>{let et=j.content??"";ue.trim()!==""&&(et.trim().length===0||ue.startsWith(et)||ue.trimStart().startsWith(et.trim()))&&(j.content=ue)},K=()=>{if(R){let ue=R.close?.();ue instanceof Promise&&ue.catch(()=>{})}qe.delete(j.id),nt.delete(j.id),j.streaming=!1,m(j)};if(!R){$(x),K();return}let Y=ra(O);if(Y!==null&&Y.trim()!==""){$(Y),K();return}let Q=ue=>{let et=typeof ue=="string"?ue:ue?.text??null;if(et!==null&&et.trim()!=="")return et;let Ye=R.getExtractedText();return Ye!==null&&Ye.trim()!==""?Ye:x},Z;try{Z=R.processChunk(O)}catch{$(x),K();return}if(Z instanceof Promise){Z.then(ue=>{$(Q(ue)),K()}).catch(()=>{$(x),K()});return}$(Q(Z)),K()},Ee=null,$e=(j,ae,x,S)=>{j.rawContent=ae,qe.has(j.id)||qe.set(j.id,this.createStreamParser());let O=qe.get(j.id),R=ae.trim().startsWith("{")||ae.trim().startsWith("[");if(R&&nt.set(j.id,ae),O.__isPlainTextParser===!0){j.content=S!==void 0?ae:j.content+x,nt.delete(j.id),qe.delete(j.id),j.rawContent=void 0,m(j);return}let K=O.processChunk(ae);if(K instanceof Promise)K.then(Y=>{let Q=typeof Y=="string"?Y:Y?.text??null;Q!==null&&Q.trim()!==""?(j.content=Q,m(j)):!R&&!ae.trim().startsWith("<")&&(j.content=S!==void 0?ae:j.content+x,nt.delete(j.id),qe.delete(j.id),j.rawContent=void 0,m(j))}).catch(()=>{j.content=S!==void 0?ae:j.content+x,nt.delete(j.id),qe.delete(j.id),j.rawContent=void 0,m(j)});else{let Y=typeof K=="string"?K:K?.text??null;Y!==null&&Y.trim()!==""?(j.content=Y,m(j)):!R&&!ae.trim().startsWith("<")&&(j.content=S!==void 0?ae:j.content+x,nt.delete(j.id),qe.delete(j.id),j.rawContent=void 0,m(j))}},mt=(j,ae)=>{let x=ae??j.content;if(x==null||x===""){j.streaming=!1,m(j);return}let O=nt.get(j.id)??ze(x);j.rawContent=O;let R=qe.get(j.id),$=null,K=!1;if(R&&($=R.getExtractedText(),$===null&&($=ra(O)),$===null)){let Y=R.processChunk(O);Y instanceof Promise?(K=!0,Y.then(Q=>{let Z=typeof Q=="string"?Q:Q?.text??null;Z!==null&&(j.content=Z,j.streaming=!1,qe.delete(j.id),nt.delete(j.id),m(j))}).catch(()=>{})):$=typeof Y=="string"?Y:Y?.text??null}if(!K){$!==null&&$.trim()!==""?j.content=$:nt.has(j.id)||(j.content=ze(x));let Y=qe.get(j.id);if(Y){let Q=Y.close?.();Q instanceof Promise&&Q.catch(()=>{}),qe.delete(j.id)}nt.delete(j.id),j.streaming=!1,m(j)}},At=(j,ae,x)=>{let S=D.get(j);if(S)return S;let O={id:`nested-${ae}-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...x?{variant:x}:{},...x==="reasoning"?{reasoning:{id:j,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ae}};return D.set(j,O),m(O),O},yt=[],Wt,Te=new Map,ot=0,lt="agent",kt=!1,wn=null,Ct=null,Ln=new Map,Gn=this.config.iterationDisplay??"separate";for(Wt=()=>{for(let j=0;j<yt.length;j++){let ae=yt[j].payloadType,x=yt[j].payload;if(!kt&&lt!=="flow"&&typeof x.stepType=="string"&&(lt="flow"),ae==="reasoning_start"){let S=typeof x.id=="string"?x.id:null,O=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(S&&O){A.set(S,O),At(S,O,"reasoning");continue}let R=oe(x,!0)??`reason-${u()}`,$=ee(R);$.reasoning=$.reasoning??{id:R,status:"streaming",chunks:[]},$.reasoning.startedAt=$.reasoning.startedAt??Oe(x.startedAt??x.timestamp),$.reasoning.completedAt=void 0,$.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&($.reasoning.scope=x.scope),$.streaming=!0,$.reasoning.status="streaming",m($)}else if(ae==="reasoning_delta"){let S=typeof x.id=="string"?x.id:null;if(S&&A.has(S)&&D.has(S)){let K=D.get(S),Y=x.reasoningText??x.text??x.delta??"";Y&&x.hidden!==!0&&K.reasoning&&(K.reasoning.chunks.push(String(Y)),m(K));continue}let O=oe(x,!1)??oe(x,!0)??`reason-${u()}`,R=ee(O);R.reasoning=R.reasoning??{id:O,status:"streaming",chunks:[]},R.reasoning.startedAt=R.reasoning.startedAt??Oe(x.startedAt??x.timestamp);let $=x.reasoningText??x.text??x.delta??"";if($&&x.hidden!==!0){let K=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(K!==void 0){let Y=Ue(O,K,String($));R.reasoning.chunks=[Y]}else R.reasoning.chunks.push(String($))}if(R.reasoning.status=x.done?"complete":"streaming",x.done){R.reasoning.completedAt=Oe(x.completedAt??x.timestamp);let K=R.reasoning.startedAt??Date.now();R.reasoning.durationMs=Math.max(0,(R.reasoning.completedAt??Date.now())-K)}R.streaming=R.reasoning.status!=="complete",m(R)}else if(ae==="reasoning_complete"){let S=typeof x.id=="string"?x.id:null;if(S&&A.has(S)&&D.has(S)){let Y=D.get(S);if(Y.reasoning){let Q=typeof x.text=="string"?x.text:"";Q&&Y.reasoning.chunks.length===0&&Y.reasoning.chunks.push(Q),Y.reasoning.status="complete",Y.streaming=!1,m(Y)}A.delete(S),D.delete(S);continue}let O=oe(x,!1)??oe(x,!0)??`reason-${u()}`,R=typeof x.text=="string"?x.text:"";!I.get(O)&&(R||x.scope==="loop")&&ee(O);let $=I.get(O);if($?.reasoning){(x.scope==="loop"||x.scope==="turn")&&($.reasoning.scope=x.scope),R&&$.reasoning.chunks.length===0&&$.reasoning.chunks.push(R),$.reasoning.status="complete",$.reasoning.completedAt=Oe(x.completedAt??x.timestamp);let Y=$.reasoning.startedAt??Date.now();$.reasoning.durationMs=Math.max(0,($.reasoning.completedAt??Date.now())-Y),$.streaming=!1,m($)}let K=V(x);K&&_.byStep.delete(K)}else if(ae==="tool_start"){y&&(y.streaming=!1,m(y),y=null),typeof x.iteration=="number"&&(ot=x.iteration);let S=(typeof x.toolCallId=="string"?x.toolCallId:void 0)??Me(x,!0)??`tool-${u()}`,O=x.toolName??x.name;if(Ce(O)){te.add(S);continue}M(se(x),S);let R=ke(S),$=R.toolCall??{id:S,status:"pending"};$.name=O??$.name,$.status="running",x.parameters!==void 0?$.args=x.parameters:x.args!==void 0&&($.args=x.args),$.startedAt=$.startedAt??Oe(x.startedAt??x.timestamp),$.completedAt=void 0,$.durationMs=void 0,R.toolCall=$,R.streaming=!0,x.executionId&&(R.agentMetadata={executionId:x.executionId,iteration:x.iteration}),m(R)}else if(ae==="tool_output_delta"){let S=Me(x,!1)??Me(x,!0)??`tool-${u()}`;if(te.has(S))continue;let O=ke(S),R=O.toolCall??{id:S,status:"running"};R.startedAt=R.startedAt??Oe(x.startedAt??x.timestamp);let $=x.text??x.delta??x.message??"";$&&(R.chunks=R.chunks??[],R.chunks.push(String($))),R.status="running",O.toolCall=R,O.streaming=!0;let K=x.agentContext;(K||x.executionId)&&(O.agentMetadata=O.agentMetadata??{executionId:K?.executionId??x.executionId,iteration:K?.iteration??x.iteration}),m(O)}else if(ae==="tool_complete"){let S=Me(x,!1)??Me(x,!0)??`tool-${u()}`;if(te.has(S)){te.delete(S);continue}let O=ke(S),R=O.toolCall??{id:S,status:"running"};R.status="complete",x.result!==void 0&&(R.result=x.result),typeof x.duration=="number"&&(R.duration=x.duration),R.completedAt=Oe(x.completedAt??x.timestamp);let $=x.duration??x.executionTime;if(typeof $=="number")R.durationMs=$;else{let Q=R.startedAt??Date.now();R.durationMs=Math.max(0,(R.completedAt??Date.now())-Q)}O.toolCall=R,O.streaming=!1;let K=x.agentContext;(K||x.executionId)&&(O.agentMetadata=O.agentMetadata??{executionId:K?.executionId??x.executionId,iteration:K?.iteration??x.iteration}),m(O);let Y=se(x);Y&&F.byCall.delete(Y)}else if(ae==="await"&&x.toolName){let S=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,O=S??x.toolId??`local-${u()}`,R=ke(O),$=x.toolName,K=x.origin==="webmcp"&&!Rs($)?`webmcp:${$}`:$,Y=Rs(K),Q=R.toolCall??{id:O,status:"pending"};Q.name=K,Q.args=x.parameters,Q.status=Y?"running":"complete",Q.chunks=Q.chunks??[],Q.startedAt=Q.startedAt??Oe(x.startedAt??x.timestamp??x.awaitedAt),Y?(Q.completedAt=void 0,Q.duration=void 0,Q.durationMs=void 0):Q.completedAt=Q.completedAt??Q.startedAt,R.toolCall=Q,R.streaming=!1,R.agentMetadata={...R.agentMetadata,executionId:x.executionId??R.agentMetadata?.executionId,awaitingLocalTool:!0,...S?{webMcpToolCallId:S}:{}},m(R)}else if(ae==="text_start"){let S=typeof x.id=="string"?x.id:null,O=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(S&&O){A.set(S,O);continue}let R=y;R&&(lt==="flow"?(mt(R),Ee=R):(R.streaming=!1,m(R)),y=null),E=typeof x.id=="string"?x.id:E,k=""}else if(ae==="text_delta"){let S=typeof x.id=="string"?x.id:null,O=S?A.get(S):void 0;if(S&&O){let $=typeof x.delta=="string"?x.delta:"",K=(B.get(S)??"")+$;if(B.set(S,K),K.trim()==="")continue;let Y=At(S,O);Y.agentMetadata={...Y.agentMetadata,executionId:x.executionId,parentToolId:O},$e(Y,K,$,void 0);continue}if(E=typeof x.id=="string"?x.id:E,lt==="flow"){let $=typeof x.delta=="string"?x.delta:"";if(k+=$,k.trim()==="")continue;let K=ge();K.agentMetadata={executionId:x.executionId,iteration:x.iteration},$e(K,k,$,void 0),w=K;continue}let R=ge();R.content+=x.delta??"",R.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:wn??void 0,agentName:Ct?.agentName},w=R,m(R)}else if(ae==="text_complete"){let S=typeof x.id=="string"?x.id:null;if(S&&A.has(S)){let R=D.get(S);R&&mt(R),A.delete(S),B.delete(S),D.delete(S);continue}let O=y;O&&(lt==="flow"?(mt(O),Ee=O):((O.content??"")===""&&typeof x.text=="string"&&(O.content=x.text),O.streaming=!1,m(O)),y=null),E=null,k=""}else if(ae==="step_complete"){let S=x.stepType,O=x.executionType;if(S==="tool"||O==="context")continue;if(x.success===!1){let R=x.error,$=typeof R=="string"&&R!==""?R:R!=null&&typeof R=="object"&&Reflect.has(R,"message")?String(R.message??"Step failed"):"Step failed";n({type:"error",error:new Error($)});let K=y;K&&K.streaming&&(K.streaming=!1,m(K)),n({type:"status",status:"idle"});continue}{let R=Ee;Ee=null;let $=x.stopReason,K=x.result?.response;if(R)$&&(R.stopReason=$),K!=null?an(R,K):R.streaming!==!1&&(qe.delete(R.id),nt.delete(R.id),R.streaming=!1,m(R));else{let Y=K!=null&&K!=="";if(Y||$){let Q=ge();$&&(Q.stopReason=$),Y?mt(Q,K):(Q.streaming=!1,m(Q))}}continue}}else if(ae==="execution_start")lt=x.kind==="flow"?"flow":"agent",kt=!0,lt==="agent"&&(Ct={executionId:x.executionId,agentId:x.agentId??"virtual",agentName:x.agentName??"",status:"running",currentIteration:0,maxTurns:x.maxTurns??1,startedAt:Oe(x.startedAt)});else if(ae==="turn_start"){let S=typeof x.iteration=="number"?x.iteration:ot;if(S!==ot){if(Ct&&(Ct.currentIteration=S),Gn==="separate"&&S>1){let O=y;O&&(O.streaming=!1,m(O),Ln.set(S-1,O),y=null)}ot=S}wn=typeof x.id=="string"?x.id:null,w=null}else if(ae==="tool_input_delta"){let S=x.toolCallId??F.lastId;if(S){let O=N.get(S);O?.toolCall&&(O.toolCall.chunks=O.toolCall.chunks??[],O.toolCall.chunks.push(x.delta??""),m(O))}}else{if(ae==="tool_input_complete")continue;if(ae==="turn_complete"){let S=x.stopReason,O=y??w;if(S&&O!==null){let R=x.id;(!R||O.agentMetadata?.turnId===R)&&(O.stopReason=S,m(O))}wn===x.id&&(wn=null)}else if(ae==="media_start"){let S=String(x.id);Te.set(S,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(ae==="media_delta"){let S=Te.get(String(x.id));S&&typeof x.delta=="string"&&S.parts.push(x.delta)}else if(ae==="media_complete"){let S=String(x.id),O=Te.get(S);Te.delete(S);let R=(typeof x.mediaType=="string"?x.mediaType:void 0)??O?.mediaType??"application/octet-stream",$=typeof x.data=="string"?x.data:void 0,K=typeof x.url=="string"?x.url:O&&O.parts.length>0?O.parts.join(""):void 0,Y=null;if($)Y={type:"media",data:$,mediaType:R};else if(K){let et=R.toLowerCase();Y={type:et==="image"||et.startsWith("image/")?"image-url":"file-url",url:K,mediaType:R}}let Q=x.toolCallId??O?.toolCallId,Z=Y?[Y]:[],ue=[];for(let et of Z){if(!et||typeof et!="object")continue;let Ye=et,Be=typeof Ye.type=="string"?Ye.type:void 0,ye=typeof Ye.mediaType=="string"?Ye.mediaType.toLowerCase():"",we=null,ct="";if(Be==="media"){let _e=typeof Ye.data=="string"?Ye.data:void 0;if(!_e)continue;ct=ye.length>0?ye:"application/octet-stream",we=`data:${ct};base64,${_e}`}else if(Be==="image-url"){let _e=typeof Ye.url=="string"?Ye.url:void 0;if(!_e)continue;ct=ye,we=_e}else if(Be==="file-url"){let _e=typeof Ye.url=="string"?Ye.url:void 0;if(!_e)continue;ct=ye,we=_e}else continue;if(we)if(Be==="image-url"||ct.startsWith("image/"))ue.push({type:"image",image:we,...ct.includes("/")?{mimeType:ct}:{}});else if(ct.startsWith("audio/"))ue.push({type:"audio",audio:we,mimeType:ct});else if(ct.startsWith("video/"))ue.push({type:"video",video:we,mimeType:ct});else{let _e=ct||"application/octet-stream";ue.push({type:"file",data:we,mimeType:_e,filename:JS(_e)})}}if(ue.length>0){let et=u(),Ye=Q,ye={id:`agent-media-${typeof Ye=="string"&&Ye.length>0?`${Ye}-${et}`:String(et)}`,role:"assistant",content:"",contentParts:ue,createdAt:new Date().toISOString(),streaming:!1,sequence:et,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:ot}};m(ye);let we=y;we&&(we.streaming=!1,m(we)),y=null,T.current=null}}else if(ae==="execution_complete"){let S=x.kind??lt;S==="agent"&&Ct&&(Ct.status=x.success?"complete":"error",Ct.completedAt=Oe(x.completedAt),Ct.stopReason=x.stopReason);let O=y;O&&(S==="flow"&&O.streaming!==!1?mt(O):(O.streaming=!1,m(O)),y=null),E=null,k="",Ee=null,n({type:"status",status:"idle",terminal:!0})}else if(ae==="execution_error"){let S=typeof x.error=="string"?x.error:x.error?.message??"Execution error";n({type:"error",error:new Error(S)})}else if(ae!=="ping"){if(ae==="approval_start"){let S=x.approvalId??`approval-${u()}`,O={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:S,status:"pending",agentId:Ct?.agentId??"virtual",executionId:x.executionId??Ct?.executionId??"",toolName:x.toolName??"",toolType:x.toolType,description:x.description??`Execute ${x.toolName??"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(O)}else if(ae==="step_await"&&x.awaitReason==="approval_required"){let S=x.approvalId??`approval-${u()}`,O={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:S,status:"pending",agentId:Ct?.agentId??"virtual",executionId:x.executionId??Ct?.executionId??"",toolName:x.toolName??"",toolType:x.toolType,description:x.description??`Execute ${x.toolName??"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(O)}else if(ae==="approval_complete"){let S=x.approvalId;if(S){let R={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:S,status:x.decision??"approved",agentId:Ct?.agentId??"virtual",executionId:x.executionId??Ct?.executionId??"",toolName:x.toolName??"",description:x.description??"",resolvedAt:Date.now()}};m(R)}}else if(ae==="artifact_start"||ae==="artifact_delta"||ae==="artifact_update"||ae==="artifact_complete"){if(ae==="artifact_start"){let S=x.artifactType,O=String(x.id),R=typeof x.title=="string"?x.title:void 0,$=x.file,K;$&&typeof $=="object"&&!Array.isArray($)&&typeof $.path=="string"&&typeof $.mimeType=="string"&&(K={path:$.path,mimeType:$.mimeType,...typeof $.language=="string"?{language:$.language}:{}}),n({type:"artifact_start",id:O,artifactType:S,title:R,component:typeof x.component=="string"?x.component:void 0,...K?{file:K}:{}});let Y=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?{...x.props}:void 0;if(xe.set(O,{markdown:"",title:R,file:K,...Y?{props:Y}:{}}),!Se.has(O)){Se.add(O);let Q=dr(this.config.features?.artifacts,{artifactType:S,...K?{file:K}:{}}),Z=typeof x.component=="string"?x.component:void 0,ue={id:`artifact-ref-${O}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:Ji(Q,{artifactId:O,title:R,artifactType:S,status:"streaming",...K?{file:K}:{},...Z?{component:Z}:{}})};pe.set(O,ue),m(ue)}}else if(ae==="artifact_delta"){let S=String(x.id),O=typeof x.delta=="string"?x.delta:String(x.delta??"");n({type:"artifact_delta",id:S,artDelta:O});let R=xe.get(S);R&&(R.markdown+=O)}else if(ae==="artifact_update"){let S=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};n({type:"artifact_update",id:String(x.id),props:S,component:typeof x.component=="string"?x.component:void 0});let O=xe.get(String(x.id));O&&(O.props={...O.props??{},...S})}else if(ae==="artifact_complete"){let S=String(x.id);n({type:"artifact_complete",id:S});let O=pe.get(S);if(O){O.streaming=!1;try{let R=JSON.parse(O.rawContent??"{}");if(R.props){R.props.status="complete";let $=xe.get(S);$?.markdown&&(R.props.markdown=$.markdown),$?.file&&(R.props.file=$.file),R.component==="PersonaArtifactInline"&&$?.props&&Object.keys($.props).length>0&&(R.props.componentProps=$.props)}O.rawContent=JSON.stringify(R)}catch{}xe.delete(S),m(O),pe.delete(S)}}}else if(ae==="transcript_insert"){let S=x.message;if(!S||typeof S!="object")continue;let O=String(S.id??`msg-${u()}`),R=S.role,K={id:O,role:R==="user"?"user":R==="system"?"system":"assistant",content:typeof S.content=="string"?S.content:"",rawContent:typeof S.rawContent=="string"?S.rawContent:void 0,createdAt:typeof S.createdAt=="string"?S.createdAt:new Date().toISOString(),streaming:S.streaming===!0,...typeof S.variant=="string"?{variant:S.variant}:{},sequence:u()};if(m(K),K.rawContent)try{let Q=JSON.parse(K.rawContent)?.props?.artifactId;typeof Q=="string"&&Se.add(Q)}catch{}y=null,T.current=null,qe.delete(O),nt.delete(O)}else if(ae==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let S=typeof x.error=="string"?x.error:x.error?.message!=null?String(x.error.message):"Execution error";n({type:"error",error:new Error(S)});let O=y;O&&O.streaming&&(O.streaming=!1,m(O)),n({type:"status",status:"idle"})}}else if(ae==="step_error"||ae==="dispatch_error"||ae==="flow_error"){let S=null;if(x.error instanceof Error)S=x.error;else if(ae==="dispatch_error"){let O=x.message??x.error;O!=null&&O!==""&&(S=new Error(String(O)))}else{let O=x.error;typeof O=="string"&&O!==""?S=new Error(O):O!=null&&typeof O=="object"&&Reflect.has(O,"message")&&(S=new Error(String(O.message??O)))}if(S){n({type:"error",error:S});let O=y;O&&O.streaming&&(O.streaming=!1,m(O)),n({type:"status",status:"idle"})}}}}}yt.length=0};;){let{done:j,value:ae}=await s.read();if(j)break;l+=a.decode(ae,{stream:!0});let x=l.split(`
185
1082
 
186
- `);l=h.pop()??"";for(let O of h){let R=O.split(`
187
- `),_="message",Z="",q=null;for(let fe of R)fe.startsWith("event:")?_=fe.replace("event:","").trim():fe.startsWith("data:")?Z+=fe.replace("data:","").trim():fe.startsWith("id:")&&(q=fe.slice(3).trim());let ee=()=>{q!==null&&q!==""&&n({type:"cursor",id:q})};if(!Z){ee();continue}let ge;try{ge=JSON.parse(Z)}catch(fe){n({type:"error",error:fe instanceof Error?fe:new Error("Failed to parse chat stream payload")});continue}let qe=_!=="message"?_:ge.type??"message";if(this.onSSEEvent?.(qe,ge),this.parseSSEEvent){M.current=y;let fe=await this.handleCustomSSEEvent(ge,n,M,f,d,I);if(M.current&&M.current!==y&&(y=M.current),fe){ee();continue}}nt.push({payloadType:qe,payload:ge}),Pe(),ee()}}Pe()}};function aa(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function Br(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var la="[Image]";function lg(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function Dr(t){return{type:"text",text:t}}var cg=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Py=["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"],to=[...cg,...Py];function Iy(t){return cg.includes(t)||t.startsWith("image/")}function ca(t){return Iy(t.type)}async function dg(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;ca(t)?e({type:"image",image:r,mimeType:t.type,alt:t.name}):e({type:"file",data:r,mimeType:t.type,filename:t.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(t)})}function pg(t,e=to,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function Ry(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function ug(t,e){let n=Ry(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[t]||n||"FILE"}yc();var gg=16e3,Wy=24e3,Hy=4096,By=1380533830;function Dy(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===By?new Uint8Array(t,44):new Uint8Array(t)}function Oy(t){let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${e}`}var Ns=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(){if(this.callLive)return;let e=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:gg,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(g=>g.stop());return}this.mediaStream=s;let i=window.AudioContext||window.webkitAudioContext,l=new i({sampleRate:gg});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Or(Wy);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(g=>g.stop()),l.close().catch(()=>{});return}this.playback=p,p.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let c=`${Oy(o)}/ws/agents/${encodeURIComponent(e)}/voice`,d=new WebSocket(c,["runtype.bearer",n]);d.binaryType="arraybuffer",this.ws=d,d.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,d,r))},d.onmessage=g=>this.handleMessage(g,r),d.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},d.onclose=g=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(g.code!==1e3){let b=g.code?` (code ${g.code})`:"";this.emitError(new Error(`Voice connection closed${b}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}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,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let i=e.createScriptProcessor(Hy,1,1);this.processor=i,i.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=l.inputBuffer.getChannelData(0),c=new Int16Array(p.length);for(let d=0;d<p.length;d++){let g=Math.max(-1,Math.min(1,p[d]));c[d]=g<0?g*32768:g*32767}o.send(c.buffer)},s.connect(i),i.connect(e.destination)}handleMessage(e,n){if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let o;try{o=JSON.parse(e.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,n){if(n!==this.callGeneration||!this.playback)return;let o=Dy(e);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}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(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,o){this.transcriptCallbacks.forEach(r=>r(e,n,o))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}};var Zo=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<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(n=>n(e)),this.statusCallbacks.forEach(n=>n("error")),e}}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 Nr(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new Ns(t.runtype);case"browser":if(!Zo.isSupported())throw new Error("Browser speech recognition not supported");return new Zo(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function fg(t){if(t?.type==="custom"&&t.custom)return Nr({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return Nr({type:"runtype",runtype:t.runtype});if(Zo.isSupported())return Nr({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function vc(t){try{return fg(t),!0}catch{return!1}}function da(t){let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of e){let o=t.find(r=>r.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var Fr=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(e.text),s=o.getVoices();if(e.voice){let i=s.find(l=>l.name===e.voice);i&&(r.voice=i)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):da(s));e.rate!==void 0&&(r.rate=e.rate),e.pitch!==void 0&&(r.pitch=e.pitch),r.onend=()=>n.onEnd?.(),r.onerror=i=>{let l=i.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var Fs=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){if(this.activeId===e){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.generation;this.engine?.stop(),this.set(e,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(e,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function xc(t){if(!t)return"";let e=Ny(t);return mg(e!==null?e:t)}function Ny(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function mg(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
1083
+ `);l=x.pop()??"";for(let S of x){let O=S.split(`
1084
+ `),R="message",$="",K=null;for(let ue of O)ue.startsWith("event:")?R=ue.replace("event:","").trim():ue.startsWith("data:")?$+=ue.replace("data:","").trim():ue.startsWith("id:")&&(K=ue.slice(3).trim());let Y=()=>{K!==null&&K!==""&&n({type:"cursor",id:K})};if(!$){Y();continue}let Q;try{Q=JSON.parse($)}catch(ue){n({type:"error",error:ue instanceof Error?ue:new Error("Failed to parse chat stream payload")});continue}let Z=R!=="message"?R:Q.type??"message";if(this.onSSEEvent?.(Z,Q),this.parseSSEEvent){T.current=y;let ue=await this.handleCustomSSEEvent(Q,n,T,m,u,W);if(T.current&&T.current!==y&&(y=T.current),ue){Y();continue}}yt.push({payloadType:Z,payload:Q}),Wt(),Y()}}Wt()}};function pc(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function zs(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}la();au();var my=16e3,tA=24e3,nA=4096,oA=1380533830;function rA(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===oA?new Uint8Array(t,44):new Uint8Array(t)}function sA(t){let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${e}`}var ca=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(){if(this.callLive)return;let e=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let r=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let s=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:my,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(g=>g.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,l=new a({sampleRate:my});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let d=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new Vs(tA);if(r!==this.callGeneration){d.destroy(),s.getTracks().forEach(g=>g.stop()),l.close().catch(()=>{});return}this.playback=d,d.onFinished(()=>{r===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let p=`${sA(o)}/ws/agents/${encodeURIComponent(e)}/voice`,u=new WebSocket(p,["runtype.bearer",n]);u.binaryType="arraybuffer",this.ws=u,u.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(l,s,u,r))},u.onmessage=g=>this.handleMessage(g,r),u.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},u.onclose=g=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(g.code!==1e3){let b=g.code?` (code ${g.code})`:"";this.emitError(new Error(`Voice connection closed${b}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}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,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let a=e.createScriptProcessor(nA,1,1);this.processor=a,a.onaudioprocess=l=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let d=l.inputBuffer.getChannelData(0),p=new Int16Array(d.length);for(let u=0;u<d.length;u++){let g=Math.max(-1,Math.min(1,d[u]));p[u]=g<0?g*32768:g*32767}o.send(p.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,n){if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let o;try{o=JSON.parse(e.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",o.text??"",!1);break;case"transcript_final":{let r=o.role==="assistant"?"assistant":"user";this.emitStatus(r==="user"?"processing":"speaking"),this.emitTranscript(r,o.text??"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,n){if(n!==this.callGeneration||!this.playback)return;let o=rA(e);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}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(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,o){this.transcriptCallbacks.forEach(r=>r(e,n,o))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}};var Yr=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<"u"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=this.config?.language||"en-US",this.recognition.continuous=this.config?.continuous||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{let o=Array.from(n.results).map(s=>s[0]).map(s=>s.transcript).join(""),r=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(s=>s({text:o,confidence:r?.8:.5,provider:"browser"})),r&&!this.config?.continuous&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(n=>n(e)),this.statusCallbacks.forEach(n=>n("error")),e}}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 js(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new ca(t.runtype);case"browser":if(!Yr.isSupported())throw new Error("Browser speech recognition not supported");return new Yr(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function hy(t){if(t?.type==="custom"&&t.custom)return js({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return js({type:"runtype",runtype:t.runtype});if(Yr.isSupported())return js({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function lu(t){try{return hy(t),!0}catch{return!1}}function gc(t){let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of e){let o=t.find(r=>r.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var qs=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(e.text),s=o.getVoices();if(e.voice){let a=s.find(l=>l.name===e.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):gc(s));e.rate!==void 0&&(r.rate=e.rate),e.pitch!==void 0&&(r.pitch=e.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let l=a.error;l==="canceled"||l==="interrupted"?n.onEnd?.():n.onError?.(new Error(l||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var da=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){if(this.activeId===e){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){let o=++this.generation;this.engine?.stop(),this.set(e,"loading");try{if(!this.engine){let r=await this.resolveEngine();if(o!==this.generation)return;if(!r){this.set(null,"idle");return}this.engine=r}this.engine.speak(n,{onStart:()=>{o===this.generation&&this.set(e,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){this.generation++,this.engine?.stop(),this.set(null,"idle")}destroy(){this.stop(),this.engine?.destroy?.(),this.engine=null,this.listeners.clear()}set(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function cu(t){if(!t)return"";let e=iA(t);return yy(e!==null?e:t)}function iA(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let o=JSON.parse(e);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function yy(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
188
1085
  `),e=e.replace(/\n{2,}/g,`
189
- `),e.trim()}var xg=null;var wc=()=>xg?xg():Promise.resolve().then(()=>(vg(),yg));var Uy=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function jy(t,e){return Uy.some(n=>t[n]!==e[n])}function Cc(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
1086
+ `),e.trim()}var xy=null;var du=()=>xy?xy():Promise.resolve().then(()=>(Cy(),wy));var pA=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId","getIdentityProof","getStoredConversationId","setStoredConversationId","clearStoredConversationId","clearStoredSessionId"];function uA(t,e){return pA.some(n=>t[n]!==e[n])}var So=class extends Error{constructor(e,n){super(n),this.name="SessionHistoryError",this.code=e}};function pu(t,e){let n=t instanceof Error?t:new Error(String(t));if(typeof e=="string")return e;if(typeof e=="function")return e(n);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${o}
190
1087
 
191
- _Details: ${n.message}_`:o}var _s=t=>({isError:!0,content:[{type:"text",text:t}]}),Ag=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Sg=t=>kr(t)||t===eo,ga=class{constructor(e={},n){this.config=e;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Fs(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(kr(n.name)||n.name===eo&&So(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.messages=[...e.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new Os(e),this.wireDefaultWebMcpConfirm();for(let o of e.initialArtifacts??[])this.artifacts.set(o.id,{...o,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(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||wc().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return vc(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=Fr.isSupported()?new Fr({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,i=e.browserFallback!==!1;if(o&&r&&s)return wc().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let c=new l({host:o,agentId:r,clientToken:s,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return i&&n?new p(c,n,{onFallback:d=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${d.message}`)}):c});if(i&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=Nr(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,i,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:i,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:i,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:i,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}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(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}updateConfig(e){let n=this.config.features?.artifacts?.display,o={...this.config,...e},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!jy(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new Os(this.config),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:r,contentParts:s,id:i,createdAt:l,sequence:p,streaming:c=!1,voiceProcessing:d,rawContent:g}=e,f={id:i??(n==="user"?aa():n==="assistant"?Br():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:c,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...d!==void 0&&{voiceProcessing:d},...g!==void 0&&{rawContent:g}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:r,content:s,llmContent:i,contentParts:l,id:p,createdAt:c,sequence:d,streaming:g=!1,voiceProcessing:b,rawContent:f}=o,C={id:p??(r==="user"?aa():r==="assistant"?Br():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:c??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:g,...i!==void 0&&{llmContent:i},...l!==void 0&&{contentParts:l},...b!==void 0&&{voiceProcessing:b},...f!==void 0&&{rawContent:f}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:r="",llmContent:s,id:i,createdAt:l,sequence:p}=e,c={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...i!==void 0&&{id:i},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(e,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
1088
+ _Details: ${n.message}_`:o}var pa=t=>({isError:!0,content:[{type:"text",text:t}]}),My=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Ty=t=>Rs(t)||t===jo,hc=class t{constructor(e={},n,o={}){this.config=e;this.callbacks=n;this.historyInternals=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.activeConversationId=null;this.activeConversationRevision=null;this.historyNextMessageCursor=null;this.historyOpenEpoch=0;this.suppressWelcomeInjection=!1;this.historyRecovery=null;this.historySendBlocked=!1;this.historyGate=null;this.olderPageRequests=new Map;this.projectionFinalizationPromise=null;this.acknowledgedProjections=new Map;this.pendingProjections=null;this.bootConversationRevision=null;this.bootRevisionCaptured=!1;this.visitorStoreUnsubscribe=null;this.subscribedVisitorStore=null;this.credentialReinitPending=!1;this.credentialReinitPromise=null;this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new da(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(Rs(n.name)||n.name===jo&&fr(this.config).enabled);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null,this.invalidateConversationRevision(),this.scheduleProjectionFinalization());let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.historyInternals=this.composeHistoryInternals(o),this.messages=[...e.initialMessages??[]].map(r=>({...r,sequence:r.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new aa(e,this.historyInternals),this.syncVisitorStoreSubscription(),this.wireDefaultWebMcpConfirm();for(let r of e.initialArtifacts??[])this.artifacts.set(r.id,{...r,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(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||du().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return lu(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=qs.isSupported()?new qs({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=e.browserFallback!==!1;if(o&&r&&s)return du().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:d})=>{let p=new l({host:o,agentId:r,clientToken:s,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return a&&n?new d(p,n,{onFallback:u=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${u.message}`)}):p});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=js(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let d=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=d.id}if(l){this.pendingVoiceUserMessageId=null;let d=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=d.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let d=this.injectMessage({role:"assistant",content:a,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=d.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}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(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;this.config.features?.history?.enabled&&(await this.historyInternals.historyBootstrapReady,this.bootConversationRevision=this.historyInternals.getStoredConversationRevision?.()??null,this.bootRevisionCaptured=!0);try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}setClientSession(e){this.clientSession=e,this.injectWelcomeMessage(e)}injectWelcomeMessage(e){if(this.suppressWelcomeInjection||!e.config.welcomeMessage||this.messages.length!==0)return;let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}setHistoryInternals(e){this.historyInternals=this.composeHistoryInternals(e),this.client.setHistoryInternals(this.historyInternals),this.syncVisitorStoreSubscription()}destroy(){this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=null}composeHistoryInternals(e){let n=e.onHistoryContinuityChanged;return{...e,onHistoryContinuityChanged:o=>{this.handleHistoryContinuityChanged(o),n?.(o)}}}get historyProvider(){return this.historyInternals.historyProvider??null}requireHistoryProvider(){let e=this.historyProvider;if(!e)throw new So("history_unavailable","No conversation history provider is installed");return e}historyContext(e){let n=this.requireHistoryProvider(),o=e??this.config.features?.history?.scope,r=this.config.getIdentityProof?"verified-user":"browser",s=o??(n.capabilities.scopes.includes(r)?r:n.capabilities.scopes[0]??r);if(!n.capabilities.scopes.includes(s))throw new xo("unsupported_scope","This history scope is not supported.");return{scope:s}}getHistoryState(){return{activeConversationId:this.activeConversationId,conversationRevision:this.activeConversationRevision,nextMessageCursor:this.historyNextMessageCursor,recovery:this.historyRecovery,sendBlocked:this.historySendBlocked}}getActiveConversationId(){return this.activeConversationId}emitHistoryState(){this.callbacks.onHistoryStateChanged?.(this.getHistoryState())}notifyHistory(e,n){this.callbacks.onHistoryNotice?.({code:e,message:n})}async awaitHistorySettled(){let e=this.historyGate;e&&await e.catch(()=>{});let n=this.projectionFinalizationPromise;n&&await n.catch(()=>{})}assertHistoryIdle(){if(this.streaming||this.status==="paused"||this.status==="resuming")throw new So("conversation_busy","Finish or stop the current turn before switching conversations")}listConversations(e){return this.requireHistoryProvider().list({...e?.cursor?{cursor:e.cursor}:{},...e?.limit!==void 0?{limit:e.limit}:{},...e?.targetId!==void 0?{targetId:e.targetId}:{},context:this.historyContext(e?.scope)})}async openConversation(e,n){let o=this.requireHistoryProvider();this.assertHistoryIdle();let r=this.historyContext(n?.scope);await this.awaitHistorySettled();let s=++this.historyOpenEpoch,a=await o.getPage(e,{context:r});if(s!==this.historyOpenEpoch)throw new So("superseded","A later selection won");let l=await o.prepareOpen(e,{context:r});if(s!==this.historyOpenEpoch)throw l.discard(),new So("superseded","A later selection won");this.suppressWelcomeInjection=!0;try{await this.commitActivation(l)}finally{this.suppressWelcomeInjection=!1}this.activeConversationId=l.conversationId||e,this.activeConversationRevision=l.conversationRevision||a.conversationRevision||null,this.historyNextMessageCursor=a.nextCursor,this.historyRecovery=null,this.historySendBlocked=!1,this.resetConversationScopedState();for(let d of a.messages)this.acknowledgedProjections.set(d.id,d.content);return this.persistConversationMetadata(),this.hydrateMessages(a.messages),this.emitHistoryState(),{summary:a.summary,nextMessageCursor:a.nextCursor}}loadOlderMessages(e,n,o){let r=this.requireHistoryProvider(),s=this.historyContext(o?.scope),a=n??this.historyNextMessageCursor;if(!a)return Promise.resolve({messages:[],nextMessageCursor:null});let l=`${e} ${a}`,d=this.olderPageRequests.get(l);if(d)return d;let p=this.fetchOlderPage(r,e,a,s).finally(()=>{this.olderPageRequests.delete(l)});return this.olderPageRequests.set(l,p),p}async fetchOlderPage(e,n,o,r){let s=this.messages[0]?.createdAt,a=await e.getPage(n,{cursor:o,...s?{beforeCreatedAt:s}:{},context:r});if(this.activeConversationId&&this.activeConversationId!==n)return{messages:[],nextMessageCursor:a.nextCursor};let l=ia(this.messages,a.messages);this.messages=this.sortMessages(l.map(d=>this.ensureSequence(d))),this.historyNextMessageCursor=a.nextCursor;for(let d of a.messages)this.acknowledgedProjections.set(d.id,d.content);return this.historyInternals.setStoredMessageCursor?.(a.nextCursor),this.callbacks.onMessagesChanged([...this.messages]),this.emitHistoryState(),{messages:a.messages,nextMessageCursor:a.nextCursor}}async startNewConversation(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let r=++this.historyOpenEpoch,s=await n.prepareStartNew({context:o});if(r!==this.historyOpenEpoch)throw s.discard(),new So("superseded","A later action won");await this.installFreshConversation(s)}async installFreshConversation(e){this.discardConversationState(),await this.commitActivation(e),this.activeConversationId=e.conversationId||null,this.activeConversationRevision=e.conversationRevision||null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.persistConversationMetadata(),this.emitHistoryState()}async deleteConversation(e,n){let o=this.requireHistoryProvider(),r=this.historyContext(n?.scope);await this.awaitHistorySettled(),await o.delete(e,{context:r}),e===this.activeConversationId&&await this.recoverFromDestroyedConversation(r)}async updateConversation(e,n,o){let r=this.requireHistoryProvider();if(!r.update)throw new So("history_unavailable","This history provider cannot update conversations");let s=this.historyContext(o?.scope);return await this.awaitHistorySettled(),r.update(e,n,{context:s})}canUpdateConversations(){return typeof this.historyProvider?.update=="function"}async clearConversationHistory(e){let n=this.requireHistoryProvider(),o=this.historyContext(e?.scope);await this.awaitHistorySettled();let r=await n.deleteAll({...e?.targetId!==void 0?{targetId:e.targetId}:{},context:o});return await this.recoverFromDestroyedConversation(o),r}async resetHistoryDevice(){let e=this.requireHistoryProvider();if(!e.resetDevice)throw new So("history_unavailable","This history provider cannot reset the device");this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null;try{return await e.resetDevice()}finally{this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.historySendBlocked=!1,this.emitHistoryState()}}async recoverFromDestroyedConversation(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historySendBlocked=!0,this.historyRecovery=null,this.emitHistoryState(),await this.prepareReplacementConversation(e)}async prepareReplacementConversation(e){let n=this.historyProvider;if(!n){this.historySendBlocked=!1,this.emitHistoryState();return}try{let o=await n.prepareStartNew({context:e});await this.installFreshConversation(o)}catch{this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue.")}}async retryRequiredConversation(){if(!(this.historyRecovery!=="new_conversation_required"||!this.historyProvider)&&(this.historyRecovery=null,await this.prepareReplacementConversation(this.historyContext()),this.historyRecovery==="new_conversation_required"))throw new So("new_conversation_required","A new conversation is required before sending")}async commitActivation(e){await e.commit();let n=this.client.getClientSession();n&&n.sessionId!==this.clientSession?.sessionId&&this.bindActivatedSession(n)}bindActivatedSession(e){this.clientSession=e,this.config.setStoredSessionId?.(e.sessionId),e.conversationId&&(this.activeConversationId=e.conversationId,this.activeConversationRevision=e.conversationRevision??null,this.config.setStoredConversationId?.(e.conversationId),this.historyInternals.setStoredConversationRevision?.(e.conversationRevision??null)),this.suppressWelcomeInjection||this.injectWelcomeMessage(e)}persistConversationMetadata(){this.activeConversationId?this.config.setStoredConversationId?.(this.activeConversationId):this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(this.activeConversationRevision),this.historyInternals.setStoredMessageCursor?.(this.historyNextMessageCursor)}resetConversationScopedState(){this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.acknowledgedProjections.clear(),this.setPendingProjections(null)}discardConversationState(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.resetConversationScopedState(),this.olderPageRequests.clear(),this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.historyInternals.setStoredConversationRevision?.(null),this.historyInternals.setStoredMessageCursor?.(null),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}handleHistoryContinuityChanged(e){this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.historySendBlocked=!0,this.discardConversationState(),this.activeConversationId=e.conversationId,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),this.notifyHistory("history_continuity_reset","This browser was reconnected to a different conversation, so the previous messages were cleared."),this.historyGate=Promise.resolve().then(()=>{this.historySendBlocked=!1,this.historyGate=null,this.emitHistoryState()})}syncVisitorStoreSubscription(){let e=this.historyInternals.visitorStore??null;e!==this.subscribedVisitorStore&&(this.visitorStoreUnsubscribe?.(),this.visitorStoreUnsubscribe=null,this.subscribedVisitorStore=e,e&&(this.visitorStoreUnsubscribe=e.subscribe(n=>this.handleExternalCredentialChange(n))))}handleExternalCredentialChange(e){if(e.source!=="external"||e.previousToken===null)return;this.clientSession=null,this.client.handleExternalCredentialChange(),this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.credentialReinitPending=!0,this.credentialReinitPromise=null;let n=this.messages.length>0;n||this.activeConversationId!==null||(this.config.getStoredConversationId?.()??null)!==null?this.discardConversationState():(this.config.clearStoredSessionId?.(),this.config.clearStoredConversationId?.(),this.olderPageRequests.clear(),this.setPendingProjections(null)),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.historyRecovery=null,this.emitHistoryState(),n&&this.notifyHistory("history_continuity_reset","This browser's conversation history was reset in another tab, so the previous messages were cleared.")}completeCredentialReinit(){return this.credentialReinitPending?(this.credentialReinitPromise||(this.credentialReinitPromise=this.runCredentialReinit().finally(()=>{this.credentialReinitPromise=null})),this.credentialReinitPromise):Promise.resolve()}async runCredentialReinit(){if(!this.isClientTokenMode()){this.credentialReinitPending=!1;return}try{this.bindActivatedSession(await this.client.initSession()),this.credentialReinitPending=!1}catch{}}reconcileBootConversation(e){let n=this.historyProvider,o=this.clientSession?.conversationId??this.config.getStoredConversationId?.()??this.activeConversationId;if(!n||!o)return Promise.resolve();let r=this.historyContext(e?.scope);this.historySendBlocked=!0,this.emitHistoryState();let s=this.runBootReconciliation(n,o,r).finally(()=>{this.historySendBlocked=this.historyRecovery!==null,this.historyGate===s&&(this.historyGate=null),this.emitHistoryState()});return this.historyGate=s,s}async runBootReconciliation(e,n,o){this.activeConversationId=n;let r=this.clientSession?.conversationRevision??this.activeConversationRevision??null,s=this.bootRevisionCaptured?this.bootConversationRevision:this.historyInternals.getStoredConversationRevision?.()??null;if(this.bootRevisionCaptured=!1,this.historyNextMessageCursor=this.historyInternals.getStoredMessageCursor?.()??this.historyNextMessageCursor,await this.replayPendingProjections(),r&&s&&r===s){this.activeConversationRevision=r;return}let a=await e.getPage(n,{context:o}),l=new Set(a.messages.map(g=>g.id)),d=this.messages.some(g=>l.has(g.id)),p=a.messages[0]?.createdAt,u;if(!d)u=a.messages.map(g=>this.ensureSequence(g));else{let g=this.resumable?this.activeAssistantMessageId:null,b=this.messages.filter(m=>l.has(m.id)||m.id===g?!0:p!==void 0&&m.createdAt<p);u=ia(b,a.messages).map(m=>this.ensureSequence(m))}this.historyNextMessageCursor=a.nextCursor,this.activeConversationRevision=a.conversationRevision||r||null,this.acknowledgedProjections.clear();for(let g of a.messages)this.acknowledgedProjections.set(g.id,g.content);this.persistConversationMetadata(),this.messages=this.sortMessages(u),this.callbacks.onMessagesChanged([...this.messages])}projectionFinalizationEnabled(){return this.config.features?.history?.enabled===!0&&this.isClientTokenMode()}setPendingProjections(e){this.pendingProjections=e,this.historyInternals.setPendingDisplayProjections?.(e)}readPendingProjections(){return this.historyInternals.getPendingDisplayProjections?.()??this.pendingProjections}recordDispatchedProjections(e){if(this.projectionFinalizationEnabled())for(let n of e){let o=sa(n);o!==void 0&&this.acknowledgedProjections.set(n.id,o)}}scheduleProjectionFinalization(){if(!this.projectionFinalizationEnabled())return;let e=this.activeConversationId;if(!e)return;let n=[];for(let o of this.messages){if(o.role!=="assistant"||o.streaming)continue;let r=sa(o);r!==void 0&&this.acknowledgedProjections.get(o.id)!==r&&n.push({id:o.id,displayContent:r})}n.length!==0&&(this.setPendingProjections({conversationId:e,messageIds:n.map(o=>o.id)}),this.enqueueProjectionFinalization(e,n))}enqueueProjectionFinalization(e,n){let r=(this.projectionFinalizationPromise??Promise.resolve()).catch(()=>{}).then(()=>this.finalizeProjections(e,n,!1)).finally(()=>{this.projectionFinalizationPromise===r&&(this.projectionFinalizationPromise=null)});this.projectionFinalizationPromise=r}async finalizeProjections(e,n,o){if(this.activeConversationId!==e)return;let r=n.filter(s=>this.acknowledgedProjections.get(s.id)!==s.displayContent);if(r.length===0){this.clearFinalizedMarker(e,n);return}try{let{conversationRevision:s}=await this.client.finalizeDisplayProjections(e,r);for(let a of r)this.acknowledgedProjections.set(a.id,a.displayContent);this.activeConversationId===e&&s&&(this.activeConversationRevision=s),this.clearFinalizedMarker(e,n)}catch(s){if(!o&&this.isTransientProjectionError(s)){await this.finalizeProjections(e,r,!0);return}if(s instanceof Ze&&(s.code==="not_found"||s.code==="conversation_deleted")){this.clearFinalizedMarker(e,n);return}this.notifyHistory("projection_finalization_failed","Some message formatting could not be saved for history; it will be retried.")}}isTransientProjectionError(e){return e instanceof Ze?e.code==="request_failed":e instanceof Error}clearFinalizedMarker(e,n){let o=this.readPendingProjections();if(!o||o.conversationId!==e)return;let r=new Set(n.map(a=>a.id)),s=o.messageIds.filter(a=>!r.has(a));this.setPendingProjections(s.length?{conversationId:e,messageIds:s}:null)}async replayPendingProjections(){if(!this.projectionFinalizationEnabled())return;let e=this.readPendingProjections();if(!e)return;if(this.activeConversationId&&e.conversationId!==this.activeConversationId){this.setPendingProjections(null);return}let n=[];for(let o of e.messageIds){let r=this.messages.find(s=>s.id===o);!r||typeof r.content!="string"||n.push({id:o,displayContent:r.content})}if(n.length===0){this.setPendingProjections(null);return}this.enqueueProjectionFinalization(e.conversationId,n),await this.projectionFinalizationPromise?.catch(()=>{})}invalidateConversationRevision(){this.activeConversationId&&(this.activeConversationRevision=null,this.historyInternals.setStoredConversationRevision?.(null))}async awaitHistorySendable(){await this.awaitHistorySettled(),await this.completeCredentialReinit(),this.historyRecovery==="new_conversation_required"&&await this.retryRequiredConversation()}static isConversationDeleted(e){return e instanceof Ze&&e.code==="conversation_deleted"}async dispatchWithDeletedRecovery(e,n,o,r){this.recordDispatchedProjections(e);try{await this.client.dispatch({messages:e,signal:n.signal,assistantMessageId:o},this.handleEvent);return}catch(s){if(!t.isConversationDeleted(s))throw s;let a=await this.recoverFromDeletedConversation(r);if(!a)throw s;this.recordDispatchedProjections([a]),await this.client.dispatch({messages:[a],signal:n.signal,assistantMessageId:o},this.handleEvent)}}async recoverFromDeletedConversation(e){let n=this.messages.find(r=>r.id===e);if(!n)return null;let o={...n};this.historyOpenEpoch+=1,this.projectionFinalizationPromise=null,this.discardConversationState(),this.activeConversationId=null,this.activeConversationRevision=null,this.historyNextMessageCursor=null,this.suppressWelcomeInjection=!0;try{let r=this.historyProvider;if(r){let s=await r.prepareStartNew({context:this.historyContext()});await this.installFreshConversation(s)}else{this.client.clearClientSession();let s=await this.client.initSession();this.bindActivatedSession(s)}}catch{return this.historySendBlocked=!0,this.historyRecovery="new_conversation_required",this.emitHistoryState(),this.notifyHistory("new_conversation_required","That conversation was deleted. Start a new conversation to continue."),null}finally{this.suppressWelcomeInjection=!1}return this.appendMessage(o),this.setStreaming(!0),this.notifyHistory("conversation_deleted_recovered","That conversation was deleted. Started a new conversation."),this.messages.find(r=>r.id===o.id)??o}updateConfig(e){let n=this.config.features?.artifacts?.display,o={...this.config,...e},r=JSON.stringify(n)!==JSON.stringify(o.features?.artifacts?.display);if(!uA(this.config,o)){this.config=o,this.client.updateConfig(o),r&&this.refreshArtifactReferenceBlocks();return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let s=this.client.getSSEEventCallback();this.config=o,this.client=new aa(this.config,this.historyInternals),r&&this.refreshArtifactReferenceBlocks(),this.wireDefaultWebMcpConfirm(),s&&this.client.setSSEEventCallback(s)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:l,sequence:d,streaming:p=!1,voiceProcessing:u,rawContent:g}=e,m={id:a??(n==="user"?pc():n==="assistant"?zs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:p,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...g!==void 0&&{rawContent:g}};return this.upsertMessage(m),m}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:r,content:s,llmContent:a,contentParts:l,id:d,createdAt:p,sequence:u,streaming:g=!1,voiceProcessing:b,rawContent:m}=o,w={id:d??(r==="user"?pc():r==="assistant"?zs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:p??new Date().toISOString(),sequence:u??this.nextSequence(),streaming:g,...a!==void 0&&{llmContent:a},...l!==void 0&&{contentParts:l},...b!==void 0&&{voiceProcessing:b},...m!==void 0&&{rawContent:m}};n.push(w)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:l,sequence:d}=e,p={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(p),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...l!==void 0&&{createdAt:l},...d!==void 0&&{sequence:d}})}async applyMentionBundle(e,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
192
1089
 
193
- `),i=[s,n].filter(Boolean).join(`
1090
+ `),a=[s,n].filter(Boolean).join(`
194
1091
 
195
- `),l=Array.isArray(e.contentParts)&&e.contentParts.length>0,p=r.contentParts.length>0;if(l){let c=[];s&&c.push(Dr(s)),c.push(...r.contentParts),c.push(...e.contentParts),e.contentParts=c}else if(p){let c=[];i&&c.push(Dr(i)),c.push(...r.contentParts),e.contentParts=c}else s&&(e.llmContent=i);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,n){let o=e.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=aa(),s=Br();this.activeAssistantMessageId=null;let i=n?.contentParts&&lg(n.contentParts)?la:"",l={id:r,role:"user",content:o||i,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let d=this.messages.find(g=>g.id===r)??l;if(await this.applyMentionBundle(d,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let c=[...this.messages];try{await this.client.dispatch({messages:c,signal:p.signal,assistantMessageId:s},this.handleEvent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;let g=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!g){let b=Cc(d,this.config.errorMessage);if(b){let f={id:s,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g||(d instanceof Error?this.callbacks.onError?.(d):this.callbacks.onError?.(new Error(String(d))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let e=Br();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let i=Cc(r,this.config.errorMessage);if(i){let l={id:e,role:"assistant",createdAt:new Date().toISOString(),content:i,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(s=>s.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let r=`approval-${e.id}`,s={...e,status:n,resolvedAt:Date.now()},i=this.messages.find(d=>d.id===r),l={id:r,role:"assistant",content:"",createdAt:i?.createdAt??new Date().toISOString(),...i?.sequence!==void 0?{sequence:i.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,c=p&&typeof p=="object"?p.onDecision:void 0;try{let d;if(c?d=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):d=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),d){let g=null;if(d instanceof Response){if(!d.ok){let b=await d.json().catch(()=>null);throw new Error(b?.error??`Approval request failed: ${d.status}`)}g=d.body}else d instanceof ReadableStream&&(g=d);g?await this.connectStream(g,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(d){let g=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}persistAskUserQuestionProgress(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){if(this.messages.find(d=>d.id===e.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=e.agentMetadata?.executionId,s=e.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let i=typeof n=="string"?void 0:n;if(i===void 0&&typeof n=="string"){let d=e.toolCall?.args,g=Array.isArray(d?.questions)?d.questions:[];if(g.length===1){let b=typeof g[0]?.question=="string"?g[0].question:"";b&&(i={[b]:n})}}this.markAskUserQuestionResolved(e,i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,p=e.toolCall?.args,c=Array.isArray(p?.questions)?p.questions:[];if(c.length===0){let d=typeof n=="string"?n:Object.entries(n).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let d=i??{};c.forEach((g,b)=>{let f=typeof g?.question=="string"?g.question:"";if(!f)return;let y=d[f],C=Array.isArray(y)?y.join(", "):typeof y=="string"?y:"";this.appendMessage({id:`ask-user-q-${l}-${b}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${b}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let d=await this.client.resumeFlow(r,{[s]:n});if(!d.ok){let g=await d.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${d.status}`)}d.body?await this.connectStream(d.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(d){let g=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)))}}enqueueWebMcpAwait(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){let o=[this.messages.find(r=>r.id===e.id)?.toolCall?.startedAt,e.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(e){return e.toolCall?.name!==eo?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,r=Date.now(),s){this.messages.some(i=>i.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let i=await Promise.all(n.map(async p=>{let c=p.toolCall?.name,d=p.toolCall?.id;if(!c||!d)return null;let g=`${e}:${d}`;if(this.webMcpInflightKeys.has(g)||this.webMcpResolvedKeys.has(g)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(g),o.push(g);let b=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??c;if(c===eo)return{dedupeKey:g,resumeKey:f,output:mc(),toolMessage:p,startedAt:b,completedAt:Date.now()};let y=new AbortController;this.webMcpResolveControllers.add(y),r.push(y);let C=this.client.executeWebMcpToolCall(c,p.toolCall?.args,y.signal),M;if(!C)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await C}catch(I){let S=I instanceof Error&&(I.name==="AbortError"||I.message.includes("aborted")||I.message.includes("abort"));return S||this.callbacks.onError?.(I instanceof Error?I:new Error(String(I))),this.markWebMcpToolComplete(p,_s(S?"Aborted by cancel()":Ag(I)),b),this.webMcpInflightKeys.delete(g),null}return y.signal.aborted?(this.markWebMcpToolComplete(p,_s("Aborted by cancel()"),b),this.webMcpInflightKeys.delete(g),null):{dedupeKey:g,resumeKey:f,output:M,toolMessage:p,startedAt:b,completedAt:Date.now()}})),l=[];try{if(l=i.filter(d=>d!==null),l.length===0)return;let p={};for(let d of l)p[d.resumeKey]=d.output;let c=await this.client.resumeFlow(e,p,{signal:s.signal});if(!c.ok){let d=await c.json().catch(()=>null);throw new Error(d?.error??`Resume failed: ${c.status}`)}for(let d of l)this.webMcpResolvedKeys.add(d.dedupeKey),this.markWebMcpToolComplete(d.toolMessage,d.output,d.startedAt,d.completedAt,d.toolMessage.toolCall?.name===eo?{suggestRepliesResolved:!0}:void 0);c.body&&await this.connectStream(c.body,{allowReentry:!0})}catch(p){if(!(p instanceof Error&&(p.name==="AbortError"||p.message.includes("aborted")||p.message.includes("abort"))))this.callbacks.onError?.(p instanceof Error?p:new Error(String(p)));else for(let d of l)this.markWebMcpToolComplete(d.toolMessage,_s("Aborted by cancel()"),d.startedAt)}finally{for(let p of o)this.webMcpInflightKeys.delete(p);for(let p of r)this.webMcpResolveControllers.delete(p);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.name,r=e.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let y=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(y)||this.webMcpResolvedKeys.has(y))return;this.webMcpInflightKeys.add(y);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(y)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(y)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let i=this.markWebMcpToolRunning(e),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:p}=l;this.setStreaming(!0);let c=o===eo,d=e.toolCall?.args,g=c?null:this.client.executeWebMcpToolCall(o,d,p),b="execute",f=i;try{let y;if(c?y=mc():g?y=await g:y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(e,_s("Aborted by cancel()"),i);return}let C=e.agentMetadata?.webMcpToolCallId??o;b="resume",await this.resumeWithToolOutput(n,C,y,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,y,i,f,c?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(y){let C=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));(b==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(e,_s(C||p.aborted?"Aborted by cancel()":Ag(y)),i),C||this.callbacks.onError?.(y instanceof Error?y:new Error(String(y)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,n,o,r){let s=await this.client.resumeFlow(e,{[n]:o},{signal:r?.signal});if(!s.ok){let i=await s.json().catch(()=>null);throw new Error(i?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),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(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=xo(this.config.features?.artifacts,e),r=Ls(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),s=this.messages.find(i=>i.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let e=!1;for(let n of this.artifacts.values()){let o=this.messages.find(i=>i.id===`artifact-ref-${n.id}`);if(!o)continue;let r=xo(this.config.features?.artifacts,n),s=Ls(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(e){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(e=>{this.reconnecting&&this.resumable&&e.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(Cg(),wg)).then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,r)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>Cc(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Br(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=xc(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return da(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=xc(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let i={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(i.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(i.agentMetadata={...i.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let d=r.approval,g=n.approval;i.approval={...d,...g,executionId:g.executionId||d.executionId,toolName:g.toolName||d.toolName,description:g.description||d.description,toolType:g.toolType??d.toolType,reason:g.reason??d.reason,parameters:g.parameters??d.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,c=n.toolCall?.id;if(l&&Sg(l)&&p&&c&&n.agentMetadata?.awaitingLocalTool===!0){let d=`${p}:${c}`,g=this.webMcpInflightKeys.has(d),b=this.webMcpResolvedKeys.has(d),f=r.toolCall?.name,y=r.agentMetadata?.executionId===p&&r.toolCall?.id===c&&f!==void 0&&Sg(f)&&r.toolCall?.status==="complete";(g||b||y)&&(i.agentMetadata={...i.agentMetadata??{},awaitingLocalTool:!1},i.toolCall=r.toolCall,i.streaming=r.streaming)}return i}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=n.sequence??0,l=o.sequence??0;return i!==l?i-l:n.id.localeCompare(o.id)})}};Ye();xt();var fa={allowedTypes:to,maxFileSize:10*1024*1024,maxFiles:4};function Ky(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Gy(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var $s=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:e.allowedTypes??fa.allowedTypes,maxFileSize:e.maxFileSize??fa.maxFileSize,maxFiles:e.maxFiles??fa.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}remountPreviews(e){if(this.previewsContainer=e,e){e.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:fa.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){if(e.length){for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=pg(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await dg(n),s=ca(n)?URL.createObjectURL(n):null,i={id:Ky(),file:n,previewUrl:s,contentPart:r};this.attachments.push(i),this.renderPreview(i)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(e){let n=this.attachments.findIndex(s=>s.id===e);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=ca(e.file),o=v("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let i=v("img");i.src=e.previewUrl,i.alt=e.file.name,i.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",o.appendChild(i)}else{let i=v("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--persona-container, #f3f4f6)",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let l=Gy(e.file.type),p=ie(l,20,"var(--persona-muted, #6b7280)",1.5);p&&i.appendChild(p);let c=v("span");c.textContent=ug(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",i.appendChild(c),o.appendChild(i)}let r=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=ie("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n})}};Ye();ma();Ac();Ye();xt();var Bt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Ut=1e5,ba=Ut+1;var Yy=8,Jy=8,Sc=10,Mc=new WeakMap,kg=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,Zy=t=>{let e=t.getRootNode?.();return kg(e)?e:t.ownerDocument.body},Tc=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n));function jt(t){Mc.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,enabled:r=!0,gap:s=Yy,viewportPadding:i=Jy}=t,l=()=>e.ownerDocument,p=()=>l().defaultView??window,c=null,d=null,g=null,b=!1,f=!1,y=!1,C=()=>(typeof o=="function"?o():o).trim(),M=()=>{g?.(),g=null,c?.remove(),c=null,d=null},I=()=>{if(!c)return;let H=l(),w=p(),N=e.getBoundingClientRect(),K=c.getBoundingClientRect(),te=H.documentElement.clientWidth||w.innerWidth,Q=H.documentElement.clientHeight||w.innerHeight,se=te-i-K.width,J=N.left+N.width/2-K.width/2,oe=Tc(J,i,se),Y=N.top-i,pe=Q-i-N.bottom,ne=K.height+s,me=Y>=ne||Y>=pe?"top":"bottom",ve=me==="top"?N.top-s-K.height:N.bottom+s,be=Q-i-K.height,Te=Tc(ve,i,be),ze=N.left+N.width/2,Oe=Math.max(Sc,K.width-Sc),Ne=Tc(ze-oe,Sc,Oe);c.dataset.placement=me,c.style.left=`${oe}px`,c.style.top=`${Te}px`,c.style.setProperty("--persona-tooltip-arrow-x",`${Ne}px`)},S=()=>{if(y||!r||c||!e.isConnected)return;let H=C(),w=Zy(e);if(!H||!w)return;let N=l(),K=p();c=N.createElement("div"),c.className="persona-control-tooltip",c.setAttribute("role","tooltip"),c.dataset.state="measuring",c.style.zIndex=String(ba),d=N.createElement("span"),d.className="persona-control-tooltip__label",d.textContent=H,c.appendChild(d);let te=N.createElement("span");te.className="persona-control-tooltip__arrow",c.appendChild(te),w.appendChild(c),I(),c.dataset.state="open";let Q=()=>{if(!e.isConnected){M();return}d&&(d.textContent=C()),I()};K.addEventListener("scroll",Q,!0),K.addEventListener("resize",Q);let se=e.getRootNode(),J=kg(se)?se:N.documentElement,oe=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||M()});oe?.observe(J,{childList:!0,subtree:!0}),g=()=>{K.removeEventListener("scroll",Q,!0),K.removeEventListener("resize",Q),oe?.disconnect()}},E=()=>{b||f?S():M()},L=()=>{let H=p();(!H.matchMedia||!H.matchMedia("(hover: none)").matches)&&(b=!0,E())},D=()=>{b=!1,E()},z=()=>{f=!0,E()},$=()=>{f=!1,E()},F=H=>{H.key==="Escape"&&(b=!1,f=!1,M())};n.addEventListener("mouseenter",L),n.addEventListener("mouseleave",D),e.addEventListener("focus",z),e.addEventListener("blur",$),e.addEventListener("keydown",F);let B={get isOpen(){return c!==null},show:S,hide:M,reposition:I,destroy:()=>{y||(y=!0,M(),n.removeEventListener("mouseenter",L),n.removeEventListener("mouseleave",D),e.removeEventListener("focus",z),e.removeEventListener("blur",$),e.removeEventListener("keydown",F),Mc.delete(e))}};return Mc.set(e,B),B}function Lg(t){let{config:e,onOpen:n}=t,o=t.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),i=e.buttonIconName??"plus",l=e.buttonTooltipText??"Add context",p=v("div","persona-send-button-wrapper"),c=ye("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),d=ie(i,s,"currentColor",1.5);return d?c.appendChild(d):c.textContent="+",c.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),n()}),p.appendChild(c),jt({anchor:c,trigger:p,text:()=>c.getAttribute("aria-label")??l}),{button:c,wrapper:p}}var{setLoader:GS,load:av}=Er({fallbackImport:()=>Promise.resolve().then(()=>(Xg(),Qg))});var Wc=av;var{setLoader:iM,load:bv}=Er({fallbackImport:()=>Promise.resolve().then(()=>(cf(),lf)),resetOnSetLoader:!0});var df=bv;Ye();xt();function Ks(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=ye("span",{className:Bn("persona-mention-token",e.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":t.sourceId,title:t.label,role:"img","aria-label":`${t.label} mention`}});t.color&&n.style.setProperty("--persona-mention-token-accent",t.color);let o=ie(t.iconName??"at-sign",13,"currentColor",2);if(o){let r=v("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(ye("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function pf(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=ha(e).filter(E=>E.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(E=>E.sources.some(L=>typeof L.matchCommand=="function")),r=E=>o.some(L=>L.trigger?L.position==="line-start"?E.split(`
196
- `).some(z=>z.startsWith(L.trigger)):(L.position==="anywhere"?E:E.split(`
197
- `)[0]).startsWith(L.trigger):!1),s=(E,L)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${E}`,{detail:L}))}catch{}},i=ye("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,c=t.textarea,d=null,g=null,b=null,f=null,y=()=>{if(l)return Promise.resolve(l);if(p)return p;let E=Wc().then(L=>(l=L.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:d??void 0,anchor:t.anchor,contextRow:i,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:S,emit:s}),l)).catch(L=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",L),p===E&&(p=null),null));return p=E,E},C=()=>{df().then(E=>{let L=E.mountInlineComposer({textarea:t.textarea,renderToken:z=>Ks(z,{render:e.renderMentionToken}),onMentionRemoved:z=>l?.untrackMention(z)});d=L.input,g=L.destroy;let D=c;D.replaceWith(L.element),c=L.element,f={next:L.element,prev:D},b?.(L.element,D),l?l.rebindComposer(L.input):p&&p.then(z=>z?.rebindComposer(L.input))}).catch(E=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",E)})};e.display==="inline"&&C();let M=[],I=new Map;for(let E of n){if(!E.showButton)continue;let L=Lg({config:{...e,buttonIconName:E.buttonIconName,buttonTooltipText:E.buttonTooltipText},buttonSize:t.config.sendButton?.size,onOpen:()=>{y().then(D=>D?.openMenu(E.trigger))}});M.push(L),I.set(E.trigger,L.button)}let S=(E,L,D)=>{let z=I.get(L);z&&(z.setAttribute("aria-expanded",E?"true":"false"),E?z.setAttribute("aria-controls",D):z.removeAttribute("aria-controls"))};return{affordanceButtons:M.map(E=>E.wrapper),contextRow:i,handleInput:E=>{if(l){l.handleInput();return}if(!Tg(E))return;let L=c,D=L.selectionStart??0;zs(L.value,D,n)&&y().then(z=>z?.handleInput())},handleKeydown:E=>{if(l?.isMenuOpen())return l.handleKeydown(E);if(E.key==="Backspace"&&l?.hasMentions()&&!f){let L=c,D=L.selectionStart===0&&L.selectionEnd===0;if((L.value.length===0||D)&&l.removeLastChip())return E.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async E=>r(E)?(l??await y())?.dispatchInlineCommand(E)??null:null,clear:()=>l?.clear(),prefetch:()=>{Wc().catch(()=>{})},onComposerSwap:E=>{b=E,f&&E(f.next,f.prev)},destroy:()=>{l?.destroy(),g?.();for(let E of M)E.wrapper.remove();i.remove()}}}var uf=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Gs(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];uf(s)&&uf(r)?n[o]=Gs(s,r):n[o]=r}return n}var no="min(440px, calc(100vw - 24px))",ff="440px",yv={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:no,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)"},it={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:yv,copy:{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:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",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:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function gf(t,e){if(!(!t&&!e))return t?e?Gs(t,e):t:e}function La(t){return t?{...it,...t,theme:gf(it.theme,t.theme),darkTheme:gf(it.darkTheme,t.darkTheme),launcher:{...it.launcher,...t.launcher,dock:{...it.launcher?.dock,...t.launcher?.dock},clearChat:{...it.launcher?.clearChat,...t.launcher?.clearChat}},copy:{...it.copy,...t.copy},sendButton:{...it.sendButton,...t.sendButton},statusIndicator:{...it.statusIndicator,...t.statusIndicator},voiceRecognition:{...it.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=it.features?.artifacts,n=t.features?.artifacts,o=it.features?.scrollToBottom,r=t.features?.scrollToBottom,s=it.features?.scrollBehavior,i=t.features?.scrollBehavior,l=it.features?.streamAnimation,p=t.features?.streamAnimation,c=it.features?.askUserQuestion,d=t.features?.askUserQuestion,g=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},b=o===void 0&&r===void 0?void 0:{...o,...r},f=s===void 0&&i===void 0?void 0:{...s,...i},y=l===void 0&&p===void 0?void 0:{...l,...p},C=c===void 0&&d===void 0?void 0:{...c,...d,styles:{...c?.styles,...d?.styles}};return{...it.features,...t.features,...b!==void 0?{scrollToBottom:b}:{},...f!==void 0?{scrollBehavior:f}:{},...g!==void 0?{artifacts:g}:{},...y!==void 0?{streamAnimation:y}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:t.suggestionChips??it.suggestionChips,suggestionChipsConfig:{...it.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...it.layout,...t.layout,header:{...it.layout?.header,...t.layout?.header},messages:{...it.layout?.messages,...t.layout?.messages,avatar:{...it.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...it.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...it.layout?.slots,...t.layout?.slots}},markdown:{...it.markdown,...t.markdown,options:{...it.markdown?.options,...t.markdown?.options}},messageActions:{...it.messageActions,...t.messageActions}}:it}var Pa="16px",Ia="transparent",vv={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"}},xv={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"}},wv={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"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:no,maxWidth:ff,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Pa,canvasBackground:Ia},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:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},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 tn(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?tn(t,o):o}function mf(t){let e={};function n(o,r){for(let[s,i]of Object.entries(o)){let l=`${r}.${s}`;if(typeof i=="string"){let p=tn(t,i);p!==void 0&&(e[l]={path:l,value:p,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof i=="object"&&i!==null&&n(i,l)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function Cv(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function hf(t,e){let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=hf(s,r):n[o]=r}return n}function Av(t,e){return e?hf(t,e):t}function _r(t,e={}){let n={palette:vv,semantic:xv,components:wv},o={palette:{...n.palette,...t?.palette,colors:{...n.palette.colors,...t?.palette?.colors},spacing:{...n.palette.spacing,...t?.palette?.spacing},typography:{...n.palette.typography,...t?.palette?.typography},shadows:{...n.palette.shadows,...t?.palette?.shadows},borders:{...n.palette.borders,...t?.palette?.borders},radius:{...n.palette.radius,...t?.palette?.radius}},semantic:{...n.semantic,...t?.semantic,colors:{...n.semantic.colors,...t?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...t?.semantic?.spacing},typography:{...n.semantic.typography,...t?.semantic?.typography}},components:Av(n.components,t?.components)};if(e.validate!==!1){let r=Cv(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(e.plugins)for(let r of e.plugins)o=r.transform(o);return o}function bf(t){let e=mf(t),n={};for(let[w,N]of Object.entries(e)){let K=w.replace(/\./g,"-");n[`--persona-${K}`]=N.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-primary"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-text-inverse"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Pa,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Ia,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??n["--persona-muted"];let o=t.components?.header;o?.shadow&&(n["--persona-header-shadow"]=o.shadow),o?.borderBottom&&(n["--persona-header-border-bottom"]=o.borderBottom),n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem";let r=n["--persona-components-introCard-background"],s=n["--persona-components-introCard-shadow"],i=(!r||r==="transparent"||r==="none")&&(!s||s==="none"),l=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=i&&l==="1.5rem"?"1.5rem 0":l,n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-intro-card-border"]=n["--persona-components-introCard-border"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-composer-padding"]=n["--persona-components-composer-padding"]??"0.75rem 1rem",n["--persona-composer-gap"]=n["--persona-components-composer-gap"]??"0.5rem",n["--persona-composer-font-size"]=n["--persona-components-composer-fontSize"]??"0.875rem",n["--persona-composer-line-height"]=n["--persona-components-composer-lineHeight"]??"1.25rem",n["--persona-composer-border-color"]=n["--persona-components-composer-borderColor"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-thumb"]=n["--persona-components-scrollbar-thumb"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-track"]=n["--persona-components-scrollbar-track"]??"transparent",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let p=n["--persona-components-markdown-heading-h1-fontSize"];p&&(n["--persona-md-h1-size"]=p);let c=n["--persona-components-markdown-heading-h1-fontWeight"];c&&(n["--persona-md-h1-weight"]=c);let d=n["--persona-components-markdown-heading-h2-fontSize"];d&&(n["--persona-md-h2-size"]=d);let g=n["--persona-components-markdown-heading-h2-fontWeight"];g&&(n["--persona-md-h2-weight"]=g);let b=n["--persona-components-markdown-prose-fontFamily"];b&&b!=="inherit"&&(n["--persona-md-prose-font-family"]=b),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-code-block-border-radius"]=n["--persona-components-markdown-codeBlock-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let f=t.components,y=f?.iconButton;y&&(y.background&&(n["--persona-icon-btn-bg"]=y.background),y.border&&(n["--persona-icon-btn-border"]=y.border),y.color&&(n["--persona-icon-btn-color"]=y.color),y.padding&&(n["--persona-icon-btn-padding"]=y.padding),y.borderRadius&&(n["--persona-icon-btn-radius"]=y.borderRadius),y.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=y.hoverBackground),y.hoverColor&&(n["--persona-icon-btn-hover-color"]=y.hoverColor),y.activeBackground&&(n["--persona-icon-btn-active-bg"]=y.activeBackground),y.activeBorder&&(n["--persona-icon-btn-active-border"]=y.activeBorder));let C=f?.labelButton;C&&(C.background&&(n["--persona-label-btn-bg"]=C.background),C.border&&(n["--persona-label-btn-border"]=C.border),C.color&&(n["--persona-label-btn-color"]=C.color),C.padding&&(n["--persona-label-btn-padding"]=C.padding),C.borderRadius&&(n["--persona-label-btn-radius"]=C.borderRadius),C.hoverBackground&&(n["--persona-label-btn-hover-bg"]=C.hoverBackground),C.fontSize&&(n["--persona-label-btn-font-size"]=C.fontSize),C.gap&&(n["--persona-label-btn-gap"]=C.gap));let M=f?.toggleGroup;M&&(M.gap&&(n["--persona-toggle-group-gap"]=M.gap),M.borderRadius&&(n["--persona-toggle-group-radius"]=M.borderRadius));let I=f?.artifact;if(I?.toolbar){let w=I.toolbar;w.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=w.iconHoverColor),w.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=w.iconHoverBackground),w.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=w.iconPadding),w.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=w.iconBorderRadius),w.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=w.iconBorder),w.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=w.toggleGroupGap),w.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=w.toggleBorderRadius),w.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=w.toggleGroupPadding),w.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=w.toggleGroupBorder),w.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=w.toggleGroupBorderRadius),w.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=tn(t,w.toggleGroupBackground)??w.toggleGroupBackground),w.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=w.copyBackground),w.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=w.copyBorder),w.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=w.copyColor),w.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=w.copyBorderRadius),w.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=w.copyPadding),w.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=w.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??w.copyMenuBackground),w.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=w.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??w.copyMenuBorder),w.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=w.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??w.copyMenuShadow),w.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=w.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??w.copyMenuBorderRadius),w.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=w.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??w.copyMenuItemHoverBackground),w.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=w.iconBackground),w.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=w.toolbarBorder)}if(I?.tab){let w=I.tab;w.background&&(n["--persona-artifact-tab-bg"]=w.background),w.activeBackground&&(n["--persona-artifact-tab-active-bg"]=w.activeBackground),w.activeBorder&&(n["--persona-artifact-tab-active-border"]=w.activeBorder),w.borderRadius&&(n["--persona-artifact-tab-radius"]=w.borderRadius),w.textColor&&(n["--persona-artifact-tab-color"]=w.textColor),w.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=w.hoverBackground),w.listBackground&&(n["--persona-artifact-tab-list-bg"]=w.listBackground),w.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=w.listBorderColor),w.listPadding&&(n["--persona-artifact-tab-list-padding"]=w.listPadding)}if(I?.pane){let w=I.pane;if(w.toolbarBackground){let N=tn(t,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=N}}if(I?.card){let w=I.card;w.background&&(n["--persona-artifact-card-bg"]=w.background),w.border&&(n["--persona-artifact-card-border"]=w.border),w.borderRadius&&(n["--persona-artifact-card-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=w.hoverBackground),w.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=w.hoverBorderColor)}if(I?.inline){let w=I.inline;w.background&&(n["--persona-artifact-inline-bg"]=tn(t,w.background)??w.background),w.border&&(n["--persona-artifact-inline-border"]=w.border),w.borderRadius&&(n["--persona-artifact-inline-radius"]=w.borderRadius),w.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=tn(t,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=tn(t,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=tn(t,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=tn(t,w.mutedColor)??w.mutedColor),w.frameHeight&&(n["--persona-artifact-inline-frame-height"]=w.frameHeight)}let S=f?.code;S&&(S.keywordColor&&(n["--persona-code-keyword-color"]=S.keywordColor),S.stringColor&&(n["--persona-code-string-color"]=S.stringColor),S.commentColor&&(n["--persona-code-comment-color"]=S.commentColor),S.numberColor&&(n["--persona-code-number-color"]=S.numberColor),S.tagColor&&(n["--persona-code-tag-color"]=S.tagColor),S.attrColor&&(n["--persona-code-attr-color"]=S.attrColor),S.propertyColor&&(n["--persona-code-property-color"]=S.propertyColor),S.lineNumberColor&&(n["--persona-code-line-number-color"]=S.lineNumberColor),S.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=S.gutterBorderColor),S.background&&(n["--persona-code-bg"]=tn(t,S.background)??S.background));let E=n["--persona-surface"],L=n["--persona-container"],D=n["--persona-palette-colors-gray-100"]??"#f3f4f6",z=n["--persona-palette-colors-gray-200"]??"#e5e7eb",$=n["--persona-palette-colors-gray-300"]??"#d1d5db",F=!L||L===E,B=F?D:L,H=F?z:L;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??B,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??H,F&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??$),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??B,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??B,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??B,n}var Sv={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"}}},yf=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},zc=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Mv=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":zc()},vf=t=>Mv(t),Tv=t=>_r(t),Ev=t=>_r({...t,palette:{...t?.palette,colors:{...Sv.colors,...t?.palette?.colors}}},{validate:!1}),$r=t=>{let e=vf(t),n=yf(t?.theme),o=yf(t?.darkTheme);return e==="dark"?Ev(Gs(n??{},o??{})):Tv(n)},kv=t=>bf(t),Qs=(t,e)=>{let n=$r(e),o=kv(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",vf(e))},Ra=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(zc())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t(zc());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};xt();Ye();var To=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");function Fn(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function xf(t){let e=Fn(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function Wa(t){if(typeof t!="string")return"";let e=t.indexOf(`
1092
+ `),l=Array.isArray(e.contentParts)&&e.contentParts.length>0,d=r.contentParts.length>0;if(l){let p=[];s&&p.push(hr(s)),p.push(...r.contentParts),p.push(...e.contentParts),e.contentParts=p}else if(d){let p=[];a&&p.push(hr(a)),p.push(...r.contentParts),e.contentParts=p}else s&&(e.llmContent=a);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,n){let o=e.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=pc(),s=zs();this.activeAssistantMessageId=null;let a=n?.contentParts&&lc(n.contentParts)?$s:"",l={id:r,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(l),this.setStreaming(!0);let d=new AbortController;if(this.abortController=d,n?.mentions){let u=this.messages.find(g=>g.id===r)??l;if(await this.applyMentionBundle(u,o,n.mentions.finalize),d.signal.aborted||this.abortController!==d)return;this.callbacks.onMessagesChanged([...this.messages])}let p=[...this.messages];try{await this.dispatchWithDeletedRecovery(p,d,s,r)}catch(u){if(this.status==="resuming"||this.reconnecting)return;let g=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));if(!g){let b=pu(u,this.config.errorMessage);if(b){let m={id:s,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.nextSequence()};this.appendMessage(m)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,g||(u instanceof Error?this.callbacks.onError?.(u):this.callbacks.onError?.(new Error(String(u))))}}async continueConversation(){if(this.streaming)return;(this.historyGate||this.projectionFinalizationPromise||this.historySendBlocked||this.credentialReinitPending)&&await this.awaitHistorySendable(),this.abortController?.abort(),this.teardownReconnect();let e=zs();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:n.signal,assistantMessageId:e},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=pu(r,this.config.errorMessage);if(a){let l={id:e,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(l)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,s||(r instanceof Error?this.callbacks.onError?.(r):this.callbacks.onError?.(new Error(String(r))))}}async connectStream(e,n){if(this.streaming&&!n?.allowReentry)return;n?.allowReentry||this.abortController?.abort(),n?.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let o=n?.preserveAssistantId?n.assistantMessageId:void 0,r=!1;for(let s of this.messages)s.streaming&&s.id!==o&&(s.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n?.assistantMessageId,n?.seedContent)}catch(s){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.callbacks.onError?.(s instanceof Error?s:new Error(String(s)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;e?.enabled===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){try{if(this.config.webmcp?.autoApprove?.(e)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:e.description??`Allow the assistant to run ${e.toolName}?`,parameters:e.args},o=`approval-${n.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(r=>{this.webMcpApprovalResolvers.set(o,r)})}resolveWebMcpApproval(e,n){let o=this.webMcpApprovalResolvers.get(e);if(!o)return;this.webMcpApprovalResolvers.delete(e);let r=this.messages.find(s=>s.id===e);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(e,n,o){let r=`approval-${e.id}`,s={...e,status:n,resolvedAt:Date.now()},a=this.messages.find(u=>u.id===r),l={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(l),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,p=d&&typeof d=="object"?d.onDecision:void 0;try{let u;if(p?u=await p({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,o):u=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),u){let g=null;if(u instanceof Response){if(!u.ok){let b=await u.json().catch(()=>null);throw new Error(b?.error??`Approval request failed: ${u.status}`)}g=u.body}else u instanceof ReadableStream&&(g=u);g?await this.connectStream(g,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(u){let g=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}persistAskUserQuestionProgress(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let o=this.messages.find(r=>r.id===e.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){if(this.messages.find(u=>u.id===e.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=e.agentMetadata?.executionId,s=e.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let u=e.toolCall?.args,g=Array.isArray(u?.questions)?u.questions:[];if(g.length===1){let b=typeof g[0]?.question=="string"?g[0].question:"";b&&(a={[b]:n})}}this.markAskUserQuestionResolved(e,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,d=e.toolCall?.args,p=Array.isArray(d?.questions)?d.questions:[];if(p.length===0){let u=typeof n=="string"?n:Object.entries(n).map(([g,b])=>`${g}: ${Array.isArray(b)?b.join(", "):b}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:u,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let u=a??{};p.forEach((g,b)=>{let m=typeof g?.question=="string"?g.question:"";if(!m)return;let y=u[m],w=Array.isArray(y)?y.join(", "):typeof y=="string"?y:"";this.appendMessage({id:`ask-user-q-${l}-${b}`,role:"assistant",content:m,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${b}`,role:"user",content:w||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let u=await this.client.resumeFlow(r,{[s]:n});if(!u.ok){let g=await u.json().catch(()=>null);throw new Error(g?.error??`Resume failed: ${u.status}`)}u.body?await this.connectStream(u.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(u){let g=u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"));this.setStreaming(!1),this.abortController=null,g||this.callbacks.onError?.(u instanceof Error?u:new Error(String(u)))}}enqueueWebMcpAwait(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let r=this.webMcpAwaitBatches.get(n);r||(r={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,r)),!r.seen.has(o)&&(r.seen.add(o),r.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(e,o)}resolveWebMcpToolStartedAt(e){let o=[this.messages.find(r=>r.id===e.id)?.toolCall?.startedAt,e.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(e){return e.toolCall?.name!==jo?!1:(this.messages.find(o=>o.id===e.id)??e).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,o,r=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:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async d=>{let p=d.toolCall?.name,u=d.toolCall?.id;if(!p||!u)return null;let g=`${e}:${u}`;if(this.webMcpInflightKeys.has(g)||this.webMcpResolvedKeys.has(g)||this.isSuggestRepliesAlreadyResolved(d))return null;this.webMcpInflightKeys.add(g),o.push(g);let b=this.markWebMcpToolRunning(d),m=d.agentMetadata?.webMcpToolCallId??p;if(p===jo)return{dedupeKey:g,resumeKey:m,output:ou(),toolMessage:d,startedAt:b,completedAt:Date.now()};let y=new AbortController;this.webMcpResolveControllers.add(y),r.push(y);let w=this.client.executeWebMcpToolCall(p,d.toolCall?.args,y.signal),T;if(!w)T={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{T=await w}catch(W){let E=W instanceof Error&&(W.name==="AbortError"||W.message.includes("aborted")||W.message.includes("abort"));return E||this.callbacks.onError?.(W instanceof Error?W:new Error(String(W))),this.markWebMcpToolComplete(d,pa(E?"Aborted by cancel()":My(W)),b),this.webMcpInflightKeys.delete(g),null}return y.signal.aborted?(this.markWebMcpToolComplete(d,pa("Aborted by cancel()"),b),this.webMcpInflightKeys.delete(g),null):{dedupeKey:g,resumeKey:m,output:T,toolMessage:d,startedAt:b,completedAt:Date.now()}})),l=[];try{if(l=a.filter(u=>u!==null),l.length===0)return;let d={};for(let u of l)d[u.resumeKey]=u.output;let p=await this.client.resumeFlow(e,d,{signal:s.signal});if(!p.ok){let u=await p.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${p.status}`)}for(let u of l)this.webMcpResolvedKeys.add(u.dedupeKey),this.markWebMcpToolComplete(u.toolMessage,u.output,u.startedAt,u.completedAt,u.toolMessage.toolCall?.name===jo?{suggestRepliesResolved:!0}:void 0);p.body&&await this.connectStream(p.body,{allowReentry:!0})}catch(d){if(!(d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"))))this.callbacks.onError?.(d instanceof Error?d:new Error(String(d)));else for(let u of l)this.markWebMcpToolComplete(u.toolMessage,pa("Aborted by cancel()"),u.startedAt)}finally{for(let d of o)this.webMcpInflightKeys.delete(d);for(let d of r)this.webMcpResolveControllers.delete(d);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){let n=e.agentMetadata?.executionId,o=e.toolCall?.name,r=e.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let y=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(y)||this.webMcpResolvedKeys.has(y))return;this.webMcpInflightKeys.add(y);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(y)}catch(w){this.callbacks.onError?.(w instanceof Error?w:new Error(String(w)))}finally{this.webMcpInflightKeys.delete(y)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),l=new AbortController;this.webMcpResolveControllers.add(l);let{signal:d}=l;this.setStreaming(!0);let p=o===jo,u=e.toolCall?.args,g=p?null:this.client.executeWebMcpToolCall(o,u,d),b="execute",m=a;try{let y;if(p?y=ou():g?y=await g:y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(e,pa("Aborted by cancel()"),a);return}let w=e.agentMetadata?.webMcpToolCallId??o;b="resume",await this.resumeWithToolOutput(n,w,y,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,y,a,m,p?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(y){let w=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));(b==="execute"||w||d.aborted)&&this.markWebMcpToolComplete(e,pa(w||d.aborted?"Aborted by cancel()":My(y)),a),w||this.callbacks.onError?.(y instanceof Error?y:new Error(String(y)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(l),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,n,o,r){let s=await this.client.resumeFlow(e,{[n]:o},{signal:r?.signal});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),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(){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){this.stopSpeaking(),this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=e.artifactType==="markdown"?{id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content,...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{},...e.presentation?{presentation:e.presentation}:{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),e.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(e){let n=`artifact-ref-${e.id}`,o=dr(this.config.features?.artifacts,e),r=Ji(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...e.presentation?{presentation:e.presentation}:{},...e.component?{component:e.component}:{},...e.props?{componentProps:e.props}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}refreshArtifactReferenceBlocks(){let e=!1;for(let n of this.artifacts.values()){let o=this.messages.find(a=>a.id===`artifact-ref-${n.id}`);if(!o)continue;let r=dr(this.config.features?.artifacts,n),s=Ji(r,{artifactId:n.id,title:n.title,artifactType:n.artifactType,status:n.status,...n.file?{file:n.file}:{},...n.presentation?{presentation:n.presentation}:{},...n.component?{component:n.component}:{},...n.props?{componentProps:n.props}:{},...n.markdown!==void 0?{markdown:n.markdown}:{}});o.rawContent!==s&&(o.rawContent=s,o.streaming=n.status==="streaming",e=!0)}e&&this.callbacks.onMessagesChanged([...this.messages])}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){this.callbacks.onArtifactsState?.({artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:"",...e.file?{file:e.file}:{}}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:e.component??"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let n=this.artifacts.get(e.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+e.artDelta);break}case"artifact_update":{let n=this.artifacts.get(e.id);n?.artifactType==="component"&&(n.props={...n.props,...e.props},e.component&&(n.component=e.component));break}case"artifact_complete":{let n=this.artifacts.get(e.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,n=null){this.artifacts.clear();for(let o of e)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(e){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&this.abortController?.signal.aborted!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>e.agentMetadata?.awaitingLocalTool===!0&&e.agentMetadata?.askUserQuestionAnswered!==!0||e.variant==="approval"&&e.approval?.status==="pending")}beginReconnect(){this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,this.callbacks.onReconnect?.({phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(e=>{this.reconnecting&&this.resumable&&e.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(Ay(),Sy)).then(({createReconnectController:e})=>{let n=e(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:n=>e.setStatus(n),setStreaming:n=>e.setStreaming(n),setReconnecting:n=>{e.reconnecting=n},setAbortController:n=>{e.abortController=n},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(n,o,r)=>e.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>e.appendMessage(n),nextSequence:()=>e.nextSequence(),emitReconnect:n=>e.callbacks.onReconnect?.(n),buildErrorContent:n=>pu(new Error(n),e.config.errorMessage),onError:n=>e.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=zs(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let n=this.messages[e];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){this.reconnecting=!1,this.reconnectController?.teardown(),this.clearResumable()}clearResumable(){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&this.config.onExecutionState?.(null)}notifyExecutionState(e){let n=this.config.onExecutionState;if(n){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{this.executionStateTimer=null,this.config.onExecutionState?.(this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!e?.enabled||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let o=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let r=cu(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return gc(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=cu(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(e,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let u=r.approval,g=n.approval;a.approval={...u,...g,executionId:g.executionId||u.executionId,toolName:g.toolName||u.toolName,description:g.description||u.description,toolType:g.toolType??u.toolType,reason:g.reason??u.reason,parameters:g.parameters??u.parameters}}let l=n.toolCall?.name,d=n.agentMetadata?.executionId,p=n.toolCall?.id;if(l&&Ty(l)&&d&&p&&n.agentMetadata?.awaitingLocalTool===!0){let u=`${d}:${p}`,g=this.webMcpInflightKeys.has(u),b=this.webMcpResolvedKeys.has(u),m=r.toolCall?.name,y=r.agentMetadata?.executionId===d&&r.toolCall?.id===p&&m!==void 0&&Ty(m)&&r.toolCall?.status==="complete";(g||b||y)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.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((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,l=o.sequence??0;return a!==l?a-l:n.id.localeCompare(o.id)})}};Qe();Rt();var yc={allowedTypes:qo,maxFileSize:10*1024*1024,maxFiles:4};function mA(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function hA(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var ua=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:e.allowedTypes??yc.allowedTypes,maxFileSize:e.maxFileSize??yc.maxFileSize,maxFiles:e.maxFiles??yc.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}remountPreviews(e){if(this.previewsContainer=e,e){e.innerHTML="";for(let n of this.attachments)this.renderPreview(n)}this.updatePreviewsVisibility()}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:yc.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){if(e.length){for(let n of e){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=ty(n,this.config.allowedTypes,this.config.maxFileSize);if(!o.valid){let r=o.error?.includes("type")?"type":"size";this.config.onFileRejected?.(n,r);continue}try{let r=await ey(n),s=cc(n)?URL.createObjectURL(n):null,a={id:mA(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(e){let n=this.attachments.findIndex(s=>s.id===e);if(n===-1)return;let o=this.attachments[n];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(n,1);let r=this.previewsContainer?.querySelector(`[data-attachment-id="${e}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=cc(e.file),o=v("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",e.id),o.style.width="48px",o.style.height="48px",n&&e.previewUrl){let a=v("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",o.appendChild(a)}else{let a=v("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 l=hA(e.file.type),d=fe(l,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let p=v("span");p.textContent=ny(e.file.type,e.file.name),p.style.fontSize="8px",p.style.fontWeight="600",p.style.color="var(--persona-muted, #6b7280)",p.style.textTransform="uppercase",p.style.lineHeight="1",a.appendChild(p),o.appendChild(a)}let r=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=fe("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e?.allowedTypes,maxFileSize:e?.maxFileSize,maxFiles:e?.maxFiles,onFileRejected:e?.onFileRejected,onAttachmentsChange:n})}};Qe();bc();uu();Qe();Rt();var Zt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},mn=1e5,Us=mn+1;var vA=8,wA=8,gu=10,Ly=200,Iy=300,Hy=0,wc=t=>Math.max(0,t);function Ry(t){t.delayMs!==void 0&&(Ly=wc(t.delayMs)),t.skipDelayMs!==void 0&&(Iy=wc(t.skipDelayMs))}var CA=()=>Date.now()<Hy,xA=t=>{Hy=t>0?Date.now()+t:0},fu=new WeakMap,Wy=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,SA=t=>{let e=t.getRootNode?.();return Wy(e)?e:t.ownerDocument.body},mu=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n)),AA=[...["background","foreground","hint-fg","radius","font-size","padding","max-width","shadow","arrow-display"].map(t=>`--persona-tooltip-${t}`),"--persona-font-family","--persona-radius-sm"];function hn(t){fu.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,hint:r,enabled:s=!0,gap:a=vA,viewportPadding:l=wA}=t,d=()=>e.ownerDocument,p=()=>d().defaultView??window,u=null,g=null,b=null,m=null,y,w=!1,T=!1,W=!1,E=()=>(typeof o=="function"?o():o).trim(),k=()=>(typeof r=="function"?r():r??"").trim(),A=()=>wc(t.delayMs??Ly),D=()=>wc(t.skipDelayMs??Iy),B=()=>{y!==void 0&&(p().clearTimeout(y),y=void 0)},I=()=>{B();let ee=u!==null;m?.(),m=null,u?.remove(),u=null,g=null,b=null,ee&&xA(D())},N=()=>{if(!u)return;let ee=d(),M=p(),te=e.getBoundingClientRect(),pe=u.getBoundingClientRect(),Se=ee.documentElement.clientWidth||M.innerWidth,xe=ee.documentElement.clientHeight||M.innerHeight,Ce=Se-l-pe.width,Me=te.left+te.width/2-pe.width/2,ke=mu(Me,l,Ce),Oe=te.top-l,ze=xe-l-te.bottom,qe=pe.height+a,nt=Oe>=qe||Oe>=ze?"top":"bottom",De=nt==="top"?te.top-a-pe.height:te.bottom+a,Ue=xe-l-pe.height,an=mu(De,l,Ue),Ee=te.left+te.width/2,$e=Math.max(gu,pe.width-gu),mt=mu(Ee-ke,gu,$e);u.dataset.placement=nt,u.style.left=`${ke}px`,u.style.top=`${an}px`,u.style.setProperty("--persona-tooltip-arrow-x",`${mt}px`)},_=()=>{if(W||!s||u||!e.isConnected)return;let ee=E(),M=SA(e);if(!ee||!M)return;let te=d(),pe=p();u=te.createElement("div"),u.className="persona-control-tooltip",u.setAttribute("role","tooltip"),u.dataset.state="measuring",u.style.zIndex=String(Us);let Se=pe.getComputedStyle?.(e);if(Se){for(let qe of AA){let nt=Se.getPropertyValue(qe).trim();nt&&u.style.setProperty(qe,nt)}Se.fontFamily&&(u.style.fontFamily=Se.fontFamily)}g=te.createElement("span"),g.className="persona-control-tooltip__label",g.textContent=ee,u.appendChild(g);let xe=k();xe&&(b=te.createElement("span"),b.className="persona-control-tooltip__hint",b.textContent=xe,u.appendChild(b));let Ce=te.createElement("span");Ce.className="persona-control-tooltip__arrow",u.appendChild(Ce),M.appendChild(u),N(),u.dataset.state="open";let Me=()=>{if(!e.isConnected){I();return}g&&(g.textContent=E()),b&&(b.textContent=k()),N()};pe.addEventListener("scroll",Me,!0),pe.addEventListener("resize",Me);let ke=e.getRootNode(),Oe=Wy(ke)?ke:te.documentElement,ze=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||I()});ze?.observe(Oe,{childList:!0,subtree:!0}),m=()=>{pe.removeEventListener("scroll",Me,!0),pe.removeEventListener("resize",Me),ze?.disconnect()}},F=ee=>{if(!(W||u)){if(B(),ee||A()<=0||CA()){_();return}y=p().setTimeout(()=>{y=void 0,_()},A())}},P=()=>{w||T?F(T):I()},V=()=>{let ee=p();(!ee.matchMedia||!ee.matchMedia("(hover: none)").matches)&&(w=!0,P())},se=()=>{w=!1,P()},ve=()=>{try{T=e.matches(":focus-visible")}catch{T=!0}P()},he=()=>{T=!1,P()},ge=()=>{w=!1,T=!1,I()},re=ee=>{ee.key==="Escape"&&ge()};n.addEventListener("mouseenter",V),n.addEventListener("mouseleave",se),e.addEventListener("focus",ve),e.addEventListener("blur",he),e.addEventListener("keydown",re),e.addEventListener("click",ge);let oe={get isOpen(){return u!==null},show:_,hide:I,reposition:N,destroy:()=>{W||(W=!0,I(),n.removeEventListener("mouseenter",V),n.removeEventListener("mouseleave",se),e.removeEventListener("focus",ve),e.removeEventListener("blur",he),e.removeEventListener("keydown",re),e.removeEventListener("click",ge),fu.delete(e))}};return fu.set(e,oe),oe}function By(t){let{config:e,onOpen:n}=t,o=t.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=e.buttonIconName??"plus",l=e.buttonTooltipText??"Add context",d=v("div","persona-send-button-wrapper"),p=J("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-mention-button",attrs:{type:"button","data-persona-composer-mention-button":"","aria-label":l,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),u=fe(a,s,"currentColor",1.5);return u?p.appendChild(u):p.textContent="+",p.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),n()}),d.appendChild(p),hn({anchor:p,trigger:d,text:()=>p.getAttribute("aria-label")??l}),{button:p,wrapper:d}}var{setLoader:vL,load:HA}=Co({fallbackImport:()=>Promise.resolve().then(()=>(nb(),tb))});var Cu=HA;var{setLoader:IL,load:zA}=Co({fallbackImport:()=>Promise.resolve().then(()=>(fb(),gb)),resetOnSetLoader:!0});var mb=zA;Qe();Rt();function wa(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=J("span",{className:zt("persona-mention-token",e.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":t.sourceId,title:t.label,role:"img","aria-label":`${t.label} mention`}});t.color&&n.style.setProperty("--persona-mention-token-accent",t.color);let o=fe(t.iconName??"at-sign",13,"currentColor",2);if(o){let r=v("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(J("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function hb(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=vc(e).filter(k=>k.sources.length>0);if(n.length===0)return typeof console<"u"&&console.warn("[Persona] contextMentions.enabled is true but no sources were provided; mentions are disabled."),null;let o=n.filter(k=>k.sources.some(A=>typeof A.matchCommand=="function")),r=k=>o.some(A=>A.trigger?A.position==="line-start"?k.split(`
1093
+ `).some(B=>B.startsWith(A.trigger)):(A.position==="anywhere"?k:k.split(`
1094
+ `)[0]).startsWith(A.trigger):!1),s=(k,A)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${k}`,{detail:A}))}catch{}},a=J("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,d=null,p=t.textarea,u=null,g=null,b=null,m=null,y=()=>{if(l)return Promise.resolve(l);if(d)return d;let k=Cu().then(A=>(l=A.mountContextMentions({mentionConfig:e,textarea:t.textarea,composerInput:u??void 0,anchor:t.anchor,contextRow:a,getMessages:t.getMessages,getConfig:()=>t.config,liveRegionHost:t.liveRegionHost,popoverContainer:t.popoverContainer,onPickerOpenChange:E,emit:s}),l)).catch(A=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",A),d===k&&(d=null),null));return d=k,k},w=()=>{mb().then(k=>{let A=k.mountInlineComposer({textarea:t.textarea,renderToken:B=>wa(B,{render:e.renderMentionToken}),onMentionRemoved:B=>l?.untrackMention(B)});u=A.input,g=A.destroy;let D=p;D.replaceWith(A.element),p=A.element,m={next:A.element,prev:D},b?.(A.element,D),l?l.rebindComposer(A.input):d&&d.then(B=>B?.rebindComposer(A.input))}).catch(k=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",k)})};e.display==="inline"&&w();let T=[],W=new Map;for(let k of n){if(!k.showButton)continue;let A=By({config:{...e,buttonIconName:k.buttonIconName,buttonTooltipText:k.buttonTooltipText},buttonSize:t.config.sendButton?.size,onOpen:()=>{y().then(D=>D?.openMenu(k.trigger))}});T.push(A),W.set(k.trigger,A.button)}let E=(k,A,D)=>{let B=W.get(A);B&&(B.setAttribute("aria-expanded",k?"true":"false"),k?B.setAttribute("aria-controls",D):B.removeAttribute("aria-controls"))};return{affordanceButtons:T.map(k=>k.wrapper),contextRow:a,handleInput:k=>{if(l){l.handleInput();return}if(!ky(k))return;let A=p,D=A.selectionStart??0;ga(A.value,D,n)&&y().then(B=>B?.handleInput())},handleKeydown:k=>{if(l?.isMenuOpen())return l.handleKeydown(k);if(k.key==="Backspace"&&l?.hasMentions()&&!m){let A=p,D=A.selectionStart===0&&A.selectionEnd===0;if((A.value.length===0||D)&&l.removeLastChip())return k.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async k=>r(k)?(l??await y())?.dispatchInlineCommand(k)??null:null,clear:()=>l?.clear(),prefetch:()=>{Cu().catch(()=>{})},onComposerSwap:k=>{b=k,m&&k(m.next,m.prev)},destroy:()=>{l?.destroy(),g?.();for(let k of T)k.wrapper.remove();a.remove()}}}var yb=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Ks(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];yb(s)&&yb(r)?n[o]=Ks(s,r):n[o]=r}return n}var Uo="min(440px, calc(100vw - 24px))",vb="440px",VA={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:Uo,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},ft={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",tooltip:{delayMs:200,skipDelayMs:300},launcher:VA,copy:{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:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,groupedMode:"stack",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"},history:{enabled:!1,presentation:"panel",showScopeStatus:!0,showDelete:!0,showDeleteAll:!0}},suggestionChips:["Show me what you can help with","Walk me through getting started","Answer a question about this page"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function bb(t,e){if(!(!t&&!e))return t?e?Ks(t,e):t:e}function Bc(t){return t?{...ft,...t,theme:bb(ft.theme,t.theme),darkTheme:bb(ft.darkTheme,t.darkTheme),launcher:{...ft.launcher,...t.launcher,dock:{...ft.launcher?.dock,...t.launcher?.dock},clearChat:{...ft.launcher?.clearChat,...t.launcher?.clearChat}},tooltip:{...ft.tooltip,...t.tooltip},copy:{...ft.copy,...t.copy},sendButton:{...ft.sendButton,...t.sendButton},statusIndicator:{...ft.statusIndicator,...t.statusIndicator},voiceRecognition:{...ft.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=ft.features?.artifacts,n=t.features?.artifacts,o=ft.features?.scrollToBottom,r=t.features?.scrollToBottom,s=ft.features?.scrollBehavior,a=t.features?.scrollBehavior,l=ft.features?.streamAnimation,d=t.features?.streamAnimation,p=ft.features?.askUserQuestion,u=t.features?.askUserQuestion,g=ft.features?.history,b=t.features?.history,m=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},y=o===void 0&&r===void 0?void 0:{...o,...r},w=s===void 0&&a===void 0?void 0:{...s,...a},T=l===void 0&&d===void 0?void 0:{...l,...d},W=p===void 0&&u===void 0?void 0:{...p,...u,styles:{...p?.styles,...u?.styles}},E=g===void 0&&b===void 0?void 0:{...g,...b,copy:{...g?.copy,...b?.copy}};return{...ft.features,...t.features,...y!==void 0?{scrollToBottom:y}:{},...w!==void 0?{scrollBehavior:w}:{},...m!==void 0?{artifacts:m}:{},...T!==void 0?{streamAnimation:T}:{},...W!==void 0?{askUserQuestion:W}:{},...E!==void 0?{history:E}:{}}})(),suggestionChips:t.suggestionChips??ft.suggestionChips,suggestionChipsConfig:{...ft.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...ft.layout,...t.layout,header:{...ft.layout?.header,...t.layout?.header},messages:{...ft.layout?.messages,...t.layout?.messages,avatar:{...ft.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...ft.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...ft.layout?.slots,...t.layout?.slots}},markdown:{...ft.markdown,...t.markdown,options:{...ft.markdown?.options,...t.markdown?.options}},messageActions:{...ft.messageActions,...t.messageActions}}:ft}var Dc="16px",Nc="transparent",jA={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},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"}},qA={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"}},UA={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm",hoverBackground:"rgba(0, 0, 0, 0.05)"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"semantic.colors.surface",foreground:"semantic.colors.primary",border:"semantic.colors.border",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Uo,maxWidth:vb,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Dc,canvasBackground:Nc},header:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},suggestion:{chip:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.full",padding:"0.5rem 0.875rem",gap:"0.5rem",itemGap:"8px",minHeight:"36px",fontSize:"0.8125rem",lineHeight:"1.25",iconSize:"16px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},card:{background:"semantic.colors.surface",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.xl",padding:"1rem",shadow:"palette.shadows.sm",gap:"0.625rem",itemGap:"8px",minHeight:"72px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"18px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"},list:{background:"transparent",foreground:"semantic.colors.text",border:"semantic.colors.border",borderRadius:"palette.radius.md",padding:"0.75rem",gap:"0.625rem",itemGap:"8px",minHeight:"44px",fontSize:"0.875rem",lineHeight:"1.35",iconSize:"17px",hoverBackground:"palette.colors.gray.100",hoverBorder:"palette.colors.gray.300",pressedBackground:"palette.colors.gray.200",focusRing:"semantic.colors.interactive.focus",disabledOpacity:"0.5"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},scrollbar:{thumb:"semantic.colors.border",track:"transparent"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit",borderRadius:"palette.radius.md"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},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 En(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),o=t;for(let r of n){if(o==null)return;o=o[r]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?En(t,o):o}function wb(t){let e={};function n(o,r){for(let[s,a]of Object.entries(o)){let l=`${r}.${s}`;if(typeof a=="string"){let d=En(t,a);d!==void 0&&(e[l]={path:l,value:d,type:r.includes("color")?"color":r.includes("spacing")?"spacing":r.includes("typography")?"typography":r.includes("shadow")?"shadow":r.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,l)}}return n(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function KA(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function Cb(t,e){let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=Cb(s,r):n[o]=r}return n}function GA(t,e){return e?Cb(t,e):t}function Gs(t,e={}){let n={palette:jA,semantic:qA,components:UA},o={palette:{...n.palette,...t?.palette,colors:{...n.palette.colors,...t?.palette?.colors},spacing:{...n.palette.spacing,...t?.palette?.spacing},typography:{...n.palette.typography,...t?.palette?.typography},shadows:{...n.palette.shadows,...t?.palette?.shadows},borders:{...n.palette.borders,...t?.palette?.borders},radius:{...n.palette.radius,...t?.palette?.radius}},semantic:{...n.semantic,...t?.semantic,colors:{...n.semantic.colors,...t?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...t?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...t?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...t?.semantic?.spacing},typography:{...n.semantic.typography,...t?.semantic?.typography}},components:GA(n.components,t?.components)};if(e.validate!==!1){let r=KA(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(e.plugins)for(let r of e.plugins)o=r.transform(o);return o}var Lu=t=>t.trim()==="0"?"0px":t;function xb(t){let e=wb(t),n={};for(let[M,te]of Object.entries(e)){let pe=M.replace(/\./g,"-");n[`--persona-${pe}`]=te.value}n["--persona-primary"]=n["--persona-semantic-colors-primary"]??n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=n["--persona-semantic-colors-secondary"]??n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=n["--persona-semantic-colors-accent"]??n["--persona-palette-colors-accent-500"],n["--persona-surface"]=n["--persona-semantic-colors-surface"]??n["--persona-palette-colors-gray-50"],n["--persona-background"]=n["--persona-semantic-colors-background"]??n["--persona-palette-colors-gray-50"],n["--persona-container"]=n["--persona-semantic-colors-container"]??n["--persona-palette-colors-gray-100"],n["--persona-text"]=n["--persona-semantic-colors-text"]??n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=n["--persona-semantic-colors-text-muted"]??n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=n["--persona-semantic-colors-text-inverse"]??n["--persona-palette-colors-gray-50"],n["--persona-border"]=n["--persona-semantic-colors-border"]??n["--persona-palette-colors-gray-200"],n["--persona-divider"]=n["--persona-semantic-colors-divider"]??n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=n["--persona-components-voice-recording-indicator"]??n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=n["--persona-components-voice-recording-background"]??n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=n["--persona-components-voice-processing-icon"]??n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=n["--persona-components-voice-speaking-icon"]??n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=n["--persona-components-approval-requested-background"]??n["--persona-surface"],n["--persona-approval-border"]=n["--persona-components-approval-requested-border"]??n["--persona-border"],n["--persona-approval-text"]=n["--persona-components-approval-requested-text"]??n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=n["--persona-components-approval-requested-shadow"]??"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=n["--persona-components-approval-approve-background"]??n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=n["--persona-components-approval-deny-background"]??n["--persona-container"],n["--persona-attachment-image-bg"]=n["--persona-components-attachment-image-background"]??n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=n["--persona-components-attachment-image-border"]??n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=n["--persona-semantic-typography-fontFamily"]??n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=n["--persona-semantic-typography-fontSize"]??n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=n["--persona-semantic-typography-fontWeight"]??n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=n["--persona-semantic-typography-lineHeight"]??n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=n["--persona-palette-radius-sm"]??"0.125rem",n["--persona-radius-md"]=n["--persona-palette-radius-md"]??"0.375rem",n["--persona-radius-lg"]=n["--persona-palette-radius-lg"]??"0.5rem",n["--persona-radius-xl"]=n["--persona-palette-radius-xl"]??"0.75rem",n["--persona-radius-full"]=n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-radius"]=n["--persona-components-launcher-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-launcher-bg"]=n["--persona-components-launcher-background"]??n["--persona-surface"],n["--persona-launcher-fg"]=n["--persona-components-launcher-foreground"]??n["--persona-primary"];let o=n["--persona-components-launcher-foreground"];n["--persona-launcher-fg-muted"]=o&&o!==n["--persona-primary"]?`color-mix(in srgb, ${o} 70%, transparent)`:n["--persona-muted"],n["--persona-launcher-border"]=n["--persona-components-launcher-border"]??n["--persona-border"],n["--persona-button-primary-bg"]=n["--persona-components-button-primary-background"]??n["--persona-primary"],n["--persona-button-primary-fg"]=n["--persona-components-button-primary-foreground"]??n["--persona-text-inverse"],n["--persona-button-radius"]=n["--persona-components-button-primary-borderRadius"]??n["--persona-palette-radius-full"]??"9999px",n["--persona-button-ghost-bg"]=n["--persona-components-button-ghost-background"]??"transparent",n["--persona-button-ghost-fg"]=n["--persona-components-button-ghost-foreground"]??n["--persona-text"],n["--persona-button-ghost-radius"]=n["--persona-components-button-ghost-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-button-ghost-hover-bg"]=n["--persona-components-button-ghost-hoverBackground"]??"rgba(0, 0, 0, 0.05)",n["--persona-panel-radius"]=n["--persona-components-panel-borderRadius"]??n["--persona-radius-xl"]??"0.75rem",n["--persona-panel-border"]=n["--persona-components-panel-border"]??`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=n["--persona-components-panel-shadow"]??n["--persona-palette-shadows-xl"]??"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-panel-inset"]=n["--persona-components-panel-inset"]??Dc,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Nc,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"];let r=n["--persona-header-bg"],s=n["--persona-components-header-foreground"],a=s?`color-mix(in srgb, ${s} 72%, ${r})`:void 0;n["--persona-header-border"]=n["--persona-components-header-border"]??(s?`color-mix(in srgb, ${s} 14%, ${r})`:void 0)??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-title-color"]??n["--persona-components-header-titleForeground"]??s??n["--persona-primary"],n["--persona-header-subtitle-fg"]=n["--persona-components-header-subtitle-color"]??n["--persona-components-header-subtitleForeground"]??a??n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=n["--persona-components-header-actionIconForeground"]??a??n["--persona-muted"],n["--persona-header-control-size"]=n["--persona-components-header-controlSize"]??"32px",n["--persona-header-control-icon-size"]=n["--persona-components-header-controlIconSize"]??"20px";let l=t.components?.header;l?.shadow&&(n["--persona-header-shadow"]=l.shadow),l?.borderBottom&&(n["--persona-header-border-bottom"]=l.borderBottom),l?.minHeight&&(n["--persona-header-min-height"]=l.minHeight);let d=n["--persona-components-history-railHeader-background"];d&&(n["--persona-history-rail-header-bg"]=d);let p=n["--persona-components-history-railHeader-border"];p&&(n["--persona-history-rail-header-border"]=p);let u=n["--persona-components-history-railHeader-minHeight"];u&&(n["--persona-history-rail-header-min-height"]=u);for(let[M,te]of[["margin","margin"],["borderRadius","radius"],["shadow","shadow"],["background","bg"]]){let pe=n[`--persona-components-history-overlay-${M}`];pe&&(n[`--persona-history-overlay-${te}`]=pe)}for(let[M,te]of[["background","bg"],["borderRadius","radius"]]){let pe=n[`--persona-components-history-menu-${M}`];pe&&(n[`--persona-history-menu-${te}`]=pe)}let g=t.components?.history?.motion;if(g){let M=Se=>{if(Se===void 0)return;let xe=String(Se).trim();return/^\d+(\.\d+)?$/.test(xe)?`${xe}ms`:xe},te=M(g.enterDurationMs);te!==void 0&&(n["--persona-history-enter-ms"]=te);let pe=M(g.exitDurationMs);pe!==void 0&&(n["--persona-history-exit-ms"]=pe),g.enterEasing&&(n["--persona-history-enter-easing"]=g.enterEasing),g.exitEasing&&(n["--persona-history-exit-easing"]=g.exitEasing)}let b=n["--persona-components-history-dangerForeground"];b&&(n["--persona-history-danger-fg"]=b),n["--persona-danger"]=n["--persona-components-history-confirm-dangerBackground"]??n["--persona-palette-colors-error-700"]??"#b42318",n["--persona-danger-fg"]=n["--persona-components-history-confirm-dangerForeground"]??"#ffffff";for(let M of["scrim","shadow"]){let te=n[`--persona-components-history-confirm-${M}`];te&&(n[`--persona-history-confirm-${M}`]=te)}for(let[M,te]of[["background","background"],["foreground","foreground"],["hintForeground","hint-fg"],["borderRadius","radius"],["fontSize","font-size"],["padding","padding"],["maxWidth","max-width"],["shadow","shadow"]]){let pe=n[`--persona-components-tooltip-${M}`];pe&&(n[`--persona-tooltip-${te}`]=pe)}t.components?.tooltip?.arrow===!1&&(n["--persona-tooltip-arrow-display"]="none");for(let[M,te]of[["hoverBackground","hover-bg"],["hoverForeground","hover-fg"],["borderRadius","radius"]]){let pe=n[`--persona-components-messageActions-${M}`];pe&&(n[`--persona-message-action-${te}`]=pe)}n["--persona-intro-card-bg"]=n["--persona-components-introCard-background"]??"transparent",n["--persona-intro-card-radius"]=n["--persona-components-introCard-borderRadius"]??"1rem";let m=n["--persona-components-introCard-background"],y=n["--persona-components-introCard-shadow"],w=(!m||m==="transparent"||m==="none")&&(!y||y==="none"),T=n["--persona-components-introCard-padding"]??"1.5rem";n["--persona-intro-card-padding"]=w&&T==="1.5rem"?"1.5rem 0":T,n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"none",n["--persona-intro-card-border"]=n["--persona-components-introCard-border"]??"none",n["--persona-input-background"]=n["--persona-components-input-background"]??n["--persona-surface"],n["--persona-input-placeholder"]=n["--persona-components-input-placeholder"]??n["--persona-text-muted"],n["--persona-message-user-bg"]=n["--persona-components-message-user-background"]??n["--persona-accent"],n["--persona-message-user-text"]=n["--persona-components-message-user-text"]??n["--persona-text-inverse"],n["--persona-message-user-shadow"]=n["--persona-components-message-user-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=n["--persona-components-message-assistant-background"]??n["--persona-surface"],n["--persona-message-assistant-text"]=n["--persona-components-message-assistant-text"]??n["--persona-text"],n["--persona-message-assistant-border"]=n["--persona-components-message-assistant-border"]??n["--persona-border"],n["--persona-message-assistant-shadow"]=n["--persona-components-message-assistant-shadow"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=n["--persona-components-scrollToBottom-background"]??n["--persona-button-primary-bg"]??n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=n["--persona-components-scrollToBottom-foreground"]??n["--persona-button-primary-fg"]??n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=n["--persona-components-scrollToBottom-border"]??n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=n["--persona-components-scrollToBottom-size"]??"40px",n["--persona-scroll-to-bottom-radius"]=n["--persona-components-scrollToBottom-borderRadius"]??n["--persona-button-radius"]??n["--persona-radius-full"]??"9999px",n["--persona-scroll-to-bottom-shadow"]=n["--persona-components-scrollToBottom-shadow"]??n["--persona-palette-shadows-sm"]??"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=n["--persona-components-scrollToBottom-padding"]??"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=n["--persona-components-scrollToBottom-gap"]??"0.5rem",n["--persona-scroll-to-bottom-font-size"]=n["--persona-components-scrollToBottom-fontSize"]??n["--persona-palette-typography-fontSize-sm"]??"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=n["--persona-components-scrollToBottom-iconSize"]??"14px",n["--persona-tool-bubble-shadow"]=n["--persona-components-toolBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=n["--persona-components-reasoningBubble-shadow"]??"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=n["--persona-components-composer-shadow"]??"none",n["--persona-composer-padding"]=n["--persona-components-composer-padding"]??"0.75rem 1rem",n["--persona-composer-gap"]=n["--persona-components-composer-gap"]??"0.5rem",n["--persona-composer-font-size"]=n["--persona-components-composer-fontSize"]??"0.875rem",n["--persona-composer-line-height"]=n["--persona-components-composer-lineHeight"]??"1.25rem",n["--persona-composer-border-color"]=n["--persona-components-composer-borderColor"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-thumb"]=n["--persona-components-scrollbar-thumb"]??n["--persona-border"]??"#e5e7eb",n["--persona-scrollbar-track"]=n["--persona-components-scrollbar-track"]??"transparent",n["--persona-md-inline-code-bg"]=n["--persona-components-markdown-inlineCode-background"]??n["--persona-container"],n["--persona-md-inline-code-color"]=n["--persona-components-markdown-inlineCode-foreground"]??n["--persona-text"],n["--persona-md-link-color"]=n["--persona-components-markdown-link-foreground"]??n["--persona-accent"]??"#0f0f0f";let W=n["--persona-components-markdown-heading-h1-fontSize"];W&&(n["--persona-md-h1-size"]=W);let E=n["--persona-components-markdown-heading-h1-fontWeight"];E&&(n["--persona-md-h1-weight"]=E);let k=n["--persona-components-markdown-heading-h2-fontSize"];k&&(n["--persona-md-h2-size"]=k);let A=n["--persona-components-markdown-heading-h2-fontWeight"];A&&(n["--persona-md-h2-weight"]=A);let D=n["--persona-components-markdown-prose-fontFamily"];D&&D!=="inherit"&&(n["--persona-md-prose-font-family"]=D),n["--persona-md-code-block-bg"]=n["--persona-components-markdown-codeBlock-background"]??n["--persona-container"],n["--persona-md-code-block-border-color"]=n["--persona-components-markdown-codeBlock-borderColor"]??n["--persona-border"],n["--persona-md-code-block-text-color"]=n["--persona-components-markdown-codeBlock-textColor"]??"inherit",n["--persona-md-code-block-border-radius"]=n["--persona-components-markdown-codeBlock-borderRadius"]??n["--persona-radius-md"]??"0.375rem",n["--persona-md-table-header-bg"]=n["--persona-components-markdown-table-headerBackground"]??n["--persona-container"],n["--persona-md-table-border-color"]=n["--persona-components-markdown-table-borderColor"]??n["--persona-border"],n["--persona-md-hr-color"]=n["--persona-components-markdown-hr-color"]??n["--persona-divider"],n["--persona-md-blockquote-border-color"]=n["--persona-components-markdown-blockquote-borderColor"]??n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=n["--persona-components-markdown-blockquote-background"]??"transparent",n["--persona-md-blockquote-text-color"]=n["--persona-components-markdown-blockquote-textColor"]??n["--persona-palette-colors-gray-500"],n["--cw-container"]=n["--persona-components-collapsibleWidget-container"]??n["--persona-surface"],n["--cw-surface"]=n["--persona-components-collapsibleWidget-surface"]??n["--persona-surface"],n["--cw-border"]=n["--persona-components-collapsibleWidget-border"]??n["--persona-border"],n["--persona-message-border"]=n["--persona-components-message-border"]??n["--persona-border"];let B=t.components,I=B?.iconButton;I&&(I.background&&(n["--persona-icon-btn-bg"]=I.background),I.border&&(n["--persona-icon-btn-border"]=I.border),I.color&&(n["--persona-icon-btn-color"]=I.color),I.padding&&(n["--persona-icon-btn-padding"]=I.padding),I.borderRadius&&(n["--persona-icon-btn-radius"]=I.borderRadius),I.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=I.hoverBackground),I.hoverColor&&(n["--persona-icon-btn-hover-color"]=I.hoverColor),I.activeBackground&&(n["--persona-icon-btn-active-bg"]=I.activeBackground),I.activeBorder&&(n["--persona-icon-btn-active-border"]=I.activeBorder));let N=B?.labelButton;N&&(N.background&&(n["--persona-label-btn-bg"]=N.background),N.border&&(n["--persona-label-btn-border"]=N.border),N.color&&(n["--persona-label-btn-color"]=N.color),N.padding&&(n["--persona-label-btn-padding"]=N.padding),N.borderRadius&&(n["--persona-label-btn-radius"]=N.borderRadius),N.hoverBackground&&(n["--persona-label-btn-hover-bg"]=N.hoverBackground),N.fontSize&&(n["--persona-label-btn-font-size"]=N.fontSize),N.gap&&(n["--persona-label-btn-gap"]=N.gap));let _=B?.toggleGroup;_&&(_.gap&&(n["--persona-toggle-group-gap"]=_.gap),_.borderRadius&&(n["--persona-toggle-group-radius"]=_.borderRadius));let F=B?.artifact;if(F?.toolbar){let M=F.toolbar;M.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=M.iconHoverColor),M.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=M.iconHoverBackground),M.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=M.iconPadding),M.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=M.iconBorderRadius),M.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=M.iconBorder),M.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Lu(M.toggleGroupGap)),M.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=M.toggleBorderRadius),M.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=Lu(M.toggleGroupPadding)),M.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=M.toggleGroupBorder),M.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=M.toggleGroupBorderRadius),M.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=En(t,M.toggleGroupBackground)??M.toggleGroupBackground),M.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=M.copyBackground),M.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=M.copyBorder),M.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=M.copyColor),M.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Lu(M.copyBorderRadius)),M.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=M.copyPadding),M.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=M.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??M.copyMenuBackground),M.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=M.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??M.copyMenuBorder),M.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=M.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??M.copyMenuShadow),M.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=M.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??M.copyMenuBorderRadius),M.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=M.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??M.copyMenuItemHoverBackground),M.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=M.iconBackground),M.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=M.toolbarBorder)}if(F?.tab){let M=F.tab;M.background&&(n["--persona-artifact-tab-bg"]=M.background),M.activeBackground&&(n["--persona-artifact-tab-active-bg"]=M.activeBackground),M.activeBorder&&(n["--persona-artifact-tab-active-border"]=M.activeBorder),M.borderRadius&&(n["--persona-artifact-tab-radius"]=M.borderRadius),M.textColor&&(n["--persona-artifact-tab-color"]=M.textColor),M.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=M.hoverBackground),M.listBackground&&(n["--persona-artifact-tab-list-bg"]=M.listBackground),M.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=M.listBorderColor),M.listPadding&&(n["--persona-artifact-tab-list-padding"]=M.listPadding)}if(F?.pane){let M=F.pane;if(M.toolbarBackground){let te=En(t,M.toolbarBackground)??M.toolbarBackground;n["--persona-artifact-toolbar-bg"]=te}}if(F?.card){let M=F.card;M.background&&(n["--persona-artifact-card-bg"]=M.background),M.border&&(n["--persona-artifact-card-border"]=M.border),M.borderRadius&&(n["--persona-artifact-card-radius"]=M.borderRadius),M.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=M.hoverBackground),M.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=M.hoverBorderColor)}if(F?.inline){let M=F.inline;M.background&&(n["--persona-artifact-inline-bg"]=En(t,M.background)??M.background),M.border&&(n["--persona-artifact-inline-border"]=M.border),M.borderRadius&&(n["--persona-artifact-inline-radius"]=M.borderRadius),M.chromeBackground&&(n["--persona-artifact-inline-chrome-bg"]=En(t,M.chromeBackground)??M.chromeBackground),M.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=En(t,M.chromeBorder)??M.chromeBorder),M.titleColor&&(n["--persona-artifact-inline-title-color"]=En(t,M.titleColor)??M.titleColor),M.mutedColor&&(n["--persona-artifact-inline-muted-color"]=En(t,M.mutedColor)??M.mutedColor),M.frameHeight&&(n["--persona-artifact-inline-frame-height"]=M.frameHeight)}let P=B?.code;P&&(P.keywordColor&&(n["--persona-code-keyword-color"]=P.keywordColor),P.stringColor&&(n["--persona-code-string-color"]=P.stringColor),P.commentColor&&(n["--persona-code-comment-color"]=P.commentColor),P.numberColor&&(n["--persona-code-number-color"]=P.numberColor),P.tagColor&&(n["--persona-code-tag-color"]=P.tagColor),P.attrColor&&(n["--persona-code-attr-color"]=P.attrColor),P.propertyColor&&(n["--persona-code-property-color"]=P.propertyColor),P.lineNumberColor&&(n["--persona-code-line-number-color"]=P.lineNumberColor),P.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=P.gutterBorderColor),P.background&&(n["--persona-code-bg"]=En(t,P.background)??P.background));let V=n["--persona-surface"],se=n["--persona-container"],ve=n["--persona-palette-colors-gray-100"]??"#f3f4f6",he=n["--persona-palette-colors-gray-200"]??"#e5e7eb",ge=n["--persona-palette-colors-gray-300"]??"#d1d5db",re=!se||se===V,oe=re?ve:se,ee=re?he:se;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??oe,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??ee,re&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??ge),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??oe,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??oe,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??oe,n}var YA={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"}}},XA={components:{button:{ghost:{hoverBackground:"rgba(255, 255, 255, 0.08)"}},history:{dangerForeground:"#f87171",confirm:{dangerBackground:"palette.colors.error.600",scrim:"rgba(0, 0, 0, 0.6)"}}}},Sb=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Iu=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",QA=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Iu()},Ab=t=>QA(t),JA=t=>Gs(t),ZA=t=>{let e=Ks(XA,t??{})??{};return Gs({...e,palette:{...e.palette,colors:{...YA.colors,...e.palette?.colors}}},{validate:!1})},Ys=t=>{let e=Ab(t),n=Sb(t?.theme),o=Sb(t?.darkTheme);return e==="dark"?ZA(Ks(n??{},o??{})):JA(n)},eM=t=>xb(t),Ca=(t,e)=>{let n=Ys(e),o=eM(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",Ab(e))},Oc=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Iu())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>t(Iu());n.addEventListener?(n.addEventListener("change",o),e.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),e.push(()=>n.removeListener(o)))}return()=>{e.forEach(n=>n())}};Rt();Qe();var yr=(t,e)=>t?.layout?.contentMaxWidth??(e?t?.launcher?.composerBar?.contentMaxWidth??"720px":"768px");var Mb=null;var Hu=()=>{if(Mb!==null)return Mb;if(typeof navigator>"u")return!1;let e=navigator.userAgentData?.platform??navigator.platform??"";return/mac|iphone|ipad|ipod/i.test(e)},tM="ArrowUp ArrowDown ArrowLeft ArrowRight PageUp PageDown Space",_c=(t,e)=>{console.warn(`[persona] ${t} shortcut: ${e}`)},Fc=t=>{let e=t.toLowerCase().split("+").map(r=>r.trim()),n=e.pop(),o={key:n,mod:!1,shift:!1,alt:!1};for(let r of e)if(r==="mod"||r==="cmd"||r==="ctrl")o.mod=!0;else if(r==="shift")o.shift=!0;else if(r==="alt"||r==="option")o.alt=!0;else return _c("unknown modifier in",t),null;return!o.mod||o.shift&&o.alt||/^(enter|esc(ape)?)$/.test(n)||!/^([^+\s]|[a-z]{2,12})$/.test(n)?(_c("unsupported",t),null):(n==="space"&&(o.key=" "),o)},nM=t=>tM.split(" ").find(e=>e.toLowerCase()===t)??(t===" "?"Space":t.length===1?t.toUpperCase():t[0].toUpperCase()+t.slice(1)),Tb=(t,e)=>{let n=Fc(t);if(!n)return"";let o=Hu(),r=nM(n.key);if(!e&&o)return`${n.alt?"\u2325":""}${n.shift?"\u21E7":""}\u2318${r}`;let s=[e?o?"Meta":"Control":"Ctrl"];return n.alt&&s.push("Alt"),n.shift&&s.push("Shift"),s.push(r),s.join("+")},$c=t=>Tb(t,!1),xa=t=>Tb(t,!0),oM=(t,e)=>e.key?.toLowerCase()===t.key&&(Hu()?e.metaKey:e.ctrlKey)===t.mod&&!(Hu()?e.ctrlKey:e.metaKey)&&e.shiftKey===t.shift&&e.altKey===t.alt,rM=t=>{if(!(t instanceof HTMLElement))return!1;let e=t.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"||t.isContentEditable},Eb=t=>{let e=new Map,n=t?.ownerDocument??(typeof document<"u"?document:null),o=(s,a)=>{if((s.scope??"widget")==="page")return!0;if(!t)return!1;let l=a.composedPath?.();return l?.length?l.includes(t):t.contains(a.target)},r=s=>{if(s.isComposing||!e.size)return;let a=s.composedPath?.()[0]??s.target;for(let l of e.values())if(oM(l.parsed,s)&&l.when?.()!==!1&&o(l,s)&&!(!l.allowInInput&&rM(a))){s.preventDefault();try{l.run(s)}catch(d){_c(`${l.id} threw on`,l.combo),console.warn(d)}return}};return n?.addEventListener("keydown",r),{register(s){let a=Fc(s.combo);if(!a)return()=>{};let l=`${a.mod?"m":""}${a.shift?"s":""}${a.alt?"a":""}${a.key}`,d=e.get(l);return d?(_c(`${d.id} already owns`,s.combo),()=>{}):(e.set(l,{...s,parsed:a}),s.element?.setAttribute("aria-keyshortcuts",xa(s.combo)),()=>{e.get(l)?.id===s.id&&e.delete(l),s.element?.removeAttribute("aria-keyshortcuts")})},destroy(){e.clear(),n?.removeEventListener("keydown",r)}}};function Ao(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function kb(t){let e=Ao(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function zc(t){if(typeof t!="string")return"";let e=t.indexOf(`
198
1095
  `);if(e===-1||!t.slice(0,e).startsWith("```"))return t;let o=t.slice(e+1),r=o.lastIndexOf(`
199
- `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function er(t){let e=xf(t.path);if(e)return e==="html"||e==="htm"?"html":e==="svg"?"svg":e==="md"||e==="mdx"?"markdown":"other";let n=(t.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function Eo(t){switch(er(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=xf(t.path);return e?e.toUpperCase():"File"}}}function wf(t){let e=t.markdown??"";return t.file?{filename:Fn(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:Wa(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}Ye();Ye();var Uc="http://www.w3.org/2000/svg";function Cf(t){let e=document.createElementNS(Uc,"svg");e.setAttribute("class",Bn("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS(Uc,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Uc,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),e.appendChild(n),e.appendChild(o),e}Ye();Ye();var ko=(t,e,n)=>{let o=n;for(let r of e){let s=v("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,t.appendChild(s),o++}return o};function Af(t,e,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){t.textContent=e;return}if(o==="pulse"){t.setAttribute("data-preserve-animation","true"),t.classList.add("persona-tool-loading-pulse"),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),t.textContent=e;return}t.setAttribute("data-preserve-animation","true"),t.classList.add(`persona-tool-loading-${o}`),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&t.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&t.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),ko(t,e,0)}var jc="persona-artifact-status-label",Sf="persona-artifact-status-detail",Mf="data-artifact-status-label",Vc=new Map,Tf=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function zr(t){t&&Vc.delete(t)}function Lv(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?Eo(e):t.artifactType==="component"?"Component":"Document"}function Ur(t,e,n){let o=Lv(t),r=`Generating ${o.toLowerCase()}...`,s=e?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let i=t.id,l=Vc.get(i);t.status!=="complete"&&l===void 0&&(l=Tf(),Vc.set(i,l));let p=l===void 0?0:Math.max(0,Tf()-l),c=t.artifactType==="component",d=!c&&typeof t.markdown=="string"?t.markdown:"",g=c?0:d.length,b=c||d===""?0:d.split(`
200
- `).length,f=t.artifactType==="markdown"?t.file:void 0,y={artifactId:i,artifactType:t.artifactType,title:t.title,typeLabel:o,file:f,chars:g,lines:b,elapsedMs:p,content:()=>c?"":d,surface:n};try{let C=s(y);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:r}}catch{return{label:r}}}function Pv(t){t.className=jc,t.removeAttribute("data-preserve-animation"),t.style.removeProperty("--persona-tool-anim-duration"),t.style.removeProperty("--persona-tool-anim-color"),t.style.removeProperty("--persona-tool-anim-secondary-color"),t.replaceChildren()}function tr(t,e,n){let o=t.querySelector(`:scope > .${jc}`);o||(o=v("span",jc),t.appendChild(o)),o.getAttribute(Mf)!==e.label&&(Pv(o),Af(o,e.label,n),o.setAttribute(Mf,e.label));let r=t.querySelector(`:scope > .${Sf}`),s=e.detail;s?(r||(r=v("span",Sf),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}Ye();var Iv={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},Rv=15e4,Ha={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};function Wv(t,e){let n=(t||"").trim().toLowerCase();if(n&&Ha[n])return Ha[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(Ha[r])return Ha[r]}}return null}function Ba(t,e){let n=[],o=0,r=0,s=i=>{i>r&&n.push({type:"plain",value:t.slice(r,i)})};for(;o<t.length;){let i=!1;for(let l of e){l.re.lastIndex=o;let p=l.re.exec(t);if(p&&p.index===o&&p[0].length>0){s(o);let c=l.map?l.map(p[0]):l.type;n.push({type:c,value:p[0]}),o+=p[0].length,r=o,i=!0;break}}i||(o+=1)}return s(t.length),n}var Hv=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),Bv=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:t=>Hv.has(t)?"keyword":"plain"}];function Ef(t){return Ba(t,Bv)}var Dv=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:t=>t==="true"||t==="false"||t==="null"?"keyword":"plain"}];function Ov(t){let e=Ba(t,Dv);for(let n=0;n<e.length;n+=1){if(e[n].type!=="string")continue;let o=n+1;for(;o<e.length&&e[o].value.trim()==="";)o+=1;let r=e[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(e[n].type="property")}return e}var Nv=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];function kf(t){let e=Ba(t,Nv),n="";for(let o=0;o<e.length;o+=1){let r=e[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let i=o+1;for(;i<e.length&&e[i].value.trim()==="";)i+=1;let l=e[i];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return e}var Fv=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}];function _v(t){let e=[],n=(s,i)=>{i&&e.push({type:s,value:i})},o=t.length,r=0;for(;r<o;){if(t.startsWith("<!--",r)){let i=t.indexOf("-->",r+4),l=i===-1?o:i+3;n("comment",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&t[r+1]==="!"){let i=t.indexOf(">",r),l=i===-1?o:i+1;n("tag",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&/[A-Za-z/]/.test(t[r+1]||"")){let i=t.indexOf(">",r),l=i===-1?o:i+1,p=t.slice(r,l);for(let d of Ba(p,Fv))e.push(d);r=l;let c=/^<\s*(script|style)\b/i.exec(p);if(c&&!/\/>\s*$/.test(p)){let d=c[1].toLowerCase(),b=new RegExp("</\\s*"+d+"\\s*>","i").exec(t.slice(r)),f=b?r+b.index:o,y=t.slice(r,f),C=d==="script"?Ef(y):kf(y);for(let M of C)e.push(M);r=f}continue}let s=t.indexOf("<",r);if(s===r)n("plain",t[r]),r+=1;else{let i=s===-1?o:s;n("plain",t.slice(r,i)),r=i}}return e}function $v(t,e){switch(e){case"html":return _v(t);case"css":return kf(t);case"js":return Ef(t);case"json":return Ov(t)}}function zv(t){let e=Nu(),n=v("span","persona-code-line"),o=(r,s)=>{if(!s)return;let i=Iv[r];if(i){let l=v("span",i);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of t){let s=r.value.split(`
201
- `);for(let i=0;i<s.length;i+=1)i>0&&(e.appendChild(n),e.appendChild(document.createTextNode(`
202
- `)),n=v("span","persona-code-line")),o(r.type,s[i])}return n.childNodes.length>0?e.appendChild(n):e.lastChild||e.appendChild(n),e}function Lf(t,e,n){let o=t.length<=Rv?Wv(e,n):null,r=o?$v(t,o):[{type:"plain",value:t}];return zv(r)}Ye();xt();Ye();xt();function jr(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=t,i=v("div","persona-dropdown-menu persona-hidden");i.setAttribute("role","menu"),i.setAttribute("data-persona-theme-zone","dropdown"),s?(i.style.position="fixed",i.style.zIndex=String(ba)):(i.style.position="absolute",i.style.top="100%",i.style.marginTop="4px",r==="bottom-right"?i.style.right="0":i.style.left="0");for(let f of e){if(f.dividerBefore){let M=document.createElement("hr");i.appendChild(M)}let y=document.createElement("button");if(y.type="button",y.setAttribute("role","menuitem"),y.setAttribute("data-dropdown-item-id",f.id),f.destructive&&y.setAttribute("data-destructive",""),f.icon){let M=ie(f.icon,16,"currentColor",1.5);M&&y.appendChild(M)}let C=document.createElement("span");C.textContent=f.label,y.appendChild(C),y.addEventListener("click",M=>{M.stopPropagation(),d(),n(f.id)}),i.appendChild(y)}let l=null;function p(){if(!s)return;let f=o.getBoundingClientRect();i.style.top=`${f.bottom+4}px`,r==="bottom-right"?(i.style.right=`${window.innerWidth-f.right}px`,i.style.left="auto"):(i.style.left=`${f.left}px`,i.style.right="auto")}function c(){p(),i.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=y=>{!i.contains(y.target)&&!o.contains(y.target)&&d()};document.addEventListener("click",f,!0),l=()=>document.removeEventListener("click",f,!0)})}function d(){i.classList.add("persona-hidden"),l?.(),l=null}function g(){i.classList.contains("persona-hidden")?c():d()}function b(){d(),i.remove()}return s&&s.appendChild(i),{element:i,show:c,hide:d,toggle:g,destroy:b}}function Dt(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,onClick:i,aria:l}=t,p=v("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let c=ie(e,o??16,"currentColor",r??2);if(c&&p.appendChild(c),i&&p.addEventListener("click",i),l)for(let[d,g]of Object.entries(l))p.setAttribute(d,g);return p}function nr(t){let{icon:e,label:n,variant:o="default",size:r="sm",iconSize:s,className:i,onClick:l,aria:p}=t,c="persona-label-btn";o!=="default"&&(c+=" persona-label-btn--"+o),c+=" persona-label-btn--"+r,i&&(c+=" "+i);let d=v("button",c);if(d.type="button",d.setAttribute("aria-label",n),e){let b=ie(e,s??14,"currentColor",2);b&&d.appendChild(b)}let g=v("span");if(g.textContent=n,d.appendChild(g),l&&d.addEventListener("click",l),p)for(let[b,f]of Object.entries(p))d.setAttribute(b,f);return d}function Da(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,s=v("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let i=n,l=[];function p(){for(let d of l)d.btn.setAttribute("aria-pressed",d.id===i?"true":"false")}for(let d of e){let g;d.icon?g=Dt({icon:d.icon,label:d.label,className:d.className,onClick:()=>{i=d.id,p(),o(d.id)}}):(g=v("button","persona-icon-btn"+(d.className?" "+d.className:"")),g.type="button",g.setAttribute("aria-label",d.label),g.title=d.label,g.textContent=d.label,g.addEventListener("click",()=>{i=d.id,p(),o(d.id)})),g.setAttribute("aria-pressed",d.id===i?"true":"false"),l.push({id:d.id,btn:g}),s.appendChild(g)}function c(d){i=d,p()}return{element:s,setSelected:c}}function Pf(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:i,className:l,hover:p}=t,c=v("div","persona-combo-btn"+(l?" "+l:""));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 d=v("span","persona-combo-btn-label");d.textContent=e,c.appendChild(d);let g=ie(n,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",c.appendChild(g)),p&&(c.style.borderRadius=p.borderRadius??"10px",c.style.padding=p.padding??"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",()=>{c.style.backgroundColor=p.background??"",c.style.borderColor=p.border??""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let b=jr({items:o,onSelect:f=>{c.setAttribute("aria-expanded","false"),r(f)},anchor:c,position:s,portal:i});return i||c.appendChild(b.element),c.addEventListener("click",f=>{f.stopPropagation();let y=!b.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",y?"false":"true"),b.toggle()}),c.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),c.click())}),{element:c,setLabel:f=>{d.textContent=f,c.setAttribute("aria-label",f)},open:()=>{c.setAttribute("aria-expanded","true"),b.show()},close:()=>{c.setAttribute("aria-expanded","false"),b.hide()},toggle:()=>{let f=!b.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",f?"false":"true"),b.toggle()},destroy:()=>{b.destroy(),c.remove()}}}Ye();var Oa="persona-artifact-custom-action-btn";function Vr(t,e){let n=e?.documentChrome??!1,o;if(typeof t.icon=="function"){if(t.showLabel){let r="persona-label-btn persona-label-btn--sm "+Oa+(n?" persona-artifact-doc-copy-btn":"");o=v("button",r)}else{let r="persona-icon-btn "+Oa+(n?" persona-artifact-doc-icon-btn":"");o=v("button",r)}o.type="button",o.setAttribute("aria-label",t.label),o.title=t.label;try{let r=t.icon();r&&o.appendChild(r)}catch{}if(t.showLabel){let r=v("span");r.textContent=t.label,o.appendChild(r)}}else t.showLabel||!t.icon?o=nr({icon:t.icon,label:t.label,className:Oa+(n?" persona-artifact-doc-copy-btn":"")}):o=Dt({icon:t.icon,label:t.label,className:Oa+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function Xs(t){if(!t)return null;let e={artifactId:t.id,title:t.title??"",artifactType:t.artifactType};return t.artifactType==="markdown"?(e.markdown=t.markdown??"",t.file&&(e.file=t.file)):e.jsonPayload=JSON.stringify({component:t.component,props:t.props},null,2),e}function If(t,e){let n=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0,o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=n?Fn(n.path):o,s=typeof t.artifactId=="string"?t.artifactId:"",i=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",p=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0,c=n?Eo(n):l==="component"?"Component":"Document",d=document.createElement("div");d.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&d.setAttribute("data-open-artifact",s);let g=document.createElement("div");g.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-muted, #9ca3af)",g.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 b=document.createElement("div");b.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let f=document.createElement("div");f.className="persona-truncate persona-text-sm persona-font-medium",f.style.color="var(--persona-text, #1f2937)",f.textContent=r;let y=document.createElement("div");if(y.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",y.style.color="var(--persona-muted, #9ca3af)",i==="streaming"){let C=e?.config?.features?.artifacts,M={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{},...p?{presentation:p}:{}},I=Ur(M,C,"card");tr(y,I,C)}else s&&zr(s),y.textContent=c;if(b.append(f,y),d.append(g,b),i==="complete"){let C=e?.config?.features?.artifacts?.cardActions;if(C&&C.length>0){let I={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let S of C)try{if(S.visible===void 0||S.visible(I)){let E=Vr(S);E.setAttribute("data-artifact-custom-action",S.id),E.className=`${E.className} persona-flex-shrink-0`,d.append(E)}}catch{}}let M=nr({label:"Download",className:"persona-flex-shrink-0"});M.title=`Download ${r}`,M.setAttribute("data-download-artifact",s),d.append(M)}return d}var Na=(t,e)=>{let n=e?.config?.features?.artifacts?.renderCard;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",i=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:i,status:s},config:e.config,defaultRenderer:()=>If(t,e)});if(l)return l}return If(t,e)};Ye();xt();var Lo=new WeakMap;function qc(t,e,n){if(e.length===0)return;let o=new Map(e.map(r=>[r.id,r]));t.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=Lo.get(r);if(!s)return;let i=o.get(r.getAttribute("data-artifact-inline")??"");i&&s(i,n)})}function Df(t){return Lo.has(t)}function Uv(t){let e=typeof t.artifactId=="string"?t.artifactId:"",n=typeof t.title=="string"&&t.title?t.title:void 0,o=t.status==="streaming"?"streaming":"complete",r=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0;if(t.artifactType==="component"){let i=t.componentProps,l=i&&typeof i=="object"&&!Array.isArray(i)?i:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:l,...r?{presentation:r}:{}}}let s=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0;return{id:e,artifactType:"markdown",title:n,status:o,markdown:typeof t.markdown=="string"?t.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function Rf(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?Fn(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?Eo(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function jv(t){let e={artifactId:t.id,title:t.title??"",status:t.status,artifactType:t.artifactType};return t.artifactType==="markdown"&&(typeof t.markdown=="string"&&(e.markdown=t.markdown),t.file&&(e.file=t.file)),e}var Wf=180,Vv=240,qv=.8,Kv=300,Gv=500,Qv="cubic-bezier(0.2, 0, 0, 1)",Hf=240,Xv=.35;function Yv(t,e,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!e||!t.isConnected||s||typeof t.animate!="function"){o(),r();return}t.style.height=`${e}px`,t.style.overflow="hidden";let i=[];for(let l of Array.from(t.children))l instanceof HTMLElement&&i.push(l.animate([{opacity:1},{opacity:0}],{duration:Wf,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let I of i)I.cancel();o();let l=()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow")};if(!t.isConnected){l(),r();return}t.style.height="auto";let p=t.getBoundingClientRect().height;if(t.style.height=`${e}px`,!p||Math.abs(p-e)<1){l(),r();return}let c=Math.abs(e-p),d=Math.round(Math.min(Gv,Math.max(Kv,Vv+c*qv))),g=Math.round(d*Xv),b=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,f=b?b.animate([{opacity:0},{opacity:1}],{duration:Hf,delay:g,easing:"ease-out",fill:"backwards"}):null,y=t.animate([{height:`${e}px`},{height:`${p}px`}],{duration:d,easing:Qv});t.style.height=`${p}px`;let C=!1,M=()=>{C||(C=!0,l(),r())};Promise.allSettled([y.finished,f?.finished].filter(Boolean)).then(M),window.setTimeout(M,Math.max(d,g+Hf)+120)},Wf)}function Jv(t){let e=t?.inlineChrome;if(e===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof e=="object"?e:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var Ys="--persona-artifact-inline-body-height";function Zv(t){let e=t?.inlineBody,n=e?.streamingView==="status"?"status":"source",o=e?.viewMode==="source"?"source":"rendered",r=320,s=320,i=e?.height;typeof i=="number"||i==="auto"?(r=i,s=i):i&&typeof i=="object"&&(r=i.streaming??320,s=i.complete??320);let l=e?.overflow==="clip"?"clip":"scroll",p=l==="clip"?!1:e?.followOutput!==!1,c,d,g=e?.fadeMask;g===!0?(c=!0,d=!0):g===!1?(c=!1,d=!1):g&&typeof g=="object"?(c=g.top===!0,d=g.bottom===!0):l==="clip"?(c=!1,d=!0):(c=!0,d=!0);let b=e?.transition==="none"?"none":"auto",f=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:l,fadeTop:c,fadeBottom:d,transition:b,completeDisplay:f}}function Bf(t,e){let n=Uv(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:i,showViewToggle:l}=Jv(o),p=o?.inlineActions??[],c=Zv(o),d=c.completeDisplay==="card",g=null,b=n,f=v("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let y=Y=>Na(jv(Y),e),C=Y=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(Ys),f.replaceChildren(y(Y)),Lo.set(f,pe=>{f.replaceChildren(y(pe))})};if(d&&n.status==="complete")return C(n),f;let M=Fa(n,{config:e.config,bodyLayout:c,resolveViewMode:()=>g??c.viewMode}),I=v("div","persona-artifact-inline-body");I.appendChild(M.el);let S=Y=>{let pe=Y.status!=="complete",ne=pe?c.streamingHeight:c.completeHeight,me=typeof ne=="number";me?f.style.setProperty(Ys,`${ne}px`):f.style.removeProperty(Ys);let ve=!!M.el.querySelector(".persona-code-pre"),be=!!M.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");I.classList.toggle("persona-artifact-content-flush",ve),I.classList.toggle("persona-artifact-inline-body--sized",me&&be),I.classList.toggle("persona-artifact-inline-body--cap",!pe&&!be&&typeof c.completeHeight=="number")},E=n.status,L=(Y,pe)=>{E!=="complete"&&Y.status==="complete"?(typeof c.completeHeight=="number"?f.style.setProperty(Ys,`${c.completeHeight}px`):f.style.removeProperty(Ys),Nf(I,pe?.suppressTransition?"none":c.transition,Y.id,()=>{M.update(Y),S(Y)})):M.update(Y),S(Y),E=Y.status};S(n);let D=c.overflow==="clip"&&i&&!!n.id;if(D&&(I.setAttribute("data-expand-artifact-inline",n.id),I.setAttribute("role","button"),I.setAttribute("tabindex","0"),I.classList.add("persona-cursor-pointer"),I.setAttribute("aria-label",`Open ${Rf(n).title} in panel`)),!r)return f.appendChild(I),Lo.set(f,L),f;let z=v("div","persona-artifact-inline-chrome");z.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let $=v("div","persona-artifact-inline-chrome-lead"),F=v("span","persona-flex persona-items-center persona-flex-shrink-0"),B=ie("file-text",16,"currentColor",2);B&&F.appendChild(B);let H=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),w=v("span","persona-artifact-inline-type");$.append(F,H,w);let N=v("div","persona-artifact-inline-chrome-actions"),K=v("span","persona-flex persona-items-center persona-gap-1"),te=()=>g??c.viewMode,Q=l?Da({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:te(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Y=>{let pe=Y==="source"?"source":"rendered";pe!==te()&&(g=pe,M.update(b),S(b))}}):null,se=s?Dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;se&&n.id&&se.setAttribute("data-copy-artifact",n.id);let J=i?Dt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;J&&n.id&&J.setAttribute("data-expand-artifact-inline",n.id),N.appendChild(K),Q&&N.appendChild(Q.element),se&&N.appendChild(se),J&&N.appendChild(J),z.append($,N),f.append(z,I);let oe=Y=>{let{title:pe,typeLabel:ne}=Rf(Y);H.textContent=pe,H.title=pe,D&&I.setAttribute("aria-label",`Open ${pe} in panel`);let me=Y.status!=="complete";if(me){w.classList.contains("persona-artifact-inline-status")||(w.className="persona-artifact-inline-status",w.removeAttribute("data-preserve-animation"),w.replaceChildren());let ve=Ur(Y,o,"inline-chrome");tr(w,ve,o)}else zr(Y.id),w.className="persona-artifact-inline-type",w.removeAttribute("data-preserve-animation"),w.replaceChildren(),w.textContent=ne;if(se&&se.classList.toggle("persona-hidden",me),Q){let ve=Y.artifactType==="markdown"?Y.file:void 0,be=!1;if(!me&&ve&&c.viewMode!=="source"){let Te=er(ve);Te==="markdown"?be=!0:(Te==="html"||Te==="svg")&&(be=o?.filePreview?.enabled!==!1)}Q.element.classList.toggle("persona-hidden",!be),Q.setSelected(te())}if(K.replaceChildren(),!me&&p.length>0){let ve=Xs(Y);if(ve)for(let be of p)try{if(be.visible===void 0||be.visible(ve)){let Te=Vr(be,{documentChrome:!0});Te.setAttribute("data-artifact-custom-action",be.id),Te.classList.add("persona-flex-shrink-0"),K.appendChild(Te)}}catch{}}};return oe(n),Lo.set(f,(Y,pe)=>{if(d&&E!=="complete"&&Y.status==="complete"){let ne=f.isConnected?f.getBoundingClientRect().height:0;E="complete";let me=Y,ve=!1,be=Te=>{me=Te,ve=!0};Lo.set(f,be),Yv(f,ne,{swap:()=>{C(me),ve=!1,Lo.set(f,be)},onSettled:()=>{ve?C(me):Lo.set(f,Te=>{f.replaceChildren(y(Te))})}});return}(Y.status!=="complete"||Y.id!==b.id)&&(g=null),b=Y,L(Y,pe),oe(Y)}),f}var Of=(t,e)=>{let n=e?.config?.features?.artifacts?.renderInline;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",i=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:i,status:s},config:e.config,defaultRenderer:()=>Bf(t,e)});if(l)return l}return Bf(t,e)};var Kc=class{constructor(){this.components=new Map;this.options=new Map}register(e,n,o){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n),o?this.options.set(e,o):this.options.delete(e)}unregister(e){this.components.delete(e),this.options.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.options.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(e){Object.entries(e).forEach(([n,o])=>{this.register(n,o)})}},oo=new Kc;oo.register("PersonaArtifactCard",Na,{bubbleChrome:!1});oo.register("PersonaArtifactInline",Of,{bubbleChrome:!1});function Js(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?Wa(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}var Gc=!1;function ex(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Nf(t,e,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(e!=="auto"||!t||typeof r!="function"||Gc||s){o();return}Gc=!0;let i=ex(n);t.style.setProperty("view-transition-name",i);let l=()=>{Gc=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var tx="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",nx="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function ox(t){let e=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=v("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=t.component?`Component: ${t.component}`:"Component";let o=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(t.props??{},null,2),e.appendChild(n),e.appendChild(o),e}function rx(t){if(t===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let e=t&&typeof t=="object"?t:void 0;return{enabled:!0,delayMs:e?.delayMs??200,minVisibleMs:e?.minVisibleMs??300,timeoutMs:e?.timeoutMs??8e3,injectReadySignal:e?.injectReadySignal!==!1,label:e?.label===!1?!1:e?.label??"Starting preview...",labelDelayMs:e?.labelDelayMs??2e3,renderIndicator:e?.renderIndicator}}var sx=220;function ix(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let t=new Uint32Array(2);return crypto.getRandomValues(t),t[0].toString(36)+t[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function ax(t){return`
203
- <script>(function(){var d=false;var t=`+JSON.stringify(t)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function lx(t,e,n){let o=v("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let i=n.renderIndicator({artifactId:t,config:e});if(i)return o.appendChild(i),{el:o,revealLabel:()=>{}}}catch{}let r=v("div","persona-artifact-frame-loading-indicator");r.appendChild(Cf());let s=null;return n.label!==!1&&(s=v("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function cx(t,e,n,o,r,s){let i=null,l=0,p=!1,c=new Set,d=()=>{c.forEach(E=>clearTimeout(E)),c.clear()},g=(E,L)=>{let D=setTimeout(()=>{c.delete(D),E()},L);c.add(D)},b=()=>{i&&i.parentElement&&i.remove(),i=null},f=()=>{if(i||p)return;let E=lx(r,s,o);i=E.el,t.appendChild(i),l=Date.now(),o.label!==!1&&g(E.revealLabel,o.labelDelayMs)},y=()=>{i&&(i.classList.add("persona-artifact-frame-loading--out"),g(b,sx))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",I):e.removeEventListener("load",S)},M=()=>{if(p||(p=!0,C(),d(),!i))return;let E=Math.max(0,o.minVisibleMs-(Date.now()-l));E>0?g(y,E):y()};function I(E){if(n===null)return;let L=E.data;!L||L.persona!=="artifact-preview-ready"||L.token!==n||E.source===e.contentWindow&&M()}function S(){let E=L=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>L()):setTimeout(L,0)};E(()=>E(()=>M()))}return g(f,o.delayMs),g(M,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",I):e.addEventListener("load",S),()=>{p=!0,d(),C(),b()}}function Fa(t,e){let{config:n}=e,o=e.registry??oo,r=e.bodyLayout,s=n.markdown?Qi(n.markdown):null,i=Xi(n.sanitize),l=t,p=!1,c=J=>{let oe=Jn()!==null;s&&!oe&&!p&&(p=!0,Gi(()=>se(l)));let Y=s?s(J):vo(J);return s&&oe&&i?i(Y):Y},d=v("div","persona-artifact-preview-body"),g=null,b=null,f=null,y=()=>{f&&(f(),f=null),g=null,b=null},C=null,M=null,I=null,S=!1,E=()=>{C=null,M=null,I=null,S=!1},L=null,D=null,z=()=>{L=null,D=null},$=40,F=0,B=J=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>J()):setTimeout(J,0),H=J=>J.scrollHeight-J.clientHeight-J.scrollTop<=$,w=J=>{if(!r)return;let oe=J.scrollHeight-J.clientHeight>1,Y=J.scrollHeight-J.clientHeight-J.scrollTop;J.classList.toggle("persona-artifact-fade-top",r.fadeTop&&oe&&J.scrollTop>1),J.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&oe&&Y>1)},N=J=>{F||(F=B(()=>{F=0,J.scrollTop=J.scrollHeight,w(J)}))},K=(J,oe,Y,pe)=>{let ne=!!r,me=Y.id+"|"+(ne?"w":"p");if(!C||I!==me||C.parentElement!==d){y(),z(),d.replaceChildren();let Te=v("pre",tx+" persona-code-pre"),ze=v("code","persona-code");if(Te.appendChild(ze),ne){let Oe=v("div","persona-artifact-source-window");if(Oe.appendChild(Te),d.appendChild(Oe),!(r?.overflow==="clip")&&typeof Oe.addEventListener=="function"){let Be=()=>Oe.scrollHeight-Oe.clientHeight>1;Oe.addEventListener("scroll",()=>{H(Oe)&&(S=!1),w(Oe)},{passive:!0}),Oe.addEventListener("wheel",Ue=>{Be()&&Ue.deltaY<0&&(S=!0)},{passive:!0}),Oe.addEventListener("touchmove",()=>{Be()&&(S=!0)},{passive:!0})}C=Oe}else d.appendChild(Te),C=Te;M=ze,I=me}let ve=ne?C:null;ve&&(ve.classList.toggle("persona-artifact-source-window--fixed",pe),ve.classList.toggle("persona-artifact-source-window--clip",pe&&r?.overflow==="clip"));let be=ve?H(ve):!0;if(M.replaceChildren(Lf(J,oe?.language,oe?.path)),ve){let Te=Y.status!=="complete";pe&&Te&&r?.followOutput&&!S&&be?N(ve):Te||(S=!1),w(ve)}},te=J=>{y(),E(),z(),d.replaceChildren();let oe=v("div",nx);oe.innerHTML=c(J),d.appendChild(oe)},Q=J=>{let oe=J.id,Y=n.features?.artifacts,pe=Ur(J,Y,"status-body");if(L&&D===oe&&L.parentElement===d){let ve=L.querySelector(".persona-artifact-status-view-text");ve&&tr(ve,pe,Y);return}y(),E(),d.replaceChildren();let ne=v("div","persona-artifact-status-view"),me=v("div","persona-artifact-status-view-text");tr(me,pe,Y),ne.appendChild(me),d.appendChild(ne),L=ne,D=oe},se=J=>{l=J;let oe=e.resolveViewMode?.(J)??r?.viewMode??"rendered",Y=J.artifactType==="markdown"?J.file:void 0,pe=J.status!=="complete";pe||zr(J.id);let ne=pe?r?.streamingHeight:r?.completeHeight,me=!!r&&typeof ne=="number";if(r?.streamingView==="status"&&pe){Q(J);return}if(Y){let be=Wa(J.markdown??""),Te=er(Y),ze=n.features?.artifacts?.filePreview?.enabled!==!1;if(!pe&&oe==="rendered"&&ze&&(Te==="html"||Te==="svg")){let Ne=J.id+"\0"+be;if(g&&b===Ne&&g.parentElement===d)return;E(),z(),y(),d.replaceChildren();let Be=n.features?.artifacts?.filePreview,Ue=Be?.iframeSandbox??"allow-scripts";!Be?.dangerouslyAllowSameOrigin&&Ue.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),Ue=Ue.split(/\s+/).filter(bt=>bt&&bt!=="allow-same-origin").join(" "));let Me=rx(Be?.loading),Ee=v("div","persona-artifact-frame"),Ve=v("iframe","persona-artifact-iframe");Ve.setAttribute("sandbox",Ue),Ve.setAttribute("data-artifact-id",J.id);let Jt=null;Me.enabled&&Me.injectReadySignal?(Jt=ix(),Ve.srcdoc=be+ax(Jt)):Ve.srcdoc=be,Ee.appendChild(Ve),d.appendChild(Ee),Me.enabled&&(f=cx(Ee,Ve,Jt,Me,J.id,n)),g=Ee,b=Ne;return}if(y(),!pe&&Te==="markdown"&&oe==="rendered"){te(be);return}K(be,{language:Y.language,path:Y.path},J,me);return}if(J.artifactType==="markdown"){if(oe==="source"){y(),K(J.markdown??"",void 0,J,me);return}te(J.markdown??"");return}y(),E(),z(),d.replaceChildren();let ve=J.component?o.get(J.component):void 0;if(ve){let Te={message:{id:J.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let ze=ve(J.props??{},Te);if(ze){d.appendChild(ze);return}}catch{}}d.appendChild(ox(J))};return se(t),{el:d,update(J){se(J)}}}var Ff=require("idiomorph"),_a=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;Ff.Idiomorph.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let i=r.textContent??"",l=s.textContent??"";if(i!==l)return}return!1}}}}})};var _f=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Qc={index:-1,draft:""};function $f(t){let{direction:e,history:n,currentValue:o,atStart:r,state:s}=t,i=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(e==="up"){if(!i&&!r)return{handled:!1,state:s};if(!i){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!i)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function zf(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function Uf(){return new Map}function jf(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function Vf(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function qf(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}function Kf(t){return t.role!=="assistant"||t.variant==="tool"||t.variant==="reasoning"?!1:t.variant==="approval"?!0:!!(t.content?.trim()||t.rawContent?.trim()||t.contentParts?.length)}function $a(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function _n(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function ro(t,e){return _n(t)-t.scrollTop<=e}function za(t){let{following:e,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:i=!1,pauseOnUpwardScroll:l=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:c=!1}=t,d=n-o;return i||Math.abs(d)<s?{action:"none",delta:d,nextLastScrollTop:n}:!e&&r&&(!c||d>0)?{action:"resume",delta:d,nextLastScrollTop:n}:e&&l&&d<0?{action:"pause",delta:d,nextLastScrollTop:n}:e&&p&&!r?{action:"pause",delta:d,nextLastScrollTop:n}:{action:"none",delta:d,nextLastScrollTop:n}}function Ua(t){let{following:e,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=t;return e&&n<0?"pause":!e&&r&&n>0&&o?"resume":"none"}function Gf(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function Xc(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight+(t.slack??0));return{targetScrollTop:e,spacerHeight:n}}function Qf(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var Zs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},dx=["pre","code","a","script","style"],ja=t=>({type:t?.type??Zs.type,placeholder:t?.placeholder??Zs.placeholder,speed:t?.speed??Zs.speed,duration:t?.duration??Zs.duration,buffer:t?.buffer??Zs.buffer}),px=[{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"}],Yf=new Map;for(let t of px)Yf.set(t.name,t);var qr=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:Yf.get(t)??null,Va=(t,e,n,o,r)=>{if(!r)return t;if(n?.bufferContent)return n.bufferContent(t,o);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
204
- `);return s<0?"":t.slice(0,s)}return t},ux=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=e,r},gx=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=e,r},Yc=/\s/,fx=(t,e)=>{let n=t.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(e.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},mx=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=0;for(;l<s.length;)if(Yc.test(s[l])){let p=l;for(;p<s.length&&Yc.test(s[p]);)p+=1;i.appendChild(o.createTextNode(s.slice(l,p))),l=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let c=l;for(;c<s.length&&!Yc.test(s[c]);)p.appendChild(ux(o,s[c],e,n.value)),n.value+=1,c+=1;i.appendChild(p),l=c}r.replaceChild(i,t)},hx=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let i=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let p of l)p&&(/^\s+$/.test(p)?i.appendChild(o.createTextNode(p)):(i.appendChild(gx(o,p,e,n.value)),n.value+=1));r.replaceChild(i,t)},ei=(t,e,n,o)=>{if(!t||typeof document>"u")return t;let r=document.createElement("div");r.innerHTML=t;let s=new Set((o?.skipTags??dx).map(g=>g.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=i.nextNode();for(;p;)fx(p,s)||l.push(p),p=i.nextNode();let c={value:o?.startIndex??0},d=e==="char"?mx:hx;for(let g of l)d(g,n,c);return r.innerHTML},qa=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},ti=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let n=t.createElement("div");return n.className="persona-stream-skeleton-line",e.appendChild(n),e},Xf=new WeakMap,bx=(t,e)=>{if(!t.styles)return;let n=Xf.get(e);if(n||(n=new Set,Xf.set(e,n)),n.has(t.name)){let s=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(t.name)}n.add(t.name);let r=(e instanceof ShadowRoot?e.ownerDocument:e.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",t.name),r.textContent=t.styles,e.appendChild(r)},Jc=new WeakMap,yx=(t,e)=>{if(!t.onAttach)return;let n=Jc.get(e);if(n||(n=new Map,Jc.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},Jf=t=>{let e=Jc.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},Ka=(t,e)=>{bx(t,e),yx(t,e)};function Zc(t,e=Ut){let n=t.style.position,o=t.style.zIndex,r=t.style.isolation,s=getComputedStyle(t),i=s.position==="static"||s.position==="";return i&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{i&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=r}}var ni=0,Po=null;function ed(t=document){if(ni++,ni===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;Po={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,ni=Math.max(0,ni-1),ni===0&&Po)){let n=t.body,o=t.defaultView??window;n.style.overflow=Po.originalOverflow,n.style.position=Po.originalPosition,n.style.top=Po.originalTop,n.style.width=Po.originalWidth,o.scrollTo(0,Po.scrollY),Po=null}}}var oi={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ot=t=>(t?.launcher?.mountMode??"floating")==="docked",ri=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",An=t=>{let e=t?.launcher?.dock;return{side:e?.side??oi.side,width:e?.width??oi.width,animate:e?.animate??oi.animate,reveal:e?.reveal??oi.reveal,maxHeight:e?.maxHeight??oi.maxHeight}};Ye();Ye();xt();var td=t=>t==="followUp"?"follow-up":t,nd=(t,e=0)=>{if(typeof t=="string"){let r=t.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=t.label.trim();if(!n)return null;let o=t.prompt?.trim()||n;return{id:t.id?.trim()||o||`suggestion-${e}`,label:n,prompt:o,description:t.description?.trim()||void 0,icon:t.icon,iconColor:t.iconColor?.trim()||void 0,behavior:t.behavior,emphasis:t.emphasis??"default"}},vx=t=>{switch(t){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'}},Zf=new WeakSet,xx=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,wx=t=>{xx()||t.forEach((e,n)=>{typeof e.animate=="function"&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},od=t=>{var S,E,L;let{item:e,index:n,surface:o,source:r,variant:s,streaming:i,config:l,plugins:p,chipsConfig:c,session:d,getTextarea:g,eventTarget:b}=t,f=o==="followUp",y=e.behavior,C=()=>{if(d.isStreaming())return;let D={suggestion:{...e},surface:o,source:r,behavior:y},z=b.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:D,bubbles:!0,composed:!0,cancelable:!0}));if(f&&b.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!z)return;for(let F of p)if(F.onSuggestionSelect?.({suggestion:{...e},surface:o,source:r,variant:s,config:l})===!1)return;let $=g();if(y==="fill"){$.value=e.prompt,$.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),$.focus();return}$.value="",d.sendMessage(e.prompt)},M=()=>{let D=v("button",`persona-suggestion persona-suggestion--${s}`);if(D.type="button",D.disabled=i,D.dataset.suggestionId=e.id,D.dataset.emphasis=e.emphasis,D.dataset.behavior=y,s==="chip"&&(c?.fontFamily&&(D.style.fontFamily=vx(c.fontFamily)),c?.fontWeight&&(D.style.fontWeight=c.fontWeight),c?.paddingX&&(D.style.paddingLeft=c.paddingX,D.style.paddingRight=c.paddingX),c?.paddingY&&(D.style.paddingTop=c.paddingY,D.style.paddingBottom=c.paddingY)),e.icon){let $=ie(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);$&&($.classList.add("persona-suggestion__icon"),e.iconColor&&($.style.color=e.iconColor),D.appendChild($))}let z=v("span","persona-suggestion__copy");if(z.appendChild(ye("span",{className:"persona-suggestion__label",text:e.label})),e.description&&s!=="chip"&&z.appendChild(ye("span",{className:"persona-suggestion__description",text:e.description})),D.appendChild(z),s!=="chip"){let $=ie("arrow-right",16,"currentColor",1.8);$&&($.classList.add("persona-suggestion__arrow"),D.appendChild($))}return D.addEventListener("click",C),D},I=null;for(let D of p)if(D.renderSuggestion&&(I=D.renderSuggestion({suggestion:{...e},index:n,surface:o,source:r,variant:s,streaming:i,config:l,defaultRenderer:M,select:C}),I))break;return I??(I=M()),(S=I.dataset).suggestionId||(S.suggestionId=e.id),(E=I.dataset).behavior||(E.behavior=y),(L=I.dataset).emphasis||(L.emphasis=e.emphasis),I instanceof HTMLButtonElement||I.setAttribute("aria-disabled",i?"true":"false"),I},si=t=>{let e=[],n=[],o=null,r=null,s=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},i=()=>{if(r=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){s();return}let d=Math.max(0,t.scrollWidth-t.clientWidth);if(d<=1){s();return}let g=getComputedStyle(t).direction==="rtl",b=Math.min(d,Math.max(0,Math.abs(t.scrollLeft))),f=4,y=b<=f,C=b>=d-f,M=g?!C:!y,I=g?!y:!C;t.toggleAttribute("data-scroll-left",M),t.toggleAttribute("data-scroll-right",I)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&i();return}r=requestAnimationFrame(i)};t.addEventListener("scroll",l,{passive:!0});let p=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return p?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",l),p?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(d,g,b,f,y,C)=>{t.replaceChildren(),e.length=0,n.length=0;let M=C?.source??"config",I=C?.surface??(M==="config"?"starter":"followUp"),S=I==="followUp",E=C?.variant??"chip",L=C?.behavior??"send",D=C?.overflow??"wrap",z=C?.config??{},$=C?.plugins??[],F=typeof C?.maxItems=="number"?Math.max(0,Math.floor(C.maxItems)):void 0,B=S?"followUps":"starters";!Zf.has(z)&&z.debug===!0&&E!=="chip"&&z.suggestions?.[B]?.overflow!==void 0&&(Zf.add(z),console.info(`[persona] suggestions.${B}.overflow applies to the "chip" variant only; the "${E}" variant manages its own stacking.`));let H=se=>se.map(nd).filter(J=>J!==null).map(J=>({...J,behavior:J.behavior??L})),w=H(d??[]);$.forEach(se=>{se.transformSuggestions&&(w=H(se.transformSuggestions({suggestions:w.map(J=>({...J})),surface:I,source:M,config:z})))});let N=F===void 0?w:w.slice(0,F);if(!N.length){t.hidden=!0,o=null,s();return}if(!S&&(f??g.getMessages()).some(J=>J.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=td(I),t.dataset.variant=E,t.dataset.overflow=D;let K=document.createDocumentFragment(),te=g.isStreaming();N.forEach((se,J)=>{let oe=od({item:se,index:J,surface:I,source:M,variant:E,streaming:te,config:z,plugins:$,chipsConfig:y,session:g,getTextarea:()=>b,eventTarget:t});K.appendChild(oe),n.push(oe),[...oe instanceof HTMLButtonElement?[oe]:[],...Array.from(oe.querySelectorAll("button"))].forEach(pe=>{e.includes(pe)||(pe.disabled=te,e.push(pe))})}),t.appendChild(K),i(),l();let Q=JSON.stringify({normalized:N,surface:I,variant:E,source:M});Q!==o&&(o=Q,wx(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:N.map(se=>({...se})),surface:I,source:M,variant:E},bubbles:!0,composed:!0})),S&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:N.map(se=>se.prompt)},bubbles:!0,composed:!0})))}}};var un={"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"};Ye();xt();Ye();xt();var Cx="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ga=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=Cx,buttonSize:r,iconSize:s="28px"}=e,i=t?.launcher??{},l=r??i.closeButtonSize??"32px",p=v("div",o),c=i.closeButtonTooltipText??"Close chat",d=i.closeButtonShowTooltip??!0,g=i.closeButtonIconName??"x",b=i.closeButtonIconText??"\xD7",f=!!(i.closeButtonBorderWidth||i.closeButtonBorderColor),y=ye("button",{className:Bn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!i.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!i.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:l,width:l,display:n?void 0:"none",color:i.closeButtonColor||Yt.actionIconColor,backgroundColor:i.closeButtonBackgroundColor||void 0,border:f?`${i.closeButtonBorderWidth||"0px"} solid ${i.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:i.closeButtonBorderRadius||void 0,paddingLeft:i.closeButtonPaddingX||void 0,paddingRight:i.closeButtonPaddingX||void 0,paddingTop:i.closeButtonPaddingY||void 0,paddingBottom:i.closeButtonPaddingY||void 0}}),C=ie(g,s,"currentColor",1);return C?(C.style.display="block",y.appendChild(C)):y.textContent=b,p.appendChild(y),jt({anchor:y,trigger:p,text:()=>y.getAttribute("aria-label")??c,enabled:d}),{button:y,wrapper:p}},Ax="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Qa=(t,e={})=>{let{wrapperClassName:n=Ax,buttonSize:o,iconSize:r="20px"}=e,i=(t?.launcher??{}).clearChat??{},l=o??i.size??"32px",p=i.iconName??"refresh-cw",c=i.iconColor??"",d=i.backgroundColor??"",g=i.borderWidth??"",b=i.borderColor??"",f=i.borderRadius??"",y=i.paddingX??"",C=i.paddingY??"",M=i.tooltipText??"Clear chat",I=i.showTooltip??!0,S=v("div",n),E=!!(g||b),L=ye("button",{className:Bn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"hover:persona-bg-gray-100",!E&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":M},style:{height:l,width:l,color:c||Yt.actionIconColor,backgroundColor:d||void 0,border:E?`${g||"0px"} solid ${b||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:y||void 0,paddingRight:y||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),D=ie(p,r,"currentColor",1);return D&&(D.style.display="block",L.appendChild(D)),S.appendChild(L),jt({anchor:L,trigger:S,text:()=>L.getAttribute("aria-label")??M,enabled:I}),{button:L,wrapper:S}};var Yt={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))"},rd={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},Sx={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},or=t=>{let{config:e,showClose:n=!0}=t,o=ye("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)))"}}),r=e?.launcher??{},s=r.headerIconSize??"48px",i=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,p=r.headerIconName,c=ye("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(!l)if(p){let D=parseFloat(s)||24,z=ie(p,D*.6,"currentColor",1);z?c.replaceChildren(z):c.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let D=v("img");D.src=e.launcher.iconUrl,D.alt="",D.className="persona-rounded-xl persona-object-cover",D.style.height=s,D.style.width=s,c.replaceChildren(D)}else c.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let d=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=ye("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Yt.titleColor,...rd}}),b=ye("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Yt.subtitleColor,...Sx}});d.append(g,b),l?o.append(d):o.append(c,d);let f=r.clearChat??{},y=f.enabled??!0,C=f.placement??"inline",M=null,I=null;if(y){let z=Qa(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=z.button,I=z.wrapper,C==="top-right"&&(I.style.right="48px"),C==="inline"&&o.appendChild(I)}let S=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&C==="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:E,wrapper:L}=Ga(e,{showClose:n,wrapperClassName:S});return i!=="top-right"&&o.appendChild(L),{header:o,iconHolder:c,headerTitle:g,headerSubtitle:b,closeButton:E,closeButtonWrapper:L,clearChatButton:M,clearChatButtonWrapper:I}},ii=(t,e,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";t.appendChild(e.header),r==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};Ye();xt();var Mx=t=>{let e=or({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return e};function Tx(t,e,n){if(e?.length)for(let o of e){let r=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0");if(r.type="button",r.style.height="32px",r.style.width="32px",r.style.color=Yt.actionIconColor,r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=ie(o.icon,16,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=v("div","persona-relative");s.appendChild(r);let i=jr({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(i.element),r.addEventListener("click",l=>{l.stopPropagation(),i.toggle()}),t.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),t.appendChild(r)}}var Ex=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=t,i=e?.launcher??{},l=v("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,c,d;if(p)c=Pf({label:i.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,c.style.color=Yt.titleColor,d=c.querySelector(".persona-combo-btn-label")??c;else{if(c=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=v("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=Yt.titleColor,Object.assign(d.style,rd),d.textContent=i.title??"Chat Assistant",c.appendChild(d),r?.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let L=r.onTitleClick;c.addEventListener("click",D=>{D.target.closest("button")||L()}),c.addEventListener("keydown",D=>{(D.key==="Enter"||D.key===" ")&&(D.preventDefault(),L())})}let E=r?.titleRowHover;E&&(c.style.borderRadius=E.borderRadius??"10px",c.style.padding=E.padding??"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",()=>{c.style.backgroundColor=E.background??"",c.style.borderColor=E.border??""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}l.appendChild(c);let g=i.closeButtonSize??"32px",b=v("div",""),f=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=g,f.style.width=g,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=i.closeButtonColor||Yt.actionIconColor;let y=i.closeButtonIconName??"x",C=ie(y,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),b.appendChild(f);let M=v("div","persona-flex persona-items-center persona-gap-1");p||Tx(M,r?.trailingActions,r?.onAction??s),M.appendChild(b),l.appendChild(M);let I=v("div");I.style.display="none";let S=v("span");return S.style.display="none",{header:l,iconHolder:I,headerTitle:d,headerSubtitle:S,closeButton:f,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}},em={default:Mx,minimal:Ex},kx=t=>em[t]??em.default,Xa=(t,e,n)=>{if(e?.render){let i=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),l=v("div");l.style.display="none";let p=v("span"),c=v("span"),d=v("button");d.style.display="none";let g=v("div");return g.style.display="none",{header:i,iconHolder:l,headerTitle:p,headerSubtitle:c,closeButton:d,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",s=kx(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(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};Ye();Ye();xt();var Ya=t=>{let e=v("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=t?.copy?.inputPlaceholder??"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-text 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 n=3,o=20,r=()=>{let p=e.ownerDocument?.defaultView;if(!p?.getComputedStyle)return o;let c=p.getComputedStyle(e).lineHeight;if(!c||!c.trim().endsWith("px"))return o;let d=parseFloat(c);return Number.isFinite(d)&&d>0?d:o},s=`${n*o}px`;e.style.maxHeight=s,e.style.overflowY="auto";let i=()=>{let p=e.style.maxHeight;if(p!==s){let d=parseFloat(p);if(Number.isFinite(d)&&d>0)return d}let c=n*r();return s=`${c}px`,e.style.maxHeight=s,c},l=()=>{e.addEventListener("input",()=>{e.style.height="auto";let p=Math.min(e.scrollHeight,i());e.style.height=`${p}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:l}},Ja=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",r=e.iconName,s=e.stopIconName??"square",i=e.tooltipText??"Send message",l=e.stopTooltipText??"Stop generating",p=t?.copy?.sendButtonLabel??"Send",c=t?.copy?.stopButtonLabel??"Stop",d=e.showTooltip??!1,g=e.size??"40px",b=e.backgroundColor,f=e.textColor,y=v("div","persona-send-button-wrapper"),C=ye("button",{className:Bn("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!b&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?g:void 0,height:n?g:void 0,minWidth:n?g:void 0,minHeight:n?g:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&b||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:n?"0":e.paddingX||void 0,paddingRight:n?"0":e.paddingX||void 0,paddingTop:n?"0":e.paddingY||void 0,paddingBottom:n?"0":e.paddingY||void 0}}),M=null,I=null;if(n){let L=parseFloat(e.iconSize??"")||Math.round((parseFloat(g)||24)*.5),D=e.iconStrokeWidth??2,z=f?.trim()||"currentColor";r?(M=ie(r,L,z,D),M?C.appendChild(M):C.textContent=o):C.textContent=o,I=ie(s,L,z,D)}else C.textContent=p;C.setAttribute("aria-label",i),y.appendChild(C),jt({anchor:C,trigger:y,text:()=>C.getAttribute("aria-label")??"",enabled:d});let S="send";return{button:C,wrapper:y,setMode:L=>{if(L===S)return;S=L;let D=L==="stop"?l:i;if(C.setAttribute("aria-label",D),n){if(M&&I){let z=L==="stop"?I:M;C.replaceChildren(z)}}else C.textContent=L==="stop"?c:p}}},Za=t=>{let e=t?.voiceRecognition??{};if(!(e.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=e.provider?.type==="runtype";if(!(o||r))return null;let i=t?.sendButton?.size??"40px",l=e.iconName??"mic",p=e.iconSize??i,c=parseFloat(p)||24,d=e.backgroundColor??t?.sendButton?.backgroundColor,g=e.iconColor??t?.sendButton?.textColor,b=v("div","persona-send-button-wrapper"),f=ye("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":e.tooltipText??"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:g||"var(--persona-text, #111827)",backgroundColor:d||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}}),C=ie(l,c,g||"currentColor",1.5);C?f.appendChild(C):f.textContent="\u{1F3A4}",b.appendChild(f);let M=e.tooltipText??"Start voice recognition",I=e.showTooltip??!1;return jt({anchor:f,trigger:b,text:()=>f.getAttribute("aria-label")??M,enabled:I}),{button:f,wrapper:b}},el=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=t?.sendButton?.size??"40px",o=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=v("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(e.allowedTypes??to).join(","),r.multiple=(e.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=e.buttonIconName??"paperclip",i=n,l=parseFloat(i)||40,p=Math.round(l*.6),c=v("div","persona-send-button-wrapper"),d=ye("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":e.buttonTooltipText??"Attach file"},style:{width:i,height:i,minWidth:i,minHeight:i,fontSize:"18px",lineHeight:"1"}}),g=ie(s,p,"currentColor",1.5);g?d.appendChild(g):d.textContent="\u{1F4CE}",d.addEventListener("click",f=>{f.preventDefault(),r.click()}),c.appendChild(d);let b=e.buttonTooltipText??"Attach file";return jt({anchor:d,trigger:c,text:()=>d.getAttribute("aria-label")??b}),{button:d,wrapper:c,input:r,previewsContainer:o}},tl=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=v("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=e.visible??!0;o.style.display=r?"":"none";let s=e.idleText??"Online";if(e.idleLink){let i=v("a");i.href=e.idleLink,i.target="_blank",i.rel="noopener noreferrer",i.textContent=s,i.style.color="inherit",i.style.textDecoration="none",o.appendChild(i)}else o.textContent=s;return o},nl=()=>ye("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ai=t=>{let{config:e}=t,n=ye("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=nl(),r=ye("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:i}=Ya(e);i();let l=Ja(e),p=Za(e),c=el(e),d=tl(e);c&&(c.previewsContainer.style.gap="8px",r.append(c.previewsContainer,c.input)),r.append(s);let g=ye("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),b=v("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=v("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&b.append(c.wrapper),p&&f.append(p.wrapper),f.append(l.wrapper),g.append(b,f),r.append(g),r.addEventListener("click",y=>{y.target!==l.button&&y.target!==l.wrapper&&y.target!==p?.button&&y.target!==p?.wrapper&&y.target!==c?.button&&y.target!==c?.wrapper&&s.focus()}),n.append(o,r,d),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:d,attachmentButton:c?.button??null,attachmentButtonWrapper:c?.wrapper??null,attachmentInput:c?.input??null,attachmentPreviewsContainer:c?.previewsContainer??null,actionsRow:g,leftActions:b,rightActions:f,setSendButtonMode:l.setMode}};Ye();xt();var tm=()=>{let t=ye("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=v("span","persona-pill-peek__icon"),n=ie("message-square",16,"currentColor",1.5);n&&e.appendChild(n);let o=v("span","persona-pill-peek__text"),r=v("span","persona-pill-peek__caret"),s=ie("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},ol=t=>{let{config:e}=t,n=ye("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=nl(),r=tl(e);r.style.display="none";let{textarea:s,attachAutoResize:i}=Ya(e);s.style.maxHeight="100px",i();let l=Ja(e),p=Za(e),c=el(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let d=ye("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=v("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&g.append(c.wrapper);let b=v("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&b.append(p.wrapper),b.append(l.wrapper),d.addEventListener("click",y=>{y.target!==l.button&&y.target!==l.wrapper&&y.target!==p?.button&&y.target!==p?.wrapper&&y.target!==c?.button&&y.target!==c?.wrapper&&s.focus()}),c&&d.append(c.input),d.append(g,s,b),c&&n.append(c.previewsContainer),n.append(o,d,r);let f=d;return{footer:n,suggestions:o,composerForm:d,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:c?.button??null,attachmentButtonWrapper:c?.wrapper??null,attachmentInput:c?.input??null,attachmentPreviewsContainer:c?.previewsContainer??null,actionsRow:f,leftActions:g,rightActions:b,setSendButtonMode:l.setMode}};Ye();xt();Ye();xt();var Lx=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Px=(t,e)=>{if(!t)return null;let n=Lx(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},Ix=(t,e)=>{let n=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},Rx=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},sd=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},id=320,sm=320,Wx=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),Hx=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),Bx=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),Dx=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Ox=t=>{if(!t||t.length===0)return null;let e=ye("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=ye("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=v("span","persona-mention-chip-icon"),s=ie(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(ye("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},Nx=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(Ks(o.ref,{readonly:!0,render:e}))}return n},nm="\uE000",om="\uE001",Fx=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=b=>`${nm}${r}:${b}${om}`,i=e.map((b,f)=>b.kind==="text"?b.text:s(f)).join(""),l=n(i);if(!e.every((b,f)=>b.kind==="text"||l.includes(s(f)))){t.replaceChildren(Nx(e,o));return}t.innerHTML=l;let c=new RegExp(`${nm}${r}:(\\d+)${om}`),d=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),g=[];for(let b=d.nextNode();b;b=d.nextNode())g.push(b);for(let b of g){let f=b;for(let y=c.exec(f.data);y;y=c.exec(f.data)){let C=e[Number(y[1])],M=f.splitText(y.index);M.data=M.data.slice(y[0].length),C?.kind==="mention"&&M.parentNode?.insertBefore(Ks(C.ref,{readonly:!0,render:o}),M),f=M}}},_x=(t,e,n)=>{if(t.length===0)return null;try{let o=v("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let r=0,s=!1,i=()=>{s||(s=!0,o.remove(),n?.())};return t.forEach((l,p)=>{let c=v("img");c.alt=l.alt?.trim()||`Attached image ${p+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${id}px`,c.style.maxHeight=`${sm}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 d=!1;r+=1,c.addEventListener("error",()=>{d||(d=!0,r=Math.max(0,r-1),c.remove(),r===0&&i())}),c.addEventListener("load",()=>{d=!0}),Rx(l.image)?(c.src=l.image,o.appendChild(c)):(d=!0,r=Math.max(0,r-1),c.remove())}),r===0?(i(),null):o}catch{return n?.(),null}},$x=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!sd(o.audio))return;let r=v("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${id}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},zx=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!sd(o.video))return;let r=v("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${id}px`,r.style.maxHeight=`${sm}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Ux=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!sd(o.data))return;let r=v("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},li=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(r),t},jx=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:li};if(e){let r=e(o);if(r!==null)return r}return li()},Vx=(t,e)=>{let n=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=v("img");r.src=o,r.alt=e==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},rm=(t,e,n="div")=>{let o=v(n,"persona-text-xs persona-text-persona-muted"),r=new Date(t.createdAt);return e.format?o.textContent=e.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},ci=(t,e="bubble")=>{let n=["persona-message-bubble"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},qx=(t,e,n)=>{let o=e.showCopy??!0,r=e.showUpvote??!0,s=e.showDownvote??!0,i=e.showReadAloud??!1;if(!o&&!r&&!s&&!i){let y=v("div");return y.style.display="none",y.id=`actions-${t.id}`,y.setAttribute("data-actions-for",t.id),y}let l=e.visibility??"hover",p=e.align??"right",c=e.layout??"pill-inside",d={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[p],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],b=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${d} ${g} ${l==="hover"?"persona-message-actions-hover":""}`);b.id=`actions-${t.id}`,b.setAttribute("data-actions-for",t.id);let f=(y,C,M)=>{let I=Dt({icon:y,label:C,size:14,className:"persona-message-action-btn"});return I.setAttribute("data-action",M),I};return o&&b.appendChild(f("copy","Copy message","copy")),i&&b.appendChild(f("volume-2","Read aloud","read-aloud")),r&&b.appendChild(f("thumbs-up","Upvote","upvote")),s&&b.appendChild(f("thumbs-down","Downvote","downvote")),b},ad=(t,e,n,o,r,s)=>{let i=n??{},l=i.layout??"bubble",p=i.avatar,c=i.timestamp,d=p?.show??!1,g=c?.show??!1,b=p?.position??"left",f=c?.position??"below",y=ci(t.role,l),C=v("div",y.join(" "));C.id=`bubble-${t.id}`,C.setAttribute("data-message-id",t.id),C.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),l==="flat"?(C.style.backgroundColor="transparent",C.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(C.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let M=Wx(t),I=t.content?.trim()??"",E=M.length>0&&I===la,L=ja(s?.widgetConfig?.features?.streamAnimation),D=s?.widgetConfig?.features?.streamAnimation?.plugins,z=t.role==="assistant"&&L.type!=="none"?qr(L.type,D):null,$=t.role==="assistant"&&z?.isAnimating?.(t)===!0,F=t.role==="assistant"&&z!==null&&(!!t.streaming||$);F&&z?.bubbleClass&&C.classList.add(z.bubbleClass);let B=document.createElement("div");B.classList.add("persona-message-content"),t.streaming&&B.classList.add("persona-content-streaming"),F&&z&&(z.containerClass&&B.classList.add(z.containerClass),B.style.setProperty("--persona-stream-step",`${L.speed}ms`),B.style.setProperty("--persona-stream-duration",`${L.duration}ms`));let H=F?Va(t.content??"",L.buffer,z,t,!!t.streaming):t.content??"",w=()=>{let ne=e({text:H,message:t,streaming:!!t.streaming,raw:t.rawContent});return F&&z?.wrap==="char"?ei(ne,"char",t.id,{skipTags:z.skipTags}):F&&z?.wrap==="word"?ei(ne,"word",t.id,{skipTags:z.skipTags}):ne},N=null;if(E?(N=document.createElement("div"),N.innerHTML=w(),N.style.display="none",B.appendChild(N)):t.contentSegments?.length?Fx(B,t.contentSegments,ne=>e({text:ne,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):B.innerHTML=w(),F&&z?.useCaret&&!E&&I){let ne=qa(),me=B.querySelectorAll(".persona-stream-char, .persona-stream-word"),ve=me[me.length-1];if(ve?.parentNode)ve.parentNode.insertBefore(ne,ve.nextSibling);else{let be=B.lastElementChild;be?be.appendChild(ne):B.appendChild(ne)}}if(g&&f==="inline"&&t.createdAt){let ne=rm(t,c,"span");ne.classList.add("persona-timestamp-inline");let me=B.lastElementChild;me?me.appendChild(ne):B.appendChild(ne)}if(M.length>0){let ne=_x(M,!E&&!!I,()=>{E&&N&&(N.style.display="")});ne?C.appendChild(ne):E&&N&&(N.style.display="")}let K=Hx(t);if(K.length>0){let ne=$x(K);ne&&C.appendChild(ne)}let te=Bx(t);if(te.length>0){let ne=zx(te);ne&&C.appendChild(ne)}let Q=Dx(t);if(Q.length>0){let ne=Ux(Q);ne&&C.appendChild(ne)}let se=t.contentSegments?.length?null:Ox(t.contextMentions);if(se&&C.appendChild(se),C.appendChild(B),g&&f==="below"&&t.createdAt){let ne=rm(t,c);ne.classList.add("persona-mt-1"),C.appendChild(ne)}let J=t.role==="assistant"?Px(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let ne=!!(H&&H.trim()),me=L.placeholder==="skeleton",ve=me&&L.buffer==="line"&&ne;if(ne)ve&&C.appendChild(ti());else if(me)C.appendChild(ti());else{let be=jx("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);be&&C.appendChild(be)}}if(J&&t.stopReason&&!t.streaming&&(I||(B.style.display="none"),C.appendChild(Ix(t.stopReason,J))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1&&o){let ne=qx(t,o,r);C.appendChild(ne)}if(!d||t.role==="system")return C;let Y=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),pe=Vx(p,t.role);return b==="right"||b==="left"&&t.role==="user"?Y.append(C,pe):Y.append(pe,C),Y};var Kx=40,Gx=(t,e)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}if(typeof e=="function"){let n=null;try{n=e()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){t.hidden=!0;return}t.appendChild(n),t.hidden=!1;return}if(e.type==="lucide"){let n=ie(e.name,Kx);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(ye("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(ye("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},im=(t,e,n={})=>{let o=ye("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=v("h2","persona-welcome-title"),s=v("p","persona-welcome-subtitle");return{host:ye("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},o,r,s,e),iconHolder:o,title:r,subtitle:s,starterSuggestions:e}},Kr=(t,e,n)=>{e.hidden=!n,e.style.display=n?"":"none",t.classList.toggle("persona-gap-6",n),t.classList.toggle("persona-gap-3",!n)},sl=(t,e)=>{t.title.textContent=e.title,t.subtitle.textContent=e.subtitle,t.subtitle.hidden=e.subtitle==="",Gx(t.iconHolder,e.icon),t.host.setAttribute("data-persona-welcome-variant",e.variant),t.host.setAttribute("data-persona-welcome-dismiss",e.dismiss)},Qx="data-persona-welcome-plugin",am="data-persona-welcome-overlay",rl="persona-welcome-overlay-active",ld=new WeakMap,lm=(t,e,n)=>{n.setAttribute(Qx,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(am,""),t.classList.contains(rl)||(ld.set(t,t.scrollTop),t.classList.add(rl),t.scrollTop=0)},cm=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(am),t.classList.contains(rl)&&(t.classList.remove(rl),t.scrollTop=ld.get(t)??t.scrollTop,ld.delete(t))},dm=()=>{let t=ye("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},il=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=ye("div",{className:ci("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:e,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});t.appendChild(ye("div",{className:"persona-flex"},r)),t.hidden=!1},Xx=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,pm=(t,e)=>{if(Xx()||typeof t.animate!="function"||!t.isConnected)return e(null),null;let n=t.animate([{opacity:"1",transform:"none"},{opacity:"0",transform:"translateY(-4px)"}],{duration:180,easing:"ease-out",fill:"forwards"}),o=!1,r=()=>{o||(o=!0,e(n))};return n.finished.then(r).catch(r),n};var Yx="Hello \u{1F44B}",Jx="I can answer questions and help you get things done here.",um=new WeakSet,Sn=(t,e)=>!!t&&t[e]!==void 0,Zx=(t,e)=>{!t||t.debug!==!0||!e.length||um.has(t)||(um.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},rr=t=>{let e=t?.welcome,n=t?.copy,o=Sn(e,"variant")?e.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":Sn(e,"dismiss")?e.dismiss:"never",s=[];return Sn(e,"title")&&Sn(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),Sn(e,"subtitle")&&Sn(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),Sn(e,"variant")&&Sn(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&Sn(e,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&Sn(e,"dismiss")&&e.dismiss!=="on-first-message"&&s.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".'),Zx(t,s),{title:Sn(e,"title")?e.title:n?.welcomeTitle??Yx,subtitle:Sn(e,"subtitle")?e.subtitle:n?.welcomeSubtitle??Jx,icon:e?.icon,variant:o,dismiss:r,message:o==="hero"?void 0:e?.message}},Gr=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var gm=t=>{let e=t?.launcher?.enabled??!0,n=Ot(t);if(ri(t)){let d=t?.launcher?.composerBar??{},g=v("div","persona-widget-wrapper persona-fixed persona-transition");g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=d.expandedSize??"anchored",g.style.zIndex=String(t?.launcher?.zIndex??Ut);let b=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");b.style.width="100%",g.appendChild(b);let f=v("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=d.expandedSize??"anchored",f.style.zIndex=String(t?.launcher?.zIndex??Ut),{wrapper:g,panel:b,pillRoot:f}}if(n){let d=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),g=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return d.appendChild(g),{wrapper:d,panel:g}}if(!e){let d=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),g=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),b=t?.launcher?.width??"100%";return d.style.width=b,g.style.width="100%",d.appendChild(g),{wrapper:d,panel:g}}let r=t?.launcher??{},s=r.position&&un[r.position]?un[r.position]:un["bottom-right"],i=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(t?.launcher?.zIndex??Ut);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=t?.launcher?.width??t?.launcherWidth??no;return l.style.width=c,l.style.maxWidth=c,i.appendChild(l),{wrapper:i,panel:l}},cd=t=>{let e=ye("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":td(t)}});return e.hidden=!0,e},fm=(t,e)=>{let n=cd("starter"),o=im(t,n,{flatShadow:Ot(t)}),r=rr(t);sl(o,r),Kr(e,o.host,Gr(r,t?.initialMessages));let s=dm();return il(s,r.message,t),{welcome:o,greetingHost:s}},ew=(t,e)=>{let n=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=Ga(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=t?.launcher?.clearChat?.enabled??!0,i=null,l=null;if(s){let $=Qa(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});i=$.button,l=$.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=ye("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=ye("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{welcome:d,greetingHost:g}=fm(t,c),{host:b,title:f,subtitle:y}=d,C=d.starterSuggestions,M=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),I=cd("followUp"),S=To(t,!0);S&&(M.style.maxWidth=S,M.style.marginLeft="auto",M.style.marginRight="auto",M.style.width="100%"),c.append(b,g,M,I);let E=ye("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"}}),L=ol({config:t}),{root:D,textNode:z}=tm();return n.append(p,r,c,E),l&&n.appendChild(l),{container:n,body:c,messagesWrapper:M,starterSuggestions:C,transcriptSuggestions:I,composerOverlay:E,suggestions:L.suggestions,textarea:L.textarea,sendButton:L.sendButton,sendButtonWrapper:L.sendButtonWrapper,micButton:L.micButton,micButtonWrapper:L.micButtonWrapper,composerForm:L.composerForm,statusText:L.statusText,welcomeHost:b,welcomeIconHolder:d.iconHolder,greetingHost:g,introTitle:f,introSubtitle:y,closeButton:o,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:p,footer:L.footer,attachmentButton:L.attachmentButton,attachmentButtonWrapper:L.attachmentButtonWrapper,attachmentInput:L.attachmentInput,attachmentPreviewsContainer:L.attachmentPreviewsContainer,actionsRow:L.actionsRow,leftActions:L.leftActions,rightActions:L.rightActions,setSendButtonMode:L.setSendButtonMode,peekBanner:D,peekTextNode:z}},mm=(t,e=!0)=>{if(ri(t))return ew(t,e);let n=ye("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,r=t?.layout?.showHeader!==!1,s=o?Xa(t,o,{showClose:e}):or({config:t,showClose:e}),i=ye("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"}});i.style.setProperty("scrollbar-gutter","stable");let{welcome:l,greetingHost:p}=fm(t,i),{host:c,title:d,subtitle:g}=l,b=l.starterSuggestions,f=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),y=cd("followUp"),C=To(t,!1);C&&(f.style.maxWidth=C,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),i.append(c,p,f,y);let M=ai({config:t}),I=t?.layout?.showFooter!==!1;r?ii(n,s,t):(s.header.style.display="none",ii(n,s,t)),n.append(i);let S=ye("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 I||(M.footer.style.display="none"),n.append(M.footer),n.append(S),{container:n,body:i,messagesWrapper:f,starterSuggestions:b,transcriptSuggestions:y,composerOverlay:S,suggestions:M.suggestions,textarea:M.textarea,sendButton:M.sendButton,sendButtonWrapper:M.sendButtonWrapper,micButton:M.micButton,micButtonWrapper:M.micButtonWrapper,composerForm:M.composerForm,statusText:M.statusText,welcomeHost:c,welcomeIconHolder:l.iconHolder,greetingHost:p,introTitle:d,introSubtitle:g,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}};Ye();xt();var dd=(t,e)=>{let n=v("button");n.type="button",n.innerHTML=`
1096
+ `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function Xr(t){let e=kb(t.path);if(e)return e==="html"||e==="htm"?"html":e==="svg"?"svg":e==="md"||e==="mdx"?"markdown":"other";let n=(t.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function br(t){switch(Xr(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=kb(t.path);return e?e.toUpperCase():"File"}}}function Vc(t){let e=t.markdown??"";return t.file?{filename:Ao(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:zc(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}function jc(t){let e=new Blob([t.content],{type:t.mime}),n=URL.createObjectURL(e),o=document.createElement("a");o.href=n,o.download=t.filename,o.click(),URL.revokeObjectURL(n)}Qe();Qe();var Ru="http://www.w3.org/2000/svg";function Pb(t){let e=document.createElementNS(Ru,"svg");e.setAttribute("class",zt("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS(Ru,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Ru,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),e.appendChild(n),e.appendChild(o),e}Qe();Qe();var vr=(t,e,n)=>{let o=n;for(let r of e){let s=v("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,t.appendChild(s),o++}return o};function Lb(t,e,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){t.textContent=e;return}if(o==="pulse"){t.setAttribute("data-preserve-animation","true"),t.classList.add("persona-tool-loading-pulse"),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),t.textContent=e;return}t.setAttribute("data-preserve-animation","true"),t.classList.add(`persona-tool-loading-${o}`),t.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&t.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&t.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),vr(t,e,0)}var Wu="persona-artifact-status-label",Ib="persona-artifact-status-detail",Hb="data-artifact-status-label",Bu=new Map,Rb=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function Xs(t){t&&Bu.delete(t)}function sM(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?br(e):t.artifactType==="component"?"Component":"Document"}function Qs(t,e,n){let o=sM(t),r=`Generating ${o.toLowerCase()}...`,s=e?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=t.id,l=Bu.get(a);t.status!=="complete"&&l===void 0&&(l=Rb(),Bu.set(a,l));let d=l===void 0?0:Math.max(0,Rb()-l),p=t.artifactType==="component",u=!p&&typeof t.markdown=="string"?t.markdown:"",g=p?0:u.length,b=p||u===""?0:u.split(`
1097
+ `).length,m=t.artifactType==="markdown"?t.file:void 0,y={artifactId:a,artifactType:t.artifactType,title:t.title,typeLabel:o,file:m,chars:g,lines:b,elapsedMs:d,content:()=>p?"":u,surface:n};try{let w=s(y);return typeof w=="string"?{label:w}:w&&typeof w=="object"&&typeof w.label=="string"?{label:w.label,detail:typeof w.detail=="string"?w.detail:void 0}:{label:r}}catch{return{label:r}}}function iM(t){t.className=Wu,t.removeAttribute("data-preserve-animation"),t.style.removeProperty("--persona-tool-anim-duration"),t.style.removeProperty("--persona-tool-anim-color"),t.style.removeProperty("--persona-tool-anim-secondary-color"),t.replaceChildren()}function Qr(t,e,n){let o=t.querySelector(`:scope > .${Wu}`);o||(o=v("span",Wu),t.appendChild(o)),o.getAttribute(Hb)!==e.label&&(iM(o),Lb(o,e.label,n),o.setAttribute(Hb,e.label));let r=t.querySelector(`:scope > .${Ib}`),s=e.detail;s?(r||(r=v("span",Ib),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}Qe();var aM={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},lM=15e4,qc={html:"html",htm:"html",xhtml:"html",xml:"html",svg:"html",css:"css",js:"js",jsx:"js",mjs:"js",cjs:"js",ts:"js",tsx:"js",mts:"js",cts:"js",javascript:"js",typescript:"js",ecmascript:"js",json:"json",jsonc:"json",json5:"json"};function cM(t,e){let n=(t||"").trim().toLowerCase();if(n&&qc[n])return qc[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(qc[r])return qc[r]}}return null}function Uc(t,e){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:t.slice(r,a)})};for(;o<t.length;){let a=!1;for(let l of e){l.re.lastIndex=o;let d=l.re.exec(t);if(d&&d.index===o&&d[0].length>0){s(o);let p=l.map?l.map(d[0]):l.type;n.push({type:p,value:d[0]}),o+=d[0].length,r=o,a=!0;break}}a||(o+=1)}return s(t.length),n}var dM=new Set(["abstract","any","as","async","await","boolean","break","case","catch","class","const","continue","debugger","declare","default","delete","do","else","enum","export","extends","false","finally","for","from","function","get","if","implements","import","in","instanceof","interface","keyof","let","namespace","never","new","null","number","object","of","private","protected","public","readonly","return","satisfies","set","static","string","super","switch","symbol","this","throw","true","try","type","typeof","undefined","unknown","var","void","while","yield"]),pM=[{type:"comment",re:/\/\/[^\n]*/y},{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/`(?:\\[\s\S]|[^\\`])*`/y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"number",re:/0[xX][0-9a-fA-F]+|(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_$][\w$]*/y,map:t=>dM.has(t)?"keyword":"plain"}];function Wb(t){return Uc(t,pM)}var uM=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:t=>t==="true"||t==="false"||t==="null"?"keyword":"plain"}];function gM(t){let e=Uc(t,uM);for(let n=0;n<e.length;n+=1){if(e[n].type!=="string")continue;let o=n+1;for(;o<e.length&&e[o].value.trim()==="";)o+=1;let r=e[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(e[n].type="property")}return e}var fM=[{type:"comment",re:/\/\*[\s\S]*?\*\//y},{type:"string",re:/"(?:\\.|[^"\\\n])*"/y},{type:"string",re:/'(?:\\.|[^'\\\n])*'/y},{type:"keyword",re:/@[A-Za-z-]+/y},{type:"number",re:/#[0-9a-fA-F]{3,8}\b/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[a-z%]+)?/y},{type:"plain",re:/[A-Za-z_-][\w-]*/y}];function Bb(t){let e=Uc(t,fM),n="";for(let o=0;o<e.length;o+=1){let r=e[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let a=o+1;for(;a<e.length&&e[a].value.trim()==="";)a+=1;let l=e[a];l&&l.value.replace(/^\s*/,"").startsWith(":")&&(n===""||n==="{"||n==="}"||n===";"||n===",")&&(r.type="property")}let s=r.value.replace(/\s+$/,"");s&&(n=s[s.length-1])}return e}var mM=[{type:"tag",re:/<\/?\s*[A-Za-z][\w:-]*/y},{type:"string",re:/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*(?=\s*=)/y},{type:"attr",re:/[A-Za-z_:@][\w:.-]*/y},{type:"tag",re:/\/?>/y}];function hM(t){let e=[],n=(s,a)=>{a&&e.push({type:s,value:a})},o=t.length,r=0;for(;r<o;){if(t.startsWith("<!--",r)){let a=t.indexOf("-->",r+4),l=a===-1?o:a+3;n("comment",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&t[r+1]==="!"){let a=t.indexOf(">",r),l=a===-1?o:a+1;n("tag",t.slice(r,l)),r=l;continue}if(t[r]==="<"&&/[A-Za-z/]/.test(t[r+1]||"")){let a=t.indexOf(">",r),l=a===-1?o:a+1,d=t.slice(r,l);for(let u of Uc(d,mM))e.push(u);r=l;let p=/^<\s*(script|style)\b/i.exec(d);if(p&&!/\/>\s*$/.test(d)){let u=p[1].toLowerCase(),b=new RegExp("</\\s*"+u+"\\s*>","i").exec(t.slice(r)),m=b?r+b.index:o,y=t.slice(r,m),w=u==="script"?Wb(y):Bb(y);for(let T of w)e.push(T);r=m}continue}let s=t.indexOf("<",r);if(s===r)n("plain",t[r]),r+=1;else{let a=s===-1?o:s;n("plain",t.slice(r,a)),r=a}}return e}function yM(t,e){switch(e){case"html":return hM(t);case"css":return Bb(t);case"js":return Wb(t);case"json":return gM(t)}}function bM(t){let e=Eh(),n=v("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=aM[r];if(a){let l=v("span",a);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of t){let s=r.value.split(`
1098
+ `);for(let a=0;a<s.length;a+=1)a>0&&(e.appendChild(n),e.appendChild(document.createTextNode(`
1099
+ `)),n=v("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?e.appendChild(n):e.lastChild||e.appendChild(n),e}function Db(t,e,n){let o=t.length<=lM?cM(e,n):null,r=o?yM(t,o):[{type:"plain",value:t}];return bM(r)}Qe();Rt();Qe();Rt();function Sa(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:s,onOpenChange:a}=t,l=v("div","persona-dropdown-menu persona-hidden");l.setAttribute("role","menu"),l.setAttribute("data-persona-theme-zone","dropdown"),s?(l.style.position="fixed",l.style.zIndex=String(Us)):(l.style.position="absolute",l.style.top="100%",l.style.marginTop="4px",r==="bottom-right"?l.style.right="0":l.style.left="0");for(let y of e){if(y.dividerBefore){let W=document.createElement("hr");l.appendChild(W)}let w=document.createElement("button");if(w.type="button",w.setAttribute("role","menuitem"),w.setAttribute("data-dropdown-item-id",y.id),y.destructive&&w.setAttribute("data-destructive",""),y.icon){let W=fe(y.icon,16,"currentColor",1.5);W&&w.appendChild(W)}let T=document.createElement("span");T.textContent=y.label,w.appendChild(T),w.addEventListener("click",W=>{W.stopPropagation(),g(),n(y.id)}),l.appendChild(w)}let d=null;function p(){if(!s)return;let y=o.getBoundingClientRect();l.style.top=`${y.bottom+4}px`,r==="bottom-right"?(l.style.right=`${window.innerWidth-y.right}px`,l.style.left="auto"):(l.style.left=`${y.left}px`,l.style.right="auto")}function u(){let y=l.classList.contains("persona-hidden");p(),l.classList.remove("persona-hidden"),y&&a?.(!0),requestAnimationFrame(()=>{let w=T=>{!l.contains(T.target)&&!o.contains(T.target)&&g()};document.addEventListener("click",w,!0),d=()=>document.removeEventListener("click",w,!0)})}function g(){let y=!l.classList.contains("persona-hidden");l.classList.add("persona-hidden"),d?.(),d=null,y&&a?.(!1)}function b(){l.classList.contains("persona-hidden")?u():g()}function m(){g(),l.remove()}return s&&s.appendChild(l),{element:l,show:u,hide:g,toggle:b,destroy:m}}function en(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:l}=t,d=v("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let p=fe(e,o??16,"currentColor",r??2);if(p&&d.appendChild(p),a&&d.addEventListener("click",a),l)for(let[u,g]of Object.entries(l))d.setAttribute(u,g);return d}function Jr(t){let{icon:e,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:l,aria:d}=t,p="persona-label-btn";o!=="default"&&(p+=" persona-label-btn--"+o),p+=" persona-label-btn--"+r,a&&(p+=" "+a);let u=v("button",p);if(u.type="button",u.setAttribute("aria-label",n),e){let b=fe(e,s??14,"currentColor",2);b&&u.appendChild(b)}let g=v("span");if(g.textContent=n,u.appendChild(g),l&&u.addEventListener("click",l),d)for(let[b,m]of Object.entries(d))u.setAttribute(b,m);return u}function Kc(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,s=v("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,l=[];function d(){for(let u of l)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of e){let g;u.icon?g=en({icon:u.icon,label:u.label,className:u.className,onClick:()=>{a=u.id,d(),o(u.id)}}):(g=v("button","persona-icon-btn"+(u.className?" "+u.className:"")),g.type="button",g.setAttribute("aria-label",u.label),g.title=u.label,g.textContent=u.label,g.addEventListener("click",()=>{a=u.id,d(),o(u.id)})),g.setAttribute("aria-pressed",u.id===a?"true":"false"),l.push({id:u.id,btn:g}),s.appendChild(g)}function p(u){a=u,d()}return{element:s,setSelected:p}}function Nb(t){let{label:e,icon:n,iconSize:o,iconOnly:r,menuItems:s,onSelect:a,onPrimary:l,position:d="bottom-left",portal:p,chevronLabel:u="More options",chevronIconSize:g,className:b,primaryClassName:m,chevronClassName:y}=t,w=v("div","persona-split-btn"+(b?" "+b:"")),T={label:e,className:"persona-split-btn-primary"+(m?" "+m:""),onClick:l},W=r&&n?en({...T,icon:n,size:o??14}):Jr({...T,icon:n,iconSize:o??14}),E=en({icon:"chevron-down",label:u,size:g??14,className:"persona-split-btn-chevron"+(y?" "+y:""),aria:{"aria-haspopup":"true","aria-expanded":"false"}});w.append(W,E);let k=null,A=()=>{if(k)return k;let D=(typeof p=="function"?p():p)??void 0;return k=Sa({items:s,onSelect:a,anchor:w,position:d,portal:D,onOpenChange:B=>{E.setAttribute("aria-expanded",B?"true":"false")}}),D||w.appendChild(k.element),k};return w.isConnected?A():requestAnimationFrame(()=>{k||A()}),E.addEventListener("click",D=>{D.stopPropagation(),A().toggle()}),{element:w,primaryButton:W,chevronButton:E,openMenu:()=>A().show(),closeMenu:()=>k?.hide(),toggleMenu:()=>A().toggle(),destroy:()=>{k?.destroy(),w.remove()}}}function Ob(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:l,hover:d}=t,p=v("div","persona-combo-btn"+(l?" "+l:""));p.style.position="relative",p.style.display="inline-flex",p.style.alignItems="center",p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0"),p.setAttribute("aria-haspopup","true"),p.setAttribute("aria-expanded","false"),p.setAttribute("aria-label",e);let u=v("span","persona-combo-btn-label");u.textContent=e,p.appendChild(u);let g=fe(n,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",p.appendChild(g)),d&&(p.style.borderRadius=d.borderRadius??"10px",p.style.padding=d.padding??"6px 4px 6px 12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=d.background??"",p.style.borderColor=d.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}));let b=Sa({items:o,onSelect:y=>{p.setAttribute("aria-expanded","false"),r(y)},anchor:p,position:s,portal:a});a||p.appendChild(b.element);let m=()=>p.getAttribute("data-persona-menu-locked")==="true";return p.addEventListener("click",y=>{if(y.stopPropagation(),m())return;let w=!b.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",w?"false":"true"),b.toggle()}),p.addEventListener("keydown",y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),p.click())}),{element:p,setLabel:y=>{u.textContent=y,p.setAttribute("aria-label",y)},open:()=>{p.setAttribute("aria-expanded","true"),b.show()},close:()=>{p.setAttribute("aria-expanded","false"),b.hide()},toggle:()=>{let y=!b.element.classList.contains("persona-hidden");p.setAttribute("aria-expanded",y?"false":"true"),b.toggle()},destroy:()=>{b.destroy(),p.remove()}}}Qe();var Gc="persona-artifact-custom-action-btn";function Js(t,e){let n=e?.documentChrome??!1,o;if(typeof t.icon=="function"){if(t.showLabel){let r="persona-label-btn persona-label-btn--sm "+Gc+(n?" persona-artifact-doc-copy-btn":"");o=v("button",r)}else{let r="persona-icon-btn "+Gc+(n?" persona-artifact-doc-icon-btn":"");o=v("button",r)}o.type="button",o.setAttribute("aria-label",t.label),o.title=t.label;try{let r=t.icon();r&&o.appendChild(r)}catch{}if(t.showLabel){let r=v("span");r.textContent=t.label,o.appendChild(r)}}else t.showLabel||!t.icon?o=Jr({icon:t.icon,label:t.label,className:Gc+(n?" persona-artifact-doc-copy-btn":"")}):o=en({icon:t.icon,label:t.label,className:Gc+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function Aa(t){if(!t)return null;let e={artifactId:t.id,title:t.title??"",artifactType:t.artifactType};return t.artifactType==="markdown"?(e.markdown=t.markdown??"",t.file&&(e.file=t.file)):e.jsonPayload=JSON.stringify({component:t.component,props:t.props},null,2),e}function _b(t,e){let n=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0,o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=n?Ao(n.path):o,s=typeof t.artifactId=="string"?t.artifactId:"",a=t.status==="streaming"?"streaming":"complete",l=typeof t.artifactType=="string"?t.artifactType:"markdown",d=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0,p=n?br(n):l==="component"?"Component":"Document",u=document.createElement("div");u.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",u.tabIndex=0,u.setAttribute("role","button"),u.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&u.setAttribute("data-open-artifact",s);let g=document.createElement("div");g.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-muted, #9ca3af)",g.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 b=document.createElement("div");b.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let m=document.createElement("div");m.className="persona-truncate persona-text-sm persona-font-medium",m.style.color="var(--persona-text, #1f2937)",m.textContent=r;let y=document.createElement("div");if(y.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",y.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let w=e?.config?.features?.artifacts,T={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{},...d?{presentation:d}:{}},W=Qs(T,w,"card");Qr(y,W,w)}else s&&Xs(s),y.textContent=p;if(b.append(m,y),u.append(g,b),a==="complete"){let w=e?.config?.features?.artifacts?.cardActions;if(w&&w.length>0){let W={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let E of w)try{if(E.visible===void 0||E.visible(W)){let k=Js(E);k.setAttribute("data-artifact-custom-action",E.id),k.className=`${k.className} persona-flex-shrink-0`,u.append(k)}}catch{}}let T=Jr({label:"Download",className:"persona-flex-shrink-0"});T.title=`Download ${r}`,T.setAttribute("data-download-artifact",s),u.append(T)}return u}var Yc=(t,e)=>{let n=e?.config?.features?.artifacts?.renderCard;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>_b(t,e)});if(l)return l}return _b(t,e)};Qe();Rt();var wr=new WeakMap;function Du(t,e,n){if(e.length===0)return;let o=new Map(e.map(r=>[r.id,r]));t.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=wr.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function jb(t){return wr.has(t)}function vM(t){let e=typeof t.artifactId=="string"?t.artifactId:"",n=typeof t.title=="string"&&t.title?t.title:void 0,o=t.status==="streaming"?"streaming":"complete",r=t.presentation&&typeof t.presentation=="object"&&!Array.isArray(t.presentation)?t.presentation:void 0;if(t.artifactType==="component"){let a=t.componentProps,l=a&&typeof a=="object"&&!Array.isArray(a)?a:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:l,...r?{presentation:r}:{}}}let s=t.file&&typeof t.file=="object"&&!Array.isArray(t.file)?t.file:void 0;return{id:e,artifactType:"markdown",title:n,status:o,markdown:typeof t.markdown=="string"?t.markdown:"",...s?{file:s}:{},...r?{presentation:r}:{}}}function Fb(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?Ao(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?br(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function wM(t){let e={artifactId:t.id,title:t.title??"",status:t.status,artifactType:t.artifactType};return t.artifactType==="markdown"&&(typeof t.markdown=="string"&&(e.markdown=t.markdown),t.file&&(e.file=t.file)),e}var $b=180,CM=240,xM=.8,SM=300,AM=500,MM="cubic-bezier(0.2, 0, 0, 1)",zb=240,TM=.35;function EM(t,e,n){let{swap:o,onSettled:r}=n,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(!e||!t.isConnected||s||typeof t.animate!="function"){o(),r();return}t.style.height=`${e}px`,t.style.overflow="hidden";let a=[];for(let l of Array.from(t.children))l instanceof HTMLElement&&a.push(l.animate([{opacity:1},{opacity:0}],{duration:$b,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let W of a)W.cancel();o();let l=()=>{t.style.removeProperty("height"),t.style.removeProperty("overflow")};if(!t.isConnected){l(),r();return}t.style.height="auto";let d=t.getBoundingClientRect().height;if(t.style.height=`${e}px`,!d||Math.abs(d-e)<1){l(),r();return}let p=Math.abs(e-d),u=Math.round(Math.min(AM,Math.max(SM,CM+p*xM))),g=Math.round(u*TM),b=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,m=b?b.animate([{opacity:0},{opacity:1}],{duration:zb,delay:g,easing:"ease-out",fill:"backwards"}):null,y=t.animate([{height:`${e}px`},{height:`${d}px`}],{duration:u,easing:MM});t.style.height=`${d}px`;let w=!1,T=()=>{w||(w=!0,l(),r())};Promise.allSettled([y.finished,m?.finished].filter(Boolean)).then(T),window.setTimeout(T,Math.max(u,g+zb)+120)},$b)}function kM(t){let e=t?.inlineChrome;if(e===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof e=="object"?e:void 0;return{chromeEnabled:!0,showCopy:n?.showCopy!==!1,showExpand:n?.showExpand!==!1,showViewToggle:n?.showViewToggle!==!1}}var Ma="--persona-artifact-inline-body-height";function PM(t){let e=t?.inlineBody,n=e?.streamingView==="status"?"status":"source",o=e?.viewMode==="source"?"source":"rendered",r=320,s=320,a=e?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let l=e?.overflow==="clip"?"clip":"scroll",d=l==="clip"?!1:e?.followOutput!==!1,p,u,g=e?.fadeMask;g===!0?(p=!0,u=!0):g===!1?(p=!1,u=!1):g&&typeof g=="object"?(p=g.top===!0,u=g.bottom===!0):l==="clip"?(p=!1,u=!0):(p=!0,u=!0);let b=e?.transition==="none"?"none":"auto",m=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:d,overflow:l,fadeTop:p,fadeBottom:u,transition:b,completeDisplay:m}}function Vb(t,e){let n=vM(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:l}=kM(o),d=o?.inlineActions??[],p=PM(o),u=p.completeDisplay==="card",g=null,b=n,m=v("div","persona-artifact-inline persona-w-full persona-max-w-full");m.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&m.setAttribute("data-artifact-inline",n.id);let y=M=>Yc(wM(M),e),w=null,T=M=>{w?.destroy(),w=null,m.classList.add("persona-artifact-inline--card"),m.style.removeProperty(Ma),m.replaceChildren(y(M)),wr.set(m,te=>{m.replaceChildren(y(te))})};if(u&&n.status==="complete")return T(n),m;let W=Xc(n,{config:e.config,bodyLayout:p,resolveViewMode:()=>g??p.viewMode});w=W;let E=v("div","persona-artifact-inline-body");E.appendChild(W.el);let k=M=>{let te=M.status!=="complete",pe=te?p.streamingHeight:p.completeHeight,Se=typeof pe=="number";Se?m.style.setProperty(Ma,`${pe}px`):m.style.removeProperty(Ma);let xe=!!W.el.querySelector(".persona-code-pre"),Ce=!!W.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");E.classList.toggle("persona-artifact-content-flush",xe),E.classList.toggle("persona-artifact-inline-body--sized",Se&&Ce),E.classList.toggle("persona-artifact-inline-body--cap",!te&&!Ce&&typeof p.completeHeight=="number")},A=n.status,D=(M,te)=>{A!=="complete"&&M.status==="complete"?(typeof p.completeHeight=="number"?m.style.setProperty(Ma,`${p.completeHeight}px`):m.style.removeProperty(Ma),Ub(E,te?.suppressTransition?"none":p.transition,M.id,()=>{W.update(M),k(M)})):W.update(M),k(M),A=M.status};k(n);let B=p.overflow==="clip"&&a&&!!n.id;if(B&&(E.setAttribute("data-expand-artifact-inline",n.id),E.setAttribute("role","button"),E.setAttribute("tabindex","0"),E.classList.add("persona-cursor-pointer"),E.setAttribute("aria-label",`Open ${Fb(n).title} in panel`)),!r)return m.appendChild(E),wr.set(m,D),m;let I=v("div","persona-artifact-inline-chrome");I.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let N=v("div","persona-artifact-inline-chrome-lead"),_=v("span","persona-flex persona-items-center persona-flex-shrink-0"),F=fe("file-text",16,"currentColor",2);F&&_.appendChild(F);let P=v("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),V=v("span","persona-artifact-inline-type");N.append(_,P,V);let se=v("div","persona-artifact-inline-chrome-actions"),ve=v("span","persona-flex persona-items-center persona-gap-1"),he=()=>g??p.viewMode,ge=l?Kc({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"},{id:"source",icon:"code-xml",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}],selectedId:he(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:M=>{let te=M==="source"?"source":"rendered";te!==he()&&(g=te,W.update(b),k(b))}}):null,re=s?en({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;re&&n.id&&re.setAttribute("data-copy-artifact",n.id);let oe=a?en({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;oe&&n.id&&oe.setAttribute("data-expand-artifact-inline",n.id),se.appendChild(ve),ge&&se.appendChild(ge.element),re&&se.appendChild(re),oe&&se.appendChild(oe),I.append(N,se),m.append(I,E);let ee=M=>{let{title:te,typeLabel:pe}=Fb(M);P.textContent=te,P.title=te,B&&E.setAttribute("aria-label",`Open ${te} in panel`);let Se=M.status!=="complete";if(Se){V.classList.contains("persona-artifact-inline-status")||(V.className="persona-artifact-inline-status",V.removeAttribute("data-preserve-animation"),V.replaceChildren());let xe=Qs(M,o,"inline-chrome");Qr(V,xe,o)}else Xs(M.id),V.className="persona-artifact-inline-type",V.removeAttribute("data-preserve-animation"),V.replaceChildren(),V.textContent=pe;if(re&&re.classList.toggle("persona-hidden",Se),ge){let xe=M.artifactType==="markdown"?M.file:void 0,Ce=!1;if(!Se&&xe&&p.viewMode!=="source"){let Me=Xr(xe);Me==="markdown"?Ce=!0:(Me==="html"||Me==="svg")&&(Ce=o?.filePreview?.enabled!==!1)}ge.element.classList.toggle("persona-hidden",!Ce),ge.setSelected(he())}if(ve.replaceChildren(),!Se&&d.length>0){let xe=Aa(M);if(xe)for(let Ce of d)try{if(Ce.visible===void 0||Ce.visible(xe)){let Me=Js(Ce,{documentChrome:!0});Me.setAttribute("data-artifact-custom-action",Ce.id),Me.classList.add("persona-flex-shrink-0"),ve.appendChild(Me)}}catch{}}};return ee(n),wr.set(m,(M,te)=>{if(u&&A!=="complete"&&M.status==="complete"){let pe=m.isConnected?m.getBoundingClientRect().height:0;A="complete";let Se=M,xe=!1,Ce=Me=>{Se=Me,xe=!0};wr.set(m,Ce),EM(m,pe,{swap:()=>{T(Se),xe=!1,wr.set(m,Ce)},onSettled:()=>{xe?T(Se):wr.set(m,Me=>{m.replaceChildren(y(Me))})}});return}(M.status!=="complete"||M.id!==b.id)&&(g=null),b=M,D(M,te),ee(M)}),m}var qb=(t,e)=>{let n=e?.config?.features?.artifacts?.renderInline;if(n){let o=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",s=t.status==="streaming"?"streaming":"complete",a=typeof t.artifactType=="string"?t.artifactType:"markdown",l=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:e.config,defaultRenderer:()=>Vb(t,e)});if(l)return l}return Vb(t,e)};var Nu=class{constructor(){this.components=new Map;this.options=new Map}register(e,n,o){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n),o?this.options.set(e,o):this.options.delete(e)}unregister(e){this.components.delete(e),this.options.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getOptions(e){return this.options.get(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(e){Object.entries(e).forEach(([n,o])=>{this.register(n,o)})}},Ko=new Nu;Ko.register("PersonaArtifactCard",Yc,{bubbleChrome:!1});Ko.register("PersonaArtifactInline",qb,{bubbleChrome:!1});function Ta(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?zc(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}var Ou=!1;function LM(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Ub(t,e,n,o){let r=typeof document<"u"?document.startViewTransition:void 0,s=!1;try{s=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{s=!1}if(e!=="auto"||!t||typeof r!="function"||Ou||s){o();return}Ou=!0;let a=LM(n);t.style.setProperty("view-transition-name",a);let l=()=>{Ou=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var IM="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",HM="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function RM(t){let e=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=v("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=t.component?`Component: ${t.component}`:"Component";let o=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(t.props??{},null,2),e.appendChild(n),e.appendChild(o),e}function WM(t){if(t===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let e=t&&typeof t=="object"?t:void 0;return{enabled:!0,delayMs:e?.delayMs??200,minVisibleMs:e?.minVisibleMs??300,timeoutMs:e?.timeoutMs??8e3,injectReadySignal:e?.injectReadySignal!==!1,label:e?.label===!1?!1:e?.label??"Starting preview...",labelDelayMs:e?.labelDelayMs??2e3,renderIndicator:e?.renderIndicator}}var BM=220;function DM(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let t=new Uint32Array(2);return crypto.getRandomValues(t),t[0].toString(36)+t[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function NM(t){return`
1100
+ <script>(function(){var d=false;var t=`+JSON.stringify(t)+";function r(){if(d)return;d=true;try{parent.postMessage({persona:'artifact-preview-ready',token:t},'*');}catch(e){}}function s(){if(typeof requestAnimationFrame==='function'){requestAnimationFrame(function(){requestAnimationFrame(r);});}setTimeout(r,150);}if(document.readyState==='complete'){s();}else{window.addEventListener('load',s);}})();</script>"}function OM(t,e,n){let o=v("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:t,config:e});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=v("div","persona-artifact-frame-loading-indicator");r.appendChild(Pb());let s=null;return n.label!==!1&&(s=v("div","persona-artifact-frame-loading-text"),s.textContent=n.label,r.appendChild(s)),o.appendChild(r),{el:o,revealLabel:()=>{s&&s.classList.add("persona-artifact-frame-loading-text--visible")}}}function _M(t,e,n,o,r,s){let a=null,l=0,d=!1,p=new Set,u=()=>{p.forEach(k=>clearTimeout(k)),p.clear()},g=(k,A)=>{let D=setTimeout(()=>{p.delete(D),k()},A);p.add(D)},b=()=>{a&&a.parentElement&&a.remove(),a=null},m=()=>{if(a||d)return;let k=OM(r,s,o);a=k.el,t.appendChild(a),l=Date.now(),o.label!==!1&&g(k.revealLabel,o.labelDelayMs)},y=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),g(b,BM))},w=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",W):e.removeEventListener("load",E)},T=()=>{if(d||(d=!0,w(),u(),!a))return;let k=Math.max(0,o.minVisibleMs-(Date.now()-l));k>0?g(y,k):y()};function W(k){if(n===null)return;let A=k.data;!A||A.persona!=="artifact-preview-ready"||A.token!==n||k.source===e.contentWindow&&T()}function E(){let k=A=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>A()):setTimeout(A,0)};k(()=>k(()=>T()))}return g(m,o.delayMs),g(T,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",W):e.addEventListener("load",E),()=>{d=!0,u(),w(),b()}}function Xc(t,e){let{config:n}=e,o=e.registry??Ko,r=e.bodyLayout,s=n.markdown?Ql(n.markdown):null,a=Jl(n.sanitize),l=t,d=!1,p=re=>{let oe=zo()!==null;s&&!oe&&!d&&(d=!0,Xl(()=>ge(l)));let ee=s?s(re):cr(re);return s&&oe&&a?a(ee):ee},u=v("div","persona-artifact-preview-body"),g=null,b=null,m=null,y=()=>{m&&(m(),m=null),g=null,b=null},w=null,T=null,W=null,E=!1,k=()=>{w=null,T=null,W=null,E=!1},A=null,D=null,B=()=>{A=null,D=null},I=40,N=0,_=re=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>re()):setTimeout(re,0),F=re=>re.scrollHeight-re.clientHeight-re.scrollTop<=I,P=re=>{if(!r)return;let oe=re.scrollHeight-re.clientHeight>1,ee=re.scrollHeight-re.clientHeight-re.scrollTop;re.classList.toggle("persona-artifact-fade-top",r.fadeTop&&oe&&re.scrollTop>1),re.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&oe&&ee>1)},V=re=>{N||(N=_(()=>{N=0,re.scrollTop=re.scrollHeight,P(re)}))},se=(re,oe,ee,M)=>{let te=!!r,pe=ee.id+"|"+(te?"w":"p");if(!w||W!==pe||w.parentElement!==u){y(),B(),u.replaceChildren();let Ce=v("pre",IM+" persona-code-pre"),Me=v("code","persona-code");if(Ce.appendChild(Me),te){let ke=v("div","persona-artifact-source-window");if(ke.appendChild(Ce),u.appendChild(ke),!(r?.overflow==="clip")&&typeof ke.addEventListener=="function"){let ze=()=>ke.scrollHeight-ke.clientHeight>1;ke.addEventListener("scroll",()=>{F(ke)&&(E=!1),P(ke)},{passive:!0}),ke.addEventListener("wheel",qe=>{ze()&&qe.deltaY<0&&(E=!0)},{passive:!0}),ke.addEventListener("touchmove",()=>{ze()&&(E=!0)},{passive:!0})}w=ke}else u.appendChild(Ce),w=Ce;T=Me,W=pe}let Se=te?w:null;Se&&(Se.classList.toggle("persona-artifact-source-window--fixed",M),Se.classList.toggle("persona-artifact-source-window--clip",M&&r?.overflow==="clip"));let xe=Se?F(Se):!0;if(T.replaceChildren(Db(re,oe?.language,oe?.path)),Se){let Ce=ee.status!=="complete";M&&Ce&&r?.followOutput&&!E&&xe?V(Se):Ce||(E=!1),P(Se)}},ve=re=>{y(),k(),B(),u.replaceChildren();let oe=v("div",HM);oe.innerHTML=p(re),u.appendChild(oe)},he=re=>{let oe=re.id,ee=n.features?.artifacts,M=Qs(re,ee,"status-body");if(A&&D===oe&&A.parentElement===u){let Se=A.querySelector(".persona-artifact-status-view-text");Se&&Qr(Se,M,ee);return}y(),k(),u.replaceChildren();let te=v("div","persona-artifact-status-view"),pe=v("div","persona-artifact-status-view-text");Qr(pe,M,ee),te.appendChild(pe),u.appendChild(te),A=te,D=oe},ge=re=>{l=re;let oe=e.resolveViewMode?.(re)??r?.viewMode??"rendered",ee=re.artifactType==="markdown"?re.file:void 0,M=re.status!=="complete";M||Xs(re.id);let te=M?r?.streamingHeight:r?.completeHeight,pe=!!r&&typeof te=="number";if(r?.streamingView==="status"&&M){he(re);return}if(ee){let xe=zc(re.markdown??""),Ce=Xr(ee),Me=n.features?.artifacts?.filePreview?.enabled!==!1;if(!M&&oe==="rendered"&&Me&&(Ce==="html"||Ce==="svg")){let Oe=re.id+"\0"+xe;if(g&&b===Oe&&g.parentElement===u)return;k(),B(),y(),u.replaceChildren();let ze=n.features?.artifacts?.filePreview,qe=ze?.iframeSandbox??"allow-scripts";!ze?.dangerouslyAllowSameOrigin&&qe.includes("allow-same-origin")&&(console.warn("[AgentWidget] Stripped allow-same-origin from filePreview.iframeSandbox: it lets artifact content run with the page origin. Set filePreview.dangerouslyAllowSameOrigin to keep it."),qe=qe.split(/\s+/).filter(Ee=>Ee&&Ee!=="allow-same-origin").join(" "));let nt=WM(ze?.loading),De=v("div","persona-artifact-frame"),Ue=v("iframe","persona-artifact-iframe");Ue.setAttribute("sandbox",qe),Ue.setAttribute("data-artifact-id",re.id);let an=null;nt.enabled&&nt.injectReadySignal?(an=DM(),Ue.srcdoc=xe+NM(an)):Ue.srcdoc=xe,De.appendChild(Ue),u.appendChild(De),nt.enabled&&(m=_M(De,Ue,an,nt,re.id,n)),g=De,b=Oe;return}if(y(),!M&&Ce==="markdown"&&oe==="rendered"){ve(xe);return}se(xe,{language:ee.language,path:ee.path},re,pe);return}if(re.artifactType==="markdown"){if(oe==="source"){y(),se(re.markdown??"",void 0,re,pe);return}ve(re.markdown??"");return}y(),k(),B(),u.replaceChildren();let Se=re.component?o.get(re.component):void 0;if(Se){let Ce={message:{id:re.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Me=Se(re.props??{},Ce);if(Me){u.appendChild(Me);return}}catch{}}u.appendChild(RM(re))};return ge(t),{el:u,update(re){ge(re)},destroy(){y()}}}var Kb=require("idiomorph"),Qc=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;Kb.Idiomorph.morph(t,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",l=s.textContent??"";if(a!==l)return}return!1}}}}})};var Gb=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var _u={index:-1,draft:""};function Yb(t){let{direction:e,history:n,currentValue:o,atStart:r,state:s}=t,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let l=n.length-1;return{handled:!0,value:n[l],state:{index:l,draft:o}}}if(s.index>0){let l=s.index-1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let l=s.index+1;return{handled:!0,value:n[l],state:{index:l,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function Xb(t,e){return[t.id,t.role,t.content?.length??0,t.content?.slice(-32)??"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",t.variant??"",t.rawContent?.length??0,t.llmContent?.length??0,t.approval?.status??"",t.toolCall?.status??"",t.toolCall?.name??"",t.toolCall?.chunks?.length??0,t.toolCall?.chunks?.[t.toolCall.chunks.length-1]?.slice(-32)??"",typeof t.toolCall?.args=="string"?t.toolCall.args.length:t.toolCall?.args?JSON.stringify(t.toolCall.args).length:0,t.reasoning?.chunks?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.length??0,t.reasoning?.chunks?.[t.reasoning.chunks.length-1]?.slice(-32)??"",t.contentParts?.length??0,t.stopReason??"",e].join("\0")}function Qb(){return new Map}function Jb(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function Zb(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function ev(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}$u();var Ea={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},FM=["pre","code","a","script","style"],td=t=>({type:t?.type??Ea.type,placeholder:t?.placeholder??Ea.placeholder,speed:t?.speed??Ea.speed,duration:t?.duration??Ea.duration,buffer:t?.buffer??Ea.buffer}),$M=[{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"}],sv=new Map;for(let t of $M)sv.set(t.name,t);var Zs=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:sv.get(t)??null,nd=(t,e,n,o,r)=>{if(!r)return t;if(n?.bufferContent)return n.bufferContent(t,o);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
1101
+ `);return s<0?"":t.slice(0,s)}return t},zM=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=e,r},VM=(t,e,n,o)=>{let r=t.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=e,r},zu=/\s/,jM=(t,e)=>{let n=t.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(e.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},qM=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=0;for(;l<s.length;)if(zu.test(s[l])){let d=l;for(;d<s.length&&zu.test(s[d]);)d+=1;a.appendChild(o.createTextNode(s.slice(l,d))),l=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let p=l;for(;p<s.length&&!zu.test(s[p]);)d.appendChild(zM(o,s[p],e,n.value)),n.value+=1,p+=1;a.appendChild(d),l=p}r.replaceChild(a,t)},UM=(t,e,n)=>{let o=t.ownerDocument,r=t.parentNode;if(!o||!r)return;let s=t.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),l=s.split(/(\s+)/);for(let d of l)d&&(/^\s+$/.test(d)?a.appendChild(o.createTextNode(d)):(a.appendChild(VM(o,d,e,n.value)),n.value+=1));r.replaceChild(a,t)},ka=(t,e,n,o)=>{if(!t||typeof document>"u")return t;let r=document.createElement("div");r.innerHTML=t;let s=new Set((o?.skipTags??FM).map(g=>g.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],d=a.nextNode();for(;d;)jM(d,s)||l.push(d),d=a.nextNode();let p={value:o?.startIndex??0},u=e==="char"?qM:UM;for(let g of l)u(g,n,p);return r.innerHTML},od=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},Pa=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let n=t.createElement("div");return n.className="persona-stream-skeleton-line",e.appendChild(n),e},rv=new WeakMap,KM=(t,e)=>{if(!t.styles)return;let n=rv.get(e);if(n||(n=new Set,rv.set(e,n)),n.has(t.name)){let s=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(t.name)}n.add(t.name);let r=(e instanceof ShadowRoot?e.ownerDocument:e.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",t.name),r.textContent=t.styles,e.appendChild(r)},Vu=new WeakMap,GM=(t,e)=>{if(!t.onAttach)return;let n=Vu.get(e);if(n||(n=new Map,Vu.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},iv=t=>{let e=Vu.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},rd=(t,e)=>{KM(t,e),GM(t,e)};function ju(t,e=mn){let n=t.style.position,o=t.style.zIndex,r=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=n),t.style.zIndex=o,t.style.isolation=r}}var La=0,Cr=null;function qu(t=document){if(La++,La===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;Cr={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:r},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${r}px`,n.style.width="100%"}let e=!1;return()=>{if(!e&&(e=!0,La=Math.max(0,La-1),La===0&&Cr)){let n=t.body,o=t.defaultView??window;n.style.overflow=Cr.originalOverflow,n.style.position=Cr.originalPosition,n.style.top=Cr.originalTop,n.style.width=Cr.originalWidth,o.scrollTo(0,Cr.scrollY),Cr=null}}}var Ia={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Kt=t=>(t?.launcher?.mountMode??"floating")==="docked",Ha=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",ro=t=>{let e=t?.launcher?.dock;return{side:e?.side??Ia.side,width:e?.width??Ia.width,animate:e?.animate??Ia.animate,reveal:e?.reveal??Ia.reveal,maxHeight:e?.maxHeight??Ia.maxHeight}};Qe();Qe();Rt();var Uu=t=>t==="followUp"?"follow-up":t,Ku=(t,e=0)=>{if(typeof t=="string"){let r=t.trim();return r?{id:r,label:r,prompt:r,emphasis:"default"}:null}let n=t.label.trim();if(!n)return null;let o=t.prompt?.trim()||n;return{id:t.id?.trim()||o||`suggestion-${e}`,label:n,prompt:o,description:t.description?.trim()||void 0,icon:t.icon,iconColor:t.iconColor?.trim()||void 0,behavior:t.behavior,emphasis:t.emphasis??"default"}},YM=t=>{switch(t){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'}},av=new WeakSet,XM=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,QM=t=>{XM()||t.forEach((e,n)=>{typeof e.animate=="function"&&e.animate([{opacity:"0",transform:"translateY(4px)"},{opacity:"1",transform:"none"}],{duration:250,delay:n*60,easing:"ease-out",fill:"backwards"})})},Gu=t=>{var E,k,A;let{item:e,index:n,surface:o,source:r,variant:s,streaming:a,config:l,plugins:d,chipsConfig:p,session:u,getTextarea:g,eventTarget:b}=t,m=o==="followUp",y=e.behavior,w=()=>{if(u.isStreaming())return;let D={suggestion:{...e},surface:o,source:r,behavior:y},B=b.dispatchEvent(new CustomEvent("persona:suggestion:selected",{detail:D,bubbles:!0,composed:!0,cancelable:!0}));if(m&&b.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:e.prompt},bubbles:!0,composed:!0})),!B)return;for(let N of d)if(N.onSuggestionSelect?.({suggestion:{...e},surface:o,source:r,variant:s,config:l})===!1)return;let I=g();if(y==="fill"){I.value=e.prompt,I.dispatchEvent(new Event("input",{bubbles:!0,composed:!0})),I.focus();return}I.value="",u.sendMessage(e.prompt)},T=()=>{let D=v("button",`persona-suggestion persona-suggestion--${s}`);if(D.type="button",D.disabled=a,D.dataset.suggestionId=e.id,D.dataset.emphasis=e.emphasis,D.dataset.behavior=y,s==="chip"&&(p?.fontFamily&&(D.style.fontFamily=YM(p.fontFamily)),p?.fontWeight&&(D.style.fontWeight=p.fontWeight),p?.paddingX&&(D.style.paddingLeft=p.paddingX,D.style.paddingRight=p.paddingX),p?.paddingY&&(D.style.paddingTop=p.paddingY,D.style.paddingBottom=p.paddingY)),e.icon){let I=fe(e.icon,"var(--persona-suggestion-icon-size)","currentColor",1.8);I&&(I.classList.add("persona-suggestion__icon"),e.iconColor&&(I.style.color=e.iconColor),D.appendChild(I))}let B=v("span","persona-suggestion__copy");if(B.appendChild(J("span",{className:"persona-suggestion__label",text:e.label})),e.description&&s!=="chip"&&B.appendChild(J("span",{className:"persona-suggestion__description",text:e.description})),D.appendChild(B),s!=="chip"){let I=fe("arrow-right",16,"currentColor",1.8);I&&(I.classList.add("persona-suggestion__arrow"),D.appendChild(I))}return D.addEventListener("click",w),D},W=null;for(let D of d)if(D.renderSuggestion&&(W=D.renderSuggestion({suggestion:{...e},index:n,surface:o,source:r,variant:s,streaming:a,config:l,defaultRenderer:T,select:w}),W))break;return W??(W=T()),(E=W.dataset).suggestionId||(E.suggestionId=e.id),(k=W.dataset).behavior||(k.behavior=y),(A=W.dataset).emphasis||(A.emphasis=e.emphasis),W instanceof HTMLButtonElement||W.setAttribute("aria-disabled",a?"true":"false"),W},Ra=t=>{let e=[],n=[],o=null,r=null,s=()=>{t.removeAttribute("data-scroll-left"),t.removeAttribute("data-scroll-right")},a=()=>{if(r=null,t.hidden||t.dataset.variant!=="chip"||t.dataset.overflow!=="scroll"){s();return}let u=Math.max(0,t.scrollWidth-t.clientWidth);if(u<=1){s();return}let g=getComputedStyle(t).direction==="rtl",b=Math.min(u,Math.max(0,Math.abs(t.scrollLeft))),m=4,y=b<=m,w=b>=u-m,T=g?!w:!y,W=g?!y:!w;t.toggleAttribute("data-scroll-left",T),t.toggleAttribute("data-scroll-right",W)},l=()=>{if(r!==null||typeof requestAnimationFrame!="function"){typeof requestAnimationFrame!="function"&&a();return}r=requestAnimationFrame(a)};t.addEventListener("scroll",l,{passive:!0});let d=typeof ResizeObserver=="function"?new ResizeObserver(l):null;return d?.observe(t),{buttons:e,elements:n,destroy:()=>{t.removeEventListener("scroll",l),d?.disconnect(),r!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(r),r=null},render:(u,g,b,m,y,w)=>{t.replaceChildren(),e.length=0,n.length=0;let T=w?.source??"config",W=w?.surface??(T==="config"?"starter":"followUp"),E=W==="followUp",k=w?.variant??"chip",A=w?.behavior??"send",D=w?.overflow??"wrap",B=w?.config??{},I=w?.plugins??[],N=typeof w?.maxItems=="number"?Math.max(0,Math.floor(w.maxItems)):void 0,_=E?"followUps":"starters";!av.has(B)&&B.debug===!0&&k!=="chip"&&B.suggestions?.[_]?.overflow!==void 0&&(av.add(B),console.info(`[persona] suggestions.${_}.overflow applies to the "chip" variant only; the "${k}" variant manages its own stacking.`));let F=ge=>ge.map(Ku).filter(re=>re!==null).map(re=>({...re,behavior:re.behavior??A})),P=F(u??[]);I.forEach(ge=>{ge.transformSuggestions&&(P=F(ge.transformSuggestions({suggestions:P.map(re=>({...re})),surface:W,source:T,config:B})))});let V=N===void 0?P:P.slice(0,N);if(!V.length){t.hidden=!0,o=null,s();return}if(!E&&(m??g.getMessages()).some(re=>re.role==="user")){t.hidden=!0,o=null;return}t.hidden=!1,t.classList.add("persona-suggestions"),t.dataset.personaSuggestionSurface=Uu(W),t.dataset.variant=k,t.dataset.overflow=D;let se=document.createDocumentFragment(),ve=g.isStreaming();V.forEach((ge,re)=>{let oe=Gu({item:ge,index:re,surface:W,source:T,variant:k,streaming:ve,config:B,plugins:I,chipsConfig:y,session:g,getTextarea:()=>b,eventTarget:t});se.appendChild(oe),n.push(oe),[...oe instanceof HTMLButtonElement?[oe]:[],...Array.from(oe.querySelectorAll("button"))].forEach(M=>{e.includes(M)||(M.disabled=ve,e.push(M))})}),t.appendChild(se),a(),l();let he=JSON.stringify({normalized:V,surface:W,variant:k,source:T});he!==o&&(o=he,QM(n),t.dispatchEvent(new CustomEvent("persona:suggestion:shown",{detail:{suggestions:V.map(ge=>({...ge})),surface:W,source:T,variant:k},bubbles:!0,composed:!0})),E&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:V.map(ge=>ge.prompt)},bubbles:!0,composed:!0})))}}};var Un={"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"};Qe();Rt();Qe();Rt();var JM="persona-header-control",ZM="persona-header-control--glyph",eT="persona-header-control--sparse",tT=20,nT={x:[1.4,1.05]},lv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",oT="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",sd=(t,e,n={})=>{let{iconSize:o,iconText:r}=n,[s,a]=nT[e]??[1,1.5],l=!o;t.classList.toggle(ZM,l),t.classList.toggle(eT,l&&s!==1);let d=parseFloat(o??"")||tT,p=fe(e,`${Math.round(d*s)}px`,"currentColor",a);p?(p.style.display="block",l||(p.style.strokeWidth=`calc(var(--persona-components-header-controlStrokeWidth, 1.5) * ${Number((a/1.5).toFixed(4))})`),t.replaceChildren(p)):r&&(t.textContent=r)},Zr=t=>{let{ariaLabel:e,tooltip:n=!0,tooltipHint:o,iconName:r,iconText:s,wrapperClassName:a=lv,size:l,iconSize:d,color:p,backgroundColor:u,borderWidth:g,borderColor:b,borderRadius:m,paddingX:y,paddingY:w,hidden:T,extraClassName:W,attrs:E}=t,k=v("div",a),A=!!(g||b),D=J("button",{className:zt(JM,"persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"persona-bg-transparent hover:persona-bg-gray-100",!A&&"persona-border-none",!m&&"persona-rounded-full",W),attrs:{type:"button","aria-label":e,...E},style:{width:l,height:l,minWidth:l,minHeight:l,display:T?"none":void 0,color:p||kn.actionIconColor,backgroundColor:u,border:A?`${g||"0px"} solid ${b||"transparent"}`:void 0,borderRadius:m,paddingLeft:y,paddingRight:y,paddingTop:w,paddingBottom:w}});return r?sd(D,r,{iconSize:d,iconText:s}):s&&(D.textContent=s),k.appendChild(D),hn({anchor:D,trigger:k,text:()=>D.getAttribute("aria-label")??e,hint:o,enabled:n}),{button:D,wrapper:k}},ei=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=lv,buttonSize:r,iconSize:s}=e,a=t?.launcher??{},l=a.closeButtonTooltipText??"Close chat",d=a.closeButtonShowTooltip??!0,{button:p,wrapper:u}=Zr({ariaLabel:l,tooltip:d,iconName:a.closeButtonIconName??"x",iconText:a.closeButtonIconText??"\xD7",wrapperClassName:o,size:r??a.closeButtonSize,iconSize:s,color:a.closeButtonColor,backgroundColor:a.closeButtonBackgroundColor,borderWidth:a.closeButtonBorderWidth,borderColor:a.closeButtonBorderColor,borderRadius:a.closeButtonBorderRadius,paddingX:a.closeButtonPaddingX,paddingY:a.closeButtonPaddingY,hidden:!n});return{button:p,wrapper:u}},ti=(t,e={})=>{let{wrapperClassName:n=oT,buttonSize:o,iconSize:r}=e,a=(t?.launcher??{}).clearChat??{},l=a.tooltipText??"Clear chat",d=a.showTooltip??!0,{button:p,wrapper:u}=Zr({ariaLabel:l,tooltip:d,iconName:a.iconName??"refresh-cw",wrapperClassName:n,size:o??a.size,iconSize:r,color:a.iconColor,backgroundColor:a.backgroundColor,borderWidth:a.borderWidth,borderColor:a.borderColor,borderRadius:a.borderRadius,paddingX:a.paddingX,paddingY:a.paddingY});return{button:p,wrapper:u}};var kn={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))",minHeight:"var(--persona-header-min-height, auto)"},Yu={fontFamily:"var(--persona-components-header-title-fontFamily, inherit)",fontSize:"var(--persona-components-header-title-fontSize, 1rem)",fontWeight:"var(--persona-components-header-title-fontWeight, 600)",lineHeight:"var(--persona-components-header-title-lineHeight, 1.5rem)",letterSpacing:"var(--persona-components-header-title-letterSpacing, normal)"},rT={fontFamily:"var(--persona-components-header-subtitle-fontFamily, inherit)",fontSize:"var(--persona-components-header-subtitle-fontSize, 0.75rem)",fontWeight:"var(--persona-components-header-subtitle-fontWeight, inherit)",lineHeight:"var(--persona-components-header-subtitle-lineHeight, 1rem)",letterSpacing:"var(--persona-components-header-subtitle-letterSpacing, normal)"},es=t=>{let{config:e,showClose:n=!0}=t,o=J("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:{minHeight:kn.minHeight,backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),r=e?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",l=r.headerIconHidden??!1,d=r.headerIconName,p=J("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(!l)if(d){let D=parseFloat(s)||24,B=fe(d,D*.6,"currentColor",1);B?p.replaceChildren(B):p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let D=v("img");D.src=e.launcher.iconUrl,D.alt="",D.className="persona-rounded-xl persona-object-cover",D.style.height=s,D.style.width=s,p.replaceChildren(D)}else p.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let u=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=J("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:kn.titleColor,...Yu}}),b=J("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:kn.subtitleColor,...rT}});u.append(g,b),l?o.append(u):o.append(p,u);let m=r.clearChat??{},y=m.enabled??!0,w=m.placement??"inline",T=null,W=null;if(y){let B=ti(e,{wrapperClassName:w==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=B.button,W=B.wrapper,w==="top-right"&&(W.style.right="48px"),w==="inline"&&o.appendChild(W)}let E=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&w==="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:k,wrapper:A}=ei(e,{showClose:n,wrapperClassName:E});return a!=="top-right"&&o.appendChild(A),{header:o,iconHolder:p,headerTitle:g,headerSubtitle:b,closeButton:k,closeButtonWrapper:A,clearChatButton:T,clearChatButtonWrapper:W}},Wa=(t,e,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";t.appendChild(e.header),r==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};Qe();var sT=t=>{let e=es({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=t.layoutHeaderConfig?.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),n())}))}return e};function iT(t,e,n){if(e?.length)for(let o of e){let{button:r,wrapper:s}=Zr({ariaLabel:o.ariaLabel??o.label??o.id,iconName:o.icon,iconText:o.icon?void 0:o.label,tooltipHint:o.shortcut?$c(o.shortcut):void 0,wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center"});if(r.setAttribute("data-persona-header-action",o.id),o.shortcut){let a=xa(o.shortcut);a&&r.setAttribute("aria-keyshortcuts",a)}if(o.menuItems?.length){let a=Sa({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-right"});s.appendChild(a.element),r.addEventListener("click",l=>{l.stopPropagation(),a.toggle()})}else r.addEventListener("click",()=>n?.(o.id));t.appendChild(s)}}var aT=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=t,a=e?.launcher??{},l=v("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");l.setAttribute("data-persona-theme-zone","header"),l.style.minHeight=kn.minHeight,l.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",l.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",l.style.boxShadow="var(--persona-header-shadow, none)",l.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=r?.titleMenu,p,u;if(d){let A=Ob({label:a.title??"Chat Assistant",menuItems:d.menuItems,onSelect:D=>{let B=N=>{N===!1&&A.element.dispatchEvent(new CustomEvent("persona:title-menu-builtin",{bubbles:!0,composed:!0,detail:{actionId:D}}))},I=d.onSelect(D);I instanceof Promise?I.then(B,()=>{}):B(I)},hover:d.hover,className:""});p=A.element,p.style.color=kn.titleColor,u=p.querySelector(".persona-combo-btn-label")??p}else{if(p=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=v("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=kn.titleColor,Object.assign(u.style,Yu),u.textContent=a.title??"Chat Assistant",p.appendChild(u),r?.onTitleClick){p.style.cursor="pointer",p.setAttribute("role","button"),p.setAttribute("tabindex","0");let D=r.onTitleClick;p.addEventListener("click",B=>{B.target.closest("button")||D()}),p.addEventListener("keydown",B=>{(B.key==="Enter"||B.key===" ")&&(B.preventDefault(),D())})}let A=r?.titleRowHover;A&&(p.style.borderRadius=A.borderRadius??"10px",p.style.padding=A.padding??"6px 4px 6px 12px",p.style.margin="-6px 0 -6px -12px",p.style.border="1px solid transparent",p.style.transition="background-color 0.15s ease, border-color 0.15s ease",p.style.width="fit-content",p.style.flex="none",p.addEventListener("mouseenter",()=>{p.style.backgroundColor=A.background??"",p.style.borderColor=A.border??""}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="",p.style.borderColor="transparent"}))}l.appendChild(p);let g="persona-relative persona-inline-flex persona-items-center persona-justify-center",{button:b,wrapper:m}=ei(e,{showClose:n,wrapperClassName:g});o&&b.addEventListener("click",o);let y=v("div","persona-flex persona-items-center persona-gap-1");d||iT(y,r?.trailingActions,r?.onAction??s);let w=a.clearChat??{},T=null,W=null;if(w.enabled??!0){let A=w.placement??"inline",D=ti(e,{wrapperClassName:A==="top-right"?"persona-absolute persona-top-4 persona-z-50":g});T=D.button,W=D.wrapper,A==="top-right"?W.style.right="48px":y.appendChild(W)}y.appendChild(m),l.appendChild(y);let E=v("div");E.style.display="none";let k=v("span");return k.style.display="none",{header:l,iconHolder:E,headerTitle:u,headerSubtitle:k,closeButton:b,closeButtonWrapper:m,clearChatButton:T,clearChatButtonWrapper:W}},cv={default:sT,minimal:aT},lT=t=>cv[t]??cv.default,id=(t,e,n)=>{if(e?.render){let a=e.render({config:t,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),l=v("div");l.style.display="none";let d=v("span"),p=v("span"),u=v("button");u.style.display="none";let g=v("div");return g.style.display="none",{header:a,iconHolder:l,headerTitle:d,headerSubtitle:p,closeButton:u,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",s=lT(o)({config:t,showClose:e?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:e,onHeaderAction:e?.onAction});return e&&(e.showIcon===!1&&(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};Qe();Qe();Rt();var ad=t=>{let e=v("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=t?.copy?.inputPlaceholder??"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-text 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 n=3,o=20,r=()=>{let d=e.ownerDocument?.defaultView;if(!d?.getComputedStyle)return o;let p=d.getComputedStyle(e).lineHeight;if(!p||!p.trim().endsWith("px"))return o;let u=parseFloat(p);return Number.isFinite(u)&&u>0?u:o},s=`${n*o}px`;e.style.maxHeight=s,e.style.overflowY="auto";let a=()=>{let d=e.style.maxHeight;if(d!==s){let u=parseFloat(d);if(Number.isFinite(u)&&u>0)return u}let p=n*r();return s=`${p}px`,e.style.maxHeight=s,p},l=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,a());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:l}},ld=t=>{let e=t?.sendButton??{},n=e.useIcon??!1,o=e.iconText??"\u2191",r=e.iconName,s=e.stopIconName??"square",a=e.tooltipText??"Send message",l=e.stopTooltipText??"Stop generating",d=t?.copy?.sendButtonLabel??"Send",p=t?.copy?.stopButtonLabel??"Stop",u=e.showTooltip??!1,g=e.size??"40px",b=e.backgroundColor,m=e.textColor,y=v("div","persona-send-button-wrapper"),w=J("button",{className:zt("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!b&&"persona-bg-persona-primary",!n&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?g:void 0,height:n?g:void 0,minWidth:n?g:void 0,minHeight:n?g:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:n&&b||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:n?"0":e.paddingX||void 0,paddingRight:n?"0":e.paddingX||void 0,paddingTop:n?"0":e.paddingY||void 0,paddingBottom:n?"0":e.paddingY||void 0}}),T=null,W=null;if(n){let A=parseFloat(e.iconSize??"")||Math.round((parseFloat(g)||24)*.5),D=e.iconStrokeWidth??2,B=m?.trim()||"currentColor";r?(T=fe(r,A,B,D),T?w.appendChild(T):w.textContent=o):w.textContent=o,W=fe(s,A,B,D)}else w.textContent=d;w.setAttribute("aria-label",a),y.appendChild(w),hn({anchor:w,trigger:y,text:()=>w.getAttribute("aria-label")??"",enabled:u});let E="send";return{button:w,wrapper:y,setMode:A=>{if(A===E)return;E=A;let D=A==="stop"?l:a;if(w.setAttribute("aria-label",D),n){if(T&&W){let B=A==="stop"?W:T;w.replaceChildren(B)}}else w.textContent=A==="stop"?p:d}}},cd=t=>{let e=t?.voiceRecognition??{};if(!(e.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=e.provider?.type==="runtype";if(!(o||r))return null;let a=t?.sendButton?.size??"40px",l=e.iconName??"mic",d=e.iconSize??a,p=parseFloat(d)||24,u=e.backgroundColor??t?.sendButton?.backgroundColor,g=e.iconColor??t?.sendButton?.textColor,b=v("div","persona-send-button-wrapper"),m=J("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":e.tooltipText??"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:g||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),w=fe(l,p,g||"currentColor",1.5);w?m.appendChild(w):m.textContent="\u{1F3A4}",b.appendChild(m);let T=e.tooltipText??"Start voice recognition",W=e.showTooltip??!1;return hn({anchor:m,trigger:b,text:()=>m.getAttribute("aria-label")??T,enabled:W}),{button:m,wrapper:b}},dd=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=t?.sendButton?.size??"40px",o=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let r=v("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(e.allowedTypes??qo).join(","),r.multiple=(e.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=e.buttonIconName??"paperclip",a=n,l=parseFloat(a)||40,d=Math.round(l*.6),p=v("div","persona-send-button-wrapper"),u=J("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":e.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),g=fe(s,d,"currentColor",1.5);g?u.appendChild(g):u.textContent="\u{1F4CE}",u.addEventListener("click",m=>{m.preventDefault(),r.click()}),p.appendChild(u);let b=e.buttonTooltipText??"Attach file";return hn({anchor:u,trigger:p,text:()=>u.getAttribute("aria-label")??b}),{button:u,wrapper:p,input:r,previewsContainer:o}},pd=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=v("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=e.visible??!0;o.style.display=r?"":"none";let s=e.idleText??"Online";if(e.idleLink){let a=v("a");a.href=e.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},ud=()=>J("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ba=t=>{let{config:e}=t,n=J("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=ud(),r=J("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-persona-border persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=ad(e);a();let l=ld(e),d=cd(e),p=dd(e),u=pd(e);p&&(p.previewsContainer.style.gap="8px",r.append(p.previewsContainer,p.input)),r.append(s);let g=J("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),b=v("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=v("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return p&&b.append(p.wrapper),d&&m.append(d.wrapper),m.append(l.wrapper),g.append(b,m),r.append(g),r.addEventListener("click",y=>{y.target!==l.button&&y.target!==l.wrapper&&y.target!==d?.button&&y.target!==d?.wrapper&&y.target!==p?.button&&y.target!==p?.wrapper&&s.focus()}),n.append(o,r,u),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:u,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:g,leftActions:b,rightActions:m,setSendButtonMode:l.setMode}};Qe();Rt();var dv=()=>{let t=J("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=v("span","persona-pill-peek__icon"),n=fe("message-square",16,"currentColor",1.5);n&&e.appendChild(n);let o=v("span","persona-pill-peek__text"),r=v("span","persona-pill-peek__caret"),s=fe("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},gd=t=>{let{config:e}=t,n=J("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ud(),r=pd(e);r.style.display="none";let{textarea:s,attachAutoResize:a}=ad(e);s.style.maxHeight="100px",a();let l=ld(e),d=cd(e),p=dd(e);p&&p.previewsContainer.classList.add("persona-pill-composer__previews");let u=J("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=v("div","persona-widget-composer__left-actions persona-pill-composer__left");p&&g.append(p.wrapper);let b=v("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&b.append(d.wrapper),b.append(l.wrapper),u.addEventListener("click",y=>{y.target!==l.button&&y.target!==l.wrapper&&y.target!==d?.button&&y.target!==d?.wrapper&&y.target!==p?.button&&y.target!==p?.wrapper&&s.focus()}),p&&u.append(p.input),u.append(g,s,b),p&&n.append(p.previewsContainer),n.append(o,u,r);let m=u;return{footer:n,suggestions:o,composerForm:u,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:d?.button??null,micButtonWrapper:d?.wrapper??null,statusText:r,attachmentButton:p?.button??null,attachmentButtonWrapper:p?.wrapper??null,attachmentInput:p?.input??null,attachmentPreviewsContainer:p?.previewsContainer??null,actionsRow:m,leftActions:g,rightActions:b,setSendButtonMode:l.setMode}};Qe();Rt();Qe();Rt();var cT=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},dT=(t,e)=>{if(!t)return null;let n=cT(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},pT=(t,e)=>{let n=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},uT=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Xu=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},Qu=320,fv=320,gT=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),fT=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),mT=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),hT=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),yT=t=>{if(!t||t.length===0)return null;let e=J("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=J("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=v("span","persona-mention-chip-icon"),s=fe(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(J("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},bT=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(wa(o.ref,{readonly:!0,render:e}))}return n},pv="\uE000",uv="\uE001",vT=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=b=>`${pv}${r}:${b}${uv}`,a=e.map((b,m)=>b.kind==="text"?b.text:s(m)).join(""),l=n(a);if(!e.every((b,m)=>b.kind==="text"||l.includes(s(m)))){t.replaceChildren(bT(e,o));return}t.innerHTML=l;let p=new RegExp(`${pv}${r}:(\\d+)${uv}`),u=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),g=[];for(let b=u.nextNode();b;b=u.nextNode())g.push(b);for(let b of g){let m=b;for(let y=p.exec(m.data);y;y=p.exec(m.data)){let w=e[Number(y[1])],T=m.splitText(y.index);T.data=T.data.slice(y[0].length),w?.kind==="mention"&&T.parentNode?.insertBefore(wa(w.ref,{readonly:!0,render:o}),T),m=T}}},wT=(t,e,n)=>{if(t.length===0)return null;try{let o=v("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),e&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return t.forEach((l,d)=>{let p=v("img");p.alt=l.alt?.trim()||`Attached image ${d+1}`,p.loading="lazy",p.decoding="async",p.referrerPolicy="no-referrer",p.style.display="block",p.style.width="100%",p.style.maxWidth=`${Qu}px`,p.style.maxHeight=`${fv}px`,p.style.height="auto",p.style.objectFit="contain",p.style.borderRadius="10px",p.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",p.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;r+=1,p.addEventListener("error",()=>{u||(u=!0,r=Math.max(0,r-1),p.remove(),r===0&&a())}),p.addEventListener("load",()=>{u=!0}),uT(l.image)?(p.src=l.image,o.appendChild(p)):(u=!0,r=Math.max(0,r-1),p.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},CT=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!Xu(o.audio))return;let r=v("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Qu}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},xT=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!Xu(o.video))return;let r=v("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Qu}px`,r.style.maxHeight=`${fv}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},ST=t=>{if(t.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!Xu(o.data))return;let r=v("a");r.href=o.data,r.download=o.filename,r.target="_blank",r.rel="noopener noreferrer",r.textContent=o.filename,r.className="persona-message-file-attachment",r.style.display="inline-flex",r.style.alignItems="center",r.style.gap="6px",r.style.padding="6px 10px",r.style.borderRadius="8px",r.style.fontSize="0.875rem",r.style.textDecoration="underline",r.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",r.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",r.style.color="inherit",e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Da=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let r=document.createElement("span");return r.className="persona-sr-only",r.textContent="Loading",t.appendChild(e),t.appendChild(n),t.appendChild(o),t.appendChild(r),t},AT=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:Da};if(e){let r=e(o);if(r!==null)return r}return Da()},MT=(t,e)=>{let n=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=e==="user"?t.userAvatar:t.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=v("img");r.src=o,r.alt=e==="user"?"User":"Assistant",r.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(r)}else n.textContent=o,n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},gv=(t,e,n="div")=>{let o=v(n,"persona-text-xs persona-text-persona-muted"),r=new Date(t.createdAt);return e.format?o.textContent=e.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Na=(t,e="bubble")=>{let n=["persona-message-bubble"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-text","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-text-persona-text","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-container","persona-border","persona-border-persona-message-border","persona-text-persona-text","persona-px-5","persona-py-3");break}return n},TT=(t,e,n)=>{let o=e.showCopy??!0,r=e.showUpvote??!0,s=e.showDownvote??!0,a=e.showReadAloud??!1;if(!o&&!r&&!s&&!a){let y=v("div");return y.style.display="none",y.id=`actions-${t.id}`,y.setAttribute("data-actions-for",t.id),y}let l=e.visibility??"hover",d=e.align??"right",p=e.layout??"pill-inside",u={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[p],b=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${u} ${g} ${l==="hover"?"persona-message-actions-hover":""}`);b.id=`actions-${t.id}`,b.setAttribute("data-actions-for",t.id);let m=(y,w,T)=>{let W=en({icon:y,label:w,size:14,className:"persona-message-action-btn"});return W.setAttribute("data-action",T),W};return o&&b.appendChild(m("copy","Copy message","copy")),a&&b.appendChild(m("volume-2","Read aloud","read-aloud")),r&&b.appendChild(m("thumbs-up","Upvote","upvote")),s&&b.appendChild(m("thumbs-down","Downvote","downvote")),b},Ju=(t,e,n,o,r,s)=>{let a=n??{},l=a.layout??"bubble",d=a.avatar,p=a.timestamp,u=d?.show??!1,g=p?.show??!1,b=d?.position??"left",m=p?.position??"below",y=Na(t.role,l),w=v("div",y.join(" "));w.id=`bubble-${t.id}`,w.setAttribute("data-message-id",t.id),w.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),l==="flat"?(w.style.backgroundColor="transparent",w.style.color=t.role==="user"?"var(--persona-primary, var(--persona-text))":"var(--persona-message-assistant-text, var(--persona-text))"):t.role==="user"?(w.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",w.style.color="var(--persona-message-user-text, white)"):t.role==="assistant"&&(w.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",w.style.color="var(--persona-message-assistant-text, var(--persona-text))");let T=gT(t),W=t.content?.trim()??"",k=T.length>0&&W===$s,A=td(s?.widgetConfig?.features?.streamAnimation),D=s?.widgetConfig?.features?.streamAnimation?.plugins,B=t.role==="assistant"&&A.type!=="none"?Zs(A.type,D):null,I=t.role==="assistant"&&B?.isAnimating?.(t)===!0,N=t.role==="assistant"&&B!==null&&(!!t.streaming||I);N&&B?.bubbleClass&&w.classList.add(B.bubbleClass);let _=document.createElement("div");_.classList.add("persona-message-content"),t.streaming&&_.classList.add("persona-content-streaming"),N&&B&&(B.containerClass&&_.classList.add(B.containerClass),_.style.setProperty("--persona-stream-step",`${A.speed}ms`),_.style.setProperty("--persona-stream-duration",`${A.duration}ms`));let F=N?nd(t.content??"",A.buffer,B,t,!!t.streaming):t.content??"",P=()=>{let te=e({text:F,message:t,streaming:!!t.streaming,raw:t.rawContent});return N&&B?.wrap==="char"?ka(te,"char",t.id,{skipTags:B.skipTags}):N&&B?.wrap==="word"?ka(te,"word",t.id,{skipTags:B.skipTags}):te},V=null;if(k?(V=document.createElement("div"),V.innerHTML=P(),V.style.display="none",_.appendChild(V)):t.contentSegments?.length?vT(_,t.contentSegments,te=>e({text:te,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):_.innerHTML=P(),N&&B?.useCaret&&!k&&W){let te=od(),pe=_.querySelectorAll(".persona-stream-char, .persona-stream-word"),Se=pe[pe.length-1];if(Se?.parentNode)Se.parentNode.insertBefore(te,Se.nextSibling);else{let xe=_.lastElementChild;xe?xe.appendChild(te):_.appendChild(te)}}if(g&&m==="inline"&&t.createdAt){let te=gv(t,p,"span");te.classList.add("persona-timestamp-inline");let pe=_.lastElementChild;pe?pe.appendChild(te):_.appendChild(te)}if(T.length>0){let te=wT(T,!k&&!!W,()=>{k&&V&&(V.style.display="")});te?w.appendChild(te):k&&V&&(V.style.display="")}let se=fT(t);if(se.length>0){let te=CT(se);te&&w.appendChild(te)}let ve=mT(t);if(ve.length>0){let te=xT(ve);te&&w.appendChild(te)}let he=hT(t);if(he.length>0){let te=ST(he);te&&w.appendChild(te)}let ge=t.contentSegments?.length?null:yT(t.contextMentions);if(ge&&w.appendChild(ge),w.appendChild(_),g&&m==="below"&&t.createdAt){let te=gv(t,p);te.classList.add("persona-mt-1"),w.appendChild(te)}let re=t.role==="assistant"?dT(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let te=!!(F&&F.trim()),pe=A.placeholder==="skeleton",Se=pe&&A.buffer==="line"&&te;if(te)Se&&w.appendChild(Pa());else if(pe)w.appendChild(Pa());else{let xe=AT("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);xe&&w.appendChild(xe)}}if(re&&t.stopReason&&!t.streaming&&(W||(_.style.display="none"),w.appendChild(pT(t.stopReason,re))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1&&o){let te=TT(t,o,r);w.appendChild(te)}if(!u||t.role==="system")return w;let ee=v("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),M=MT(d,t.role);return b==="right"||b==="left"&&t.role==="user"?ee.append(w,M):ee.append(M,w),ee};var ET=40,kT=(t,e)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}if(typeof e=="function"){let n=null;try{n=e()}catch(o){console.warn("[persona] welcome.icon renderer threw",o)}if(!n){t.hidden=!0;return}t.appendChild(n),t.hidden=!1;return}if(e.type==="lucide"){let n=fe(e.name,ET);if(!n){t.hidden=!0;return}t.appendChild(n)}else e.type==="image"?t.appendChild(J("img",{className:"persona-welcome-icon-image",attrs:{src:e.url,alt:e.alt}})):t.appendChild(J("span",{className:"persona-welcome-icon-text",text:e.text}));t.hidden=!1},mv=(t,e,n={})=>{let o=J("div",{className:"persona-welcome-icon",attrs:{"data-persona-welcome-icon":""}});o.hidden=!0;let r=v("h2","persona-welcome-title"),s=v("p","persona-welcome-subtitle");return{host:J("div",{className:"persona-welcome persona-rounded-2xl",attrs:{"data-persona-welcome":"","data-persona-intro-card":"","data-persona-welcome-variant":"card"},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:n.flatShadow?"none":"var(--persona-intro-card-shadow, none)",border:"var(--persona-intro-card-border, none)"}},o,r,s,e),iconHolder:o,title:r,subtitle:s,starterSuggestions:e}},ni=(t,e,n)=>{e.hidden=!n,e.style.display=n?"":"none",t.classList.toggle("persona-gap-6",n),t.classList.toggle("persona-gap-3",!n)},md=(t,e)=>{t.title.textContent=e.title,t.subtitle.textContent=e.subtitle,t.subtitle.hidden=e.subtitle==="",kT(t.iconHolder,e.icon),t.host.setAttribute("data-persona-welcome-variant",e.variant),t.host.setAttribute("data-persona-welcome-dismiss",e.dismiss)},PT="data-persona-welcome-plugin",hv="data-persona-welcome-overlay",fd="persona-welcome-overlay-active",Zu=new WeakMap,eg=(t,e,n)=>{n.setAttribute(PT,""),e.appendChild(n),e.setAttribute("data-persona-welcome-content","plugin"),e.setAttribute(hv,""),t.classList.contains(fd)||(Zu.set(t,t.scrollTop),t.classList.add(fd),t.scrollTop=0)},tg=(t,e,n)=>{n&&n!==e&&n.remove(),e.removeAttribute("data-persona-welcome-content"),e.removeAttribute(hv),t.classList.contains(fd)&&(t.classList.remove(fd),t.scrollTop=Zu.get(t)??t.scrollTop,Zu.delete(t))},yv=()=>{let t=J("div",{className:"persona-welcome-greeting persona-flex persona-flex-col",attrs:{"data-persona-welcome-greeting":""}});return t.hidden=!0,t},hd=(t,e,n)=>{if(t.replaceChildren(),!e){t.hidden=!0;return}let o=n?.layout?.messages?.layout??"bubble",r=J("div",{className:Na("assistant",o).join(" "),attrs:{"data-persona-theme-zone":"assistant-message"},text:e,style:o==="flat"?{backgroundColor:"transparent",color:"var(--persona-message-assistant-text, var(--persona-text))"}:{backgroundColor:"var(--persona-message-assistant-bg, var(--persona-container))",color:"var(--persona-message-assistant-text, var(--persona-text))"}});t.appendChild(J("div",{className:"persona-flex"},r)),t.hidden=!1},LT=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,bv=(t,e)=>{if(LT()||typeof t.animate!="function"||!t.isConnected)return e(null),null;let n=t.getBoundingClientRect(),o=t.parentElement,r=0,s=0,a=0;if(o){let y=getComputedStyle(o);r=parseFloat(y.rowGap)||0;let w=t.previousElementSibling,T=t.nextElementSibling,E=o.getBoundingClientRect().top+(parseFloat(y.borderTopWidth)||0)+(parseFloat(y.paddingTop)||0)-o.scrollTop;s=Math.max(0,w?n.top-w.getBoundingClientRect().bottom-r:n.top-E),a=Math.max(0,T?T.getBoundingClientRect().top-n.bottom-r:0)}let l=t.style.overflow;t.style.overflow="hidden";let d=getComputedStyle(t),p=parseFloat(d.paddingTop)||0,u=parseFloat(d.paddingBottom)||0,g=t.animate([{opacity:"1",transform:"none",height:`${n.height}px`,minHeight:"0px",paddingTop:`${p}px`,paddingBottom:`${u}px`,marginTop:`${s}px`,marginBottom:`${a}px`},{opacity:"0",transform:"translateY(-4px)",height:"0px",minHeight:"0px",paddingTop:"0px",paddingBottom:"0px",marginTop:"0px",marginBottom:`${-r}px`}],{duration:180,easing:"ease-out",fill:"forwards"}),b=!1,m=()=>{b||(b=!0,t.style.overflow=l,e(g))};return g.finished.then(m).catch(m),g};var IT="Hello \u{1F44B}",HT="I can answer questions and help you get things done here.",vv=new WeakSet,so=(t,e)=>!!t&&t[e]!==void 0,RT=(t,e)=>{!t||t.debug!==!0||!e.length||vv.has(t)||(vv.add(t),e.forEach(n=>console.warn(`[persona] ${n}`)))},ts=t=>{let e=t?.welcome,n=t?.copy,o=so(e,"variant")?e.variant:n?.showWelcomeCard===!1?"none":"card",r=o==="hero"?"on-first-message":so(e,"dismiss")?e.dismiss:"never",s=[];return so(e,"title")&&so(n,"welcomeTitle")&&s.push("welcome.title and copy.welcomeTitle are both set; welcome.title wins. copy.welcomeTitle is deprecated."),so(e,"subtitle")&&so(n,"welcomeSubtitle")&&s.push("welcome.subtitle and copy.welcomeSubtitle are both set; welcome.subtitle wins. copy.welcomeSubtitle is deprecated."),so(e,"variant")&&so(n,"showWelcomeCard")&&s.push("welcome.variant and copy.showWelcomeCard are both set; welcome.variant wins. copy.showWelcomeCard is deprecated."),o==="hero"&&so(e,"message")&&s.push('welcome.message is ignored when welcome.variant is "hero": the hero is the greeting.'),o==="hero"&&so(e,"dismiss")&&e.dismiss!=="on-first-message"&&s.push('welcome.dismiss is pinned to "on-first-message" when welcome.variant is "hero".'),RT(t,s),{title:so(e,"title")?e.title:n?.welcomeTitle??IT,subtitle:so(e,"subtitle")?e.subtitle:n?.welcomeSubtitle??HT,icon:e?.icon,variant:o,dismiss:r,message:o==="hero"?void 0:e?.message}},oi=(t,e)=>t.variant==="none"?!1:t.dismiss==="never"?!0:!(e??[]).some(n=>n.role==="user");var wv="16px",ng="10px",og="14px",Cv=t=>{let e=t?.launcher?.enabled??!0,n=Kt(t);if(Ha(t)){let u=t?.launcher?.composerBar??{},g=v("div","persona-widget-wrapper persona-fixed persona-transition");g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=u.expandedSize??"anchored",g.style.zIndex=String(t?.launcher?.zIndex??mn);let b=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");b.style.width="100%",g.appendChild(b);let m=v("div","persona-widget-pill-root");return m.setAttribute("data-persona-composer-bar",""),m.dataset.state="collapsed",m.dataset.expandedSize=u.expandedSize??"anchored",m.style.zIndex=String(t?.launcher?.zIndex??mn),{wrapper:g,panel:b,pillRoot:m}}if(n){let u=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),g=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return u.appendChild(g),{wrapper:u,panel:g}}if(!e){let u=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),g=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),b=t?.launcher?.width??"100%";return u.style.width=b,g.style.width="100%",u.appendChild(g),{wrapper:u,panel:g}}let r=t?.launcher??{},s=r.position&&Un[r.position]?Un[r.position]:Un["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(t?.launcher?.zIndex??mn);let l=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),p=t?.launcher?.width??t?.launcherWidth??Uo;return l.style.width=p,l.style.maxWidth=p,a.appendChild(l),{wrapper:a,panel:l}},rg=t=>{let e=J("div",{className:"persona-suggestions",attrs:{"data-persona-suggestions":Uu(t)}});return e.hidden=!0,e},xv=(t,e)=>{let n=rg("starter"),o=mv(t,n,{flatShadow:Kt(t)}),r=ts(t);md(o,r),ni(e,o.host,oi(r,t?.initialMessages));let s=yv();return hd(s,r.message,t),{welcome:o,greetingHost:s}},WT=(t,e)=>{let n=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:r}=ei(t,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:wv,iconSize:ng});r.style.position="absolute",r.style.top="8px",r.style.right="8px",r.style.zIndex="10";let s=t?.launcher?.clearChat?.enabled??!0,a=null,l=null;if(s){let I=ti(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:wv,iconSize:og});a=I.button,l=I.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let d=J("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),p=J("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});p.style.setProperty("scrollbar-gutter","stable");let{welcome:u,greetingHost:g}=xv(t,p),{host:b,title:m,subtitle:y}=u,w=u.starterSuggestions,T=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),W=rg("followUp"),E=yr(t,!0);E&&(T.style.maxWidth=E,T.style.marginLeft="auto",T.style.marginRight="auto",T.style.width="100%"),p.append(b,g,T,W);let k=J("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"}}),A=gd({config:t}),{root:D,textNode:B}=dv();return n.append(d,r,p,k),l&&n.appendChild(l),{container:n,body:p,messagesWrapper:T,starterSuggestions:w,transcriptSuggestions:W,composerOverlay:k,suggestions:A.suggestions,textarea:A.textarea,sendButton:A.sendButton,sendButtonWrapper:A.sendButtonWrapper,micButton:A.micButton,micButtonWrapper:A.micButtonWrapper,composerForm:A.composerForm,statusText:A.statusText,welcomeHost:b,welcomeIconHolder:u.iconHolder,greetingHost:g,introTitle:m,introSubtitle:y,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:l,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:d,footer:A.footer,attachmentButton:A.attachmentButton,attachmentButtonWrapper:A.attachmentButtonWrapper,attachmentInput:A.attachmentInput,attachmentPreviewsContainer:A.attachmentPreviewsContainer,actionsRow:A.actionsRow,leftActions:A.leftActions,rightActions:A.rightActions,setSendButtonMode:A.setSendButtonMode,peekBanner:D,peekTextNode:B}},Sv=(t,e=!0)=>{if(Ha(t))return WT(t,e);let n=J("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=t?.layout?.header,r=t?.layout?.showHeader!==!1,s=o?id(t,o,{showClose:e}):es({config:t,showClose:e}),a=J("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{welcome:l,greetingHost:d}=xv(t,a),{host:p,title:u,subtitle:g}=l,b=l.starterSuggestions,m=v("div","persona-widget-messages persona-flex persona-flex-col persona-gap-3"),y=rg("followUp"),w=yr(t,!1);w&&(m.style.maxWidth=w,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),a.append(p,d,m,y);let T=Ba({config:t}),W=t?.layout?.showFooter!==!1;r?Wa(n,s,t):(s.header.style.display="none",Wa(n,s,t)),n.append(a);let E=J("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 W||(T.footer.style.display="none"),n.append(T.footer),n.append(E),{container:n,body:a,messagesWrapper:m,starterSuggestions:b,transcriptSuggestions:y,composerOverlay:E,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,welcomeHost:p,welcomeIconHolder:l.iconHolder,greetingHost:d,introTitle:u,introSubtitle:g,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:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode}};Qe();Rt();var sg=(t,e)=>{let n=v("button");n.type="button",n.innerHTML=`
205
1102
  <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>
206
1103
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
207
1104
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
208
- <span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-primary" data-role="launcher-title"></span>
209
- <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
1105
+ <span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-launcher" data-role="launcher-title"></span>
1106
+ <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-launcher-muted" data-role="launcher-subtitle"></span>
210
1107
  </span>
211
1108
  <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>
212
- `,n.addEventListener("click",e);let o=s=>{let i=s.launcher??{},l=Ot(s),p=n.querySelector("[data-role='launcher-title']");if(p){let E=i.title??"Chat Assistant";p.textContent=E,p.setAttribute("title",E)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let E=i.subtitle??"Here to help you get answers fast";c.textContent=E,c.setAttribute("title",E)}let d=n.querySelector(".persona-flex-col");d&&(i.textHidden||l?d.style.display="none":d.style.display="");let g=n.querySelector("[data-role='launcher-icon']");if(g)if(i.agentIconHidden)g.style.display="none";else{let E=i.agentIconSize??"40px";if(g.style.height=E,g.style.width=E,i.agentIconBackgroundColor?(g.style.backgroundColor=i.agentIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),g.innerHTML="",i.agentIconName){let L=parseFloat(E)||24,D=ie(i.agentIconName,L*.6,"var(--persona-text-inverse, #ffffff)",2);D?(g.appendChild(D),g.style.display=""):(g.textContent=i.agentIconText??"\u{1F4AC}",g.style.display="")}else i.iconUrl?g.style.display="none":(g.textContent=i.agentIconText??"\u{1F4AC}",g.style.display="")}let b=n.querySelector("[data-role='launcher-image']");if(b){let E=i.agentIconSize??"40px";b.style.height=E,b.style.width=E,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(b.src=i.iconUrl,b.style.display="block"):b.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let E=i.callToActionIconSize??"32px";f.style.height=E,f.style.width=E,i.callToActionIconBackgroundColor?(f.style.backgroundColor=i.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(f.style.color=i.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let L=0;if(i.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=i.callToActionIconPadding,L=(parseFloat(i.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),i.callToActionIconHidden)f.style.display="none";else if(f.style.display=l?"none":"",f.innerHTML="",i.callToActionIconName){let D=parseFloat(E)||24,z=Math.max(D-L,8),$=ie(i.callToActionIconName,z,"currentColor",2);$?f.appendChild($):f.textContent=i.callToActionIconText??"\u2197"}else f.textContent=i.callToActionIconText??"\u2197"}let y=i.position&&un[i.position]?un[i.position]:un["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",M="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?M:`${C} ${y}`,l||(n.style.zIndex=String(i.zIndex??Ut));let I="1px solid var(--persona-border, #e5e7eb)",S="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=i.border??I,n.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:S,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=i.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",e),n.remove()};return t&&o(t),{element:n,update:o,destroy:r}},tw="teaser-dismissed",bm=new Set,hm=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${tw}`},nw=(t,e)=>{if(bm.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},ow=(t,e)=>{if(bm.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},rw=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,sw=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||Ot(t??{})?null:e},ym=(t,e)=>{let n=v("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=t??{},r=null,s=null,i=null,l=null,p=null,c=!1,d=!1,g=!1,b=!1,f=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,y=()=>{p!==null&&(clearTimeout(p),p=null)},C=()=>{!s||!c||(c=!1,s.hidden=!0)},M=Q=>{y(),g=!0,C(),ow(hm(o),Q&&f())},I=Q=>{!r||g||M(Q==="user"&&c)},S=()=>{p=null,!(!s||g||b)&&(d=!0,c=!0,s.hidden=!1,!(rw()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},E=()=>{!r||!s||g||d||b||nw(hm(o),f())||(y(),p=setTimeout(S,Math.max(0,r.delayMs??0)))},L=()=>{M(f()),e()},D=Q=>{Q.stopPropagation(),M(f())},$=dd(t,()=>{I("user"),e()}),F=()=>{y(),l?.removeEventListener("click",L),i?.removeEventListener("click",D),s?.remove(),s=null,l=null,i=null,c=!1},B=()=>{l=ye("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",L),i=ye("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),i.addEventListener("click",D),s=ye("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,i),n.insertBefore(s,$.element)},H=()=>{let Q=o.launcher?.position??"bottom-right",se=un[Q]??un["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",$.element.style.position="";return}n.className=Bn("persona-launcher-surface",se),n.setAttribute("data-teaser",Q),n.style.zIndex=String(o.launcher?.zIndex??Ut),$.element.style.position="static"},w=Q=>{let se=sw(Q);if(r=se,!se){F();return}s||B(),l.textContent=se.text,i.hidden=se.dismissible===!1,i.setAttribute("aria-label",se.dismissLabel??"Dismiss message"),E()},N=Q=>{o=Q,$.update(Q),w(Q),H()},K=(Q,se="user")=>{b=Q,Q&&I(se)},te=()=>{F(),$.destroy(),n.remove()};return n.appendChild($.element),t&&(w(t),H()),{element:n,launcher:$,get teaser(){return s?{element:s,show:S,dismiss:M}:null},setPanelOpen:K,update:N,destroy:te}};var vm=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=gm(t),s=mm(t,e),i={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,starterSuggestions:s.starterSuggestions,transcriptSuggestions:s.transcriptSuggestions,composerOverlay:s.composerOverlay,welcomeHost:s.welcomeHost,welcomeIconHolder:s.welcomeIconHolder,greetingHost:s.greetingHost,introTitle:s.introTitle,introSubtitle:s.introSubtitle},p={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:i,panelElements:s,transcript:l,header:p,composer:c,replaceHeader:b=>(p.element.replaceWith(b.header),p.element=b.header,p.iconHolder=b.iconHolder,p.headerTitle=b.headerTitle,p.headerSubtitle=b.headerSubtitle,p.closeButton=b.closeButton,p.closeButtonWrapper=b.closeButtonWrapper,p.clearChatButton=b.clearChatButton,p.clearChatButtonWrapper=b.clearChatButtonWrapper,b),replaceComposer:b=>{c.footer.replaceWith(b),c.footer=b}}},pd=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>dd(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=ym(t,n);return{instance:r,element:r.element}};var iw=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},aw=(t,e,n)=>`${iw(t)}plugin:${e}:${n}`,xm=t=>{let e=new Map,n=!1,o=()=>{if(n||t()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let s=i=>aw(t(),r,i);return{get:i=>{let l=s(i),p=o();if(p)try{return p.getItem(l)}catch{n=!0}return e.get(l)??null},set:(i,l)=>{let p=s(i),c=o();if(c)try{c.setItem(p,l);return}catch{n=!0}e.set(p,l)},remove:i=>{let l=s(i);e.delete(l);let p=o();if(p)try{p.removeItem(l)}catch{n=!0}}}}};Ye();xt();var Qr=new Set,lw=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),cw=(t,e)=>{let n=t.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,e).join(`
213
- `):""},wm=(t,e)=>{let n=Qr.has(t),o=e.querySelector('button[data-expand-header="true"]'),r=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let c=ie(n?"chevron-up":"chevron-down",16,"currentColor",2);c?l.appendChild(c):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},ud=(t,e)=>{let n=t.reasoning,o=v("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.id),!n)return o;let r=e?.features?.reasoningDisplay??{},s=r.expandable!==!1,i=s&&Qr.has(t.id),l=n.status!=="complete",p=cw(t,r.previewMaxLines??3),c=v("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",i?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let d=v("div","persona-flex persona-flex-col persona-text-left"),g=v("span","persona-text-xs persona-text-persona-primary"),b="Thinking...",f=e?.reasoning??{},y=String(n.startedAt??Date.now()),C=()=>{let te=v("span","");return te.setAttribute("data-tool-elapsed",y),te.textContent=ra(n),te},M=f.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:b,previewText:p,isActive:l,config:e??{},elapsed:ra(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(g.textContent=M,d.appendChild(g)):M instanceof HTMLElement?d.appendChild(M):(g.textContent=b,d.appendChild(g));let I=v("span","persona-text-xs persona-text-persona-primary");I.textContent=eg(n),d.appendChild(I);let S=r.loadingAnimation??"none",E=f.activeTextTemplate,L=f.completeTextTemplate,D=l?E:L,z=M instanceof HTMLElement,$=(te,Q)=>{g.textContent="";let se=sa(te,""),J=0;for(let oe of se){let Y=oe.styles.length>0?(()=>{let pe=v("span",oe.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return g.appendChild(pe),pe})():g;if(oe.isDuration&&l)Y.appendChild(C());else{let pe=oe.isDuration?ra(n):oe.text;Q?J=ko(Y,pe,J):Y.appendChild(document.createTextNode(pe))}}};if(!z&&D)if(I.style.display="none",g.style.display="",l&&S!=="none"){let te=f.loadingAnimationDuration??2e3;g.setAttribute("data-preserve-animation","true"),S==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${te}ms`),$(D,!1)):(g.classList.add(`persona-tool-loading-${S}`),g.style.setProperty("--persona-tool-anim-duration",`${te}ms`),S==="shimmer-color"&&(f.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),$(D,!0))}else $(D,!1);else if(!z&&l&&S!=="none"){g.style.display="";let te=f.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),S==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${te}ms`);else{g.classList.add(`persona-tool-loading-${S}`),g.style.setProperty("--persona-tool-anim-duration",`${te}ms`),S==="shimmer-color"&&(f.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let Q=g.textContent||b;g.textContent="",ko(g,Q,0)}n.status==="complete"&&(g.style.display="none")}else z||(n.status==="complete"?g.style.display="none":g.style.display="");let F=null;if(s){F=v("div","persona-flex persona-items-center");let Q=ie(i?"chevron-up":"chevron-down",16,"currentColor",2);Q?F.appendChild(Q):F.textContent=i?"Hide":"Show";let se=v("div","persona-flex persona-items-center persona-ml-auto");se.append(F),c.append(d,se)}else c.append(d);let B=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(B.setAttribute("data-persona-collapsed-preview","reasoning"),B.style.display="none",B.style.whiteSpace="pre-wrap",!i&&l&&r.activePreview&&p){let te=e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:n,defaultPreview:p,isActive:l,config:e??{}});lw(B,te)||(B.textContent=p),B.style.display=""}if(!i&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(c,B),o;let H=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");H.style.display=i?"":"none";let w=n.chunks.join(""),N=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return N.textContent=w||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),H.appendChild(N),(()=>{if(c.setAttribute("aria-expanded",i?"true":"false"),F){F.innerHTML="";let Q=ie(i?"chevron-up":"chevron-down",16,"currentColor",2);Q?F.appendChild(Q):F.textContent=i?"Hide":"Show"}H.style.display=i?"":"none",B.style.display=i?"none":B.textContent||B.childNodes.length?"":"none"})(),o.append(c,B,H),o};Ye();xt();var Xr=new Set,dw=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),pw=(t,e)=>{let n=t.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-e).join(`
214
- `);let r=Mo(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
215
- `):""},gd=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},uw=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=pw(t,o?.previewMaxLines??3),i=n?tg(n):"";if(!n)return{summary:i,previewText:s,isActive:!1};let l=n.status!=="complete",p=e?.toolCall??{},c=i;return r==="tool-name"?c=n.name?.trim()||i:r==="tool-preview"&&s&&(c=s),l&&p.activeTextTemplate?c=hc(n,p.activeTextTemplate,c):!l&&p.completeTextTemplate&&(c=hc(n,p.completeTextTemplate,c)),{summary:c,previewText:s,isActive:l}},Cm=(t,e,n)=>{let o=Xr.has(t),r=n?.toolCall??{},s=e.querySelector('button[data-expand-header="true"]'),i=e.querySelector(".persona-border-t"),l=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!i)return;s.setAttribute("aria-expanded",o?"true":"false");let c=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let d=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",g=ie(o?"chevron-up":"chevron-down",16,d,2);g?c.appendChild(g):c.textContent=o?"Hide":"Show"}i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},fd=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=v("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${t.id}`,r.setAttribute("data-message-id",t.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=e?.features?.toolCallDisplay??{},i=s.expandable!==!1,l=i&&Xr.has(t.id),{summary:p,previewText:c,isActive:d}=uw(t,e),g=v("button",i?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");g.type="button",i&&(g.setAttribute("aria-expanded",l?"true":"false"),g.setAttribute("data-expand-header","true")),g.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(g.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(g.style.paddingLeft=o.headerPaddingX,g.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(g.style.paddingTop=o.headerPaddingY,g.style.paddingBottom=o.headerPaddingY);let b=v("div","persona-flex persona-flex-col persona-text-left"),f=v("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let y=String(n.startedAt??Date.now()),C=()=>{let w=v("span","");return w.setAttribute("data-tool-elapsed",y),w.textContent=Hs(n),w},M=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:p,previewText:c,collapsedMode:s.collapsedMode??"tool-call",isActive:d,config:e??{},elapsed:Hs(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(f.textContent=M,b.appendChild(f)):M instanceof HTMLElement?b.appendChild(M):(f.textContent=p,b.appendChild(f));let I=s.loadingAnimation??"none",S=o.activeTextTemplate,E=o.completeTextTemplate,L=d?S:E,D=M instanceof HTMLElement,z=(w,N)=>{f.textContent="";let K=n.name?.trim()||"tool",te=sa(w,K),Q=0;for(let se of te){let J=se.styles.length>0?(()=>{let oe=v("span",se.styles.map(Y=>`persona-tool-text-${Y}`).join(" "));return f.appendChild(oe),oe})():f;if(se.isDuration&&d)J.appendChild(C());else{let oe=se.isDuration?Hs(n):se.text;N?Q=ko(J,oe,Q):J.appendChild(document.createTextNode(oe))}}};if(!D)if(d&&I!=="none"){let w=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),I==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${w}ms`),L&&z(L,!1);else if(f.classList.add(`persona-tool-loading-${I}`),f.style.setProperty("--persona-tool-anim-duration",`${w}ms`),I==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),L)z(L,!0);else{let N=f.textContent||p;f.textContent="",ko(f,N,0)}}else L&&z(L,!1);let $=null;if(i){$=v("div","persona-flex persona-items-center");let w=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",N=ie(l?"chevron-up":"chevron-down",16,w,2);N?$.appendChild(N):$.textContent=l?"Hide":"Show";let K=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");K.append($),g.append(b,K)}else g.append(b);let F=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(F.setAttribute("data-persona-collapsed-preview","tool"),F.style.display="none",F.style.whiteSpace="pre-wrap",!l&&d&&s.activePreview&&c){let w=o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:c,isActive:d,config:e??{}});dw(F,w)||(F.textContent=c),F.style.display=""}if(!l&&d&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!i)return r.append(g,F),r;let B=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(B.style.display=l?"":"none",o.contentBackgroundColor&&(B.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(B.style.color=o.contentTextColor),o.contentPaddingX&&(B.style.paddingLeft=o.contentPaddingX,B.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(B.style.paddingTop=o.contentPaddingY,B.style.paddingBottom=o.contentPaddingY),n.name){let w=v("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?w.style.color=o.contentTextColor:o.headerTextColor&&(w.style.color=o.headerTextColor),w.textContent=n.name,B.appendChild(w)}if(n.args!==void 0){let w=v("div","persona-space-y-1"),N=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(N.style.color=o.labelTextColor),N.textContent="Arguments";let K=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",gd(K,o),K.textContent=Mo(n.args),w.append(N,K),B.appendChild(w)}if(n.chunks&&n.chunks.length){let w=v("div","persona-space-y-1"),N=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(N.style.color=o.labelTextColor),N.textContent="Activity";let K=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",gd(K,o),K.textContent=n.chunks.join(""),w.append(N,K),B.appendChild(w)}if(n.status==="complete"&&n.result!==void 0){let w=v("div","persona-space-y-1"),N=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(N.style.color=o.labelTextColor),N.textContent="Result";let K=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");K.style.fontSize="0.75rem",K.style.lineHeight="1rem",gd(K,o),K.textContent=Mo(n.result),w.append(N,K),B.appendChild(w)}if(n.status==="complete"&&typeof n.duration=="number"){let w=v("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(w.style.color=o.contentTextColor),w.textContent=`Duration: ${n.duration}ms`,B.appendChild(w)}return(()=>{if(g.setAttribute("aria-expanded",l?"true":"false"),$){$.innerHTML="";let w=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",N=ie(l?"chevron-up":"chevron-down",16,w,2);N?$.appendChild(N):$.textContent=l?"Hide":"Show"}B.style.display=l?"":"none",F.style.display=l?"none":F.textContent||F.childNodes.length?"":"none"})(),r.append(g,F,B),r};Ye();xt();var sr=new Map,al=t=>{let n=(t.startsWith(Zn)?t.slice(Zn.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Am=t=>t?.approval!==!1?t?.approval:void 0,Sm=(t,e)=>{let n=Am(e)?.detailsDisplay??"collapsed";return sr.get(t)??n==="expanded"},Mm=(t,e,n)=>{let o=Am(n);t.setAttribute("aria-expanded",e?"true":"false");let r=t.querySelector("[data-approval-details-label]");r&&(r.textContent=e?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let i=ie(e?"chevron-up":"chevron-down",14,"currentColor",2);i&&s.appendChild(i)}},Tm=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=Sm(t,n);Mm(o,s,n),r.style.display=s?"":"none"};var ll=(t,e)=>{let n=t.approval,o=e?.approval!==!1?e?.approval:void 0,r=n?.status==="pending",s=v("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let i=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=v("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",d=ie(p,20,c,2);d&&l.appendChild(d);let g=v("div","persona-flex-1 persona-min-w-0"),b=v("div","persona-flex persona-items-center persona-gap-2"),f=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",b.appendChild(f),!r){let $=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");$.setAttribute("data-approval-status",n.status),n.status==="approved"?($.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",$.style.color="var(--persona-palette-colors-success-700, #15803d)",$.textContent="Approved"):n.status==="denied"?($.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",$.style.color="var(--persona-palette-colors-error-700, #b91c1c)",$.textContent="Denied"):n.status==="timeout"&&($.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",$.style.color="var(--persona-palette-colors-warning-700, #b45309)",$.textContent="Timeout"),b.appendChild($)}g.appendChild(b);let C=n.toolType==="webmcp"||n.toolName.startsWith(Zn)?ks(n.toolName):void 0,M=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),I=!n.toolName,S=M||(I?n.description:`The assistant wants to use \u201C${C??al(n.toolName)}\u201D.`),E=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(E.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(E.style.color=o.descriptionColor),E.textContent=S,g.appendChild(E),n.reason){let $=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");$.setAttribute("data-approval-reason","true"),o?.reasonColor?$.style.color=o.reasonColor:o?.descriptionColor&&($.style.color=o.descriptionColor);let F=v("span","persona-font-medium");F.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,$.appendChild(F),$.appendChild(document.createTextNode(n.reason)),g.appendChild($)}let L=o?.detailsDisplay??"collapsed",D=!!n.description&&!I,z=D||!!n.parameters;if(L!=="hidden"&&z){let $=Sm(t.id,e),F=v("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");F.type="button",F.setAttribute("data-expand-header","true"),F.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(F.style.color=o.descriptionColor);let B=v("span");B.setAttribute("data-approval-details-label","true");let H=v("span","persona-inline-flex persona-items-center");H.setAttribute("data-approval-details-chevron","true"),F.append(B,H),Mm(F,$,e),g.appendChild(F);let w=v("div");if(w.setAttribute("data-approval-details","true"),w.style.display=$?"":"none",D){let N=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(N.style.color=o.descriptionColor),N.textContent=n.description,w.appendChild(N)}if(n.parameters){let N=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(N.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(N.style.color=o.parameterTextColor),N.style.fontSize="0.75rem",N.style.lineHeight="1rem",N.textContent=Mo(n.parameters),w.appendChild(N)}g.appendChild(w)}if(r){let $=v("div","persona-flex persona-gap-2 persona-mt-2");$.setAttribute("data-approval-buttons","true");let F=v("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");F.type="button",F.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",F.style.color=o?.approveButtonTextColor??"#ffffff",F.setAttribute("data-approval-action","approve");let B=ie("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);B&&(B.style.marginRight="4px",F.appendChild(B));let H=document.createTextNode(o?.approveLabel??"Approve");F.appendChild(H);let w=v("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");w.type="button",w.style.backgroundColor=o?.denyButtonColor??"transparent",w.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",w.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,w.setAttribute("data-approval-action","deny");let N=ie("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);N&&(N.style.marginRight="4px",w.appendChild(N));let K=document.createTextNode(o?.denyLabel??"Deny");w.appendChild(K),$.append(F,w),g.appendChild($)}return i.append(l,g),s.appendChild(i),s};Ye();xt();Lc();var gw=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Em=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let o=t.popovers.get(e);o&&(o.destroy(),t.popovers.delete(e))},ir=(t,e)=>{Em(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},fw=t=>t?.approval!==!1?t?.approval:void 0,mw=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return sr.get(t)??n==="expanded"},md=t=>{let e=v("span","persona-approval-kbd");return e.textContent=t,e},hw=(t,e)=>{let n=v("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(Zn)?ks(t.toolName):void 0,s=e?.formatDescription?.({toolName:t.toolName,toolType:t.toolType,description:t.description??"",parameters:t.parameters,...r?{displayTitle:r}:{},...t.reason?{reason:t.reason}:{}});if(s)return n.textContent=s,n;let i=r??al(t.toolName),l=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=i,n.appendChild(p),l){n.append(" from ");let c=document.createElement("strong");c.textContent=l,n.appendChild(c)}return n},bw=t=>{let e=v("div","persona-approval-resolved"),n=ie("ban",15,"currentColor",2);n&&e.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=t.toolName?al(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},yw=(t,e,n,o,r,s,i)=>{let l=v("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${e.id}`,l.setAttribute("data-message-id",e.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",c=!!n.description&&p!=="hidden",d=n.parameters!=null&&p!=="hidden",g=c||d,b=g&&mw(e.id,o),f=o?.showDetailsLabel??"Show details",y=o?.hideDetailsLabel??"Hide details",C=v("button","persona-approval-head");C.type="button",g?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",b?"true":"false"),C.setAttribute("aria-label",b?y:f)):C.setAttribute("data-static","true");let M=v("span","persona-approval-logo"),I=ie("shield-check",16,"currentColor",2);I&&M.appendChild(I),C.appendChild(M);let S=hw(n,o);if(g){let F=v("span","persona-approval-toggle");F.setAttribute("aria-hidden","true");let B=ie("chevron-down",14,"currentColor",2);B&&F.appendChild(B),S.append(" "),S.appendChild(F)}C.appendChild(S),l.appendChild(C);let E=v("div","persona-approval-body");if(g){let F=v("div","persona-approval-details");if(F.setAttribute("data-role","params"),F.hidden=!b,c){let B=v("p","persona-approval-desc");o?.descriptionColor&&(B.style.color=o.descriptionColor),B.textContent=n.description,F.appendChild(B)}if(d){let B=v("pre","persona-approval-params");o?.parameterBackgroundColor&&(B.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(B.style.color=o.parameterTextColor),B.textContent=Mo(n.parameters),F.appendChild(B)}E.appendChild(F)}if(n.reason){let F=v("p","persona-approval-reason");o?.reasonColor?F.style.color=o.reasonColor:o?.descriptionColor&&(F.style.color=o.descriptionColor);let B=v("span","persona-approval-reason-label");B.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,F.append(B,document.createTextNode(n.reason)),E.appendChild(F)}let L=v("div","persona-approval-actions"),D=null,z=F=>{o?.approveButtonColor&&(F.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(F.style.color=o.approveButtonTextColor)},$=v("button","persona-approval-deny");if($.type="button",$.setAttribute("data-action","deny"),o?.denyButtonColor&&($.style.background=o.denyButtonColor),o?.denyButtonTextColor&&($.style.color=o.denyButtonTextColor),$.append(o?.denyLabel??"Deny"),i){let F=v("div","persona-approval-split"),B=v("button","persona-approval-primary");B.type="button",B.setAttribute("data-action","always"),z(B),B.append(o?.approveLabel??"Always allow",md("\u23CE"));let H=v("button","persona-approval-caret");H.type="button",H.setAttribute("data-action","toggle-menu"),H.setAttribute("aria-label","More options"),z(H);let w=ie("chevron-down",15,"currentColor",2);w&&H.appendChild(w),F.append(B,H),L.append(F,$),$.append(md("Esc"));let N=v("div","persona-approval-menu"),K=v("button","persona-approval-menu-item");K.type="button",K.append("Allow once",md("\u2318\u23CE")),N.appendChild(K),D=wa({anchor:F,content:N,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,D),K.addEventListener("click",()=>{ir(t,e.id),r()})}else{let F=v("button","persona-approval-primary persona-approval-primary--solo");F.type="button",F.setAttribute("data-action","allow"),z(F),F.append(o?.approveLabel??"Allow"),L.append(F,$)}return E.appendChild(L),l.appendChild(E),l.addEventListener("click",F=>{let B=F.target instanceof Element?F.target.closest("[data-action]"):null;if(!B)return;let H=B.getAttribute("data-action");if(H==="toggle-params"){let w=l.querySelector('[data-role="params"]');if(w){let N=w.hidden;w.hidden=!N,C.setAttribute("aria-expanded",N?"true":"false"),C.setAttribute("aria-label",N?y:f),sr.set(e.id,N)}return}if(H==="toggle-menu"){D?.toggle();return}if(H==="always"){ir(t,e.id),r({remember:!0});return}if(H==="allow"){ir(t,e.id),r();return}if(H==="deny"){ir(t,e.id),s();return}}),l},km=()=>{let t=gw();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:i})=>{let l=o?.approval;if(!l)return null;let p=fw(i);if(l.status!=="pending"){if(ir(t,o.id),l.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return bw(l)}Em(t,o.id);let c=p?.enableAlwaysAllow===!0,d=yw(t,o,l,p,r,s,c);if(c){t.pendingOrder.includes(o.id)||t.pendingOrder.push(o.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let g=b=>{Og(b)||o.id===t.latestPendingApprovalId&&(b.key!=="Escape"&&b.key!=="Enter"||(b.preventDefault(),b.stopImmediatePropagation(),ir(t,o.id),b.key==="Escape"?s():b.metaKey||b.ctrlKey?r():r({remember:!0})))};t.keyHandlers.set(o.id,g),document.addEventListener("keydown",g)}return d}},teardown:()=>{for(let o of[...t.keyHandlers.keys(),...t.popovers.keys()])ir(t,o);t.latestPendingApprovalId=null}}};var di=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){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),this.store?.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 n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var pi=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}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 o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}getAll(){return new Promise((e,n)=>{if(!this.db){e([]);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{e(i.result)},i.onerror=()=>{n(i.error)}}catch(o){n(o)}})}getCount(){return new Promise((e,n)=>{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=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((e,n)=>{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=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}};var vw=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),xw=new Set(["step_start","execution_start"]),ww=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Cw=new Set(["step_complete","agent_turn_complete"]),Aw=new Set(["flow_complete","agent_complete"]),Lm=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Im=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),gn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,ar=(t,e)=>{let n=t[e];return Im(n)?n:void 0};function hd(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function cl(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function Sw(t,e){return typeof e.type=="string"?e.type:t}function Mw(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function Tw(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function Pm(t){let e=ar(t,"result"),n=[ar(t,"tokens"),ar(t,"totalTokens"),e?ar(e,"tokens"):void 0,ar(t,"usage"),e?ar(e,"usage"):void 0];for(let o of n){if(!o)continue;let r=gn(o.output)??gn(o.outputTokens)??gn(o.completionTokens);if(r!==void 0)return r}return gn(t.outputTokens)??gn(t.completionTokens)??(e?gn(e.outputTokens)??gn(e.completionTokens):void 0)}function Ew(t){let e=ar(t,"result");return gn(t.executionTime)??gn(t.executionTimeMs)??gn(t.execution_time)??gn(t.duration)??(e?gn(e.executionTime)??gn(e.executionTimeMs):void 0)}function kw(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var ui=class{constructor(e=kw){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 n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:cl(this.metric.outputTokens,n)}}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,n){if(!Im(n)){Lm.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Sw(e,n),r=this.now();if(vw.has(o)){this.startRun(r);return}if(xw.has(o)){this.run||this.startRun(r);return}if(ww.has(o)){if(!Tw(o,n))return;let s=Mw(n);if(!s)return;this.run||this.startRun(r);let i=this.run;i.firstDeltaAt??(i.firstDeltaAt=r),i.visibleCharCount+=s.length;let l=i.exactOutputTokens+hd(i.visibleCharCount),p=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:cl(l,p),outputTokens:l,durationMs:p,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Cw.has(o)){if(!this.run)return;let s=this.run,i=Pm(n);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+hd(s.visibleCharCount),c=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:cl(p,c),outputTokens:p,durationMs:c,source:l?"usage":"estimate"};return}if(Aw.has(o)){if(!this.run)return;let s=this.run,i=Pm(n),l=i??s.exactOutputTokens+hd(s.visibleCharCount),p=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",c=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:cl(l,c),outputTokens:l,durationMs:c,source:p},this.run=null;return}if(Lm.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,o){let r=e.firstDeltaAt!==void 0?o-e.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:Ew(n)??o-e.startedAt}};Ye();xt();function Yr(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}var Lw={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)"}},Pw={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Iw=["flowName","stepName","reasoningText","text","name","tool","toolName"],Rw=100;function Ww(t,e){let n={...Lw,...e};if(n[t])return n[t];for(let o of Object.keys(n))if(o.endsWith("_")&&t.startsWith(o))return n[o];return Pw}function Hw(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function Bw(t){let e=new Date(t),n=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),r=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function Dw(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return null;for(let o of e){let r=o.split("."),s=n;for(let i of r)if(s&&typeof s=="object"&&s!==null)s=s[i];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Ow(t){return navigator.clipboard?.writeText?navigator.clipboard.writeText(t):new Promise(e=>{let n=document.createElement("textarea");n.value=t,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),e()})}function Nw(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function Fw(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function _w(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function $w(t,e,n){let o,r;try{r=JSON.parse(t.payload),o=JSON.stringify(r,null,2)}catch{r=t.payload,o=t.payload}let s=e.find(l=>l.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let l=s.renderEventStreamPayload({event:t,config:n,defaultRenderer:()=>i(),parsedPayload:r});if(l)return l}return i();function i(){let l=v("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]"),p=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=o,l.appendChild(p),l}}function bd(t,e,n,o,r,s,i,l){let p=r.has(t.id),c=v("div","persona-border-b persona-border-persona-divider persona-text-xs");Yr(c,o.classNames?.eventRow);let d=i.find(b=>b.renderEventStreamRow);if(d?.renderEventStreamRow&&l){let b=d.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>g(),isExpanded:p,onToggleExpand:()=>s(t.id)});if(b)return c.appendChild(b),c}return c.appendChild(g()),c;function g(){let b=v("div",""),f=v("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");f.setAttribute("data-event-id",t.id);let y=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=ie(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&y.appendChild(C);let M=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),I=o.timestampFormat??"relative";M.textContent=I==="relative"?Hw(t.timestamp,n):Bw(t.timestamp);let S=null;o.showSequenceNumbers!==!1&&(S=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),S.textContent=String(e+1));let E=Ww(t.type,o.badgeColors),L=v("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");L.style.backgroundColor=E.bg,L.style.color=E.text,L.style.borderColor=E.text+"50",L.textContent=t.type;let D=o.descriptionFields??Iw,z=Dw(t.payload,D),$=null;z&&($=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),$.textContent=z);let F=v("div","persona-flex-1 persona-min-w-0"),B=v("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"),H=ie("clipboard","12px","currentColor",1.5);return H&&B.appendChild(H),B.addEventListener("click",async w=>{w.stopPropagation(),await Ow(Nw(t)),B.innerHTML="";let N=ie("check","12px","currentColor",1.5);N&&B.appendChild(N),setTimeout(()=>{B.innerHTML="";let K=ie("clipboard","12px","currentColor",1.5);K&&B.appendChild(K)},1500)}),f.appendChild(y),f.appendChild(M),S&&f.appendChild(S),f.appendChild(L),$&&f.appendChild($),f.appendChild(F),f.appendChild(B),b.appendChild(f),p&&b.appendChild($w(t,i,l)),b}}function Rm(t){let{buffer:e,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:i}=t,l=r?.features?.scrollToBottom,p=l?.enabled!==!1,c=l?.iconName??"arrow-down",d=l?.label??"",g=r?.features?.eventStream??{},b=s.find(y=>y.renderEventStreamView);if(b?.renderEventStreamView&&r){let y=b.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>f().element,onClose:o});if(y)return{element:y,update:()=>{},destroy:()=>{}}}return f();function f(){let y=g.classNames,C=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Yr(C,y?.panel);let M=[],I="",S="",E=null,L=[],D={},z=0,$=$a(),F=0,B=0,H=!1,w=null,N=!1,K=0,te=new Set,Q=new Map,se="",J="",oe=null,Y,pe,ne,me,ve=null,be=null,Te=null;function ze(){let q=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),ee=v("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");if(Yr(ee,y?.headerBar),i){be=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),be.style.cursor="help",ve=v("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"),ve.textContent="-- tok/s",Te=v("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"),Te.style.display="none",Te.style.pointerEvents="none";let Mt=be,fn=Te,bi=()=>{if(!fn.textContent)return;let mn=Mt.getBoundingClientRect(),ct=q.getBoundingClientRect();fn.style.left=`${mn.left-ct.left}px`,fn.style.top=`${mn.bottom-ct.top+4}px`,fn.style.display="block"},le=()=>{fn.style.display="none"};be.addEventListener("mouseenter",bi),be.addEventListener("mouseleave",le),be.appendChild(ve)}let ge=v("div","persona-flex-1");Y=v("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 qe=v("option","");qe.value="",qe.textContent="All events (0)",Y.appendChild(qe),pe=v("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"),pe.type="button",pe.title="Copy All";let Ie=ie("clipboard-copy","12px","currentColor",1.5);Ie&&pe.appendChild(Ie);let Ke=v("span","persona-event-copy-all persona-text-xs");Ke.textContent="Copy All",pe.appendChild(Ke),be&&ee.appendChild(be),ee.appendChild(ge),ee.appendChild(Y),ee.appendChild(pe);let je=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Yr(je,y?.searchBar);let He=ie("search","14px","var(--persona-muted, #9ca3af)",1.5),Se=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");He&&Se.appendChild(He),ne=v("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"),Yr(ne,y?.searchInput),ne.type="text",ne.placeholder="Search event payloads...",me=v("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"),me.type="button",me.style.display="none";let rt=ie("x","12px","currentColor",2);return rt&&me.appendChild(rt),je.appendChild(Se),je.appendChild(ne),je.appendChild(me),q.appendChild(ee),q.appendChild(je),Te&&q.appendChild(Te),q}let Oe,Ne=s.find(q=>q.renderEventStreamToolbar);Ne?.renderEventStreamToolbar&&r?Oe=Ne.renderEventStreamToolbar({config:r,defaultRenderer:()=>ze(),eventCount:e.getSize(),filteredCount:0,onFilterChange:ee=>{I=ee,Pe(),ke()},onSearchChange:ee=>{S=ee,Pe(),ke()}})??ze():Oe=ze();let Be=v("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");Be.style.display="none";function Ue(){if(!i||!ve||!be)return;let q=i(),ee=Fw(q);ve.textContent=ee;let ge=_w(q);Te&&(Te.textContent=ge,ge||(Te.style.display="none")),be.setAttribute("aria-label",ge?`Throughput: ${ee}, ${ge}`:`Throughput: ${ee}`)}let Me=v("div","persona-flex-1 persona-min-h-0 persona-relative"),Ee=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Ee.style.height="100%";let Ve=v("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");Yr(Ve,y?.scrollIndicator),Ve.style.display="none",Ve.setAttribute("data-persona-scroll-to-bottom-has-label",d?"true":"false");let Jt=ie(c,"14px","currentColor",2);Jt&&Ve.appendChild(Jt);let bt=v("span","");bt.textContent=d,Ve.appendChild(bt);let Nt=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Nt.style.display="none",Me.appendChild(Ee),Me.appendChild(Nt),Me.appendChild(Ve),C.setAttribute("tabindex","0"),C.appendChild(Oe),C.appendChild(Be),C.appendChild(Me);function Mn(){let q=e.getAll(),ee={};for(let je of q)ee[je.type]=(ee[je.type]||0)+1;let ge=Object.keys(ee).sort(),qe=ge.length!==L.length||!ge.every((je,He)=>je===L[He]),fe=!qe&&ge.some(je=>ee[je]!==D[je]),Ie=q.length!==Object.values(D).reduce((je,He)=>je+He,0);if(!qe&&!fe&&!Ie||(L=ge,D=ee,!Y))return;let Ke=Y.value;if(Y.options[0].textContent=`All events (${q.length})`,qe){for(;Y.options.length>1;)Y.remove(1);for(let je of ge){let He=v("option","");He.value=je,He.textContent=`${je} (${ee[je]||0})`,Y.appendChild(He)}Ke&&ge.includes(Ke)?Y.value=Ke:Ke&&(Y.value="",I="")}else for(let je=1;je<Y.options.length;je++){let He=Y.options[je];He.textContent=`${He.value} (${ee[He.value]||0})`}}function Tn(){let q=e.getAll();if(I&&(q=q.filter(ee=>ee.type===I)),S){let ee=S.toLowerCase();q=q.filter(ge=>ge.type.toLowerCase().includes(ee)||ge.payload.toLowerCase().includes(ee))}return q}function nt(){return I!==""||S!==""}function Pe(){z=0,F=0,$.resume(),Ve.style.display="none"}function xe(q){te.has(q)?te.delete(q):te.add(q),oe=q;let ee=Ee.scrollTop,ge=$.isFollowing();N=!0,$.pause(),ke(),Ee.scrollTop=ee,ge&&$.resume(),N=!1}function ot(){return ro(Ee,50)}function ke(){B=Date.now(),H=!1,Ue(),Mn();let q=e.getEvictedCount();q>0?(Be.textContent=`${q.toLocaleString()} older events truncated`,Be.style.display=""):Be.style.display="none",M=Tn();let ee=M.length,ge=e.getSize()>0;ee===0&&ge&&nt()?(Nt.textContent=S?`No events matching '${S}'`:"No events matching filter",Nt.style.display="",Ee.style.display="none"):(Nt.style.display="none",Ee.style.display=""),pe&&(pe.title=nt()?`Copy Filtered (${ee})`:"Copy All"),p&&!$.isFollowing()&&ee>z&&(F+=ee-z,bt.textContent=d?`${d}${F>0?` (${F})`:""}`:"",Ve.style.display=""),z=ee;let qe=e.getAll(),fe=qe.length>0?qe[0].timestamp:0,Ie=new Set(M.map(He=>He.id));for(let He of te)Ie.has(He)||te.delete(He);let Ke=I!==se||S!==J,je=Q.size===0&&M.length>0;if(Ke||je||M.length===0){Ee.innerHTML="",Q.clear();let He=document.createDocumentFragment();for(let Se=0;Se<M.length;Se++){let rt=bd(M[Se],Se,fe,g,te,xe,s,r);Q.set(M[Se].id,rt),He.appendChild(rt)}Ee.appendChild(He),se=I,J=S,oe=null}else{if(oe!==null){let Se=Q.get(oe);if(Se&&Se.parentNode===Ee){let rt=M.findIndex(Mt=>Mt.id===oe);if(rt>=0){let Mt=bd(M[rt],rt,fe,g,te,xe,s,r);Ee.insertBefore(Mt,Se),Se.remove(),Q.set(oe,Mt)}}oe=null}let He=new Set(M.map(Se=>Se.id));for(let[Se,rt]of Q)He.has(Se)||(rt.remove(),Q.delete(Se));for(let Se=0;Se<M.length;Se++){let rt=M[Se];if(!Q.has(rt.id)){let Mt=bd(rt,Se,fe,g,te,xe,s,r);Q.set(rt.id,Mt),Ee.appendChild(Mt)}}}$.isFollowing()&&(Ee.scrollTop=Ee.scrollHeight)}function Ce(){if(Date.now()-B>=Rw){w!==null&&(cancelAnimationFrame(w),w=null),ke();return}H||(H=!0,w=requestAnimationFrame(()=>{w=null,ke()}))}let ce=(q,ee)=>{if(!pe)return;pe.innerHTML="";let ge=ie(q,"12px","currentColor",1.5);ge&&pe.appendChild(ge);let qe=v("span","persona-text-xs");qe.textContent="Copy All",pe.appendChild(qe),setTimeout(()=>{pe.innerHTML="";let fe=ie("clipboard-copy","12px","currentColor",1.5);fe&&pe.appendChild(fe);let Ie=v("span","persona-text-xs");Ie.textContent="Copy All",pe.appendChild(Ie),pe.disabled=!1},ee)},Ae=async()=>{if(pe){pe.disabled=!0;try{let q;nt()?q=M:n?(q=await n(),q.length===0&&(q=e.getAll())):q=e.getAll();let ee=q.map(ge=>{try{return JSON.parse(ge.payload)}catch{return ge.payload}});await navigator.clipboard.writeText(JSON.stringify(ee,null,2)),ce("check",1500)}catch{ce("x",1500)}}},En=()=>{Y&&(I=Y.value,Pe(),ke())},ae=()=>{!ne||!me||(me.style.display=ne.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{S=ne.value,Pe(),ke()},150))},k=()=>{!ne||!me||(ne.value="",S="",me.style.display="none",E&&clearTimeout(E),Pe(),ke())},W=()=>{if(N)return;let q=Ee.scrollTop,{action:ee,nextLastScrollTop:ge}=za({following:$.isFollowing(),currentScrollTop:q,lastScrollTop:K,nearBottom:ot(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});K=ge,ee==="resume"?($.resume(),F=0,Ve.style.display="none"):ee==="pause"&&($.pause(),p&&(bt.textContent=d,Ve.style.display=""))},h=q=>{let ee=Ua({following:$.isFollowing(),deltaY:q.deltaY,nearBottom:ot(),resumeWhenNearBottom:!0});ee==="pause"?($.pause(),p&&(bt.textContent=d,Ve.style.display="")):ee==="resume"&&($.resume(),F=0,Ve.style.display="none")},O=()=>{p&&(Ee.scrollTop=Ee.scrollHeight,$.resume(),F=0,Ve.style.display="none")},R=q=>{let ee=q.target;if(!ee||ee.closest("button"))return;let ge=ee.closest("[data-event-id]");if(!ge)return;let qe=ge.getAttribute("data-event-id");qe&&xe(qe)},_=q=>{if((q.metaKey||q.ctrlKey)&&q.key==="f"){q.preventDefault(),ne?.focus(),ne?.select();return}q.key==="Escape"&&(ne&&document.activeElement===ne?(k(),ne.blur(),C.focus()):o&&o())};pe&&pe.addEventListener("click",Ae),Y&&Y.addEventListener("change",En),ne&&ne.addEventListener("input",ae),me&&me.addEventListener("click",k),Ee.addEventListener("scroll",W),Ee.addEventListener("wheel",h,{passive:!0}),Ee.addEventListener("click",R),Ve.addEventListener("click",O),C.addEventListener("keydown",_);function Z(){E&&clearTimeout(E),w!==null&&(cancelAnimationFrame(w),w=null),H=!1,Q.clear(),pe&&pe.removeEventListener("click",Ae),Y&&Y.removeEventListener("change",En),ne&&ne.removeEventListener("input",ae),me&&me.removeEventListener("click",k),Ee.removeEventListener("scroll",W),Ee.removeEventListener("wheel",h),Ee.removeEventListener("click",R),Ve.removeEventListener("click",O),C.removeEventListener("keydown",_)}return{element:C,update:Ce,destroy:Z}}}Ye();xt();function Wm(t,e){let n=e.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";t.setAttribute("role","tablist");let s=[],i=!1,l=g=>{typeof g.scrollIntoView=="function"&&g.scrollIntoView({block:"nearest",inline:"nearest"})},p=g=>{let b=g;return s.findIndex(f=>f===b||f.contains(b))},c=g=>{let b=p(g.target);if(b<0)return;let f=b;if(g.key===r)f=Math.min(b+1,s.length-1);else if(g.key===o)f=Math.max(b-1,0);else if(g.key==="Home")f=0;else if(g.key==="End")f=s.length-1;else return;g.preventDefault(),f!==b&&e.onSelect(f)},d=g=>{let b=p(g.target);b>=0&&l(s[b])};return t.addEventListener("keydown",c),t.addEventListener("focusin",d),{beforeRender(){i=typeof document<"u"&&t.contains(document.activeElement)},render(g,b){if(s=g,g.forEach((f,y)=>{f.setAttribute("role","tab");let C=y===b;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||b<0&&y===0?0:-1}),i){let f=(b>=0?g[b]:void 0)??g[0];f&&typeof f.focus=="function"&&(l(f),f.focus())}},destroy(){t.removeEventListener("keydown",c),t.removeEventListener("focusin",d)}}}function Hm(t,e){let n=t.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",i=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),c=ae=>({start:ae===!1?!1:typeof ae=="object"&&ae?ae.start!==!1:!0,end:ae===!1?!1:typeof ae=="object"&&ae?ae.end!==!1:!0}),{start:d,end:g}=c(n?.tabFade),b=typeof document<"u"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,f=()=>{b?.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open"),N?.hide()};b&&b.addEventListener("click",()=>{f(),e.onDismiss?.()});let y=v("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");y.setAttribute("data-persona-theme-zone","artifact-pane"),r&&y.classList.add("persona-artifact-pane-document");let C=v("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");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let M=v("span","persona-text-xs persona-font-medium persona-truncate");M.textContent=s;let I=Dt({icon:"x",label:i});I.addEventListener("click",()=>{f(),e.onDismiss?.()});let S="rendered",E=Da({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:ae=>{S=ae==="source"?"source":"rendered",ce()}}),L=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=n?.documentToolbarShowCopyLabel===!0,z=n?.documentToolbarShowCopyChevron===!0,$=n?.documentToolbarCopyMenuItems,F=!!(z&&$&&$.length>0),B=null,H,w=null,N=null;if(r&&(D||z)&&!F){if(H=D?nr({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),z){let ae=ie("chevron-down",14,"currentColor",2);ae&&H.appendChild(ae)}}else r&&F?(B=v("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),H=D?nr({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),w=Dt({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"}}),B.append(H,w)):r?H=Dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(H=Dt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&H.classList.add("persona-hidden"));let K=r?Dt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Dt({icon:"refresh-cw",label:"Refresh"}),te=r?Dt({icon:"x",label:i,className:"persona-artifact-doc-icon-btn"}):Dt({icon:"x",label:i}),Q=Dt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&Q.classList.add("persona-hidden");let se=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),J=t.features?.artifacts?.toolbarActions??[],oe=()=>{let ae=Me.find(O=>O.id===Ee)??Me[Me.length-1],k=ae?.id??null,W=ae?.artifactType==="markdown"?ae.markdown??"":"",h=ae?JSON.stringify({component:ae.component,props:ae.props},null,2):"";return{markdown:W,jsonPayload:h,id:k}},Y=async()=>{let ae=Me.find(k=>k.id===Ee)??Me[Me.length-1];try{await navigator.clipboard.writeText(Js(ae))}catch{}};if(H.addEventListener("click",async()=>{let ae=n?.onDocumentToolbarCopyMenuSelect;if(ae&&F){let{markdown:k,jsonPayload:W,id:h}=oe();try{await ae({actionId:"primary",artifactId:h,markdown:k,jsonPayload:W})}catch{}return}await Y()}),w&&$?.length){let ae=()=>y.closest("[data-persona-root]")??document.body,k=()=>{N=jr({items:$.map(W=>({id:W.id,label:W.label})),onSelect:async W=>{let{markdown:h,jsonPayload:O,id:R}=oe(),_=n?.onDocumentToolbarCopyMenuSelect;try{_?await _({actionId:W,artifactId:R,markdown:h,jsonPayload:O}):W==="markdown"||W==="md"?await navigator.clipboard.writeText(h):W==="json"||W==="source"?await navigator.clipboard.writeText(O):await navigator.clipboard.writeText(h||O)}catch{}},anchor:B??w,position:"bottom-right",portal:ae()})};y.isConnected?k():requestAnimationFrame(k),w.addEventListener("click",W=>{W.stopPropagation(),N?.toggle()})}K.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}ce()}),te.addEventListener("click",()=>{f(),e.onDismiss?.()});let pe=v("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");if(r)C.replaceChildren(),B?L.append(B,K,te):L.append(H,K,te),L.insertBefore(se,te),L.insertBefore(Q,te),C.append(E.element,pe,L);else{let ae=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");ae.append(H,se,Q,I),C.appendChild(M),C.appendChild(ae)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let ne=v("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");p&&ne.style.setProperty("--persona-artifact-tab-fade-size",p);let me=t.features?.artifacts?.renderTabBar,ve=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),be=Wm(ne,{onSelect:ae=>e.onSelect(Me[ae].id)}),Te=ae=>{let k=ae.scrollWidth-ae.clientWidth,W=k>1,h=Math.abs(ae.scrollLeft);ae.classList.toggle("persona-artifact-tab-fade-start",d&&W&&h>1),ae.classList.toggle("persona-artifact-tab-fade-end",g&&W&&h<k-1)},ze=0,Oe=()=>{if(ze)return;let ae=()=>{ze=0,Te(ne)};ze=typeof requestAnimationFrame=="function"?requestAnimationFrame(ae):setTimeout(ae,0)};ne.addEventListener("scroll",()=>Oe(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Te(ne)).observe(ne);let Ne=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Be=()=>{Ne.scrollLeft=0},Ue=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Be):setTimeout(Be,0)};if(l){for(let ae of[ne,ve])ae.style.paddingLeft=l,ae.style.paddingRight=l;Ne.style.padding=l}y.appendChild(C),y.appendChild(ne),y.appendChild(ve),y.appendChild(Ne);let Me=[],Ee=null,Ve=!1,Jt=!1,bt=!0,Nt=!1,Mn=null,Tn="",nt=null,Pe=!1,xe=ae=>ae.artifactType==="markdown"&&!!ae.file||r?S:"rendered",ot=ae=>{r||(ae&&!Pe?(C.insertBefore(E.element,M),Pe=!0):!ae&&Pe&&(E.element.remove(),Pe=!1))},ke=()=>Ee&&Me.find(ae=>ae.id===Ee)||Me[Me.length-1],Ce=()=>{let ae=Xs(ke());if(!ae){se.replaceChildren();return}let k=J.filter(W=>W.visible===void 0||W.visible(ae)).map(W=>Vr(W,{documentChrome:r,onClick:()=>{let h=Xs(ke());if(h)try{Promise.resolve(W.onClick(h)).catch(()=>{})}catch{}}}));se.replaceChildren(...k)},ce=()=>{Ce();let ae=r&&Me.length<=1,k=!!me;if(ne.classList.toggle("persona-hidden",ae||k),ve.classList.toggle("persona-hidden",ae||!k),k&&me){let O=Me.map(R=>R.id).join("|")+" "+(Ee??"");if(O!==Tn){Tn=O;let R=me({records:Me,selectedId:Ee,onSelect:e.onSelect});ve.firstElementChild!==R&&ve.replaceChildren(R)}}else{be.beforeRender(),ne.replaceChildren();let O=[],R=-1;for(let[_,Z]of Me.entries()){let q=v("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");q.type="button";let ee=Z.artifactType==="markdown"?Z.file:void 0,ge=ee?Fn(ee.path):Z.title||Z.id.slice(0,8),qe=ee?.path||Z.title||ge;q.textContent=ge,q.title=qe,q.setAttribute("aria-label",qe),Z.id===Ee&&(q.classList.add("persona-bg-persona-container","persona-border-persona-border"),R=_),q.addEventListener("click",()=>e.onSelect(Z.id)),ne.appendChild(q),O.push(q)}if(be.render(O,R),R>=0&&Ee!==Mn){Mn=Ee;let _=O[R];typeof _.scrollIntoView=="function"&&_.scrollIntoView({block:"nearest",inline:"nearest"})}Te(ne)}let W=Ee&&Me.find(O=>O.id===Ee)||Me[Me.length-1];if(!W){Ne.replaceChildren(),nt=null,ot(!1);return}let h=W.artifactType==="markdown"?W.file:void 0;if(ot(!!h&&er(h)!=="other"),r){let O=h?Eo(h):W.artifactType==="markdown"?"MD":W.component??"Component",R=(W.title||"Document").trim(),_=h?Fn(h.path):R.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";pe.textContent=`${_} \xB7 ${O}`}else M.textContent=h?Fn(h.path):s;nt?(nt.el.parentElement!==Ne&&Ne.replaceChildren(nt.el),nt.update(W)):(nt=Fa(W,{config:t,resolveViewMode:xe}),Ne.replaceChildren(nt.el)),Ne.classList.toggle("persona-artifact-content-flush",!!Ne.querySelector(".persona-code-pre"))},Ae=()=>{let ae=Me.length>0;if(y.classList.toggle("persona-hidden",!ae),b){let h=((typeof y.closest=="function"?y.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;ae&&h&&Ve?(b.classList.remove("persona-hidden"),y.classList.add("persona-artifact-drawer-open")):(b.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open"))}},En=()=>{Nt=!1,ce(),Ae()};return{element:y,backdrop:b,update(ae){let k=ae.selectedId??ae.artifacts[ae.artifacts.length-1]?.id??null,W=k!==Ee;Me=ae.artifacts,Ee=k,Me.length>0&&(Ve=!0),Nt=!0,bt&&En(),W&&Be()},setMobileOpen(ae){Ve=ae,!ae&&b?(b.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open")):Ae()},setExpanded(ae){ae!==Jt&&(Jt=ae,Ue());let k=ie(ae?"minimize":"maximize",16,"currentColor",2);k&&Q.replaceChildren(k);let W=ae?"Collapse artifacts panel":"Expand artifacts panel";Q.setAttribute("aria-label",W),Q.title=W},setExpandToggleVisible(ae){Q.classList.toggle("persona-hidden",!ae)},setCopyButtonVisible(ae){r||H.classList.toggle("persona-hidden",!ae)},setCustomActions(ae){J=ae,Ce()},setTabFade(ae){let k=c(ae);k.start===d&&k.end===g||(d=k.start,g=k.end,Te(ne))},setRenderTabBar(ae){ae!==me&&(me=ae,Tn="",ce())},setVisible(ae){ae!==bt&&(bt=ae,ae&&Nt&&En())}}}function nn(t){return t?.features?.artifacts?.enabled===!0}function Bm(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!nn(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):r&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",r))}function zw(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var Dm=["panel","seamless","detached"];function yd(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&Dm.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function vd(t){return!t||!nn(t)?!1:yd(t)==="detached"}function gi(t,e){if(!nn(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-drawer-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),zw(t),Bm(t,e);return}let n=e.features?.artifacts?.layout,o=yd(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?t.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):t.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?t.style.setProperty("--persona-artifact-pane-padding",s):t.style.removeProperty("--persona-artifact-pane-padding");let i=n?.documentToolbarIconColor?.trim();i?t.style.setProperty("--persona-artifact-doc-toolbar-icon-color",i):t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let l=n?.documentToolbarToggleActiveBackground?.trim();l?t.style.setProperty("--persona-artifact-doc-toggle-active-bg",l):t.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?t.style.setProperty("--persona-artifact-doc-toggle-active-border",p):t.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Bm(t,e)}function fi(t,e){for(let l of Dm)t.classList.remove(`persona-artifact-appearance-${l}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!nn(e))return;let n=e.features?.artifacts?.layout,o=yd(e);t.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&t.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&t.style.setProperty("--persona-artifact-pane-shadow",s);let i=n?.chatShadow?.trim();i&&t.style.setProperty("--persona-artifact-chat-shadow",i)}function Om(t,e){return!e||!nn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var Uw=new Set(["__proto__","prototype","constructor"]),jw=new Set(["collapsed","card","panel","inline"]),Nm=new Set(["markdown","component"]),Vw=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,lr=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),pl=t=>!Uw.has(t),xd=t=>typeof t=="string"&&jw.has(t),cr=t=>Object.keys(t).length>0;function $n(t,e,n,o){t.push({path:e,code:n,message:o})}var qw="Ignored because this key is not part of the persisted preference schema.",dl="Ignored an unsupported value.",Kw="Expected collapsed, panel, or inline.",Gw='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Fm={kind:"mode",message:dl},Jr={kind:"string",message:"Expected a CSS length string."},so={kind:"boolean"},Qw={paneWidth:Jr,paneMaxWidth:Jr,paneMinWidth:Jr,expandedPanelWidth:Jr,resizableMinWidth:Jr,resizableMaxWidth:Jr,expandLauncherPanelWhenOpen:so,resizable:so},Xw={kind:"object",message:"Expected a preference object.",children:{showToolCalls:so,showReasoning:so,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:dl},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:dl},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:dl},expandable:so,grouped:so}},reasoningDisplay:{kind:"object",children:{expandable:so,activePreview:so}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Fm,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Fm,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Nm,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Nm}}},filePreview:{kind:"object",children:{enabled:so}},layout:{kind:"object",children:Qw}}}}};function _m(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:$n(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:$n(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:$n(o,n,"invalid_value",e.message);case"mode":return xd(t)?wn(t):$n(o,n,"invalid_value",e.message);case"modeMap":{if(!lr(t))return $n(o,n,"invalid_type","Expected an object.");let r=e.keys==="mediaType"?void 0:e.keys,s={};for(let[i,l]of Object.entries(t)){let p=r?i:Lr(i);pl(i)&&(r?r.has(i):Vw.test(p))?xd(l)?s[p]=wn(l):$n(o,`${n}.${i}`,"invalid_value",Kw):$n(o,`${n}.${i}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":Gw)}return cr(s)?s:void 0}case"object":{if(e.bareMode&&xd(t))return wn(t);if(!lr(t))return $n(o,n,"invalid_type",e.message??"Expected an object.");let r=Object.keys(e.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(t))(!pl(l)||!r.includes(l))&&$n(o,s(l),"unknown_key",qw);let i={};for(let l of r){let p=e.children[l],c=_m(t[l],p,s(l),o);if(p.deprecated&&t[l]!==void 0&&$n(o,s(l),"deprecated_key",p.deprecated),c===void 0)continue;let d=p.alias??l,g=i[d];i[d]=lr(g)&&lr(c)?{...g,...c}:c}return cr(i)?i:void 0}}}function Yw(t){let e=[];return{preferences:(t===null?void 0:_m(t,Xw,"",e))??{},issues:e}}function Zr(t){if(Array.isArray(t))return t.map(Zr);if(!lr(t))return t;let e={};for(let[n,o]of Object.entries(t))pl(n)&&o!==void 0&&(e[n]=Zr(o));return e}function $m(t,e){let n=Zr(t);for(let[o,r]of Object.entries(e)){if(!pl(o)||r===void 0)continue;let s=n[o];n[o]=lr(s)&&lr(r)?$m(s,r):Zr(r)}return n}function Jw(t){let e={},n;for(let r of t){let s=Yw(r).preferences;n=zm(n,s.artifacts?.display),e=$m(e,s)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function Zw(t,e){if(e===void 0)return t===void 0?void 0:Zr(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byMediaType,...e.byMediaType},s={...o?{default:o}:{},...cr(r)?{byMediaType:r}:{}};return cr(s)?s:void 0}function zm(t,e){if(e===void 0)return t===void 0?void 0:Zr(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byType,...n.byKind,...e.byType,...e.byKind},s=Zw(n.files,e.files),i={...o?{default:o}:{},...cr(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return cr(i)?i:void 0}function eC(t={},e){let n=Jw(e),o={...t};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...t.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...t.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=t.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let i=zm(r.display,n.artifacts.display);i!==void 0&&(s.display=i)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function wd(t){let e=t.preferences;return!e||!cr(e)?t:{...t,features:eC(t.features??{},[e])}}function tC(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function nC(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function oC(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function rC(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function Cd(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function Um(t,e,n,o,r,s){let i=tC(r,200),l=rC(e,n,o,200);l=Math.max(i,l);let p=nC(s);return p!==null&&(l=Math.min(l,p)),oC(t,i,l)}Ye();var jm={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"}},Ad=(t,e,n,o)=>{let r=t.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let i=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=jm[i]??jm.init;s.classList.add("persona-form-card","persona-space-y-4");let p=v("div","persona-space-y-1"),c=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=l.title,p.appendChild(c),l.description){let y=v("p","persona-text-sm persona-text-persona-muted");y.textContent=l.description,p.appendChild(y)}let d=document.createElement("form");d.className="persona-form-grid persona-space-y-3",l.fields.forEach(y=>{let C=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${e.id}-${i}-${y.name}`;let M=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=y.label,C.appendChild(M);let I=y.type??"text",S;I==="textarea"?(S=document.createElement("textarea"),S.rows=3):(S=document.createElement("input"),S.type=I),S.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",S.id=`${e.id}-${i}-${y.name}`,S.name=y.name,S.placeholder=y.placeholder??"",y.required&&(S.required=!0),C.appendChild(S),d.appendChild(C)});let g=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),b=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=v("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");f.type="submit",f.textContent=l.submitLabel??"Submit",g.appendChild(b),g.appendChild(f),d.appendChild(g),s.replaceChildren(p,d),d.addEventListener("submit",async y=>{y.preventDefault();let C=n.formEndpoint??"/form",M=new FormData(d),I={};M.forEach((S,E)=>{I[E]=S}),I.type=i,f.disabled=!0,b.textContent="Submitting\u2026";try{let S=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(I)});if(!S.ok)throw new Error(`Form submission failed (${S.status})`);let E=await S.json();b.textContent=E.message??"Thanks! We'll be in touch soon.",E.success&&E.nextPrompt&&await o.sendMessage(String(E.nextPrompt))}catch(S){b.textContent=S instanceof Error?S.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Sd=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...e].sort((s,i)=>(i.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},Md=new Sd;var Vm=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),sC=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),qm=(t,e,n)=>{if(!Vm(t)||!Vm(e)||sC.has(n))return e;let o={...t};for(let r of Object.keys(e)){if(e[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=qm(t[r],e[r],s)}return o};function Km(t,e){let n=qm(t,e,"");return La(n)}var Gm=()=>{let t=new Map,e=(r,s)=>(t.has(r)||t.set(r,new Set),t.get(r).add(s),()=>n(r,s)),n=(r,s)=>{t.get(r)?.delete(s)};return{on:e,off:n,emit:(r,s)=>{t.get(r)?.forEach(i=>{try{i(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var iC=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},aC=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<e.length;r+=1){let s=e[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return e.slice(n,r+1)}return null},Ed=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=iC(t),n=aC(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},Td=t=>typeof t=="string"?t:t==null?"":String(t),mi={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Td(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=Td(n.element);if(o&&e.document?.querySelector){let r=e.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:Td(n.text)}}},Qm=t=>Array.isArray(t)?t.map(e=>String(e)):[],kd=t=>{let e=new Set(Qm(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(Qm(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(e);t.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=i?t.parsers.reduce((c,d)=>c||d?.({text:i,message:s.message})||null,null):null;if(!l)return null;e.add(s.message.id),o();let p={action:l,message:s.message};t.emit("action:detected",p);for(let c of t.handlers)if(c)try{let d=()=>{t.emit("action:resubmit",p)},g=c(l,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:d});if(!g)continue;if(g.handled){let b=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:b,resubmit:g.resubmit}}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:n}};var lC=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},cC=t=>t.map(e=>({...e,streaming:!1})),dC=t=>t.map(e=>({...e,status:"complete"})),Xm=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?lC(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?cC(n.messages):void 0,artifacts:n.artifacts?dC(n.artifacts):void 0};o.setItem(t,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var Ld=require("partial-json");function Ym(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=oo.get(t.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null;let i={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(t.props,i)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,l),null}}function Jm(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Pd(t){let e=Jm(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Zm(t){let e=Jm(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var pC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function eh(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:p=!0,ratingLabels:c=pC}=t,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-csat",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Customer satisfaction feedback");let g=null,b=document.createElement("div");b.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=o,f.appendChild(y);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,f.appendChild(C),b.appendChild(f);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let I=[];for(let z=1;z<=5;z++){let $=document.createElement("button");$.type="button",$.className="persona-feedback-rating-btn persona-feedback-star-btn",$.setAttribute("role","radio"),$.setAttribute("aria-checked","false"),$.setAttribute("aria-label",`${z} star${z>1?"s":""}: ${c[z-1]}`),$.title=c[z-1],$.dataset.rating=String(z),$.innerHTML=`
1109
+ `,n.addEventListener("click",e);let o=s=>{let a=s.launcher??{},l=Kt(s),d=n.querySelector("[data-role='launcher-title']");if(d){let k=a.title??"Chat Assistant";d.textContent=k,d.setAttribute("title",k)}let p=n.querySelector("[data-role='launcher-subtitle']");if(p){let k=a.subtitle??"Here to help you get answers fast";p.textContent=k,p.setAttribute("title",k)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||l?u.style.display="none":u.style.display="");let g=n.querySelector("[data-role='launcher-icon']");if(g)if(a.agentIconHidden)g.style.display="none";else{let k=a.agentIconSize??"40px";if(g.style.height=k,g.style.width=k,a.agentIconBackgroundColor?(g.style.backgroundColor=a.agentIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),g.innerHTML="",a.agentIconName){let A=parseFloat(k)||24,D=fe(a.agentIconName,A*.6,"var(--persona-text-inverse, #ffffff)",1.5);D?(g.appendChild(D),g.style.display=""):(g.textContent=a.agentIconText??"\u{1F4AC}",g.style.display="")}else a.iconUrl?g.style.display="none":(g.textContent=a.agentIconText??"\u{1F4AC}",g.style.display="")}let b=n.querySelector("[data-role='launcher-image']");if(b){let k=a.agentIconSize??"40px";b.style.height=k,b.style.width=k,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(b.src=a.iconUrl,b.style.display="block"):b.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let k=a.callToActionIconSize??"32px";m.style.height=k,m.style.width=k,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 A=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,A=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=l?"none":"",m.innerHTML="",a.callToActionIconName){let D=parseFloat(k)||24,B=Math.max(D-A,8),I=fe(a.callToActionIconName,B,"currentColor",1.5);I?m.appendChild(I):m.textContent=a.callToActionIconText??"\u2197"}else m.textContent=a.callToActionIconText??"\u2197"}let y=a.position&&Un[a.position]?Un[a.position]:Un["bottom-right"],w="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-launcher persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",T="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-launcher persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=l?T:`${w} ${y}`,l||(n.style.zIndex=String(a.zIndex??mn));let W="1px solid var(--persona-launcher-border, var(--persona-border, #e5e7eb))",E="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??W,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:E,l?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",e),n.remove()};return t&&o(t),{element:n,update:o,destroy:r}},BT="teaser-dismissed",Mv=new Set,Av=t=>{let e=t?.persistState;return`${(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"}${BT}`},DT=(t,e)=>{if(Mv.has(t))return!0;if(!e)return!1;try{return window.localStorage.getItem(t)==="1"}catch{return!1}},NT=(t,e)=>{if(Mv.add(t),!!e)try{window.localStorage.setItem(t,"1")}catch{}},OT=()=>typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,_T=t=>{let e=t?.launcher?.teaser;return!e||!e.text||t?.launcher?.enabled===!1||Kt(t??{})?null:e},Tv=(t,e)=>{let n=v("div","persona-launcher-surface");n.setAttribute("data-persona-launcher-surface","true");let o=t??{},r=null,s=null,a=null,l=null,d=null,p=!1,u=!1,g=!1,b=!1,m=()=>(r?.frequency??"once")==="once"&&o.persistState!==!1,y=()=>{d!==null&&(clearTimeout(d),d=null)},w=()=>{!s||!p||(p=!1,s.hidden=!0)},T=he=>{y(),g=!0,w(),NT(Av(o),he&&m())},W=he=>{!r||g||T(he==="user"&&p)},E=()=>{d=null,!(!s||g||b)&&(u=!0,p=!0,s.hidden=!1,!(OT()||typeof s.animate!="function")&&s.animate([{opacity:"0",transform:"translateY(6px)"},{opacity:"1",transform:"none"}],{duration:220,easing:"ease-out",fill:"backwards"}))},k=()=>{!r||!s||g||u||b||DT(Av(o),m())||(y(),d=setTimeout(E,Math.max(0,r.delayMs??0)))},A=()=>{T(m()),e()},D=he=>{he.stopPropagation(),T(m())},I=sg(t,()=>{W("user"),e()}),N=()=>{y(),l?.removeEventListener("click",A),a?.removeEventListener("click",D),s?.remove(),s=null,l=null,a=null,p=!1},_=()=>{l=J("button",{className:"persona-launcher-teaser-text",attrs:{type:"button"}}),l.addEventListener("click",A),a=J("button",{className:"persona-launcher-teaser-dismiss",attrs:{type:"button"},text:"\xD7"}),a.addEventListener("click",D),s=J("div",{className:"persona-launcher-teaser",attrs:{"data-persona-launcher-teaser":"true",role:"status","aria-live":"polite",hidden:""}},l,a),n.insertBefore(s,I.element)},F=()=>{let he=o.launcher?.position??"bottom-right",ge=Un[he]??Un["bottom-right"];if(!s){n.className="persona-launcher-surface",n.removeAttribute("data-teaser"),n.style.zIndex="",I.element.style.position="";return}n.className=zt("persona-launcher-surface",ge),n.setAttribute("data-teaser",he),n.style.zIndex=String(o.launcher?.zIndex??mn),I.element.style.position="static"},P=he=>{let ge=_T(he);if(r=ge,!ge){N();return}s||_(),l.textContent=ge.text,a.hidden=ge.dismissible===!1,a.setAttribute("aria-label",ge.dismissLabel??"Dismiss message"),k()},V=he=>{o=he,I.update(he),P(he),F()},se=(he,ge="user")=>{b=he,he&&W(ge)},ve=()=>{N(),I.destroy(),n.remove()};return n.appendChild(I.element),t&&(P(t),F()),{element:n,launcher:I,get teaser(){return s?{element:s,show:E,dismiss:T}:null},setPanelOpen:se,update:V,destroy:ve}};var Ev=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=Cv(t),s=Sv(t,e),a={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,starterSuggestions:s.starterSuggestions,transcriptSuggestions:s.transcriptSuggestions,composerOverlay:s.composerOverlay,welcomeHost:s.welcomeHost,welcomeIconHolder:s.welcomeIconHolder,greetingHost:s.greetingHost,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},p={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:l,header:d,composer:p,replaceHeader:b=>(d.element.replaceWith(b.header),d.element=b.header,d.iconHolder=b.iconHolder,d.headerTitle=b.headerTitle,d.headerSubtitle=b.headerSubtitle,d.closeButton=b.closeButton,d.closeButtonWrapper=b.closeButtonWrapper,d.clearChatButton=b.clearChatButton,d.clearChatButtonWrapper=b.clearChatButtonWrapper,b),replaceComposer:b=>{p.footer.replaceWith(b),p.footer=b}}},ig=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>sg(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Tv(t,n);return{instance:r,element:r.element}};var FT=t=>{let e=t?.persistState;return(typeof e=="object"?e?.keyPrefix:void 0)??"persona-"},$T=(t,e,n)=>`${FT(t)}plugin:${e}:${n}`,kv=t=>{let e=new Map,n=!1,o=()=>{if(n||t()?.persistState===!1)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return n=!0,null}};return r=>{let s=a=>$T(t(),r,a);return{get:a=>{let l=s(a),d=o();if(d)try{return d.getItem(l)}catch{n=!0}return e.get(l)??null},set:(a,l)=>{let d=s(a),p=o();if(p)try{p.setItem(d,l);return}catch{n=!0}e.set(d,l)},remove:a=>{let l=s(a);e.delete(l);let d=o();if(d)try{d.removeItem(l)}catch{n=!0}}}}};Qe();Rt();var ri=new Set,zT=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),VT=(t,e)=>{let n=t.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,e).join(`
1110
+ `):""},Pv=(t,e)=>{let n=ri.has(t),o=e.querySelector('button[data-expand-header="true"]'),r=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let l=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let p=fe(n?"chevron-up":"chevron-down",16,"currentColor",2);p?l.appendChild(p):l.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},ag=(t,e)=>{let n=t.reasoning,o=v("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.id),!n)return o;let r=e?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&ri.has(t.id),l=n.status!=="complete",d=VT(t,r.previewMaxLines??3),p=v("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");p.type="button",s&&(p.setAttribute("aria-expanded",a?"true":"false"),p.setAttribute("data-expand-header","true")),p.setAttribute("data-bubble-type","reasoning");let u=v("div","persona-flex persona-flex-col persona-text-left"),g=v("span","persona-text-xs persona-text-persona-primary"),b="Thinking...",m=e?.reasoning??{},y=String(n.startedAt??Date.now()),w=()=>{let ve=v("span","");return ve.setAttribute("data-tool-elapsed",y),ve.textContent=ic(n),ve},T=m.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:b,previewText:d,isActive:l,config:e??{},elapsed:ic(n),createElapsedElement:w});typeof T=="string"&&T.trim()?(g.textContent=T,u.appendChild(g)):T instanceof HTMLElement?u.appendChild(T):(g.textContent=b,u.appendChild(g));let W=v("span","persona-text-xs persona-text-persona-primary");W.textContent=Vh(n),u.appendChild(W);let E=r.loadingAnimation??"none",k=m.activeTextTemplate,A=m.completeTextTemplate,D=l?k:A,B=T instanceof HTMLElement,I=(ve,he)=>{g.textContent="";let ge=ac(ve,""),re=0;for(let oe of ge){let ee=oe.styles.length>0?(()=>{let M=v("span",oe.styles.map(te=>`persona-tool-text-${te}`).join(" "));return g.appendChild(M),M})():g;if(oe.isDuration&&l)ee.appendChild(w());else{let M=oe.isDuration?ic(n):oe.text;he?re=vr(ee,M,re):ee.appendChild(document.createTextNode(M))}}};if(!B&&D)if(W.style.display="none",g.style.display="",l&&E!=="none"){let ve=m.loadingAnimationDuration??2e3;g.setAttribute("data-preserve-animation","true"),E==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${ve}ms`),I(D,!1)):(g.classList.add(`persona-tool-loading-${E}`),g.style.setProperty("--persona-tool-anim-duration",`${ve}ms`),E==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),I(D,!0))}else I(D,!1);else if(!B&&l&&E!=="none"){g.style.display="";let ve=m.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),E==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${ve}ms`);else{g.classList.add(`persona-tool-loading-${E}`),g.style.setProperty("--persona-tool-anim-duration",`${ve}ms`),E==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let he=g.textContent||b;g.textContent="",vr(g,he,0)}n.status==="complete"&&(g.style.display="none")}else B||(n.status==="complete"?g.style.display="none":g.style.display="");let N=null;if(s){N=v("div","persona-flex persona-items-center");let he=fe(a?"chevron-up":"chevron-down",16,"currentColor",2);he?N.appendChild(he):N.textContent=a?"Hide":"Show";let ge=v("div","persona-flex persona-items-center persona-ml-auto");ge.append(N),p.append(u,ge)}else p.append(u);let _=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(_.setAttribute("data-persona-collapsed-preview","reasoning"),_.style.display="none",_.style.whiteSpace="pre-wrap",!a&&l&&r.activePreview&&d){let ve=e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:n,defaultPreview:d,isActive:l,config:e??{}});zT(_,ve)||(_.textContent=d),_.style.display=""}if(!a&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(p,_),o;let F=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");F.style.display=a?"":"none";let P=n.chunks.join(""),V=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return V.textContent=P||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),F.appendChild(V),(()=>{if(p.setAttribute("aria-expanded",a?"true":"false"),N){N.innerHTML="";let he=fe(a?"chevron-up":"chevron-down",16,"currentColor",2);he?N.appendChild(he):N.textContent=a?"Hide":"Show"}F.style.display=a?"":"none",_.style.display=a?"none":_.textContent||_.childNodes.length?"":"none"})(),o.append(p,_,F),o};Qe();Rt();var si=new Set,jT=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),qT=(t,e)=>{let n=t.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-e).join(`
1111
+ `);let r=mr(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
1112
+ `):""},lg=(t,e)=>{t.style.backgroundColor=e.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",t.style.borderColor=e.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",t.style.color=e.codeBlockTextColor??"var(--persona-text, #171717)"},UT=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=qT(t,o?.previewMaxLines??3),a=n?jh(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let l=n.status!=="complete",d=e?.toolCall??{},p=a;return r==="tool-name"?p=n.name?.trim()||a:r==="tool-preview"&&s&&(p=s),l&&d.activeTextTemplate?p=ru(n,d.activeTextTemplate,p):!l&&d.completeTextTemplate&&(p=ru(n,d.completeTextTemplate,p)),{summary:p,previewText:s,isActive:l}},Lv=(t,e,n)=>{let o=si.has(t),r=n?.toolCall??{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),l=e.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let p=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(p){p.innerHTML="";let u=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",g=fe(o?"chevron-up":"chevron-down",16,u,2);g?p.appendChild(g):p.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},cg=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=v("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${t.id}`,r.setAttribute("data-message-id",t.id),o.backgroundColor&&(r.style.backgroundColor=o.backgroundColor),o.borderColor&&(r.style.borderColor=o.borderColor),o.borderWidth&&(r.style.borderWidth=o.borderWidth),o.borderRadius&&(r.style.borderRadius=o.borderRadius),r.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return r;let s=e?.features?.toolCallDisplay??{},a=s.expandable!==!1,l=a&&si.has(t.id),{summary:d,previewText:p,isActive:u}=UT(t,e),g=v("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");g.type="button",a&&(g.setAttribute("aria-expanded",l?"true":"false"),g.setAttribute("data-expand-header","true")),g.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(g.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(g.style.paddingLeft=o.headerPaddingX,g.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(g.style.paddingTop=o.headerPaddingY,g.style.paddingBottom=o.headerPaddingY);let b=v("div","persona-flex persona-flex-col persona-text-left"),m=v("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let y=String(n.startedAt??Date.now()),w=()=>{let P=v("span","");return P.setAttribute("data-tool-elapsed",y),P.textContent=oa(n),P},T=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:d,previewText:p,collapsedMode:s.collapsedMode??"tool-call",isActive:u,config:e??{},elapsed:oa(n),createElapsedElement:w});typeof T=="string"&&T.trim()?(m.textContent=T,b.appendChild(m)):T instanceof HTMLElement?b.appendChild(T):(m.textContent=d,b.appendChild(m));let W=s.loadingAnimation??"none",E=o.activeTextTemplate,k=o.completeTextTemplate,A=u?E:k,D=T instanceof HTMLElement,B=(P,V)=>{m.textContent="";let se=n.name?.trim()||"tool",ve=ac(P,se),he=0;for(let ge of ve){let re=ge.styles.length>0?(()=>{let oe=v("span",ge.styles.map(ee=>`persona-tool-text-${ee}`).join(" "));return m.appendChild(oe),oe})():m;if(ge.isDuration&&u)re.appendChild(w());else{let oe=ge.isDuration?oa(n):ge.text;V?he=vr(re,oe,he):re.appendChild(document.createTextNode(oe))}}};if(!D)if(u&&W!=="none"){let P=o.loadingAnimationDuration??2e3;if(m.setAttribute("data-preserve-animation","true"),W==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${P}ms`),A&&B(A,!1);else if(m.classList.add(`persona-tool-loading-${W}`),m.style.setProperty("--persona-tool-anim-duration",`${P}ms`),W==="shimmer-color"&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),A)B(A,!0);else{let V=m.textContent||d;m.textContent="",vr(m,V,0)}}else A&&B(A,!1);let I=null;if(a){I=v("div","persona-flex persona-items-center");let P=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",V=fe(l?"chevron-up":"chevron-down",16,P,2);V?I.appendChild(V):I.textContent=l?"Hide":"Show";let se=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");se.append(I),g.append(b,se)}else g.append(b);let N=v("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",!l&&u&&s.activePreview&&p){let P=o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:p,isActive:u,config:e??{}});jT(N,P)||(N.textContent=p),N.style.display=""}if(!l&&u&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(g,N),r;let _=v("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(_.style.display=l?"":"none",o.contentBackgroundColor&&(_.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(_.style.color=o.contentTextColor),o.contentPaddingX&&(_.style.paddingLeft=o.contentPaddingX,_.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(_.style.paddingTop=o.contentPaddingY,_.style.paddingBottom=o.contentPaddingY),n.name){let P=v("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?P.style.color=o.contentTextColor:o.headerTextColor&&(P.style.color=o.headerTextColor),P.textContent=n.name,_.appendChild(P)}if(n.args!==void 0){let P=v("div","persona-space-y-1"),V=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(V.style.color=o.labelTextColor),V.textContent="Arguments";let se=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",lg(se,o),se.textContent=mr(n.args),P.append(V,se),_.appendChild(P)}if(n.chunks&&n.chunks.length){let P=v("div","persona-space-y-1"),V=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(V.style.color=o.labelTextColor),V.textContent="Activity";let se=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",lg(se,o),se.textContent=n.chunks.join(""),P.append(V,se),_.appendChild(P)}if(n.status==="complete"&&n.result!==void 0){let P=v("div","persona-space-y-1"),V=v("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(V.style.color=o.labelTextColor),V.textContent="Result";let se=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",lg(se,o),se.textContent=mr(n.result),P.append(V,se),_.appendChild(P)}if(n.status==="complete"&&typeof n.duration=="number"){let P=v("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(P.style.color=o.contentTextColor),P.textContent=`Duration: ${n.duration}ms`,_.appendChild(P)}return(()=>{if(g.setAttribute("aria-expanded",l?"true":"false"),I){I.innerHTML="";let P=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",V=fe(l?"chevron-up":"chevron-down",16,P,2);V?I.appendChild(V):I.textContent=l?"Hide":"Show"}_.style.display=l?"":"none",N.style.display=l?"none":N.textContent||N.childNodes.length?"":"none"})(),r.append(g,N,_),r};Qe();Rt();var ns=new Map,yd=t=>{let n=(t.startsWith(Vo)?t.slice(Vo.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Iv=t=>t?.approval!==!1?t?.approval:void 0,Hv=(t,e)=>{let n=Iv(e)?.detailsDisplay??"collapsed";return ns.get(t)??n==="expanded"},Rv=(t,e,n)=>{let o=Iv(n);t.setAttribute("aria-expanded",e?"true":"false");let r=t.querySelector("[data-approval-details-label]");r&&(r.textContent=e?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=fe(e?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},Wv=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=Hv(t,n);Rv(o,s,n),r.style.display=s?"":"none"};var bd=(t,e)=>{let n=t.approval,o=e?.approval!==!1?e?.approval:void 0,r=n?.status==="pending",s=v("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${t.id}`,s.setAttribute("data-message-id",t.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=v("div","persona-flex-shrink-0 persona-mt-0.5");l.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",p=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":o?.titleColor??"currentColor",u=fe(d,20,p,2);u&&l.appendChild(u);let g=v("div","persona-flex-1 persona-min-w-0"),b=v("div","persona-flex persona-items-center persona-gap-2"),m=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(m.style.color=o.titleColor),m.textContent=o?.title??"Approval Required",b.appendChild(m),!r){let I=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");I.setAttribute("data-approval-status",n.status),n.status==="approved"?(I.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",I.style.color="var(--persona-palette-colors-success-700, #15803d)",I.textContent="Approved"):n.status==="denied"?(I.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",I.style.color="var(--persona-palette-colors-error-700, #b91c1c)",I.textContent="Denied"):n.status==="timeout"&&(I.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",I.style.color="var(--persona-palette-colors-warning-700, #b45309)",I.textContent="Timeout"),b.appendChild(I)}g.appendChild(b);let w=n.toolType==="webmcp"||n.toolName.startsWith(Vo)?Qi(n.toolName):void 0,T=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...w?{displayTitle:w}:{},...n.reason?{reason:n.reason}:{}}),W=!n.toolName,E=T||(W?n.description:`The assistant wants to use \u201C${w??yd(n.toolName)}\u201D.`),k=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(k.style.color=o.descriptionColor),k.textContent=E,g.appendChild(k),n.reason){let I=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");I.setAttribute("data-approval-reason","true"),o?.reasonColor?I.style.color=o.reasonColor:o?.descriptionColor&&(I.style.color=o.descriptionColor);let N=v("span","persona-font-medium");N.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,I.appendChild(N),I.appendChild(document.createTextNode(n.reason)),g.appendChild(I)}let A=o?.detailsDisplay??"collapsed",D=!!n.description&&!W,B=D||!!n.parameters;if(A!=="hidden"&&B){let I=Hv(t.id,e),N=v("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");N.type="button",N.setAttribute("data-expand-header","true"),N.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(N.style.color=o.descriptionColor);let _=v("span");_.setAttribute("data-approval-details-label","true");let F=v("span","persona-inline-flex persona-items-center");F.setAttribute("data-approval-details-chevron","true"),N.append(_,F),Rv(N,I,e),g.appendChild(N);let P=v("div");if(P.setAttribute("data-approval-details","true"),P.style.display=I?"":"none",D){let V=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(V.style.color=o.descriptionColor),V.textContent=n.description,P.appendChild(V)}if(n.parameters){let V=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o?.parameterBackgroundColor&&(V.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(V.style.color=o.parameterTextColor),V.style.fontSize="0.75rem",V.style.lineHeight="1rem",V.textContent=mr(n.parameters),P.appendChild(V)}g.appendChild(P)}if(r){let I=v("div","persona-flex persona-gap-2 persona-mt-2");I.setAttribute("data-approval-buttons","true");let N=v("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");N.type="button",N.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",N.style.color=o?.approveButtonTextColor??"#ffffff",N.setAttribute("data-approval-action","approve");let _=fe("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);_&&(_.style.marginRight="4px",N.appendChild(_));let F=document.createTextNode(o?.approveLabel??"Approve");N.appendChild(F);let P=v("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");P.type="button",P.style.backgroundColor=o?.denyButtonColor??"transparent",P.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",P.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,P.setAttribute("data-approval-action","deny");let V=fe("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);V&&(V.style.marginRight="4px",P.appendChild(V));let se=document.createTextNode(o?.denyLabel??"Deny");P.appendChild(se),I.append(N,P),g.appendChild(I)}return a.append(l,g),s.appendChild(a),s};Qe();Rt();Ec();var KT=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Bv=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let o=t.popovers.get(e);o&&(o.destroy(),t.popovers.delete(e))},os=(t,e)=>{Bv(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},GT=t=>t?.approval!==!1?t?.approval:void 0,YT=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return ns.get(t)??n==="expanded"},dg=t=>{let e=v("span","persona-approval-kbd");return e.textContent=t,e},XT=(t,e)=>{let n=v("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(Vo)?Qi(t.toolName):void 0,s=e?.formatDescription?.({toolName:t.toolName,toolType:t.toolType,description:t.description??"",parameters:t.parameters,...r?{displayTitle:r}:{},...t.reason?{reason:t.reason}:{}});if(s)return n.textContent=s,n;let a=r??yd(t.toolName),l=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),l){n.append(" from ");let p=document.createElement("strong");p.textContent=l,n.appendChild(p)}return n},QT=t=>{let e=v("div","persona-approval-resolved"),n=fe("ban",15,"currentColor",2);n&&e.appendChild(n);let o=v("span","persona-approval-resolved-name");return o.textContent=t.toolName?yd(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},JT=(t,e,n,o,r,s,a)=>{let l=v("div","persona-approval-card persona-shadow-sm");l.id=`bubble-${e.id}`,l.setAttribute("data-message-id",e.id),l.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(l.style.background=o.backgroundColor),o?.borderColor&&(l.style.borderColor=o.borderColor),o?.shadow!==void 0&&(l.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let d=o?.detailsDisplay??"collapsed",p=!!n.description&&d!=="hidden",u=n.parameters!=null&&d!=="hidden",g=p||u,b=g&&YT(e.id,o),m=o?.showDetailsLabel??"Show details",y=o?.hideDetailsLabel??"Hide details",w=v("button","persona-approval-head");w.type="button",g?(w.setAttribute("data-action","toggle-params"),w.setAttribute("aria-expanded",b?"true":"false"),w.setAttribute("aria-label",b?y:m)):w.setAttribute("data-static","true");let T=v("span","persona-approval-logo"),W=fe("shield-check",16,"currentColor",2);W&&T.appendChild(W),w.appendChild(T);let E=XT(n,o);if(g){let N=v("span","persona-approval-toggle");N.setAttribute("aria-hidden","true");let _=fe("chevron-down",14,"currentColor",2);_&&N.appendChild(_),E.append(" "),E.appendChild(N)}w.appendChild(E),l.appendChild(w);let k=v("div","persona-approval-body");if(g){let N=v("div","persona-approval-details");if(N.setAttribute("data-role","params"),N.hidden=!b,p){let _=v("p","persona-approval-desc");o?.descriptionColor&&(_.style.color=o.descriptionColor),_.textContent=n.description,N.appendChild(_)}if(u){let _=v("pre","persona-approval-params");o?.parameterBackgroundColor&&(_.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(_.style.color=o.parameterTextColor),_.textContent=mr(n.parameters),N.appendChild(_)}k.appendChild(N)}if(n.reason){let N=v("p","persona-approval-reason");o?.reasonColor?N.style.color=o.reasonColor:o?.descriptionColor&&(N.style.color=o.descriptionColor);let _=v("span","persona-approval-reason-label");_.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,N.append(_,document.createTextNode(n.reason)),k.appendChild(N)}let A=v("div","persona-approval-actions"),D=null,B=N=>{o?.approveButtonColor&&(N.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(N.style.color=o.approveButtonTextColor)},I=v("button","persona-approval-deny");if(I.type="button",I.setAttribute("data-action","deny"),o?.denyButtonColor&&(I.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(I.style.color=o.denyButtonTextColor),I.append(o?.denyLabel??"Deny"),a){let N=v("div","persona-approval-split"),_=v("button","persona-approval-primary");_.type="button",_.setAttribute("data-action","always"),B(_),_.append(o?.approveLabel??"Always allow",dg("\u23CE"));let F=v("button","persona-approval-caret");F.type="button",F.setAttribute("data-action","toggle-menu"),F.setAttribute("aria-label","More options"),B(F);let P=fe("chevron-down",15,"currentColor",2);P&&F.appendChild(P),N.append(_,F),A.append(N,I),I.append(dg("Esc"));let V=v("div","persona-approval-menu"),se=v("button","persona-approval-menu-item");se.type="button",se.append("Allow once",dg("\u2318\u23CE")),V.appendChild(se),D=Tc({anchor:N,content:V,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,D),se.addEventListener("click",()=>{os(t,e.id),r()})}else{let N=v("button","persona-approval-primary persona-approval-primary--solo");N.type="button",N.setAttribute("data-action","allow"),B(N),N.append(o?.approveLabel??"Allow"),A.append(N,I)}return k.appendChild(A),l.appendChild(k),l.addEventListener("click",N=>{let _=N.target instanceof Element?N.target.closest("[data-action]"):null;if(!_)return;let F=_.getAttribute("data-action");if(F==="toggle-params"){let P=l.querySelector('[data-role="params"]');if(P){let V=P.hidden;P.hidden=!V,w.setAttribute("aria-expanded",V?"true":"false"),w.setAttribute("aria-label",V?y:m),ns.set(e.id,V)}return}if(F==="toggle-menu"){D?.toggle();return}if(F==="always"){os(t,e.id),r({remember:!0});return}if(F==="allow"){os(t,e.id),r();return}if(F==="deny"){os(t,e.id),s();return}}),l},Dv=()=>{let t=KT();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let l=o?.approval;if(!l)return null;let d=GT(a);if(l.status!=="pending"){if(os(t,o.id),l.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return QT(l)}Bv(t,o.id);let p=d?.enableAlwaysAllow===!0,u=JT(t,o,l,d,r,s,p);if(p){t.pendingOrder.includes(o.id)||t.pendingOrder.push(o.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let g=b=>{Vy(b)||o.id===t.latestPendingApprovalId&&(b.key!=="Escape"&&b.key!=="Enter"||(b.preventDefault(),b.stopImmediatePropagation(),os(t,o.id),b.key==="Escape"?s():b.metaKey||b.ctrlKey?r():r({remember:!0})))};t.keyHandlers.set(o.id,g),document.addEventListener("keydown",g)}return u}},teardown:()=>{for(let o of[...t.keyHandlers.keys(),...t.popovers.keys()])os(t,o);t.latestPendingApprovalId=null}}};var Oa=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){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),this.store?.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 n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let o of n)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.clear()}destroy(){this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),this.store?.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var _a=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,n)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let r=o.result;r.objectStoreNames.contains(this.storeName)||r.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}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 o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}getAll(){return new Promise((e,n)=>{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=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((e,n)=>{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=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((e,n)=>{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=()=>{n(s.error)}}catch(o){n(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{e()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of e)o.put(r)}catch{}}};var ZT=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),eE=new Set(["step_start","execution_start"]),tE=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),nE=new Set(["step_complete","agent_turn_complete"]),oE=new Set(["flow_complete","agent_complete"]),Nv=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),_v=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Kn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,rs=(t,e)=>{let n=t[e];return _v(n)?n:void 0};function pg(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function vd(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function rE(t,e){return typeof e.type=="string"?e.type:t}function sE(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function iE(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function Ov(t){let e=rs(t,"result"),n=[rs(t,"tokens"),rs(t,"totalTokens"),e?rs(e,"tokens"):void 0,rs(t,"usage"),e?rs(e,"usage"):void 0];for(let o of n){if(!o)continue;let r=Kn(o.output)??Kn(o.outputTokens)??Kn(o.completionTokens);if(r!==void 0)return r}return Kn(t.outputTokens)??Kn(t.completionTokens)??(e?Kn(e.outputTokens)??Kn(e.completionTokens):void 0)}function aE(t){let e=rs(t,"result");return Kn(t.executionTime)??Kn(t.executionTimeMs)??Kn(t.execution_time)??Kn(t.duration)??(e?Kn(e.executionTime)??Kn(e.executionTimeMs):void 0)}function lE(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Fa=class{constructor(e=lE){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 n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:vd(this.metric.outputTokens,n)}}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,n){if(!_v(n)){Nv.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=rE(e,n),r=this.now();if(ZT.has(o)){this.startRun(r);return}if(eE.has(o)){this.run||this.startRun(r);return}if(tE.has(o)){if(!iE(o,n))return;let s=sE(n);if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let l=a.exactOutputTokens+pg(a.visibleCharCount),d=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:vd(l,d),outputTokens:l,durationMs:d,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(nE.has(o)){if(!this.run)return;let s=this.run,a=Ov(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let l=s.exactOutputTokens>0,d=s.exactOutputTokens+pg(s.visibleCharCount),p=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:vd(d,p),outputTokens:d,durationMs:p,source:l?"usage":"estimate"};return}if(oE.has(o)){if(!this.run)return;let s=this.run,a=Ov(n),l=a??s.exactOutputTokens+pg(s.visibleCharCount),d=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:vd(l,p),outputTokens:l,durationMs:p,source:d},this.run=null;return}if(Nv.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,o){let r=e.firstDeltaAt!==void 0?o-e.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:aE(n)??o-e.startedAt}};var{setLoader:cW,load:xE}=Co({fallbackImport:()=>Promise.resolve().then(()=>(Vv(),zv))});var jv=xE;Qe();Rt();function qv(t,e){let n=e.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";t.setAttribute("role","tablist");let s=[],a=!1,l=g=>{typeof g.scrollIntoView=="function"&&g.scrollIntoView({block:"nearest",inline:"nearest"})},d=g=>{let b=g;return s.findIndex(m=>m===b||m.contains(b))},p=g=>{let b=d(g.target);if(b<0)return;let m=b;if(g.key===r)m=Math.min(b+1,s.length-1);else if(g.key===o)m=Math.max(b-1,0);else if(g.key==="Home")m=0;else if(g.key==="End")m=s.length-1;else return;g.preventDefault(),m!==b&&e.onSelect(m)},u=g=>{let b=d(g.target);b>=0&&l(s[b])};return t.addEventListener("keydown",p),t.addEventListener("focusin",u),{beforeRender(){a=typeof document<"u"&&t.contains(document.activeElement)},render(g,b){if(s=g,g.forEach((m,y)=>{m.setAttribute("role","tab");let w=y===b;m.setAttribute("aria-selected",w?"true":"false"),m.tabIndex=w||b<0&&y===0?0:-1}),a){let m=(b>=0?g[b]:void 0)??g[0];m&&typeof m.focus=="function"&&(l(m),m.focus())}},destroy(){t.removeEventListener("keydown",p),t.removeEventListener("focusin",u)}}}function Uv(t,e){let n=t.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",l=n?.panePadding?.trim(),d=n?.tabFadeSize?.trim(),p=S=>({start:S===!1?!1:typeof S=="object"&&S?S.start!==!1:!0,end:S===!1?!1:typeof S=="object"&&S?S.end!==!1:!0}),{start:u,end:g}=p(n?.tabFade),b=typeof document<"u"?v("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,m=()=>{b?.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open"),P?.closeMenu()};b&&b.addEventListener("click",()=>{m(),e.onDismiss?.()});let y=v("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");y.setAttribute("data-persona-theme-zone","artifact-pane"),r&&y.classList.add("persona-artifact-pane-document");let w=v("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");w.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&w.classList.add("persona-artifact-toolbar-document");let T=v("span","persona-text-xs persona-font-medium persona-truncate");T.textContent=s;let W=en({icon:"x",label:a});W.addEventListener("click",()=>{m(),e.onDismiss?.()});let E="rendered",k=Kc({items:[{id:"rendered",icon:"eye",label:"Rendered view",className:r?"persona-artifact-doc-icon-btn persona-artifact-view-btn":void 0},{id:"source",icon:"code-xml",label:"Source",className:r?"persona-artifact-doc-icon-btn persona-artifact-code-btn":void 0}],selectedId:"rendered",className:"persona-artifact-toggle-group persona-shrink-0",onSelect:S=>{E=S==="source"?"source":"rendered",j()}}),A=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),D=n?.documentToolbarShowCopyLabel===!0,B=n?.documentToolbarShowCopyChevron===!0,I=n?.documentToolbarCopyMenuItems,N=!!(B&&I&&I.length>0),_=null,F,P=null;if(r&&(D||B)&&!N){if(F=D?Jr({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):en({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),B){let S=fe("chevron-down",14,"currentColor",2);S&&F.appendChild(S)}}else r&&N?(P=Nb({label:"Copy",icon:"copy",iconSize:14,iconOnly:!D,primaryClassName:"persona-artifact-doc-copy-btn",chevronLabel:"More copy options",chevronClassName:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",menuItems:(I??[]).map(S=>({id:S.id,label:S.label})),position:"bottom-right",portal:()=>y.closest("[data-persona-root]")??document.body,onSelect:S=>{Se(S)}}),_=P.element,F=P.primaryButton):r?F=en({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(F=en({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&F.classList.add("persona-hidden"));let V=r?en({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):en({icon:"refresh-cw",label:"Refresh"});n?.onDocumentToolbarRefresh||V.classList.add("persona-hidden");let se=r?en({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):en({icon:"x",label:a}),ve=en({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&ve.classList.add("persona-hidden");let he=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ge=t.features?.artifacts?.toolbarActions??[],re=()=>{let S=Ee.find(Z=>Z.id===$e)??Ee[Ee.length-1],O=S?.id??null,R=S?.artifactType==="markdown"?S.markdown??"":"",$=S?JSON.stringify({component:S.component,props:S.props},null,2):"",{filename:K,mime:Y,content:Q}=Vc({title:S?.title,markdown:S?.markdown??"",file:S?.file});return{markdown:R,jsonPayload:$,id:O,file:S?.file,suggestedFilename:K,mime:Y,content:Q}},oe=()=>{let{suggestedFilename:S,mime:O,content:R}=re();R&&jc({filename:S,mime:O,content:R})},ee=S=>{let{id:O,...R}=re();return{actionId:S,artifactId:O,...R}},M=async()=>{let S=Ee.find(O=>O.id===$e)??Ee[Ee.length-1];try{return await navigator.clipboard.writeText(Ta(S)),!0}catch{return!1}},te=null,pe=()=>{te?.();let S=F.querySelector("svg"),O=Number(S?.getAttribute("width"))||16,R=fe("check",O,"currentColor",2);if(!S||!R)return;S.replaceWith(R);let $=F.querySelector("span");$&&($.textContent="Copied");let K=setTimeout(()=>te?.(),2e3);te=()=>{clearTimeout(K),R.replaceWith(S),$&&($.textContent="Copy"),te=null}};F.addEventListener("click",async()=>{let S=n?.onDocumentToolbarCopyMenuSelect;if(S&&N){try{if(await S(ee("primary"))===!1){await M()&&pe();return}pe()}catch{}return}await M()&&pe()});async function Se(S){let O=n?.onDocumentToolbarCopyMenuSelect;try{if(O&&await O(ee(S))!==!1)return;if(S==="download"){oe();return}let{markdown:R,jsonPayload:$}=re();S==="markdown"||S==="md"?await navigator.clipboard.writeText(R):S==="json"||S==="source"?await navigator.clipboard.writeText($):await navigator.clipboard.writeText(R||$),pe()}catch{}}V.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}j()}),se.addEventListener("click",()=>{m(),e.onDismiss?.()});let xe=v("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");if(r)w.replaceChildren(),_?A.append(_,V,se):A.append(F,V,se),A.insertBefore(he,se),A.insertBefore(ve,se),w.append(k.element,xe,A);else{let S=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");S.append(F,he,ve,W),w.appendChild(T),w.appendChild(S)}l&&(w.style.paddingLeft=l,w.style.paddingRight=l);let Ce=v("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");d&&Ce.style.setProperty("--persona-artifact-tab-fade-size",d);let Me=t.features?.artifacts?.renderTabBar,ke=v("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),Oe=qv(Ce,{onSelect:S=>e.onSelect(Ee[S].id)}),ze=S=>{let O=S.scrollWidth-S.clientWidth,R=O>1,$=Math.abs(S.scrollLeft);S.classList.toggle("persona-artifact-tab-fade-start",u&&R&&$>1),S.classList.toggle("persona-artifact-tab-fade-end",g&&R&&$<O-1)},qe=0,nt=()=>{if(qe)return;let S=()=>{qe=0,ze(Ce)};qe=typeof requestAnimationFrame=="function"?requestAnimationFrame(S):setTimeout(S,0)};Ce.addEventListener("scroll",()=>nt(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>ze(Ce)).observe(Ce);let De=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Ue=()=>{De.scrollLeft=0},an=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Ue):setTimeout(Ue,0)};if(l){for(let S of[Ce,ke])S.style.paddingLeft=l,S.style.paddingRight=l;De.style.padding=l}y.appendChild(w),y.appendChild(Ce),y.appendChild(ke),y.appendChild(De);let Ee=[],$e=null,mt=!1,At=!1,yt=!0,Wt=!1,Te=null,ot="",lt=null,kt=!1,wn=S=>S.artifactType==="markdown"&&!!S.file||r?E:"rendered",Ct=S=>{r||(S&&!kt?(w.insertBefore(k.element,T),kt=!0):!S&&kt&&(k.element.remove(),kt=!1))},Ln=()=>$e&&Ee.find(S=>S.id===$e)||Ee[Ee.length-1],Gn=()=>{let S=Aa(Ln());if(!S){he.replaceChildren();return}let O=ge.filter(R=>R.visible===void 0||R.visible(S)).map(R=>Js(R,{documentChrome:r,onClick:()=>{let $=Aa(Ln());if($)try{Promise.resolve(R.onClick($)).catch(()=>{})}catch{}}}));he.replaceChildren(...O)},j=()=>{Gn();let S=r&&Ee.length<=1,O=!!Me;if(Ce.classList.toggle("persona-hidden",S||O),ke.classList.toggle("persona-hidden",S||!O),O&&Me){let K=Ee.map(Y=>Y.id).join("|")+" "+($e??"");if(K!==ot){ot=K;let Y=Me({records:Ee,selectedId:$e,onSelect:e.onSelect});ke.firstElementChild!==Y&&ke.replaceChildren(Y)}}else{Oe.beforeRender(),Ce.replaceChildren();let K=[],Y=-1;for(let[Q,Z]of Ee.entries()){let ue=v("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");ue.type="button";let et=Z.artifactType==="markdown"?Z.file:void 0,Ye=et?Ao(et.path):Z.title||Z.id.slice(0,8),Be=et?.path||Z.title||Ye;ue.textContent=Ye,ue.title=Be,ue.setAttribute("aria-label",Be),Z.id===$e&&(ue.classList.add("persona-bg-persona-container","persona-border-persona-border"),Y=Q),ue.addEventListener("click",()=>e.onSelect(Z.id)),Ce.appendChild(ue),K.push(ue)}if(Oe.render(K,Y),Y>=0&&$e!==Te){Te=$e;let Q=K[Y];typeof Q.scrollIntoView=="function"&&Q.scrollIntoView({block:"nearest",inline:"nearest"})}ze(Ce)}let R=$e&&Ee.find(K=>K.id===$e)||Ee[Ee.length-1];if(!R){De.replaceChildren(),lt?.destroy(),lt=null,Ct(!1);return}let $=R.artifactType==="markdown"?R.file:void 0;if(Ct(!!$&&Xr($)!=="other"),r){let K=$?br($):R.artifactType==="markdown"?"MD":R.component??"Component",Y=(R.title||"Document").trim(),Q=$?Ao($.path):Y.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";xe.textContent=`${Q} \xB7 ${K}`}else T.textContent=$?Ao($.path):s;lt?(lt.el.parentElement!==De&&De.replaceChildren(lt.el),lt.update(R)):(lt=Xc(R,{config:t,resolveViewMode:wn}),De.replaceChildren(lt.el)),De.classList.toggle("persona-artifact-content-flush",!!De.querySelector(".persona-code-pre"))},ae=()=>{let S=Ee.length>0;if(y.classList.toggle("persona-hidden",!S),b){let $=((typeof y.closest=="function"?y.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;S&&$&&mt?(b.classList.remove("persona-hidden"),y.classList.add("persona-artifact-drawer-open")):(b.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open"))}},x=()=>{Wt=!1,j(),ae()};return{element:y,backdrop:b,update(S){let O=S.selectedId??S.artifacts[S.artifacts.length-1]?.id??null,R=O!==$e;Ee=S.artifacts,$e=O,Ee.length>0&&(mt=!0),Wt=!0,yt&&x(),R&&Ue()},setMobileOpen(S){mt=S,!S&&b?(b.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open")):ae()},setExpanded(S){S!==At&&(At=S,an());let O=fe(S?"minimize":"maximize",16,"currentColor",2);O&&ve.replaceChildren(O);let R=S?"Collapse artifacts panel":"Expand artifacts panel";ve.setAttribute("aria-label",R),ve.title=R},setExpandToggleVisible(S){ve.classList.toggle("persona-hidden",!S)},setCopyButtonVisible(S){r||F.classList.toggle("persona-hidden",!S)},setRefreshButtonVisible(S){V.classList.toggle("persona-hidden",!S)},setCustomActions(S){ge=S,Gn()},setTabFade(S){let O=p(S);O.start===u&&O.end===g||(u=O.start,g=O.end,ze(Ce))},setRenderTabBar(S){S!==Me&&(Me=S,ot="",j())},setVisible(S){S!==yt&&(yt=S,S&&Wt&&x())},destroy(){lt?.destroy(),lt=null}}}function Pn(t){return t?.features?.artifacts?.enabled===!0}function Kv(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!Pn(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",o)):r&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",r))}function SE(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var Gv=["panel","seamless","detached"];function fg(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&Gv.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function mg(t){return!t||!Pn(t)?!1:fg(t)==="detached"}function $a(t,e){if(!Pn(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-drawer-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),SE(t),Kv(t,e);return}let n=e.features?.artifacts?.layout,o=fg(e)==="detached"?"var(--persona-panel-inset)":"0";t.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),t.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),t.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.drawerWidth?t.style.setProperty("--persona-artifact-drawer-width",n.drawerWidth):t.style.removeProperty("--persona-artifact-drawer-width"),n?.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?t.style.setProperty("--persona-artifact-pane-padding",s):t.style.removeProperty("--persona-artifact-pane-padding");let a=[[n?.documentToolbarIconColor,"--persona-artifact-doc-toolbar-icon-color"],[n?.documentToolbarToggleActiveBackground,"--persona-artifact-doc-toggle-active-bg"],[n?.documentToolbarToggleActiveBorderColor,"--persona-artifact-doc-toggle-active-border"],[n?.documentToolbarToggleActiveColor,"--persona-artifact-doc-toggle-active-color"]];for(let[l,d]of a){let p=l?.trim();p?t.style.setProperty(d,p):t.style.removeProperty(d)}Kv(t,e)}function za(t,e){for(let l of Gv)t.classList.remove(`persona-artifact-appearance-${l}`);if(t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-chat-shadow"),!Pn(e))return;let n=e.features?.artifacts?.layout,o=fg(e);t.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&t.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&t.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&t.style.setProperty("--persona-artifact-chat-shadow",a)}function Yv(t,e){return!e||!Pn(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}var AE=new Set(["__proto__","prototype","constructor"]),ME=new Set(["collapsed","card","panel","inline"]),Xv=new Set(["markdown","component"]),TE=/^[a-z0-9][a-z0-9!#$&^_.+-]*\/(\*|[a-z0-9!#$&^_.+-]+)$/,ss=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Cd=t=>!AE.has(t),hg=t=>typeof t=="string"&&ME.has(t),is=t=>Object.keys(t).length>0;function To(t,e,n,o){t.push({path:e,code:n,message:o})}var EE="Ignored because this key is not part of the persisted preference schema.",wd="Ignored an unsupported value.",kE="Expected collapsed, panel, or inline.",PE='Expected a MIME type such as "text/html" or a wildcard such as "image/*".',Qv={kind:"mode",message:wd},ai={kind:"string",message:"Expected a CSS length string."},Yo={kind:"boolean"},LE={paneWidth:ai,paneMaxWidth:ai,paneMinWidth:ai,expandedPanelWidth:ai,resizableMinWidth:ai,resizableMaxWidth:ai,expandLauncherPanelWhenOpen:Yo,resizable:Yo},IE={kind:"object",message:"Expected a preference object.",children:{showToolCalls:Yo,showReasoning:Yo,toolCallDisplay:{kind:"object",children:{collapsedMode:{kind:"enum",values:new Set(["tool-call","tool-name","tool-preview"]),message:wd},groupedMode:{kind:"enum",values:new Set(["stack","summary"]),message:wd},loadingAnimation:{kind:"enum",values:new Set(["none","pulse","shimmer","shimmer-color","rainbow"]),message:wd},expandable:Yo,grouped:Yo}},reasoningDisplay:{kind:"object",children:{expandable:Yo,activePreview:Yo}},artifacts:{kind:"object",children:{display:{kind:"object",bareMode:!0,message:"Expected an artifact display rules object.",children:{default:Qv,files:{kind:"object",bareMode:!0,message:"Expected collapsed, panel, inline, or a file display rules object.",children:{default:Qv,byMediaType:{kind:"modeMap",keys:"mediaType"}}},byType:{kind:"modeMap",keys:Xv,alias:"byKind",deprecated:"Use byKind. The legacy selector was normalized automatically."},byKind:{kind:"modeMap",keys:Xv}}},filePreview:{kind:"object",children:{enabled:Yo}},layout:{kind:"object",children:LE}}}}};function Jv(t,e,n,o){if(t!==void 0)switch(e.kind){case"boolean":return typeof t=="boolean"?t:To(o,n,"invalid_type","Expected a boolean.");case"string":return typeof t=="string"?t:To(o,n,"invalid_type",e.message);case"enum":return typeof t=="string"&&e.values.has(t)?t:To(o,n,"invalid_value",e.message);case"mode":return hg(t)?no(t):To(o,n,"invalid_value",e.message);case"modeMap":{if(!ss(t))return To(o,n,"invalid_type","Expected an object.");let r=e.keys==="mediaType"?void 0:e.keys,s={};for(let[a,l]of Object.entries(t)){let d=r?a:Ws(a);Cd(a)&&(r?r.has(a):TE.test(d))?hg(l)?s[d]=no(l):To(o,`${n}.${a}`,"invalid_value",kE):To(o,`${n}.${a}`,r?"unknown_key":"invalid_value",r?"Ignored an unsupported selector.":PE)}return is(s)?s:void 0}case"object":{if(e.bareMode&&hg(t))return no(t);if(!ss(t))return To(o,n,"invalid_type",e.message??"Expected an object.");let r=Object.keys(e.children),s=l=>n?`${n}.${l}`:l;for(let l of Object.keys(t))(!Cd(l)||!r.includes(l))&&To(o,s(l),"unknown_key",EE);let a={};for(let l of r){let d=e.children[l],p=Jv(t[l],d,s(l),o);if(d.deprecated&&t[l]!==void 0&&To(o,s(l),"deprecated_key",d.deprecated),p===void 0)continue;let u=d.alias??l,g=a[u];a[u]=ss(g)&&ss(p)?{...g,...p}:p}return is(a)?a:void 0}}}function HE(t){let e=[];return{preferences:(t===null?void 0:Jv(t,IE,"",e))??{},issues:e}}function li(t){if(Array.isArray(t))return t.map(li);if(!ss(t))return t;let e={};for(let[n,o]of Object.entries(t))Cd(n)&&o!==void 0&&(e[n]=li(o));return e}function Zv(t,e){let n=li(t);for(let[o,r]of Object.entries(e)){if(!Cd(o)||r===void 0)continue;let s=n[o];n[o]=ss(s)&&ss(r)?Zv(s,r):li(r)}return n}function RE(t){let e={},n;for(let r of t){let s=HE(r).preferences;n=ew(n,s.artifacts?.display),e=Zv(e,s)}let o=e;return o.artifacts&&(n!==void 0?o.artifacts.display=n:delete o.artifacts.display),o}function WE(t,e){if(e===void 0)return t===void 0?void 0:li(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byMediaType,...e.byMediaType},s={...o?{default:o}:{},...is(r)?{byMediaType:r}:{}};return is(s)?s:void 0}function ew(t,e){if(e===void 0)return t===void 0?void 0:li(t);if(typeof e=="string")return e;let n=typeof t=="string"?{default:t}:t??{},o=e.default??n.default,r={...n.byType,...n.byKind,...e.byType,...e.byKind},s=WE(n.files,e.files),a={...o?{default:o}:{},...is(r)?{byKind:r}:{},...s!==void 0?{files:s}:{}};return is(a)?a:void 0}function BE(t={},e){let n=RE(e),o={...t};if(n.showToolCalls!==void 0&&(o.showToolCalls=n.showToolCalls),n.showReasoning!==void 0&&(o.showReasoning=n.showReasoning),n.toolCallDisplay&&(o.toolCallDisplay={...t.toolCallDisplay,...n.toolCallDisplay}),n.reasoningDisplay&&(o.reasoningDisplay={...t.reasoningDisplay,...n.reasoningDisplay}),n.artifacts){let r=t.artifacts??{},s={...r};if(n.artifacts.display!==void 0){let a=ew(r.display,n.artifacts.display);a!==void 0&&(s.display=a)}n.artifacts.filePreview&&(s.filePreview={...r.filePreview,enabled:n.artifacts.filePreview.enabled}),n.artifacts.layout&&(s.layout={...r.layout,...n.artifacts.layout}),o.artifacts=s}return o}function yg(t){let e=t.preferences;return!e||!is(e)?t:{...t,features:BE(t.features??{},[e])}}function DE(t,e){if(!t?.trim())return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function NE(t){if(!t?.trim())return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function OE(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function _E(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function bg(t,e){let o=(e.getComputedStyle(t).gap||"0px").trim().split(/\s+/)[0]??"0px",r=/^([\d.]+)px$/i.exec(o);if(r)return Number(r[1]);let s=/^([\d.]+)/.exec(o);return s?Number(s[1]):8}function tw(t,e,n,o,r,s,a=200){let l=DE(r,200),d=_E(e,n,o,a);d=Math.max(l,d);let p=NE(s);return p!==null&&(d=Math.min(d,p)),OE(t,l,d)}Qe();var nw={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"}},vg=(t,e,n,o)=>{let r=t.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let l=nw[a]??nw.init;s.classList.add("persona-form-card","persona-space-y-4");let d=v("div","persona-space-y-1"),p=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(p.textContent=l.title,d.appendChild(p),l.description){let y=v("p","persona-text-sm persona-text-persona-muted");y.textContent=l.description,d.appendChild(y)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",l.fields.forEach(y=>{let w=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");w.htmlFor=`${e.id}-${a}-${y.name}`;let T=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");T.textContent=y.label,w.appendChild(T);let W=y.type??"text",E;W==="textarea"?(E=document.createElement("textarea"),E.rows=3):(E=document.createElement("input"),E.type=W),E.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",E.id=`${e.id}-${a}-${y.name}`,E.name=y.name,E.placeholder=y.placeholder??"",y.required&&(E.required=!0),w.appendChild(E),u.appendChild(w)});let g=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),b=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=v("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=l.submitLabel??"Submit",g.appendChild(b),g.appendChild(m),u.appendChild(g),s.replaceChildren(d,u),u.addEventListener("submit",async y=>{y.preventDefault();let w=n.formEndpoint??"/form",T=new FormData(u),W={};T.forEach((E,k)=>{W[k]=E}),W.type=a,m.disabled=!0,b.textContent="Submitting\u2026";try{let E=await fetch(w,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(W)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let k=await E.json();b.textContent=k.message??"Thanks! We'll be in touch soon.",k.success&&k.nextPrompt&&await o.sendMessage(String(k.nextPrompt))}catch(E){b.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var wg=class{constructor(){this.plugins=new Map}register(e){this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),e.onRegister?.()}unregister(e){let n=this.plugins.get(e);n&&(n.onUnregister?.(),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>(n.priority??0)-(e.priority??0))}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let o=new Set(e.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...e].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(e=>e.onUnregister?.()),this.plugins.clear()}},Cg=new wg;var ow=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),FE=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.artifacts.display","features.streamAnimation.plugins","preferences","welcome.icon"]),rw=(t,e,n)=>{if(!ow(t)||!ow(e)||FE.has(n))return e;let o={...t};for(let r of Object.keys(e)){if(e[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=rw(t[r],e[r],s)}return o};function sw(t,e){let n=rw(t,e,"");return Bc(n)}var iw=()=>{let t=new Map,e=(r,s)=>(t.has(r)||t.set(r,new Set),t.get(r).add(s),()=>n(r,s)),n=(r,s)=>{t.get(r)?.delete(s)};return{on:e,off:n,emit:(r,s)=>{t.get(r)?.forEach(a=>{try{a(s)}catch(l){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",l)}})}}};var $E=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},zE=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<e.length;r+=1){let s=e[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return e.slice(n,r+1)}return null},Sg=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=$E(t),n=zE(e);if(!n)return null;let o=JSON.parse(n);if(!o||typeof o!="object"||!o.action)return null;let{action:r,...s}=o;return{type:String(r),payload:s,raw:o}}catch{return null}},xg=t=>typeof t=="string"?t:t==null?"":String(t),Va={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:xg(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=xg(n.element);if(o&&e.document?.querySelector){let r=e.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:xg(n.text)}}},aw=t=>Array.isArray(t)?t.map(e=>String(e)):[],Ag=t=>{let e=new Set(aw(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(aw(t.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(e);t.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<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let l=a?t.parsers.reduce((p,u)=>p||u?.({text:a,message:s.message})||null,null):null;if(!l)return null;e.add(s.message.id),o();let d={action:l,message:s.message};t.emit("action:detected",d);for(let p of t.handlers)if(p)try{let u=()=>{t.emit("action:resubmit",d)},g=p(l,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:u});if(!g)continue;if(g.handled){let b=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:b,resubmit:g.resubmit}}}catch(u){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var VE=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},jE=t=>t.map(e=>({...e,streaming:!1})),qE=t=>t.map(e=>({...e,status:"complete"})),lw=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?VE(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?jE(n.messages):void 0,artifacts:n.artifacts?qE(n.artifacts):void 0};o.setItem(t,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var UE=t=>{let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e.toString(16).padStart(8,"0")},cw=async t=>{let e=globalThis.crypto?.subtle;if(e)try{let n=await e.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}catch{}return UE(t)},KE=async(t,e)=>{let n=await cw(t);return{storageKey:`${e}visitor:${n}`,leaseKey:`${e}visitor-init-lock:${n}`,lockName:`persona-visitor-init:${await cw(`${t}\0${e}`)}`}};var dw=(t,e,n)=>{let o="",r="",s="",a=!1,l=!1,d=0,p=null,u=null,g=new Set,b=()=>{if(n||a)return null;try{return typeof window>"u"||!window.localStorage?null:window.localStorage}catch{return a=!0,null}},m=()=>{let B=b();if(!B)return p;try{return B.getItem(o)}catch{return a=!0,p}},y=(B,I)=>{if(l||B===p)return;let N=p;p=B,d+=1;let _={previousToken:N,token:B,source:I,revision:d};for(let F of g)F(_)},w=B=>{l||B.key!==null&&B.key!==o||y(B.key===null?null:B.newValue??null,"external")},T=(async()=>{let B=await KE(t,e);o=B.storageKey,r=B.leaseKey,s=B.lockName,p=m(),!n&&typeof window<"u"&&window.addEventListener("storage",w)})(),W=B=>new Promise(I=>setTimeout(I,B)),E=()=>{let B=b();if(!B)return null;try{let I=B.getItem(r);if(!I)return null;let N=JSON.parse(I);return typeof N?.expiresAt=="number"&&typeof N?.ownerNonce=="string"?N:null}catch{return null}},k=B=>{let I=b();if(I)try{E()?.ownerNonce===B&&I.removeItem(r)}catch{}},A=B=>new Promise(I=>{let N=setTimeout(_,B);function _(){clearTimeout(N),window.removeEventListener("storage",F),I()}function F(P){(P.key===null||P.key===r)&&_()}window.addEventListener("storage",F)}),D=async B=>{let I=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,N=Date.now()+15e3;for(;Date.now()<N;){let _=b();if(!_)break;let F=Date.now(),P=E();if(P&&P.expiresAt>F&&P.ownerNonce!==I){await A(Math.min(P.expiresAt-F,500));continue}try{_.setItem(r,JSON.stringify({ownerNonce:I,expiresAt:F+1e4}))}catch{a=!0;break}if(await W(20+Math.random()*40),E()?.ownerNonce!==I){await A(500);continue}u=I;try{return await B()}finally{u=null,k(I)}}return B()};return{ready:T,async get(){return await T,y(m(),"external"),p},async set(B){await T;let I=b();if(I)try{I.setItem(o,B)}catch{a=!0}y(B,"local")},async clear(){await T;let B=b();if(B)try{B.removeItem(o)}catch{a=!0}y(null,"local")},revision(){return d},subscribe(B){return g.add(B),()=>{g.delete(B)}},async withFirstInitLock(B){await T;let I=globalThis.navigator?.locks;return I?.request?I.request(s,()=>B()):b()?D(B):B()},matches(B,I,N){return B===t&&I===e&&N===n},destroy(){l=!0,g.clear(),typeof window<"u"&&window.removeEventListener("storage",w),u&&k(u)}}};var{setLoader:uB,load:vk}=Co({fallbackImport:()=>Promise.resolve().then(()=>(Ew(),Tw))});var Bg=vk;var Dg=(t,e)=>{console.warn(`[persona] ${t} threw`,e)},Xo=t=>Object.freeze({...t}),kw=t=>Object.freeze({id:t.id,title:t.title,targetId:t.targetId,preview:t.preview,messageCount:t.messageCount,createdAt:t.createdAt,updatedAt:t.updatedAt}),Pw=t=>t?Xo(t):null;function Lw(t){let{plugins:e,config:n}=t,o=!1,r=!1,s=!1,a=!1,l=null,d=[],p=()=>{for(let A of d.splice(0))try{A()}catch(D){Dg("renderHistoryView cleanup",D)}},u=(A,D)=>{for(let B of e){let I=B[A];if(I)try{let N=I(D);if(N)return N}catch(N){Dg(A,N)}}return null},g=()=>({presentation:t.getPresentation(),config:n}),b={header:A=>a?u("renderHistoryHeader",Object.freeze({...g(),returnSurface:t.getReturnSurface(),identityStatus:Xo(A.identityStatus),pendingAction:Pw(A.pendingAction),copy:Xo(A.copy),actions:Object.freeze({close:w.close,startNewConversation:w.startNewConversation}),defaultRenderer:A.defaultRenderer})):null,conversation:A=>a?u("renderHistoryConversation",Object.freeze({...g(),conversation:kw(A.conversation),active:A.active,pending:A.pending,open:A.open,requestDelete:A.requestDelete,defaultRenderer:A.defaultRenderer})):null,state:A=>a?u("renderHistoryState",Object.freeze({...g(),state:Xo(A.state),identityStatus:Xo(A.identityStatus),copy:Xo(A.copy),...A.retry?{retry:A.retry}:{},...A.startNewConversation?{startNewConversation:A.startNewConversation}:{},defaultRenderer:A.defaultRenderer})):null},m=e.flatMap(A=>(A.railSections??[]).map(D=>({...D,placement:D.placement??"above-conversations",items:[],render:B=>D.render(Object.freeze({collapsed:B,presentation:t.getPresentation(),actions:w}))}))),y=t.createView({slots:b,renderDom:!1,onModelChange:()=>k(),railSections:m}),w=Object.freeze({...y.operations,close:t.close}),T=()=>(a=!0,y.setDomRenderEnabled(!0),y.element),W=A=>Object.freeze({conversations:Object.freeze(A.conversations.map(kw)),activeConversationId:A.activeConversationId,state:Xo(A.state),pendingAction:Pw(A.pendingAction),identityStatus:Xo(A.identityStatus),nextCursor:A.nextCursor,presentation:t.getPresentation(),returnSurface:t.getReturnSurface(),config:n,copy:Xo(y.copy),actions:w,defaultRenderer:T,requestRender:()=>k(),onCleanup:D=>{d.push(D)}}),E=()=>{a=!1;let A=null;for(let B of e)if(B.renderHistoryView){try{A=B.renderHistoryView(W(y.getModel()))}catch(I){Dg("renderHistoryView",I),A=null}if(A)break}let D=!A||A.contains(y.element);return a=D,y.setDomRenderEnabled(D),A??y.element};function k(){if(!(!s||o||r)){r=!0;try{p();let A=E();if(A===l)return;let D=l;l=A,t.onElementChanged(A,D)}finally{r=!1}}}return s=!0,k(),{view:y,get element(){return l??y.element},requestRender:k,dispose:()=>{o=!0,p()}}}var wk=null;function Iw(){return wk}la();var Ck=new Map([["not_found","not_found"],["conversation_deleted","not_found"],["rate_limited","rate_limited"],["authentication_required","authentication_required"],["invalid_identity_proof","authentication_required"],["visitor_identity_mismatch","authentication_required"],["visitor_required","authentication_required"],["identity_provider_failed","identity_provider_failed"],["proof_not_admitted","proof_not_admitted"],["identity_contract_violation","proof_not_admitted"],["unauthorized","authentication_failed"],["visitor_token_missing","authentication_failed"],["conversation_credential_missing","authentication_failed"]]),xk=new Map([["not_found","That conversation is no longer available."],["rate_limited","Too many history requests."],["authentication_failed","History access was not authorized."],["authentication_required","Sign in again to view account history."],["identity_provider_failed","The identity provider did not respond."],["proof_not_admitted","Account history is not available for this configuration."],["unsupported_scope","This history scope is not supported."],["unavailable","Conversation history is unavailable right now."]]),Ng=t=>xk.get(t)??"Conversation history is unavailable right now.";function Sk(t){if(t instanceof xo)return t;if(t instanceof Ze){let e=Ck.get(t.code)??"unavailable";return new xo(e,Ng(e),{...t.retryAfterSeconds!==void 0?{retryAfterSeconds:t.retryAfterSeconds}:{}})}return new xo("unavailable",Ng("unavailable"))}function Hw(t){let e=()=>t.getClient?.()??t.client,n=t.getIdentityProofConfigured()?["browser","verified-user"]:["browser"],o={scopes:n},r=l=>{if(!n.includes(l))throw new xo("unsupported_scope",Ng("unsupported_scope"))},s=async(l,d)=>{r(l);try{return await d()}catch(p){throw Sk(p)}},a=l=>{let d=!1;return{conversationId:l.session.conversationId??"",conversationRevision:l.session.conversationRevision??"",async commit(){d||(d=!0,l.commit(),await t.onActivationCommitted(l.session))},discard(){d||(d=!0,l.discard())}}};return{capabilities:o,getIdentityStatus(){return e().getHistoryIdentityStatus()},subscribeIdentityStatus(l){return e().subscribeHistoryIdentityStatus(l)},subscribeAvailability(l){return e().subscribeHistoryAvailability(l)},async list(l){return s(l.context.scope,async()=>{let d=await e().listConversations({...l.cursor?{cursor:l.cursor}:{},...l.limit!==void 0?{limit:l.limit}:{},...l.targetId?{targetId:l.targetId}:{},scope:l.context.scope});return{items:d.data,nextCursor:d.nextCursor}})},async getPage(l,d){return s(d.context.scope,async()=>{let p=await e().getConversation(l,{...d.cursor?{messageCursor:d.cursor}:{},scope:d.context.scope}),u=ry(p.messages,{...d.beforeCreatedAt?{beforeCreatedAt:d.beforeCreatedAt}:{}});return{summary:p.summary,messages:ia([],u),conversationRevision:p.conversationRevision??"",nextCursor:p.nextMessageCursor}})},async prepareOpen(l,d){return s(d.context.scope,async()=>a(await e().prepareConversationSession(l)))},async prepareStartNew(l){return s(l.context.scope,async()=>a(await e().prepareNewConversationSession()))},async delete(l,d){await s(d.context.scope,()=>e().deleteConversation(l,{scope:d.context.scope}))},async deleteAll(l){return s(l.context.scope,()=>e().deleteAllConversations({...l.targetId!==void 0?{targetId:l.targetId}:{},scope:l.context.scope}))},async resetDevice(){try{return await e().resetVisitor(),{remoteRevocationConfirmed:!0}}catch{return{remoteRevocationConfirmed:!1}}}}}Tg();Qe();var Ak="button:not([disabled])";function Td(t){let e=document.activeElement instanceof HTMLElement?document.activeElement:null,n=Math.random().toString(36).slice(2,8),o=`persona-history-confirm-title-${n}`,r=`persona-history-confirm-desc-${n}`,s=J("button",{className:"persona-history-confirm__cancel",text:t.cancelLabel,attrs:{type:"button"}}),a=J("button",{className:"persona-history-confirm__confirm",text:t.confirmLabel,attrs:{type:"button","data-persona-destructive":"true"}}),l=J("div",{className:"persona-history-confirm__dialog",attrs:{role:"alertdialog","aria-modal":"true","aria-labelledby":o,"aria-describedby":r},style:{maxWidth:"22rem",width:"100%",borderRadius:"var(--persona-radius-lg, 0.75rem)",background:"var(--persona-surface, #ffffff)",color:"var(--persona-text, #111827)",boxShadow:"var(--persona-history-confirm-shadow, 0 20px 40px -12px rgba(0, 0, 0, 0.35))",padding:"20px",display:"flex",flexDirection:"column",gap:"12px"}},J("h2",{className:"persona-history-confirm__title",text:t.title,attrs:{id:o},style:{margin:"0",fontSize:"1rem",fontWeight:"600"}}),J("p",{className:"persona-history-confirm__description",text:t.description,attrs:{id:r},style:{margin:"0",fontSize:"0.875rem",lineHeight:"1.4"}}),J("div",{className:"persona-history-confirm__actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end",flexWrap:"wrap"}},s,a));for(let p of[s,a])p.style.minHeight="44px",p.style.minWidth="88px",p.style.padding="0 16px",p.style.borderRadius="var(--persona-radius-md, 0.5rem)",p.style.cursor="pointer",p.style.font="inherit";s.style.border="1px solid var(--persona-border, rgba(0,0,0,0.12))",s.style.background="transparent",s.style.color="inherit",a.style.border="none",a.style.background="var(--persona-danger, #b42318)",a.style.color="var(--persona-danger-fg, #ffffff)";let d=J("div",{className:"persona-history-confirm",style:{position:"absolute",inset:"0",zIndex:"40",display:"flex",alignItems:"center",justifyContent:"center",padding:"16px",background:"var(--persona-history-confirm-scrim, rgba(15, 23, 42, 0.45))"}},l);return new Promise(p=>{let u=!1,g=m=>{u||(u=!0,d.removeEventListener("keydown",b,!0),d.remove(),e?.focus(),p(m))};function b(m){if(m.key==="Escape"){m.preventDefault(),m.stopPropagation(),g(!1);return}if(m.key!=="Tab")return;let y=Array.from(l.querySelectorAll(Ak));if(y.length===0)return;let w=y[0],T=y[y.length-1],W=document.activeElement;m.shiftKey&&(W===w||!l.contains(W))?(m.preventDefault(),T.focus()):!m.shiftKey&&W===T&&(m.preventDefault(),w.focus())}d.addEventListener("keydown",b,!0),d.addEventListener("pointerdown",m=>{m.target===d&&g(!1)}),s.addEventListener("click",()=>g(!1)),a.addEventListener("click",()=>g(!0)),t.host.appendChild(d),s.focus()})}var Og=require("partial-json");function Rw(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=Ko.get(t.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:l=>{r&&r(l)}};try{return s(t.props,a)}catch(l){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,l),null}}function Ww(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function _g(t){let e=Ww(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Bw(t){let e=Ww(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let o=n;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:e}}}catch{}return null}var Mk=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Dw(t){let{onSubmit:e,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,ratingLabels:p=Mk}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let g=null,b=document.createElement("div");b.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=o,m.appendChild(y);let w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=r,m.appendChild(w),b.appendChild(m);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-csat",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Satisfaction rating from 1 to 5");let W=[];for(let B=1;B<=5;B++){let I=document.createElement("button");I.type="button",I.className="persona-feedback-rating-btn persona-feedback-star-btn",I.setAttribute("role","radio"),I.setAttribute("aria-checked","false"),I.setAttribute("aria-label",`${B} star${B>1?"s":""}: ${p[B-1]}`),I.title=p[B-1],I.dataset.rating=String(B),I.innerHTML=`
216
1113
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
217
1114
  <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>
218
1115
  </svg>
219
- `,$.addEventListener("click",()=>{g=z,I.forEach((F,B)=>{let H=B<z;F.classList.toggle("selected",H),F.setAttribute("aria-checked",B===z-1?"true":"false")})}),I.push($),M.appendChild($)}b.appendChild(M);let S=null;if(p){let z=document.createElement("div");z.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=s,S.rows=3,S.setAttribute("aria-label","Additional comments"),z.appendChild(S),b.appendChild(z)}let E=document.createElement("div");E.className="persona-feedback-actions";let L=document.createElement("button");L.type="button",L.className="persona-feedback-btn persona-feedback-btn-skip",L.textContent=l,L.addEventListener("click",()=>{n?.(),d.remove()});let D=document.createElement("button");return D.type="button",D.className="persona-feedback-btn persona-feedback-btn-submit",D.textContent=i,D.addEventListener("click",async()=>{if(g===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}D.disabled=!0,D.textContent="Submitting...";try{let z=S?.value.trim()||void 0;await e(g,z),d.remove()}catch(z){D.disabled=!1,D.textContent=i,console.error("[CSAT Feedback] Failed to submit:",z)}}),E.appendChild(L),E.appendChild(D),b.appendChild(E),d.appendChild(b),d}function th(t){let{onSubmit:e,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:l="Skip",showComment:p=!0,lowLabel:c="Not likely",highLabel:d="Very likely"}=t,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let b=null,f=document.createElement("div");f.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,y.appendChild(C);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,y.appendChild(M),f.appendChild(y);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-nps",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="persona-feedback-labels";let E=document.createElement("span");E.className="persona-feedback-label-low",E.textContent=c;let L=document.createElement("span");L.className="persona-feedback-label-high",L.textContent=d,S.appendChild(E),S.appendChild(L);let D=document.createElement("div");D.className="persona-feedback-numbers";let z=[];for(let w=0;w<=10;w++){let N=document.createElement("button");N.type="button",N.className="persona-feedback-rating-btn persona-feedback-number-btn",N.setAttribute("role","radio"),N.setAttribute("aria-checked","false"),N.setAttribute("aria-label",`Rating ${w} out of 10`),N.textContent=String(w),N.dataset.rating=String(w),w<=6?N.classList.add("persona-feedback-detractor"):w<=8?N.classList.add("persona-feedback-passive"):N.classList.add("persona-feedback-promoter"),N.addEventListener("click",()=>{b=w,z.forEach((K,te)=>{K.classList.toggle("selected",te===w),K.setAttribute("aria-checked",te===w?"true":"false")})}),z.push(N),D.appendChild(N)}I.appendChild(S),I.appendChild(D),f.appendChild(I);let $=null;if(p){let w=document.createElement("div");w.className="persona-feedback-comment-container",$=document.createElement("textarea"),$.className="persona-feedback-comment",$.placeholder=s,$.rows=3,$.setAttribute("aria-label","Additional comments"),w.appendChild($),f.appendChild(w)}let F=document.createElement("div");F.className="persona-feedback-actions";let B=document.createElement("button");B.type="button",B.className="persona-feedback-btn persona-feedback-btn-skip",B.textContent=l,B.addEventListener("click",()=>{n?.(),g.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=i,H.addEventListener("click",async()=>{if(b===null){D.classList.add("persona-feedback-shake"),setTimeout(()=>D.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let w=$?.value.trim()||void 0;await e(b,w),g.remove()}catch(w){H.disabled=!1,H.textContent=i,console.error("[NPS Feedback] Failed to submit:",w)}}),F.appendChild(B),F.appendChild(H),f.appendChild(F),g.appendChild(f),g}var es="persona-chat-history",uC=30*1e3,gC=641,fC={"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 mC(t){if(!t)return[];let e=[],n=Array.from(t.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){e.push(r);continue}let s=fC[r.type]??"png";e.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function ul(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function hC(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function bC(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var Id=t=>!t||typeof t!="object"?{}:{...t},nh=t=>t.map(e=>({...e,streaming:!1})),oh=(t,e,n)=>{let o=t?.markdown?Qi(t.markdown):null,r=Xi(t?.sanitize);return t?.postprocessMessage&&r&&t?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{let i=s.text??"",l=s.message.rawContent??null;if(e){let d=e.process({text:i,raw:l??i,message:s.message,streaming:s.streaming});d!==null&&(i=d.text,d.persist||(s.message.__skipPersist=!0),d.resubmit&&!s.streaming&&n&&n())}let p=Jn()!==null,c;if(t?.postprocessMessage){let d=t.postprocessMessage({...s,text:i,raw:l??s.text??""});c=r?r(d):d}else if(o){let d=s.streaming?Tu(i):i,g=o(d);c=r&&p?r(g):g}else c=vo(i);return c}};function rh(t){let e=v("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",r=t?.iconColor??"rgba(59, 130, 246, 0.6)",s=t?.iconStrokeWidth??.5,i=ie(n,o,r,s);if(i&&e.appendChild(i),t?.label){let l=v("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var yC=(t,e)=>{let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];n[o]=s?{...s,...r}:r}return n},vC=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:yC(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),sh=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=La(e),r=o.features;o=wd(o);let s=Md.getForInstance(o.plugins),i=!1,l=xm(()=>o),{plugin:p,teardown:c}=km();o.components&&oo.registerAll(o.components);let d=Gm(),b=o.persistState===!1?null:o.storageAdapter??Xm(),f={},y=null,C=!1,M=a=>{if(o.onStateLoaded)try{let u=o.onStateLoaded(a);if(u&&typeof u=="object"&&"state"in u){let{state:m,open:x}=u;return x&&(C=!0),m}return u}catch(u){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return a};if(b?.load)try{let a=b.load();if(a&&typeof a.then=="function")y=a.then(u=>M(u??{messages:[],metadata:{}}));else{let m=M(a??{messages:[],metadata:{}});m.metadata&&(f=Id(m.metadata)),m.messages?.length&&(o={...o,initialMessages:m.messages}),m.artifacts?.length&&(o={...o,initialArtifacts:m.artifacts,initialSelectedArtifactId:m.selectedArtifactId??null})}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=M({messages:[],metadata:{}});a.messages?.length&&(o={...o,initialMessages:a.messages})}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}let I=()=>f,S=a=>{f=a({...f})??{},Il()},E=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ed],L=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[mi.message,mi.messageAndClick],D=kd({parsers:E,handlers:L,getSessionMetadata:I,updateSessionMetadata:S,emit:d.emit,documentRef:typeof document<"u"?document:null});D.syncFromMetadata();let z=o.launcher?.enabled??!0,$=o.launcher?.autoExpand??!1,F=o.autoFocusInput??!1,B=$,H=z,w=o.layout?.header?.layout,N=!1,K=()=>ri(o),te=()=>z||K(),Q=K()?!1:z?$:!0,se=!1,J=null,oe=()=>{se=!0,J&&clearTimeout(J),J=setTimeout(()=>{se&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),se=!1)},1e4)},Y=oh(o,D,oe),pe=o.features?.showReasoning??!0,ne=o.features?.showToolCalls??!0,me=o.features?.showEventStreamToggle??!1,ve=o.features?.scrollToBottom??{},be=o.features?.scrollBehavior??{},ze=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,Oe=me?new pi(ze):null,Ne=o.features?.eventStream?.maxEvents??2e3,Be=me?new di(Ne,Oe):null,Ue=me?new ui:null,Me=null,Ee=!1,Ve=null,Jt=0;Oe?.open().then(()=>Be?.restore()).catch(a=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",a)});let bt={onCopy:a=>{d.emit("message:copy",a),V?.isClientTokenMode()&&V.submitMessageFeedback(a.id,"copy").catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",u)}),o.messageActions?.onCopy?.(a)},onFeedback:a=>{d.emit("message:feedback",a),V?.isClientTokenMode()&&V.submitMessageFeedback(a.messageId,a.type).catch(u=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",u)}),o.messageActions?.onFeedback?.(a)}},Nt=o.statusIndicator??{},Mn=a=>a==="idle"?Nt.idleText??Bt.idle:a==="connecting"?Nt.connectingText??Bt.connecting:a==="connected"?Nt.connectedText??Bt.connected:a==="error"?Nt.errorText??Bt.error:a==="paused"?Nt.pausedText??Bt.paused:a==="resuming"?Nt.resumingText??Bt.resuming:Bt[a];function Tn(a,u,m,x){if(x==="idle"&&m.idleLink){a.textContent="";let A=document.createElement("a");A.href=m.idleLink,A.target="_blank",A.rel="noopener noreferrer",A.textContent=u,A.style.color="inherit",A.style.textDecoration="none",a.appendChild(A)}else a.textContent=u}let nt=vm({config:o,showClose:te()}),{wrapper:Pe,panel:xe,pillRoot:ot}=nt.shell,ke=nt.panelElements,{container:Ce,body:ce,messagesWrapper:Ae,starterSuggestions:En,transcriptSuggestions:ae,suggestions:k,textarea:W,sendButton:h,sendButtonWrapper:O,composerForm:R,statusText:_,welcomeHost:Z,welcomeIconHolder:q,greetingHost:ee,introTitle:ge,introSubtitle:qe,closeButton:fe,iconHolder:Ie,headerTitle:Ke,headerSubtitle:je,header:He,footer:Se,actionsRow:rt,rightActions:Mt}=ke,fn=ke.leftActions,bi=ke.setSendButtonMode,le=ke.micButton,mn=ke.micButtonWrapper,ct=ke.attachmentButton,hn=ke.attachmentButtonWrapper,kt=ke.attachmentInput,kn=ke.attachmentPreviewsContainer;Ce.classList.add("persona-relative"),ce.classList.add("persona-relative");let yh=12,ns=()=>ve.label??"",vh=()=>ve.iconName??"arrow-down",xh=()=>ve.enabled!==!1,an=()=>be.mode??"anchor-top",io=()=>an()==="follow"||an()==="anchor-top"&&us,os=()=>be.anchorTopOffset??16,wh=()=>be.restorePosition??"bottom",Nd=()=>be.pauseOnInteraction===!0,Fd=()=>be.showActivityWhilePinned!==!1,_d=()=>be.announce===!0,fl=()=>be.scrollbar??"on-scroll",It=v("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");It.type="button",It.style.display="none",It.setAttribute("data-persona-scroll-to-bottom","true");let rs=v("span","persona-flex persona-items-center"),ml=v("span",""),Io=v("span","");Io.setAttribute("data-persona-scroll-to-bottom-count",""),Io.style.display="none",It.append(rs,ml,Io),Ce.appendChild(It);let bn=v("div","persona-stream-anchor-spacer");bn.setAttribute("aria-hidden","true"),bn.setAttribute("data-persona-anchor-spacer",""),bn.style.flexShrink="0",bn.style.pointerEvents="none",bn.style.height="0px",bn.style.display="none",ce.appendChild(bn);let Ro=v("div","persona-sr-only");Ro.setAttribute("aria-live","polite"),Ro.setAttribute("aria-atomic","true"),Ro.setAttribute("role","status"),Ro.setAttribute("data-persona-live-region",""),Object.assign(Ro.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),Ce.appendChild(Ro);let ss=null,yi=null,$d=a=>{!_d()||!a||(yi=a,ss===null&&(ss=setTimeout(()=>{ss=null,yi&&_d()&&(Ro.textContent=yi),yi=null},400)))},Wo=()=>{let u=Se.style.display==="none"?0:Se.offsetHeight;It.style.bottom=`${u+yh}px`};Wo();let zd=()=>{let a=!!ns();It.setAttribute("aria-label",ns()||"Jump to latest"),It.title=ns(),It.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),rs.innerHTML="";let u=ie(vh(),"14px","currentColor",2);u?(rs.appendChild(u),rs.style.display=""):rs.style.display="none",ml.textContent=ns(),ml.style.display=a?"":"none"};zd();let wt=null,Zt=null,Ud=null,jd=s.find(a=>a.renderHeader);if(jd?.renderHeader){let a=jd.renderHeader({config:o,defaultRenderer:()=>{let u=or({config:o,showClose:te()});return ii(Ce,u,o),u.header},onClose:()=>dt(!1,"user")});if(a){let u=Ce.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(a),He=a,nt.header.element=a)}}let hl=()=>{if(!Be)return;if(Ee=!0,!Me&&Be&&(Me=Rm({buffer:Be,getFullHistory:()=>Be.getAllFromStore(),onClose:()=>is(),config:o,plugins:s,getThroughput:()=>Ue?.getMetric()??{status:"idle"}})),Me&&(ce.style.display="none",Se.parentNode?.insertBefore(Me.element,Se),Me.update()),et){et.style.boxShadow=`inset 0 0 0 1.5px ${Yt.actionIconColor}`;let u=o.features?.eventStream?.classNames?.toggleButtonActive;u&&u.split(/\s+/).forEach(m=>m&&et.classList.add(m))}let a=()=>{if(!Ee)return;let u=Date.now();u-Jt>=200&&(Me?.update(),Jt=u),Ve=requestAnimationFrame(a)};Jt=0,Ve=requestAnimationFrame(a),Vt(),d.emit("eventStream:opened",{timestamp:Date.now()})},is=()=>{if(Ee){if(Ee=!1,Me&&Me.element.remove(),ce.style.display="",et){et.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(u=>u&&et.classList.remove(u))}Ve!==null&&(cancelAnimationFrame(Ve),Ve=null),Vt(),d.emit("eventStream:closed",{timestamp:Date.now()})}},et=null;if(me){let a=o.features?.eventStream?.classNames,u="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"+(a?.toggleButton?" "+a.toggleButton:"");et=v("button",u),et.style.width="28px",et.style.height="28px",et.style.color=Yt.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let m=ie("activity","18px","currentColor",1.5);m&&et.appendChild(m);let x=ke.clearChatButtonWrapper,A=ke.closeButtonWrapper,P=x||A;P&&P.parentNode===He?He.insertBefore(et,P):He.appendChild(et),et.addEventListener("click",()=>{Ee?is():hl()})}let Vd=a=>{let u=o.attachments;if(!u?.enabled)return;let m=a.querySelector("[data-persona-composer-attachment-previews]")??a.querySelector(".persona-attachment-previews");if(!m){m=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),m.setAttribute("data-persona-composer-attachment-previews",""),m.style.display="none";let A=a.querySelector("[data-persona-composer-form]");A?.parentNode?A.parentNode.insertBefore(m,A):a.insertBefore(m,a.firstChild)}if(!(a.querySelector("[data-persona-composer-attachment-input]")??a.querySelector('input[type="file"]'))){let A=v("input");A.type="file",A.setAttribute("data-persona-composer-attachment-input",""),A.accept=(u.allowedTypes??to).join(","),A.multiple=(u.maxFiles??4)>1,A.style.display="none",A.setAttribute("aria-label",u.buttonTooltipText??"Attach files"),a.appendChild(A)}},bl=s.find(a=>a.renderComposer),yl=!1,qd=a=>{if(!bl?.renderComposer)return null;let u=o.composer,m=i?V.isStreaming():!1;return bl.renderComposer({config:o,defaultRenderer:a,requestRender:()=>yb(),storage:l(bl.id),onSubmit:x=>{if(!V||V.isStreaming())return;let A=x.trim(),P=wt?.hasAttachments()??!1;if(!A&&!P)return;Kp();let G;P&&(G=[],G.push(...wt.getContentParts()),A&&G.push(Dr(A))),V.sendMessage(A,{contentParts:G}),P&&wt.clearAttachments()},streaming:m,disabled:m,openAttachmentPicker:()=>{kt?.click()},models:u?.models,selectedModelId:u?.selectedModelId,onModelChange:x=>{o.composer={...o.composer,selectedModelId:x},o.agent&&(o.agent={...o.agent,model:x})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Ud?.()}:void 0})},Kd=qd(()=>ai({config:o}).footer);Kd&&(nt.replaceComposer(Kd),Se=nt.composer.footer,yl=!0);let Gd=a=>{let u=(...he)=>{for(let ue of he){let we=a.querySelector(ue);if(we)return we}return null},m=a.querySelector("[data-persona-composer-form]"),x=a.querySelector("[data-persona-composer-input]"),A=a.querySelector("[data-persona-composer-submit]"),P=a.querySelector("[data-persona-composer-mic]"),G=a.querySelector("[data-persona-composer-status]");m&&(R=m),x&&(W=x),A&&(h=A),P&&(le=P,mn=P.parentElement),G&&(_=G);let j=u("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");j&&(k=j);let X=u("[data-persona-composer-attachment-button]",".persona-attachment-button");X&&(ct=X,hn=X.parentElement),kt=u("[data-persona-composer-attachment-input]",'input[type="file"]'),kn=u("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let re=u("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");re&&(rt=re),fn=u(".persona-widget-composer__left-actions")};Vd(Se),Gd(Se);let as=To(o,K());as&&(Ae.style.maxWidth=as,Ae.style.marginLeft="auto",Ae.style.marginRight="auto",Ae.style.width="100%",ee.style.maxWidth=as,ee.style.marginLeft="auto",ee.style.marginRight="auto",ee.style.width="100%",En.style.maxWidth=as,ae.style.maxWidth=as,ae.style.marginLeft="auto",ae.style.marginRight="auto",ae.style.width="100%");let Qd=()=>{let a=To(o,K());if(!(!a||K()))for(let u of[R,k,kn,_])u&&(u.style.maxWidth=a,u.style.marginLeft="auto",u.style.marginRight="auto")};Qd();let Xd=()=>{!o.attachments?.enabled||!kt||!kn||(wt?wt.remountPreviews(kn):(wt=$s.fromConfig(o.attachments),wt.setPreviewsContainer(kn)),kt.addEventListener("change",a=>{let u=a.target;wt?.handleFileSelect(u.files),u.value=""}),Ce.querySelector(".persona-attachment-drop-overlay")||Ce.appendChild(rh(o.attachments.dropOverlay)))};Xd();let Ch=()=>Zt?.prefetch(),Yd=()=>{if(!(!o.contextMentions?.enabled||!W)&&(Zt=pf({config:o,textarea:W,anchor:R??W,getMessages:()=>V.getMessages(),liveRegionHost:Ce}),Zt)){let a=W;a.parentElement?.insertBefore(Zt.contextRow,a);let u=Zt.affordanceButtons;for(let m=u.length-1;m>=0;m--){let x=u[m];fn?fn.insertBefore(x,fn.firstChild):R?.appendChild(x)}}};Yd(),(()=>{let a=o.layout?.slots??{},u=x=>{switch(x){case"body-top":return ce.querySelector("[data-persona-intro-card]");case"messages":return Ae;case"footer-top":return k;case"composer":return R;case"footer-bottom":return _;default:return null}},m=(x,A)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")He.insertBefore(A,He.firstChild);else if(x==="header-right")He.appendChild(A);else{let P=He.querySelector(".persona-flex-col");P?P.parentNode?.insertBefore(A,P.nextSibling):He.appendChild(A)}break;case"body-top":{let P=ce.querySelector("[data-persona-intro-card]");P?P.replaceWith(A):ce.insertBefore(A,ce.firstChild);break}case"body-bottom":ce.appendChild(A);break;case"footer-top":k.replaceWith(A);break;case"footer-bottom":_.replaceWith(A);break;default:break}};for(let[x,A]of Object.entries(a))if(A)try{let P=A({config:o,defaultContent:()=>u(x)});P&&m(x,P)}catch(P){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,P)}})();let Jd=a=>{let m=a.target.closest('button[data-expand-header="true"]');if(!m)return;let x=m.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let P=m.getAttribute("data-bubble-type");if(P==="reasoning")Qr.has(A)?Qr.delete(A):Qr.add(A),wm(A,x);else if(P==="tool")Xr.has(A)?Xr.delete(A):Xr.add(A),Cm(A,x,o);else if(P==="approval"){let j=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",X=sr.get(A)??j;sr.set(A,!X),Tm(A,x,o)}_o.delete(A)};Ae.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Jd(a))}),Ae.addEventListener("keydown",a=>{let u=a.target;(a.key==="Enter"||a.key===" ")&&u.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Jd(a))}),Ae.addEventListener("copy",a=>{let{clipboardData:u}=a;if(!u)return;let m=Ae.getRootNode(),x=typeof m.getSelection=="function"?m.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let A=x.toString(),P=_f(A);!P||P===A||(u.setData("text/plain",P),a.preventDefault())});let vl=new Map,Zd=null,ep="idle",Ah={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Sh=(a,u)=>{let{icon:m,label:x}=Ah[u];a.setAttribute("aria-label",x),a.title=x,a.setAttribute("aria-pressed",u==="idle"?"false":"true"),a.classList.toggle("persona-message-action-active",u!=="idle"),a.classList.toggle("persona-message-action-loading",u==="loading");let A=ie(m,14,"currentColor",2);A&&(a.innerHTML="",a.appendChild(A))},tp=()=>{Ae.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{let x=u.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Sh(u,x&&x===Zd?ep:"idle")})};Ae.addEventListener("click",a=>{let m=a.target.closest(".persona-message-action-btn[data-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let x=m.closest("[data-actions-for]");if(!x)return;let A=x.getAttribute("data-actions-for");if(!A)return;let P=m.getAttribute("data-action");if(P==="copy"){let j=V.getMessages().find(X=>X.id===A);if(j&&bt.onCopy){let X=j.content||"";navigator.clipboard.writeText(X).then(()=>{m.classList.add("persona-message-action-success");let re=ie("check",14,"currentColor",2);re&&(m.innerHTML="",m.appendChild(re)),setTimeout(()=>{m.classList.remove("persona-message-action-success");let he=ie("copy",14,"currentColor",2);he&&(m.innerHTML="",m.appendChild(he))},2e3)}).catch(re=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",re)}),bt.onCopy(j)}}else if(P==="read-aloud")V.toggleReadAloud(A);else if(P==="upvote"||P==="downvote"){let j=(vl.get(A)??null)===P,X=P==="upvote"?"thumbs-up":"thumbs-down";if(j){vl.delete(A),m.classList.remove("persona-message-action-active");let re=ie(X,14,"currentColor",2);re&&(m.innerHTML="",m.appendChild(re))}else{let re=P==="upvote"?"downvote":"upvote",he=x.querySelector(`[data-action="${re}"]`);if(he){he.classList.remove("persona-message-action-active");let pt=ie(re==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);pt&&(he.innerHTML="",he.appendChild(pt))}vl.set(A,P),m.classList.add("persona-message-action-active");let ue=ie(X,14,"currentColor",2);ue&&(ue.setAttribute("fill","currentColor"),m.innerHTML="",m.appendChild(ue)),m.classList.remove("persona-message-action-pop"),m.offsetWidth,m.classList.add("persona-message-action-pop");let Xe=V.getMessages().find(yt=>yt.id===A);Xe&&bt.onFeedback&&bt.onFeedback({type:P,messageId:Xe.id,message:Xe})}}}),Ae.addEventListener("click",a=>{let m=a.target.closest("button[data-approval-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let x=m.closest(".persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let P=m.getAttribute("data-approval-action");if(!P)return;let G=P==="approve"?"approved":"denied",X=V.getMessages().find(he=>he.id===A);if(!X?.approval)return;let re=x.querySelector("[data-approval-buttons]");re&&re.querySelectorAll("button").forEach(ue=>{ue.disabled=!0,ue.style.opacity="0.5",ue.style.cursor="not-allowed"}),X.approval.toolType==="webmcp"?V.resolveWebMcpApproval(A,G):V.resolveApproval(X.approval,G)});let Je=null,ls=null,Ho=()=>{},cs="none",vi=null,Ln={artifacts:[],selectedId:null},zn=!1,Pn=!1,ds=!1,dr=!1,np=()=>dr||Ln.artifacts.some(a=>xo(o.features?.artifacts,a)==="panel"),xi=()=>Ln.artifacts.length>0&&!zn&&np(),at={current:null},xl=(a,u)=>{let m=V.getArtifactById(u),x=m?.markdown,A=m?.title||"artifact",P=m?.file,G=m?.artifactType??"markdown";if(!x){let re=a.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(re){let ue=V.getMessages().find(we=>we.id===re);if(ue?.rawContent)try{let we=JSON.parse(ue.rawContent);x=we?.props?.markdown,A=we?.props?.title||A,we?.props?.file&&typeof we.props.file=="object"&&(P=we.props.file),!m&&typeof we?.props?.artifactType=="string"&&(G=we.props.artifactType)}catch{}}}return{markdown:x,title:A,file:P,artifactType:G}};Ae.addEventListener("click",a=>{let m=a.target.closest("[data-download-artifact]");if(!m)return;a.preventDefault(),a.stopPropagation();let x=m.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:P,title:G,file:j}=xl(m,x);if(!P)return;let{filename:X,mime:re,content:he}=wf({title:G,markdown:P,file:j}),ue=new Blob([he],{type:re}),we=URL.createObjectURL(ue),Xe=document.createElement("a");Xe.href=we,Xe.download=X,Xe.click(),URL.revokeObjectURL(we)}),Ae.addEventListener("click",a=>{let m=a.target.closest("[data-artifact-custom-action]");if(!m)return;a.preventDefault(),a.stopPropagation();let x=m.getAttribute("data-artifact-custom-action");if(!x)return;let A=m.closest("[data-artifact-inline]"),P=A?null:m.closest("[data-open-artifact]"),G=A?A.getAttribute("data-artifact-inline"):P?.getAttribute("data-open-artifact")??null,X=(A?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(yt=>yt.id===x);if(!X)return;let{markdown:re,title:he,file:ue,artifactType:we}=xl(m,G??""),Xe={artifactId:G,title:he,artifactType:we,markdown:re,file:ue};try{Promise.resolve(X.onClick(Xe)).catch(()=>{})}catch{}}),Ae.addEventListener("click",a=>{let m=a.target.closest("[data-copy-artifact]");if(!m)return;a.preventDefault(),a.stopPropagation();let x=m.getAttribute("data-copy-artifact");if(!x)return;let A=V.getArtifactById(x),P="";if(A)P=Js(A);else{let{markdown:G,file:j,artifactType:X}=xl(m,x);X==="markdown"&&(P=Js({id:x,artifactType:"markdown",status:"complete",markdown:G??"",...j?{file:j}:{}}))}P&&navigator.clipboard.writeText(P).then(()=>{let G=ie("check",16,"currentColor",2);G&&(m.replaceChildren(G),setTimeout(()=>{let j=ie("copy",16,"currentColor",2);j&&m.replaceChildren(j)},1500))}).catch(()=>{})}),Ae.addEventListener("click",a=>{let m=a.target.closest("[data-expand-artifact-inline]");if(!m)return;a.preventDefault(),a.stopPropagation();let x=m.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(zn=!1,dr=!0,Pn=!0,ds=!0,V.selectArtifact(x),Un())}),Ae.addEventListener("click",a=>{let u=a.target;if(u.closest("[data-download-artifact]")||u.closest("[data-artifact-custom-action]"))return;let m=u.closest("[data-open-artifact]");if(!m)return;let x=m.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(a.preventDefault(),a.stopPropagation(),zn=!1,dr=!0,V.selectArtifact(x),Un())}),Ae.addEventListener("keydown",a=>{if(a.key!=="Enter"&&a.key!==" ")return;let u=a.target;!u.hasAttribute("data-open-artifact")&&!u.hasAttribute("data-expand-artifact-inline")||(a.preventDefault(),u.click())});let pr=ke.composerOverlay,ur=(a,u,m)=>{let x=u.trim();if(!x||!at.current)return;let A=a.getAttribute("data-tool-call-id")??"",P=m.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:x,answers:m.structured,values:m.values??(m.source==="multi"?x.split(", "):[x]),isFreeText:P,source:m.source},bubbles:!0,composed:!0})),Wr(pr,A);let G=at.current.getMessages().find(j=>j.toolCall?.id===A);G?.agentMetadata?.awaitingLocalTool?at.current.resolveAskUserQuestion(G,m.structured??x):at.current.sendMessage(x)},Bo=a=>{let u=at.current;if(!u)return;let m=a.getAttribute("data-tool-call-id")??"",x=u.getMessages().find(A=>A.toolCall?.id===m);x&&u.persistAskUserQuestionProgress(x,{answers:Zi(a,x),currentIndex:Cn(a)})},op=a=>Object.entries(a).map(([u,m])=>`${u}: ${Array.isArray(m)?m.join(", "):m}`).join(" | "),wl=a=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let u=Cn(a),m=Rr(a);if(u>=m-1)return;let x=at.current?.getMessages().find(A=>A.toolCall?.id===a.getAttribute("data-tool-call-id"));x&&(ta(a,x,o,u+1),Bo(a))};pr.addEventListener("click",a=>{let m=a.target.closest("[data-ask-user-action]");if(!m)return;let x=m.closest("[data-persona-ask-sheet-for]");if(!x)return;let A=m.getAttribute("data-ask-user-action");if(a.preventDefault(),a.stopPropagation(),A==="dismiss"){let P=x.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:P},bubbles:!0,composed:!0})),Wr(pr,P);let G=at.current?.getMessages().find(j=>j.toolCall?.id===P);G?.agentMetadata?.awaitingLocalTool&&(at.current?.markAskUserQuestionResolved(G),at.current?.resolveAskUserQuestion(G,"(dismissed)"));return}if(A==="pick"){let P=m.getAttribute("data-option-label");if(!P)return;let G=x.getAttribute("data-multi-select")==="true",j=Co(x);if(j&&G){let X=Jo(x)[Cn(x)],re=new Set(Array.isArray(X)?X:[]);re.has(P)?re.delete(P):re.add(P),Ao(x,Array.from(re)),Bo(x);return}if(j){Ao(x,P),Bo(x),wl(x);return}if(G){let X=m.getAttribute("aria-pressed")==="true";m.setAttribute("aria-pressed",X?"false":"true"),m.classList.toggle("persona-ask-pill-selected",!X);let re=x.querySelector('[data-ask-user-action="submit-multi"]');re&&(re.disabled=fc(x).length===0);return}ur(x,P,{source:"pick",values:[P]});return}if(A==="submit-multi"){let P=fc(x);if(P.length===0)return;ur(x,P.join(", "),{source:"multi",values:P});return}if(A==="open-free-text"){let P=x.querySelector('[data-ask-free-text-row="true"]');P&&(P.classList.remove("persona-hidden"),P.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(A==="focus-free-text"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(A==="submit-free-text"){let G=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!G.trim())return;if(Co(x)){Ao(x,G.trim()),Bo(x),wl(x);return}ur(x,G,{source:"free-text"});return}if(A==="next"||A==="back"){if(!at.current)return;let P=x.getAttribute("data-tool-call-id")??"",G=at.current.getMessages().find(ue=>ue.toolCall?.id===P);if(!G)return;let X=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(X){let ue=Jo(x)[Cn(x)];(typeof ue!="string"||ue!==X)&&Ao(x,X)}let re=A==="next"?1:-1,he=Cn(x)+re;ta(x,G,o,he),Bo(x);return}if(A==="submit-all"){if(!at.current)return;let P=x.getAttribute("data-tool-call-id")??"",G=at.current.getMessages().find(ue=>ue.toolCall?.id===P);if(!G)return;let X=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";X&&Ao(x,X);let re=Zi(x,G);at.current.persistAskUserQuestionProgress(G,{answers:re,currentIndex:Cn(x)});let he=op(re);ur(x,he||"(submitted)",{source:"submit-all",structured:re});return}if(A==="skip"){if(!at.current)return;let P=x.getAttribute("data-tool-call-id")??"",G=at.current.getMessages().find(we=>we.toolCall?.id===P);if(!G)return;let j=Co(x),X=Cn(x),re=Rr(x),he=X>=re-1;if(!j){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:P},bubbles:!0,composed:!0})),Wr(pr,P),G.agentMetadata?.awaitingLocalTool&&(at.current.markAskUserQuestionResolved(G),at.current.resolveAskUserQuestion(G,"(dismissed)"));return}Ao(x,"");let ue=x.querySelector('[data-ask-free-text-input="true"]');if(ue&&(ue.value=""),he){let we=Zi(x,G),Xe=op(we);ur(x,Xe||"(skipped)",{source:"submit-all",structured:we});return}ta(x,G,o,X+1),Bo(x);return}}),pr.addEventListener("keydown",a=>{if(a.key!=="Enter")return;let m=a.target;if(!m.matches?.('[data-ask-free-text-input="true"]'))return;let x=m.closest("[data-persona-ask-sheet-for]");if(!x)return;a.preventDefault();let A=m.value;if(A.trim()){if(Co(x)){Ao(x,A.trim()),Bo(x),wl(x);return}ur(x,A,{source:"free-text"})}});let rp=a=>{if(!/^[1-9]$/.test(a.key)||a.metaKey||a.ctrlKey||a.altKey)return;let u=a.target;if(u?.tagName==="INPUT"||u?.tagName==="TEXTAREA"||u?.isContentEditable)return;let m=pr.querySelector("[data-persona-ask-sheet-for]");if(!m||m.getAttribute("data-ask-layout")!=="rows"||m.getAttribute("data-multi-select")==="true")return;let x=Number(a.key),P=m.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];P&&(a.preventDefault(),P.click())};document.addEventListener("keydown",rp);let ao=null,Ct=null,ps=null,wi=null,Cl=()=>{},sp=!1,Ci="",Ai="";function Al(){wi?.(),wi=null}let ip=()=>{if(!ao||!Ct)return;let a=t.classList.contains("persona-artifact-welded-split"),u=t.ownerDocument.defaultView??window,m=u.innerWidth<=640;if(!a||t.classList.contains("persona-artifact-narrow-host")||m){Ct.style.removeProperty("position"),Ct.style.removeProperty("left"),Ct.style.removeProperty("top"),Ct.style.removeProperty("bottom"),Ct.style.removeProperty("width"),Ct.style.removeProperty("z-index");return}let x=ao.firstElementChild;if(!x||x===Ct)return;let A=10;Ct.style.position="absolute",Ct.style.top="0",Ct.style.bottom="0",Ct.style.width=`${A}px`,Ct.style.zIndex="5";let P=Cd(ao,u),G=x.offsetWidth+P/2-A/2;Ct.style.left=`${Math.max(0,G)}px`},Si=()=>{},Mh=()=>{let a=t.ownerDocument.defaultView??window,u=o.launcher?.mobileFullscreen??!0,m=o.launcher?.mobileBreakpoint??640;return!u||a.innerWidth>m?!1:z||Ot(o)},Mi=()=>!nn(o)||!xi()||t.classList.contains("persona-artifact-narrow-host")||Mh()||(t.ownerDocument.defaultView??window).innerWidth<gC?"none":vd(o)?"detached":"welded",Un=()=>{if(!Je||!nn(o))return;gi(t,o),fi(t,o),Si();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,u=xe.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",u>0&&u<=a);let m=xi();Je.setVisible(m),Je.update(Ln),zn?(Je.setMobileOpen(!1),Je.element.classList.add("persona-hidden"),Je.backdrop?.classList.add("persona-hidden"),Pn=!1,ds=!1):Ln.artifacts.length>0&&np()?(Je.element.classList.remove("persona-hidden"),Je.setMobileOpen(!0)):(Je.setMobileOpen(!1),Je.element.classList.add("persona-hidden"),Je.backdrop?.classList.add("persona-hidden"),Pn=!1,ds=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Je.setExpandToggleVisible(x),Je.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Je.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Je.setTabFade(o.features?.artifacts?.layout?.tabFade),Je.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!ds&&(Pn=!1),Pn!==sp){let P=Je.element;Pn?(Ci=P.style.width,Ai=P.style.maxWidth,P.style.removeProperty("width"),P.style.removeProperty("max-width")):(Ci&&(P.style.width=Ci),Ai&&(P.style.maxWidth=Ai),Ci="",Ai=""),sp=Pn}t.classList.toggle("persona-artifact-expanded",Pn),Je.setExpanded(Pn);let A=Mi();A!==cs&&(cs=A,Ho()),Cl()};if(nn(o)){xe.style.position="relative";let a=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");a.appendChild(Ce),Je=Hm(o,{onSelect:m=>at.current?.selectArtifact(m),onDismiss:()=>{zn=!0,Un()},onToggleExpand:()=>{let m=!Pn,x=Ln.selectedId??Ln.artifacts[Ln.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:m})!==!0&&(Pn=m,m||(ds=!1),Un())}}),Je.element.classList.add("persona-hidden"),ao=u,u.appendChild(a),u.appendChild(Je.element),Je.backdrop&&xe.appendChild(Je.backdrop),xe.appendChild(u),Cl=()=>{if(!ao||!Je)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){ps?.(),ps=null,Al(),Ct&&(Ct.remove(),Ct=null),Je.element.style.removeProperty("width"),Je.element.style.removeProperty("maxWidth");return}if(!Ct){let x=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");x.setAttribute("role","separator"),x.setAttribute("aria-orientation","vertical"),x.setAttribute("aria-label","Resize artifacts panel"),x.tabIndex=0;let A=t.ownerDocument,P=A.defaultView??window,G=j=>{if(!Je||j.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||P.innerWidth<=640)return;j.preventDefault(),Al();let X=j.clientX,re=Je.element.getBoundingClientRect().width,he=o.features?.artifacts?.layout,ue=Xe=>{let yt=ao.getBoundingClientRect().width,pt=t.classList.contains("persona-artifact-welded-split"),dn=Cd(ao,P),Et=pt?0:x.getBoundingClientRect().width||6,Wt=re-(Xe.clientX-X),U=Um(Wt,yt,dn,Et,he?.resizableMinWidth,he?.resizableMaxWidth);Je.element.style.width=`${U}px`,Je.element.style.maxWidth="none",ip()},we=()=>{A.removeEventListener("pointermove",ue),A.removeEventListener("pointerup",we),A.removeEventListener("pointercancel",we),wi=null;try{x.releasePointerCapture(j.pointerId)}catch{}};wi=we,A.addEventListener("pointermove",ue),A.addEventListener("pointerup",we),A.addEventListener("pointercancel",we);try{x.setPointerCapture(j.pointerId)}catch{}};x.addEventListener("pointerdown",G),Ct=x,ao.insertBefore(x,Je.element),ps=()=>{x.removeEventListener("pointerdown",G)}}if(Ct){let x=xi();Ct.classList.toggle("persona-hidden",!x),ip()}},Si=()=>{if(!z||!Je||(o.launcher?.sidebarMode??!1)||Ot(o)&&An(o).reveal==="emerge")return;let x=t.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,P=o.launcher?.mobileBreakpoint??640;if(A&&x.innerWidth<=P||!Om(o,z))return;let G=o.launcher?.width??o.launcherWidth??no,j=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";xi()?(xe.style.width=j,xe.style.maxWidth=j):(xe.style.width=G,xe.style.maxWidth=G)},typeof ResizeObserver<"u"&&(ls=new ResizeObserver(()=>{Un()}),ls.observe(xe))}else xe.appendChild(Ce);K()&&ot&&(ke.peekBanner&&ot.appendChild(ke.peekBanner),ot.appendChild(Se)),t.appendChild(Pe),ot&&t.appendChild(ot);let Sl=()=>{if(K()){xe.style.width="100%",xe.style.maxWidth="100%";let Pt=o.launcher?.composerBar??{},sn=Pe.dataset.state==="expanded",Ui=Pt.expandedSize??"anchored";if(!(sn&&Ui!=="fullscreen")){Ce.style.background="",Ce.style.border="",Ce.style.borderRadius="",Ce.style.overflow="",Ce.style.boxShadow="";return}let Ts=o.theme?.components?.panel,ji=$r(o),Sr=(Xn,Xo)=>Xn==null||Xn===""?Xo:tn(ji,Xn)??Xn,Vi="1px solid var(--persona-border)",oc="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Qo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Ce.style.background="var(--persona-surface, #ffffff)",Ce.style.border=Sr(Ts?.border,Vi),Ce.style.borderRadius=Sr(Ts?.borderRadius,Qo),Ce.style.boxShadow=Sr(Ts?.shadow,oc),Ce.style.overflow="hidden";return}let a=Ot(o),u=o.launcher?.sidebarMode??!1,m=a||u||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,A=o.launcher?.detachedPanel===!0,P=o.theme?.components?.panel,G=$r(o),j=(Pt,sn)=>Pt==null||Pt===""?sn:tn(G,Pt)??Pt,X=t.ownerDocument.defaultView??window,re=o.launcher?.mobileFullscreen??!0,he=o.launcher?.mobileBreakpoint??640,ue=X.innerWidth<=he,we=re&&ue&&z,Xe=a&&re&&ue,yt=o.launcher?.position??"bottom-left",pt=yt==="bottom-left"||yt==="top-left",dn=o.launcher?.zIndex??Ut,Et="var(--persona-panel-border, 1px solid var(--persona-border))",Wt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",U="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Re=A&&!we&&!Xe;Re?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let _e=Re?Et:u||we?"none":Et,Le=Re?Wt:we?"none":u?pt?"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))":x?"none":Wt;a&&!we&&!Re&&(Le="none",_e="none");let Tt=Re?U:u||we?"0":U,ut=j(P?.border,_e),$t=j(P?.shadow,Le),gt=j(P?.borderRadius,Tt),rn=Mi(),Ht=rn==="detached",We=rn==="welded";t.classList.toggle("persona-artifact-detached-split",Ht),t.classList.toggle("persona-artifact-welded-split",We);let $e="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",St=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&nn(o)&&vd(o)&&x&&!a;t.classList.toggle("persona-artifact-chat-flush",St);let lt=Ht||St?"none":$t,ft=Ht?Et:We?"none":ut,Ze=Ht?U:gt;St&&(ft="none",Ze="0");let De=P?.borderRadius!=null&&P.borderRadius!=="",vt=St&&!De?"0":gt,Gt=ce.scrollTop;t.style.cssText="",Pe.style.cssText="",xe.style.cssText="",Ce.style.cssText="",ce.style.cssText="",Se.style.cssText="",Ee&&(ce.style.display="none"),(m||x)&&(t.style.minWidth="0");let xn=()=>{if(Gt<=0)return;(ce.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ce.scrollTop===Gt)return;let sn=ce.scrollHeight-ce.clientHeight;sn<=0||(ce.scrollTop=Math.min(Gt,sn))})};if(we){Pe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Pe.style.cssText=`
1116
+ `,I.addEventListener("click",()=>{g=B,W.forEach((N,_)=>{let F=_<B;N.classList.toggle("selected",F),N.setAttribute("aria-checked",_===B-1?"true":"false")})}),W.push(I),T.appendChild(I)}b.appendChild(T);let E=null;if(d){let B=document.createElement("div");B.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=s,E.rows=3,E.setAttribute("aria-label","Additional comments"),B.appendChild(E),b.appendChild(B)}let k=document.createElement("div");k.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=l,A.addEventListener("click",()=>{n?.(),u.remove()});let D=document.createElement("button");return D.type="button",D.className="persona-feedback-btn persona-feedback-btn-submit",D.textContent=a,D.addEventListener("click",async()=>{if(g===null){T.classList.add("persona-feedback-shake"),setTimeout(()=>T.classList.remove("persona-feedback-shake"),500);return}D.disabled=!0,D.textContent="Submitting...";try{let B=E?.value.trim()||void 0;await e(g,B),u.remove()}catch(B){D.disabled=!1,D.textContent=a,console.error("[CSAT Feedback] Failed to submit:",B)}}),k.appendChild(A),k.appendChild(D),b.appendChild(k),u.appendChild(b),u}function Nw(t){let{onSubmit:e,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:l="Skip",showComment:d=!0,lowLabel:p="Not likely",highLabel:u="Very likely"}=t,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let b=null,m=document.createElement("div");m.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=o,y.appendChild(w);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=r,y.appendChild(T),m.appendChild(y);let W=document.createElement("div");W.className="persona-feedback-rating persona-feedback-rating-nps",W.setAttribute("role","radiogroup"),W.setAttribute("aria-label","Likelihood rating from 0 to 10");let E=document.createElement("div");E.className="persona-feedback-labels";let k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=p;let A=document.createElement("span");A.className="persona-feedback-label-high",A.textContent=u,E.appendChild(k),E.appendChild(A);let D=document.createElement("div");D.className="persona-feedback-numbers";let B=[];for(let P=0;P<=10;P++){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 ${P} out of 10`),V.textContent=String(P),V.dataset.rating=String(P),P<=6?V.classList.add("persona-feedback-detractor"):P<=8?V.classList.add("persona-feedback-passive"):V.classList.add("persona-feedback-promoter"),V.addEventListener("click",()=>{b=P,B.forEach((se,ve)=>{se.classList.toggle("selected",ve===P),se.setAttribute("aria-checked",ve===P?"true":"false")})}),B.push(V),D.appendChild(V)}W.appendChild(E),W.appendChild(D),m.appendChild(W);let I=null;if(d){let P=document.createElement("div");P.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=s,I.rows=3,I.setAttribute("aria-label","Additional comments"),P.appendChild(I),m.appendChild(P)}let N=document.createElement("div");N.className="persona-feedback-actions";let _=document.createElement("button");_.type="button",_.className="persona-feedback-btn persona-feedback-btn-skip",_.textContent=l,_.addEventListener("click",()=>{n?.(),g.remove()});let F=document.createElement("button");return F.type="button",F.className="persona-feedback-btn persona-feedback-btn-submit",F.textContent=a,F.addEventListener("click",async()=>{if(b===null){D.classList.add("persona-feedback-shake"),setTimeout(()=>D.classList.remove("persona-feedback-shake"),500);return}F.disabled=!0,F.textContent="Submitting...";try{let P=I?.value.trim()||void 0;await e(b,P),g.remove()}catch(P){F.disabled=!1,F.textContent=a,console.error("[NPS Feedback] Failed to submit:",P)}}),N.appendChild(_),N.appendChild(F),m.appendChild(N),g.appendChild(m),g}var ci="persona-chat-history",kk=30*1e3,Pk=641,Lk={"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 Ik(t){if(!t)return[];let e=[],n=Array.from(t.items??[]);for(let o of n){if(o.kind!=="file"||!o.type.startsWith("image/"))continue;let r=o.getAsFile();if(!r)continue;if(r.name){e.push(r);continue}let s=Lk[r.type]??"png";e.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let o of Array.from(t.files??[]))o.type.startsWith("image/")&&e.push(o);return e}function Ed(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function Hk(t){return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:t.storage??"session",keyPrefix:t.keyPrefix??"persona-",persist:{openState:t.persist?.openState??!0,voiceState:t.persist?.voiceState??!0,focusInput:t.persist?.focusInput??!0},clearOnChatClear:t.clearOnChatClear??!0}:null}function Rk(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var Fg=t=>!t||typeof t!="object"?{}:{...t},Ow=t=>t.map(e=>({...e,streaming:!1})),_w=(t,e,n)=>{let o=t?.markdown?Ql(t.markdown):null,r=Jl(t?.sanitize);return t?.postprocessMessage&&r&&t?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{let a=s.text??"",l=s.message.rawContent??null;if(e){let u=e.process({text:a,raw:l??a,message:s.message,streaming:s.streaming});u!==null&&(a=u.text,u.persist||(s.message.__skipPersist=!0),u.resubmit&&!s.streaming&&n&&n())}let d=zo()!==null,p;if(t?.postprocessMessage){let u=t.postprocessMessage({...s,text:a,raw:l??s.text??""});p=r?r(u):u}else if(o){let u=s.streaming?mh(a):a,g=o(u);p=r&&d?r(g):g}else p=cr(a);return p}};function Fw(t){let e=v("div","persona-attachment-drop-overlay");t?.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),t?.backdropBlur!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t?.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t?.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t?.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t?.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t?.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=t?.iconName??"upload",o=t?.iconSize??"48px",r=t?.iconColor??"rgba(59, 130, 246, 0.6)",s=t?.iconStrokeWidth??.5,a=fe(n,o,r,s);if(a&&e.appendChild(a),t?.label){let l=v("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var Wk=(t,e)=>{let n={...t};for(let[o,r]of Object.entries(e)){let s=n[o];n[o]=s?{...s,...r}:r}return n},Bk=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:Wk(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),$w=(t,e,n)=>{if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let o=Bc(e),r=()=>{Ry({delayMs:o.tooltip?.delayMs??200,skipDelayMs:o.tooltip?.skipDelayMs??300})};r();let s=o.features;o=yg(o);let a=Cg.getForInstance(o.plugins),l=Eb(t),d=[],p=!1,u=kv(()=>o),{plugin:g,teardown:b}=Dv();o.components&&Ko.registerAll(o.components);let m=iw(),w=o.persistState===!1?null:o.storageAdapter??lw(),T={},W=null,E,k=new Promise(i=>{E=i}),A=!1,D=i=>{if(o.onStateLoaded)try{let c=o.onStateLoaded(i);if(c&&typeof c=="object"&&"state"in c){let{state:f,open:h}=c;return h&&(A=!0),f}return c}catch(c){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}return i};if(w?.load)try{let i=w.load();if(i&&typeof i.then=="function")W=i.then(c=>D(c??{messages:[],metadata:{}}));else{let f=D(i??{messages:[],metadata:{}});f.metadata&&(T=Fg(f.metadata)),f.messages?.length&&(o={...o,initialMessages:f.messages}),f.artifacts?.length&&(o={...o,initialArtifacts:f.artifacts,initialSelectedArtifactId:f.selectedArtifactId??null})}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",i)}else if(o.onStateLoaded)try{let i=D({messages:[],metadata:{}});i.messages?.length&&(o={...o,initialMessages:i.messages})}catch(i){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",i)}W||E();let B=()=>T,I=i=>{T=i({...T})??{},jd()},N=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Sg],_=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Va.message,Va.messageAndClick],F=Ag({parsers:N,handlers:_,getSessionMetadata:B,updateSessionMetadata:I,emit:m.emit,documentRef:typeof document<"u"?document:null});F.syncFromMetadata();let P=o.launcher?.enabled??!0,V=o.launcher?.autoExpand??!1,se=o.autoFocusInput??!1,ve=V,he=P,ge=o.layout?.header?.layout,re=!1,oe=()=>Ha(o),ee=()=>P||oe(),M=oe()?!1:P?V:!0,te=!1,pe=null,Se=()=>{te=!0,pe&&clearTimeout(pe),pe=setTimeout(()=>{te&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),te=!1)},1e4)},xe=_w(o,F,Se),Ce=o.features?.showReasoning??!0,Me=o.features?.showToolCalls??!0,ke=o.features?.showEventStreamToggle??!1,Oe=o.features?.scrollToBottom??{},ze=o.features?.scrollBehavior??{},qe=()=>(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-",De=`${qe()}event-stream`,Ue=ke?new _a(De):null,an=o.features?.eventStream?.maxEvents??2e3,Ee=ke?new Oa(an,Ue):null,$e=ke?new Fa:null,mt=null,At=!1,yt=null,Wt=0,Te=!1,ot=null,lt=()=>{},kt=()=>{},wn=()=>{},Ct=()=>{},Ln=()=>{},Gn=()=>At||Te&&ot==="panel";Ue?.open().then(()=>Ee?.restore()).catch(i=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",i)});let j={onCopy:i=>{m.emit("message:copy",i),z?.isClientTokenMode()&&z.submitMessageFeedback(i.id,"copy").catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",c)}),o.messageActions?.onCopy?.(i)},onFeedback:i=>{m.emit("message:feedback",i),z?.isClientTokenMode()&&z.submitMessageFeedback(i.messageId,i.type).catch(c=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",c)}),o.messageActions?.onFeedback?.(i)}},ae=o.statusIndicator??{},x=i=>i==="idle"?ae.idleText??Zt.idle:i==="connecting"?ae.connectingText??Zt.connecting:i==="connected"?ae.connectedText??Zt.connected:i==="error"?ae.errorText??Zt.error:i==="paused"?ae.pausedText??Zt.paused:i==="resuming"?ae.resumingText??Zt.resuming:Zt[i];function S(i,c,f,h){if(h==="idle"&&f.idleLink){i.textContent="";let C=document.createElement("a");C.href=f.idleLink,C.target="_blank",C.rel="noopener noreferrer",C.textContent=c,C.style.color="inherit",C.style.textDecoration="none",i.appendChild(C)}else i.textContent=c}let O=Ev({config:o,showClose:ee()}),{wrapper:R,panel:$,pillRoot:K}=O.shell,Y=O.panelElements,{container:Q,body:Z,messagesWrapper:ue,starterSuggestions:et,transcriptSuggestions:Ye,suggestions:Be,textarea:ye,sendButton:we,sendButtonWrapper:ct,composerForm:_e,statusText:Bt,welcomeHost:ln,welcomeIconHolder:pi,greetingHost:cn,introTitle:ls,introSubtitle:Xa,closeButton:Ke,iconHolder:Fe,headerTitle:tn,headerSubtitle:fo,header:Pe,footer:Je,actionsRow:io,rightActions:ui}=Y,ao=Y.leftActions,Sr=Y.setSendButtonMode,de=Y.micButton,Nn=Y.micButtonWrapper,vt=Y.attachmentButton,yn=Y.attachmentButtonWrapper,Dt=Y.attachmentInput,On=Y.attachmentPreviewsContainer;Q.classList.add("persona-relative"),Z.classList.add("persona-relative");let q=12,ce=()=>Oe.label??"",He=()=>Oe.iconName??"arrow-down",Xe=()=>Oe.enabled!==!1,Le=()=>ze.mode??"anchor-top",Nt=()=>Le()==="follow"||Le()==="anchor-top"&&Ci,In=()=>ze.anchorTopOffset??16,Qo=()=>ze.restorePosition??"bottom",cs=()=>ze.pauseOnInteraction===!0,Kg=()=>ze.showActivityWhilePinned!==!1,Gg=()=>ze.announce===!0,Pd=()=>ze.scrollbar??"on-scroll",Gt=v("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");Gt.type="button",Gt.style.display="none",Gt.setAttribute("data-persona-scroll-to-bottom","true");let gi=v("span","persona-flex persona-items-center"),Ld=v("span",""),Ar=v("span","");Ar.setAttribute("data-persona-scroll-to-bottom-count",""),Ar.style.display="none",Gt.append(gi,Ld,Ar),Q.appendChild(Gt);let Yn=v("div","persona-stream-anchor-spacer");Yn.setAttribute("aria-hidden","true"),Yn.setAttribute("data-persona-anchor-spacer",""),Yn.style.flexShrink="0",Yn.style.pointerEvents="none",Yn.style.height="0px",Yn.style.display="none",Z.appendChild(Yn);let ko=v("div","persona-sr-only");ko.setAttribute("aria-live","polite"),ko.setAttribute("aria-atomic","true"),ko.setAttribute("role","status"),ko.setAttribute("data-persona-live-region",""),Object.assign(ko.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),Q.appendChild(ko);let fi=null,Qa=null,Yg=i=>{!Gg()||!i||(Qa=i,fi===null&&(fi=setTimeout(()=>{fi=null,Qa&&Gg()&&(ko.textContent=Qa),Qa=null},400)))},Mr=()=>{let c=Je.style.display==="none"?0:Je.offsetHeight;Gt.style.bottom=`${c+q}px`};Mr();let Xg=()=>{let i=!!ce();Gt.setAttribute("aria-label",ce()||"Jump to latest"),Gt.title=ce(),Gt.setAttribute("data-persona-scroll-to-bottom-has-label",i?"true":"false"),gi.innerHTML="";let c=fe(He(),"14px","currentColor",2);c?(gi.appendChild(c),gi.style.display=""):gi.style.display="none",Ld.textContent=ce(),Ld.style.display=i?"":"none"};Xg();let Pt=null,Cn=null,Qg=null,Jg=a.find(i=>i.renderHeader);if(Jg?.renderHeader){let i=Jg.renderHeader({config:o,defaultRenderer:()=>{let c=es({config:o,showClose:ee()});return Wa(Q,c,o),c.header},onClose:()=>xt(!1,"user")});if(i){let c=Pe;c&&(c.replaceWith(i),Pe=i,O.header.element=i)}}let Zg=()=>{mt&&(Z.style.display="none",Je.parentNode?.insertBefore(mt.element,Je),mt.update())},Id=()=>{if(!Ee)return;if(At=!0,mt?Zg():jv().then(c=>{mt||!At||!Ee||(mt=c.createEventStreamView({buffer:Ee,getFullHistory:()=>Ee.getAllFromStore(),onClose:()=>ds(),config:o,plugins:a,getThroughput:()=>$e?.getMetric()??{status:"idle"}}),Zg())}).catch(()=>{ds()}),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${kn.actionIconColor}`;let c=o.features?.eventStream?.classNames?.toggleButtonActive;c&&c.split(/\s+/).forEach(f=>f&&ut.classList.add(f))}let i=()=>{if(!At)return;let c=Date.now();c-Wt>=200&&(mt?.update(),Wt=c),yt=requestAnimationFrame(i)};Wt=0,yt=requestAnimationFrame(i),on(),m.emit("eventStream:opened",{timestamp:Date.now()})},ds=()=>{if(At){if(At=!1,mt&&mt.element.remove(),Z.style.display="",ut){ut.style.boxShadow="";let i=o.features?.eventStream?.classNames?.toggleButtonActive;i&&i.split(/\s+/).forEach(c=>c&&ut.classList.remove(c))}yt!==null&&(cancelAnimationFrame(yt),yt=null),on(),m.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(ke){let i=o.features?.eventStream?.classNames,c="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"+(i?.toggleButton?" "+i.toggleButton:"");ut=v("button",c),ut.style.width="28px",ut.style.height="28px",ut.style.color=kn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let f=fe("activity","18px","currentColor",1.5);f&&ut.appendChild(f);let h=Y.clearChatButtonWrapper,C=Y.closeButtonWrapper,L=h||C;L&&L.parentNode===Pe?Pe.insertBefore(ut,L):Pe.appendChild(ut),ut.addEventListener("click",()=>{At?ds():Id()})}let ef=i=>{let c=o.attachments;if(!c?.enabled)return;let f=i.querySelector("[data-persona-composer-attachment-previews]")??i.querySelector(".persona-attachment-previews");if(!f){f=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),f.setAttribute("data-persona-composer-attachment-previews",""),f.style.display="none";let C=i.querySelector("[data-persona-composer-form]");C?.parentNode?C.parentNode.insertBefore(f,C):i.insertBefore(f,i.firstChild)}if(!(i.querySelector("[data-persona-composer-attachment-input]")??i.querySelector('input[type="file"]'))){let C=v("input");C.type="file",C.setAttribute("data-persona-composer-attachment-input",""),C.accept=(c.allowedTypes??qo).join(","),C.multiple=(c.maxFiles??4)>1,C.style.display="none",C.setAttribute("aria-label",c.buttonTooltipText??"Attach files"),i.appendChild(C)}},Hd=a.find(i=>i.renderComposer),mi=!1,tf=i=>{if(!Hd?.renderComposer)return null;let c=o.composer,f=p?z.isStreaming():!1;return Hd.renderComposer({config:o,defaultRenderer:i,requestRender:()=>Wx(),storage:u(Hd.id),onSubmit:h=>{if(!z||z.isStreaming())return;let C=h.trim(),L=Pt?.hasAttachments()??!1;if(!C&&!L)return;Dm();let X;L&&(X=[],X.push(...Pt.getContentParts()),C&&X.push(hr(C))),z.sendMessage(C,{contentParts:X}),L&&Pt.clearAttachments()},streaming:f,disabled:f,openAttachmentPicker:()=>{Dt?.click()},models:c?.models,selectedModelId:c?.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Qg?.()}:void 0})},nf=tf(()=>Ba({config:o}).footer);nf&&(O.replaceComposer(nf),Je=O.composer.footer,mi=!0);let of=i=>{let c=(...le)=>{for(let be of le){let Ae=i.querySelector(be);if(Ae)return Ae}return null},f=i.querySelector("[data-persona-composer-form]"),h=i.querySelector("[data-persona-composer-input]"),C=i.querySelector("[data-persona-composer-submit]"),L=i.querySelector("[data-persona-composer-mic]"),X=i.querySelector("[data-persona-composer-status]");f&&(_e=f),h&&(ye=h),C&&(we=C),L&&(de=L,Nn=L.parentElement),X&&(Bt=X);let G=c("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");G&&(Be=G);let ie=c("[data-persona-composer-attachment-button]",".persona-attachment-button");ie&&(vt=ie,yn=ie.parentElement),Dt=c("[data-persona-composer-attachment-input]",'input[type="file"]'),On=c("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ne=c("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ne&&(io=ne),ao=c(".persona-widget-composer__left-actions")};ef(Je),of(Je);let hi=yr(o,oe());hi&&(ue.style.maxWidth=hi,ue.style.marginLeft="auto",ue.style.marginRight="auto",ue.style.width="100%",cn.style.maxWidth=hi,cn.style.marginLeft="auto",cn.style.marginRight="auto",cn.style.width="100%",et.style.maxWidth=hi,Ye.style.maxWidth=hi,Ye.style.marginLeft="auto",Ye.style.marginRight="auto",Ye.style.width="100%");let rf=()=>{let i=yr(o,oe());if(!(!i||oe()))for(let c of[_e,Be,On,Bt])c&&(c.style.maxWidth=i,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%")};rf();let sf=()=>{!o.attachments?.enabled||!Dt||!On||(Pt?Pt.remountPreviews(On):(Pt=ua.fromConfig(o.attachments),Pt.setPreviewsContainer(On)),Dt.addEventListener("change",i=>{let c=i.target;Pt?.handleFileSelect(c.files),c.value=""}),Q.querySelector(".persona-attachment-drop-overlay")||Q.appendChild(Fw(o.attachments.dropOverlay)))};sf();let eC=()=>Cn?.prefetch(),af=()=>{if(!(!o.contextMentions?.enabled||!ye)&&(Cn=hb({config:o,textarea:ye,anchor:_e??ye,getMessages:()=>z.getMessages(),liveRegionHost:Q}),Cn)){let i=ye;i.parentElement?.insertBefore(Cn.contextRow,i);let c=Cn.affordanceButtons;for(let f=c.length-1;f>=0;f--){let h=c[f];ao?ao.insertBefore(h,ao.firstChild):_e?.appendChild(h)}}};af(),(()=>{let i=o.layout?.slots??{},c=h=>{switch(h){case"body-top":return Z.querySelector("[data-persona-intro-card]");case"messages":return ue;case"footer-top":return Be;case"composer":return _e;case"footer-bottom":return Bt;default:return null}},f=(h,C)=>{switch(h){case"header-left":case"header-center":case"header-right":if(h==="header-left")Pe.insertBefore(C,Pe.firstChild);else if(h==="header-right")Pe.appendChild(C);else{let L=Pe.querySelector(".persona-flex-col");L?L.parentNode?.insertBefore(C,L.nextSibling):Pe.appendChild(C)}break;case"body-top":{let L=Z.querySelector("[data-persona-intro-card]");L?L.replaceWith(C):Z.insertBefore(C,Z.firstChild);break}case"body-bottom":Z.appendChild(C);break;case"footer-top":Be.replaceWith(C);break;case"footer-bottom":Bt.replaceWith(C);break;default:break}};for(let[h,C]of Object.entries(i))if(C)try{let L=C({config:o,defaultContent:()=>c(h)});L&&f(h,L)}catch(L){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${h}":`,L)}})();let lf=i=>{let f=i.target.closest('button[data-expand-header="true"]');if(!f)return;let h=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!h)return;let C=h.getAttribute("data-message-id");if(!C)return;let L=f.getAttribute("data-bubble-type");if(L==="reasoning")ri.has(C)?ri.delete(C):ri.add(C),Pv(C,h);else if(L==="tool")si.has(C)?si.delete(C):si.add(C),Lv(C,h,o);else if(L==="approval"){let G=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",ie=ns.get(C)??G;ns.set(C,!ie),Wv(C,h,o)}Fn.delete(C)};ue.addEventListener("pointerdown",i=>{i.target.closest('button[data-expand-header="true"]')&&(i.preventDefault(),lf(i))}),ue.addEventListener("keydown",i=>{let c=i.target;(i.key==="Enter"||i.key===" ")&&c.closest('button[data-expand-header="true"]')&&(i.preventDefault(),lf(i))}),ue.addEventListener("copy",i=>{let{clipboardData:c}=i;if(!c)return;let f=ue.getRootNode(),h=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!h||h.isCollapsed)return;let C=h.toString(),L=Gb(C);!L||L===C||(c.setData("text/plain",L),i.preventDefault())});let Rd=new Map,cf=null,df="idle",tC={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},nC=(i,c)=>{let{icon:f,label:h}=tC[c];i.setAttribute("aria-label",h),i.title=h,i.setAttribute("aria-pressed",c==="idle"?"false":"true"),i.classList.toggle("persona-message-action-active",c!=="idle"),i.classList.toggle("persona-message-action-loading",c==="loading");let C=fe(f,14,"currentColor",2);C&&(i.innerHTML="",i.appendChild(C))},pf=()=>{ue.querySelectorAll('[data-action="read-aloud"]').forEach(c=>{let h=c.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;nC(c,h&&h===cf?df:"idle")})};ue.addEventListener("click",i=>{let f=i.target.closest(".persona-message-action-btn[data-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let h=f.closest("[data-actions-for]");if(!h)return;let C=h.getAttribute("data-actions-for");if(!C)return;let L=f.getAttribute("data-action");if(L==="copy"){let G=z.getMessages().find(ie=>ie.id===C);if(G&&j.onCopy){let ie=G.content||"";navigator.clipboard.writeText(ie).then(()=>{f.classList.add("persona-message-action-success");let ne=fe("check",14,"currentColor",2);ne&&(f.innerHTML="",f.appendChild(ne)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let le=fe("copy",14,"currentColor",2);le&&(f.innerHTML="",f.appendChild(le))},2e3)}).catch(ne=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",ne)}),j.onCopy(G)}}else if(L==="read-aloud")z.toggleReadAloud(C);else if(L==="upvote"||L==="downvote"){let G=(Rd.get(C)??null)===L,ie=L==="upvote"?"thumbs-up":"thumbs-down";if(G){Rd.delete(C),f.classList.remove("persona-message-action-active");let ne=fe(ie,14,"currentColor",2);ne&&(f.innerHTML="",f.appendChild(ne))}else{let ne=L==="upvote"?"downvote":"upvote",le=h.querySelector(`[data-action="${ne}"]`);if(le){le.classList.remove("persona-message-action-active");let pn=fe(ne==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);pn&&(le.innerHTML="",le.appendChild(pn))}Rd.set(C,L),f.classList.add("persona-message-action-active");let be=fe(ie,14,"currentColor",2);be&&(be.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(be)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let gt=z.getMessages().find(Ht=>Ht.id===C);gt&&j.onFeedback&&j.onFeedback({type:L,messageId:gt.id,message:gt})}}}),ue.addEventListener("click",i=>{let f=i.target.closest("button[data-approval-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let h=f.closest(".persona-approval-bubble");if(!h)return;let C=h.getAttribute("data-message-id");if(!C)return;let L=f.getAttribute("data-approval-action");if(!L)return;let X=L==="approve"?"approved":"denied",ie=z.getMessages().find(le=>le.id===C);if(!ie?.approval)return;let ne=h.querySelector("[data-approval-buttons]");ne&&ne.querySelectorAll("button").forEach(be=>{be.disabled=!0,be.style.opacity="0.5",be.style.cursor="not-allowed"}),ie.approval.toolType==="webmcp"?z.resolveWebMcpApproval(C,X):z.resolveApproval(ie.approval,X)});let tt=null,yi=null,Tr=()=>{},bi="none",Ja=null,lo={artifacts:[],selectedId:null},Po=!1,co=!1,vi=!1,ps=!1,uf=()=>ps||lo.artifacts.some(i=>dr(o.features?.artifacts,i)==="panel"),Za=()=>lo.artifacts.length>0&&!Po&&uf(),wt={current:null},Wd=(i,c)=>{let f=z.getArtifactById(c),h=f?.markdown,C=f?.title||"artifact",L=f?.file,X=f?.artifactType??"markdown";if(!h){let ne=i.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(ne){let be=z.getMessages().find(Ae=>Ae.id===ne);if(be?.rawContent)try{let Ae=JSON.parse(be.rawContent);h=Ae?.props?.markdown,C=Ae?.props?.title||C,Ae?.props?.file&&typeof Ae.props.file=="object"&&(L=Ae.props.file),!f&&typeof Ae?.props?.artifactType=="string"&&(X=Ae.props.artifactType)}catch{}}}return{markdown:h,title:C,file:L,artifactType:X}};ue.addEventListener("click",i=>{let f=i.target.closest("[data-download-artifact]");if(!f)return;i.preventDefault(),i.stopPropagation();let h=f.getAttribute("data-download-artifact");if(!h||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:h})===!0)return;let{markdown:L,title:X,file:G}=Wd(f,h);L&&jc(Vc({title:X,markdown:L,file:G}))}),ue.addEventListener("click",i=>{let f=i.target.closest("[data-artifact-custom-action]");if(!f)return;i.preventDefault(),i.stopPropagation();let h=f.getAttribute("data-artifact-custom-action");if(!h)return;let C=f.closest("[data-artifact-inline]"),L=C?null:f.closest("[data-open-artifact]"),X=C?C.getAttribute("data-artifact-inline"):L?.getAttribute("data-open-artifact")??null,ie=(C?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(Ht=>Ht.id===h);if(!ie)return;let{markdown:ne,title:le,file:be,artifactType:Ae}=Wd(f,X??""),gt={artifactId:X,title:le,artifactType:Ae,markdown:ne,file:be};try{Promise.resolve(ie.onClick(gt)).catch(()=>{})}catch{}}),ue.addEventListener("click",i=>{let f=i.target.closest("[data-copy-artifact]");if(!f)return;i.preventDefault(),i.stopPropagation();let h=f.getAttribute("data-copy-artifact");if(!h)return;let C=z.getArtifactById(h),L="";if(C)L=Ta(C);else{let{markdown:X,file:G,artifactType:ie}=Wd(f,h);ie==="markdown"&&(L=Ta({id:h,artifactType:"markdown",status:"complete",markdown:X??"",...G?{file:G}:{}}))}L&&navigator.clipboard.writeText(L).then(()=>{let X=fe("check",16,"currentColor",2);X&&(f.replaceChildren(X),setTimeout(()=>{let G=fe("copy",16,"currentColor",2);G&&f.replaceChildren(G)},1500))}).catch(()=>{})}),ue.addEventListener("click",i=>{let f=i.target.closest("[data-expand-artifact-inline]");if(!f)return;i.preventDefault(),i.stopPropagation();let h=f.getAttribute("data-expand-artifact-inline");!h||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:h})===!0||(Po=!1,ps=!0,co=!0,vi=!0,z.selectArtifact(h),Lo())}),ue.addEventListener("click",i=>{let c=i.target;if(c.closest("[data-download-artifact]")||c.closest("[data-artifact-custom-action]"))return;let f=c.closest("[data-open-artifact]");if(!f)return;let h=f.getAttribute("data-open-artifact");!h||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:h})===!0||(i.preventDefault(),i.stopPropagation(),Po=!1,ps=!0,z.selectArtifact(h),Lo())}),ue.addEventListener("keydown",i=>{if(i.key!=="Enter"&&i.key!==" ")return;let c=i.target;!c.hasAttribute("data-open-artifact")&&!c.hasAttribute("data-expand-artifact-inline")||(i.preventDefault(),c.click())});let us=Y.composerOverlay,gs=(i,c,f)=>{let h=c.trim();if(!h||!wt.current)return;let C=i.getAttribute("data-tool-call-id")??"",L=f.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:C,answer:h,answers:f.structured,values:f.values??(f.source==="multi"?h.split(", "):[h]),isFreeText:L,source:f.source},bubbles:!0,composed:!0})),Os(us,C);let X=wt.current.getMessages().find(G=>G.toolCall?.id===C);X?.agentMetadata?.awaitingLocalTool?wt.current.resolveAskUserQuestion(X,f.structured??h):wt.current.sendMessage(h)},Er=i=>{let c=wt.current;if(!c)return;let f=i.getAttribute("data-tool-call-id")??"",h=c.getMessages().find(C=>C.toolCall?.id===f);h&&c.persistAskUserQuestionProgress(h,{answers:tc(i,h),currentIndex:oo(i)})},gf=i=>Object.entries(i).map(([c,f])=>`${c}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),Bd=i=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let c=oo(i),f=Ns(i);if(c>=f-1)return;let h=wt.current?.getMessages().find(C=>C.toolCall?.id===i.getAttribute("data-tool-call-id"));h&&(oc(i,h,o,c+1),Er(i))};us.addEventListener("click",i=>{let f=i.target.closest("[data-ask-user-action]");if(!f)return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;let C=f.getAttribute("data-ask-user-action");if(i.preventDefault(),i.stopPropagation(),C==="dismiss"){let L=h.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:L},bubbles:!0,composed:!0})),Os(us,L);let X=wt.current?.getMessages().find(G=>G.toolCall?.id===L);X?.agentMetadata?.awaitingLocalTool&&(wt.current?.markAskUserQuestionResolved(X),wt.current?.resolveAskUserQuestion(X,"(dismissed)"));return}if(C==="pick"){let L=f.getAttribute("data-option-label");if(!L)return;let X=h.getAttribute("data-multi-select")==="true",G=ur(h);if(G&&X){let ie=Gr(h)[oo(h)],ne=new Set(Array.isArray(ie)?ie:[]);ne.has(L)?ne.delete(L):ne.add(L),gr(h,Array.from(ne)),Er(h);return}if(G){gr(h,L),Er(h),Bd(h);return}if(X){let ie=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",ie?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!ie);let ne=h.querySelector('[data-ask-user-action="submit-multi"]');ne&&(ne.disabled=nu(h).length===0);return}gs(h,L,{source:"pick",values:[L]});return}if(C==="submit-multi"){let L=nu(h);if(L.length===0)return;gs(h,L.join(", "),{source:"multi",values:L});return}if(C==="open-free-text"){let L=h.querySelector('[data-ask-free-text-row="true"]');L&&(L.classList.remove("persona-hidden"),L.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(C==="focus-free-text"){h.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(C==="submit-free-text"){let X=h.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!X.trim())return;if(ur(h)){gr(h,X.trim()),Er(h),Bd(h);return}gs(h,X,{source:"free-text"});return}if(C==="next"||C==="back"){if(!wt.current)return;let L=h.getAttribute("data-tool-call-id")??"",X=wt.current.getMessages().find(be=>be.toolCall?.id===L);if(!X)return;let ie=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(ie){let be=Gr(h)[oo(h)];(typeof be!="string"||be!==ie)&&gr(h,ie)}let ne=C==="next"?1:-1,le=oo(h)+ne;oc(h,X,o,le),Er(h);return}if(C==="submit-all"){if(!wt.current)return;let L=h.getAttribute("data-tool-call-id")??"",X=wt.current.getMessages().find(be=>be.toolCall?.id===L);if(!X)return;let ie=h.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";ie&&gr(h,ie);let ne=tc(h,X);wt.current.persistAskUserQuestionProgress(X,{answers:ne,currentIndex:oo(h)});let le=gf(ne);gs(h,le||"(submitted)",{source:"submit-all",structured:ne});return}if(C==="skip"){if(!wt.current)return;let L=h.getAttribute("data-tool-call-id")??"",X=wt.current.getMessages().find(Ae=>Ae.toolCall?.id===L);if(!X)return;let G=ur(h),ie=oo(h),ne=Ns(h),le=ie>=ne-1;if(!G){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:L},bubbles:!0,composed:!0})),Os(us,L),X.agentMetadata?.awaitingLocalTool&&(wt.current.markAskUserQuestionResolved(X),wt.current.resolveAskUserQuestion(X,"(dismissed)"));return}gr(h,"");let be=h.querySelector('[data-ask-free-text-input="true"]');if(be&&(be.value=""),le){let Ae=tc(h,X),gt=gf(Ae);gs(h,gt||"(skipped)",{source:"submit-all",structured:Ae});return}oc(h,X,o,ie+1),Er(h);return}}),us.addEventListener("keydown",i=>{if(i.key!=="Enter")return;let f=i.target;if(!f.matches?.('[data-ask-free-text-input="true"]'))return;let h=f.closest("[data-persona-ask-sheet-for]");if(!h)return;i.preventDefault();let C=f.value;if(C.trim()){if(ur(h)){gr(h,C.trim()),Er(h),Bd(h);return}gs(h,C,{source:"free-text"})}});let ff=i=>{if(!/^[1-9]$/.test(i.key)||i.metaKey||i.ctrlKey||i.altKey)return;let c=i.target;if(c?.tagName==="INPUT"||c?.tagName==="TEXTAREA"||c?.isContentEditable)return;let f=us.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let h=Number(i.key),L=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[h-1];L&&(i.preventDefault(),L.click())};document.addEventListener("keydown",ff);let mo=null,Lt=null,wi=null,el=null,Dd=()=>{},mf=!1,tl="",nl="";function Nd(){el?.(),el=null}let oC=()=>{let i=Ri&&As?.isConnected?As:null,c=i?i.getBoundingClientRect().width:0;return c<=0?200:c+360},hf=()=>{if(!mo||!Lt)return;let i=t.classList.contains("persona-artifact-welded-split"),c=t.ownerDocument.defaultView??window,f=c.innerWidth<=640;if(!i||t.classList.contains("persona-artifact-narrow-host")||f){Lt.style.removeProperty("position"),Lt.style.removeProperty("left"),Lt.style.removeProperty("top"),Lt.style.removeProperty("bottom"),Lt.style.removeProperty("width"),Lt.style.removeProperty("z-index");return}let h=mo.firstElementChild;if(!h||h===Lt)return;let C=10;Lt.style.position="absolute",Lt.style.top="0",Lt.style.bottom="0",Lt.style.width=`${C}px`,Lt.style.zIndex="5";let L=bg(mo,c),X=h.offsetWidth+L/2-C/2;Lt.style.left=`${Math.max(0,X)}px`},ol=()=>{},rC=()=>{let i=t.ownerDocument.defaultView??window,c=o.launcher?.mobileFullscreen??!0,f=o.launcher?.mobileBreakpoint??640;return!c||i.innerWidth>f?!1:P||Kt(o)},rl=()=>!Pn(o)||!Za()||t.classList.contains("persona-artifact-narrow-host")||rC()||(t.ownerDocument.defaultView??window).innerWidth<Pk?"none":mg(o)?"detached":"welded",Lo=()=>{if(!tt||!Pn(o))return;$a(t,o),za(t,o),ol();let i=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,c=$.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",c>0&&c<=i);let f=Za();tt.setVisible(f),tt.update(lo),Po?(tt.setMobileOpen(!1),tt.element.classList.add("persona-hidden"),tt.backdrop?.classList.add("persona-hidden"),co=!1,vi=!1):lo.artifacts.length>0&&uf()?(tt.element.classList.remove("persona-hidden"),tt.setMobileOpen(!0)):(tt.setMobileOpen(!1),tt.element.classList.add("persona-hidden"),tt.backdrop?.classList.add("persona-hidden"),co=!1,vi=!1);let h=o.features?.artifacts?.layout?.showExpandToggle===!0;if(tt.setExpandToggleVisible(h),tt.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),tt.setRefreshButtonVisible(typeof o.features?.artifacts?.layout?.onDocumentToolbarRefresh=="function"),tt.setCustomActions(o.features?.artifacts?.toolbarActions??[]),tt.setTabFade(o.features?.artifacts?.layout?.tabFade),tt.setRenderTabBar(o.features?.artifacts?.renderTabBar),!h&&!vi&&(co=!1),co!==mf){let L=tt.element;co?(tl=L.style.width,nl=L.style.maxWidth,L.style.removeProperty("width"),L.style.removeProperty("max-width")):(tl&&(L.style.width=tl),nl&&(L.style.maxWidth=nl),tl="",nl=""),mf=co}t.classList.toggle("persona-artifact-expanded",co),tt.setExpanded(co);let C=rl();C!==bi&&(bi=C,Tr()),Dd()};if(Pn(o)){$.style.position="relative";let i=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),c=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");i.appendChild(Q),tt=Uv(o,{onSelect:f=>wt.current?.selectArtifact(f),onDismiss:()=>{Po=!0,Lo()},onToggleExpand:()=>{let f=!co,h=lo.selectedId??lo.artifacts[lo.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:h,expanded:f})!==!0&&(co=f,f||(vi=!1),Lo())}}),tt.element.classList.add("persona-hidden"),mo=c,c.appendChild(i),c.appendChild(tt.element),tt.backdrop&&$.appendChild(tt.backdrop),$.appendChild(c),Dd=()=>{if(!mo||!tt)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){wi?.(),wi=null,Nd(),Lt&&(Lt.remove(),Lt=null),tt.element.style.removeProperty("width"),tt.element.style.removeProperty("maxWidth");return}if(!Lt){let h=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");h.setAttribute("role","separator"),h.setAttribute("aria-orientation","vertical"),h.setAttribute("aria-label","Resize artifacts panel"),h.tabIndex=0;let C=t.ownerDocument,L=C.defaultView??window,X=G=>{if(!tt||G.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||L.innerWidth<=640)return;G.preventDefault(),Nd();let ie=G.clientX,ne=tt.element.getBoundingClientRect().width,le=o.features?.artifacts?.layout,be=gt=>{let Ht=mo.getBoundingClientRect().width,pn=t.classList.contains("persona-artifact-welded-split"),Bn=bg(mo,L),Ft=pn?0:h.getBoundingClientRect().width||6,Vt=ne-(gt.clientX-ie),U=tw(Vt,Ht,Bn,Ft,le?.resizableMinWidth,le?.resizableMaxWidth,oC());tt.element.style.width=`${U}px`,tt.element.style.maxWidth="none",hf()},Ae=()=>{C.removeEventListener("pointermove",be),C.removeEventListener("pointerup",Ae),C.removeEventListener("pointercancel",Ae),el=null;try{h.releasePointerCapture(G.pointerId)}catch{}};el=Ae,C.addEventListener("pointermove",be),C.addEventListener("pointerup",Ae),C.addEventListener("pointercancel",Ae);try{h.setPointerCapture(G.pointerId)}catch{}};h.addEventListener("pointerdown",X),Lt=h,mo.insertBefore(h,tt.element),wi=()=>{h.removeEventListener("pointerdown",X)}}if(Lt){let h=Za();Lt.classList.toggle("persona-hidden",!h),hf()}},ol=()=>{if(!P||!tt||(o.launcher?.sidebarMode??!1)||Kt(o)&&ro(o).reveal==="emerge")return;let h=t.ownerDocument.defaultView??window,C=o.launcher?.mobileFullscreen??!0,L=o.launcher?.mobileBreakpoint??640;if(C&&h.innerWidth<=L||!Yv(o,P))return;let X=o.launcher?.width??o.launcherWidth??Uo,G=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Za()?($.style.width=G,$.style.maxWidth=G):($.style.width=X,$.style.maxWidth=X)},typeof ResizeObserver<"u"&&(yi=new ResizeObserver(()=>{Lo()}),yi.observe($))}else $.appendChild(Q);oe()&&K&&(Y.peekBanner&&K.appendChild(Y.peekBanner),K.appendChild(Je)),t.appendChild(R),K&&t.appendChild(K);let Od=()=>{if(oe()){$.style.width="100%",$.style.maxWidth="100%";let qt=o.launcher?.composerBar??{},Tn=R.dataset.state==="expanded",Ki=qt.expandedSize??"anchored";if(!(Tn&&Ki!=="fullscreen")){Q.style.background="",Q.style.border="",Q.style.borderRadius="",Q.style.overflow="",Q.style.boxShadow="";return}let Gi=o.theme?.components?.panel,sh=Ys(o),jl=(Ur,Ul)=>Ur==null||Ur===""?Ul:En(sh,Ur)??Ur,Qt="1px solid var(--persona-border)",qp="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",ql="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Q.style.background="var(--persona-surface, #ffffff)",Q.style.border=jl(Gi?.border,Qt),Q.style.borderRadius=jl(Gi?.borderRadius,ql),Q.style.boxShadow=jl(Gi?.shadow,qp),Q.style.overflow="hidden";return}let i=Kt(o),c=o.launcher?.sidebarMode??!1,f=i||c||(o.launcher?.fullHeight??!1),h=o.launcher?.enabled===!1,C=o.launcher?.detachedPanel===!0,L=o.theme?.components?.panel,X=Ys(o),G=(qt,Tn)=>qt==null||qt===""?Tn:En(X,qt)??qt,ie=t.ownerDocument.defaultView??window,ne=o.launcher?.mobileFullscreen??!0,le=o.launcher?.mobileBreakpoint??640,be=ie.innerWidth<=le,Ae=ne&&be&&P,gt=i&&ne&&be,Ht=o.launcher?.position??"bottom-left",pn=Ht==="bottom-left"||Ht==="top-left",Bn=o.launcher?.zIndex??mn,Ft="var(--persona-panel-border, 1px solid var(--persona-border))",Vt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",U="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Ne=C&&!Ae&&!gt;Ne?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let Ve=Ne?Ft:c||Ae?"none":Ft,Ie=Ne?Vt:Ae?"none":c?pn?"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))":h?"none":Vt;i&&!Ae&&!Ne&&(Ie="none",Ve="none");let $t=Ne?U:c||Ae?"0":U,Mt=G(L?.border,Ve),un=G(L?.shadow,Ie),St=G(L?.borderRadius,$t),An=rl(),gn=An==="detached",rn=An==="welded";t.classList.toggle("persona-artifact-detached-split",gn),t.classList.toggle("persona-artifact-welded-split",rn);let je="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",Re=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Pn(o)&&mg(o)&&h&&!i;t.classList.toggle("persona-artifact-chat-flush",Re);let Yt=gn||Re?"none":un,Tt=gn?Ft:rn?"none":Mt,at=gn?U:St;Re&&(Tt="none",at="0");let Xt=L?.borderRadius!=null&&L.borderRadius!=="",jt=Re&&!Xt?"0":St,bn=Z.scrollTop;t.style.cssText="",R.style.cssText="",$.style.cssText="",Q.style.cssText="",Z.style.cssText="",mi||(Je.style.cssText=""),At&&(Z.style.display="none"),(f||h)&&(t.style.minWidth="0");let to=()=>{if(bn<=0)return;(Z.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(Z.scrollTop===bn)return;let Tn=Z.scrollHeight-Z.clientHeight;Tn<=0||(Z.scrollTop=Math.min(bn,Tn))})};if(Ae){R.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"),R.style.cssText=`
220
1117
  position: fixed !important;
221
1118
  inset: 0 !important;
222
1119
  width: 100% !important;
@@ -226,9 +1123,9 @@ _Details: ${n.message}_`:o}var _s=t=>({isError:!0,content:[{type:"text",text:t}]
226
1123
  padding: 0 !important;
227
1124
  display: flex !important;
228
1125
  flex-direction: column !important;
229
- z-index: ${dn} !important;
1126
+ z-index: ${Bn} !important;
230
1127
  background-color: var(--persona-surface, #ffffff) !important;
231
- `,xe.style.cssText=`
1128
+ `,$.style.cssText=`
232
1129
  position: relative !important;
233
1130
  display: flex !important;
234
1131
  flex-direction: column !important;
@@ -241,7 +1138,7 @@ _Details: ${n.message}_`:o}var _s=t=>({isError:!0,content:[{type:"text",text:t}]
241
1138
  padding: 0 !important;
242
1139
  box-shadow: none !important;
243
1140
  border-radius: 0 !important;
244
- `,Ce.style.cssText=`
1141
+ `,Q.style.cssText=`
245
1142
  display: flex !important;
246
1143
  flex-direction: column !important;
247
1144
  flex: 1 1 0% !important;
@@ -252,33 +1149,33 @@ _Details: ${n.message}_`:o}var _s=t=>({isError:!0,content:[{type:"text",text:t}]
252
1149
  overflow: hidden !important;
253
1150
  border-radius: 0 !important;
254
1151
  border: none !important;
255
- `,ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.overflowY="auto",Se.style.flexShrink="0",N=!0,xn();return}let zi=o?.launcher?.width??o?.launcherWidth??no;if(!u&&!a)x&&m?(xe.style.width="100%",xe.style.maxWidth="100%"):(xe.style.width=zi,xe.style.maxWidth=zi);else if(a)if(An(o).reveal==="emerge"&&!A){let sn=An(o).width;xe.style.width=sn,xe.style.maxWidth=sn}else xe.style.width="100%",xe.style.maxWidth="100%";if(Si(),xe.style.boxShadow=lt,xe.style.borderRadius=vt,Ht?xe.style.border="none":We&&(xe.style.border=ut),Ce.style.border=ft,Ce.style.borderRadius=Ze,Ce.style.boxShadow=Ht&&!St?$e:"",St&&(Ce.style.background="transparent",ce.style.background="transparent",Se.style.background="transparent",Se.style.borderTop="none"),We){let Pt=o.features?.artifacts?.layout;vi=Pt?.unifiedSplitOuterRadius?.trim()||Pt?.paneBorderRadius?.trim()||gt}else vi=null;if(a&&!we&&!Re&&!Ht&&!We&&P?.border===void 0&&(Ce.style.border="none",An(o).side==="right"?Ce.style.borderLeft="1px solid var(--persona-border)":Ce.style.borderRight="1px solid var(--persona-border)"),a&&!we&&We&&P?.border===void 0&&(An(o).side==="right"?xe.style.borderLeft="1px solid var(--persona-border)":xe.style.borderRight="1px solid var(--persona-border)"),m&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",x&&(t.style.width="100%"),Pe.style.display="flex",Pe.style.flexDirection="column",Pe.style.flex="1 1 0%",Pe.style.minHeight="0",Pe.style.maxHeight="100%",Pe.style.height="100%",x&&(Pe.style.overflow="hidden"),xe.style.display="flex",xe.style.flexDirection="column",xe.style.flex="1 1 0%",xe.style.minHeight="0",xe.style.maxHeight="100%",xe.style.height="100%",Ht||(xe.style.overflow="hidden"),Ce.style.display="flex",Ce.style.flexDirection="column",Ce.style.flex="1 1 0%",Ce.style.minHeight="0",Ce.style.maxHeight="100%",Ce.style.overflow="hidden",ce.style.flex="1 1 0%",ce.style.minHeight="0",ce.style.overflowY="auto",Se.style.flexShrink="0"),x&&(Re||Ht||St)&&!a&&(St||(Pe.style.padding="var(--persona-panel-inset)"),Pe.style.background="var(--persona-panel-canvas-bg)"),Pe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!u&&!x&&!a&&(un[yt]??un["bottom-right"]).split(" ").forEach(sn=>Pe.classList.add(sn)),u){let Pt=o.launcher?.sidebarWidth??"420px";A?Pe.style.cssText=`
1152
+ `,Z.style.flex="1 1 0%",Z.style.minHeight="0",Z.style.overflowY="auto",Je.style.flexShrink="0",re=!0,to();return}let vn=o?.launcher?.width??o?.launcherWidth??Uo;if(!c&&!i)h&&f?($.style.width="100%",$.style.maxWidth="100%"):($.style.width=vn,$.style.maxWidth=vn);else if(i)if(ro(o).reveal==="emerge"&&!C){let Tn=ro(o).width;$.style.width=Tn,$.style.maxWidth=Tn}else $.style.width="100%",$.style.maxWidth="100%";if(ol(),$.style.boxShadow=Yt,$.style.borderRadius=jt,gn?$.style.border="none":rn&&($.style.border=Mt),Q.style.border=Tt,Q.style.borderRadius=at,Q.style.boxShadow=gn&&!Re?je:"",Re&&(Q.style.background="transparent",Z.style.background="transparent",Je.style.background="transparent",Je.style.borderTop="none"),rn){let qt=o.features?.artifacts?.layout;Ja=qt?.unifiedSplitOuterRadius?.trim()||qt?.paneBorderRadius?.trim()||St}else Ja=null;if(i&&!Ae&&!Ne&&!gn&&!rn&&L?.border===void 0&&(Q.style.border="none",ro(o).side==="right"?Q.style.borderLeft="1px solid var(--persona-border)":Q.style.borderRight="1px solid var(--persona-border)"),i&&!Ae&&rn&&L?.border===void 0&&(ro(o).side==="right"?$.style.borderLeft="1px solid var(--persona-border)":$.style.borderRight="1px solid var(--persona-border)"),f&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",h&&(t.style.width="100%"),R.style.display="flex",R.style.flexDirection="column",R.style.flex="1 1 0%",R.style.minHeight="0",R.style.maxHeight="100%",R.style.height="100%",h&&(R.style.overflow="hidden"),$.style.display="flex",$.style.flexDirection="column",$.style.flex="1 1 0%",$.style.minHeight="0",$.style.maxHeight="100%",$.style.height="100%",gn||($.style.overflow="hidden"),Q.style.display="flex",Q.style.flexDirection="column",Q.style.flex="1 1 0%",Q.style.minHeight="0",Q.style.maxHeight="100%",Q.style.overflow="hidden",Z.style.flex="1 1 0%",Z.style.minHeight="0",Z.style.overflowY="auto",Je.style.flexShrink="0"),h&&(Ne||gn||Re)&&!i&&(Re||(R.style.padding="var(--persona-panel-inset)"),R.style.background="var(--persona-panel-canvas-bg)"),R.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"),!c&&!h&&!i&&(Un[Ht]??Un["bottom-right"]).split(" ").forEach(Tn=>R.classList.add(Tn)),c){let qt=o.launcher?.sidebarWidth??"420px";C?R.style.cssText=`
256
1153
  position: fixed !important;
257
1154
  top: var(--persona-panel-inset) !important;
258
1155
  bottom: var(--persona-panel-inset) !important;
259
- width: ${Pt} !important;
1156
+ width: ${qt} !important;
260
1157
  height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
261
1158
  max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
262
1159
  margin: 0 !important;
263
1160
  padding: 0 !important;
264
1161
  display: flex !important;
265
1162
  flex-direction: column !important;
266
- z-index: ${dn} !important;
267
- ${pt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
268
- `:Pe.style.cssText=`
1163
+ z-index: ${Bn} !important;
1164
+ ${pn?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
1165
+ `:R.style.cssText=`
269
1166
  position: fixed !important;
270
1167
  top: 0 !important;
271
1168
  bottom: 0 !important;
272
- width: ${Pt} !important;
1169
+ width: ${qt} !important;
273
1170
  height: 100vh !important;
274
1171
  max-height: 100vh !important;
275
1172
  margin: 0 !important;
276
1173
  padding: 0 !important;
277
1174
  display: flex !important;
278
1175
  flex-direction: column !important;
279
- z-index: ${dn} !important;
280
- ${pt?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
281
- `,xe.style.cssText=`
1176
+ z-index: ${Bn} !important;
1177
+ ${pn?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
1178
+ `,$.style.cssText=`
282
1179
  position: relative !important;
283
1180
  display: flex !important;
284
1181
  flex-direction: column !important;
@@ -289,10 +1186,10 @@ _Details: ${n.message}_`:o}var _s=t=>({isError:!0,content:[{type:"text",text:t}]
289
1186
  min-height: 0 !important;
290
1187
  margin: 0 !important;
291
1188
  padding: 0 !important;
292
- box-shadow: ${lt} !important;
293
- border-radius: ${vt} !important;
294
- ${Ht?"border: none !important;":We?`border: ${ut} !important;`:""}
295
- `,xe.style.setProperty("width","100%","important"),xe.style.setProperty("max-width","100%","important"),Ce.style.cssText=`
1189
+ box-shadow: ${Yt} !important;
1190
+ border-radius: ${jt} !important;
1191
+ ${gn?"border: none !important;":rn?`border: ${Mt} !important;`:""}
1192
+ `,$.style.setProperty("width","100%","important"),$.style.setProperty("max-width","100%","important"),Q.style.cssText=`
296
1193
  display: flex !important;
297
1194
  flex-direction: column !important;
298
1195
  flex: 1 1 0% !important;
@@ -301,16 +1198,16 @@ _Details: ${n.message}_`:o}var _s=t=>({isError:!0,content:[{type:"text",text:t}]
301
1198
  min-height: 0 !important;
302
1199
  max-height: 100% !important;
303
1200
  overflow: hidden !important;
304
- border-radius: ${Ze} !important;
305
- border: ${ft} !important;
306
- ${Ht&&!St?`box-shadow: ${$e} !important;`:""}
307
- ${St?"background: transparent !important;":""}
308
- `,Se.style.cssText=`
1201
+ border-radius: ${at} !important;
1202
+ border: ${Tt} !important;
1203
+ ${gn&&!Re?`box-shadow: ${je} !important;`:""}
1204
+ ${Re?"background: transparent !important;":""}
1205
+ `,mi||(Je.style.cssText=`
309
1206
  flex-shrink: 0 !important;
310
1207
  border-top: none !important;
311
1208
  padding: 8px 16px 12px 16px !important;
312
- ${St?"background: transparent !important;":""}
313
- `}if(!x&&!a){let Pt="max-height: -moz-available !important; max-height: stretch !important;",sn=u?"":"padding-top: 1.25em !important;",Ui=u?"":`z-index: ${o.launcher?.zIndex??Ut} !important;`;Pe.style.cssText+=Pt+sn+Ui}xn()},Ml=()=>{t.style.setProperty("--persona-content-max-width",To(o,K()))},ap=()=>{if(K())return;let a=Ot(o),u=o.launcher?.sidebarMode??!1;if(a||u||(o.launcher?.fullHeight??!1)||!z)return;let x=t.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,P=o.launcher?.mobileBreakpoint??640;if(A&&x.innerWidth<=P)return;let G=x.innerHeight,j=64,X=o.launcher?.heightOffset??0,re=Math.max(200,G-j),he=Math.min(640,re);xe.style.height=`${Math.max(200,he-X)}px`};Sl(),Qs(t,o),gi(t,o),fi(t,o),Ml(),Ho=()=>{Sl(),ap(),Qs(t,o),gi(t,o),fi(t,o),Ml(),vi?t.style.setProperty("--persona-artifact-welded-outer-radius",vi):t.style.removeProperty("--persona-artifact-welded-outer-radius")};let Fe=[];Fe.push(()=>{document.removeEventListener("keydown",rp)}),Fe.push(()=>{ss!==null&&clearTimeout(ss)});let Dn=null,On=null;Fe.push(()=>{Dn?.(),Dn=null,On?.(),On=null}),ls&&Fe.push(()=>{ls?.disconnect(),ls=null}),Fe.push(()=>{ps?.(),ps=null,Al(),Ct&&(Ct.remove(),Ct=null),Je?.element.style.removeProperty("width"),Je?.element.style.removeProperty("maxWidth")}),me&&Fe.push(()=>{Ve!==null&&(cancelAnimationFrame(Ve),Ve=null),Me?.destroy(),Me=null,Be?.destroy(),Be=null,Oe=null});let Do=null,lp=()=>{Do&&(Do(),Do=null),o.colorScheme==="auto"&&(Do=Ra(()=>{Qs(t,o)}))};lp(),Fe.push(()=>{Do&&(Do(),Do=null)}),Fe.push(c);let Ti=o.features?.streamAnimation;if(Ti?.type&&Ti.type!=="none"){let a=qr(Ti.type,Ti.plugins);a&&(Ka(a,t),Fe.push(()=>Jf(t)))}let jn=si(k),cp=si(En),dp=si(ae),Oo=[jn,cp,dp];Fe.push(()=>{Oo.forEach(a=>a.destroy())});let No=null,V,Fo=null,pp=!1,up=0,gp=null,fp=a=>a.reduce((u,m)=>m.role==="user"?u+1:u,0),mp=a=>{for(let u=a.length-1;u>=0;u--)if(Rs(a[u]))return a[u].id??null;return null},hp=!1,Th=()=>{hp||o.debug!==!0||(hp=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},bp=!1,yp=!1,vp=(a,u)=>{bp||o.debug!==!0||!u.enabled||u.expose||pp||yp&&(V.isStreaming()||a.some(Rs)||(bp=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},gr=a=>{if(!V)return;let u=a??V.getMessages(),m=re=>{re.render([],V,W,u)},x=re=>{Oo.forEach(he=>{he!==re&&m(he)})};Fo&&(fp(u)>up||mp(u)!==gp)&&(Fo=null);let A=So(o);vp(u,A);let P=A.enabled?Ju(u):null,G=Fo??P,j=Fo?"host":"agent";if(G){let re=o.suggestions?.followUps,he=re?.placement??(re?"auto":"composer"),we=(he==="auto"?K()?"composer":"after-message":he)==="after-message"?dp:jn;x(we),we.render(G,V,W,u,o.suggestionChipsConfig,{source:j,surface:"followUp",variant:re?.variant??"chip",behavior:re?.behavior??"send",overflow:re?.overflow??"wrap",maxItems:re?.maxItems??4,config:o,plugins:s});return}if(u.some(re=>re.role==="user")){Oo.forEach(m);return}let X=o.suggestions?.starters;if(X){let re=Gr(rr(o),u),he=X.placement??"auto",ue=he==="auto"?re?"welcome":"composer":he;if(ue==="welcome"&&!re){Th(),Oo.forEach(m);return}let we=ue==="welcome"?cp:jn;x(we),we.render(X.items??o.suggestionChips,V,W,u,o.suggestionChipsConfig,{surface:"starter",variant:X.variant??"card",behavior:X.behavior??"send",overflow:X.overflow??"wrap",maxItems:X.maxItems??4,config:o,plugins:s});return}x(jn),jn.render(o.suggestionChips,V,W,u,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:s})},xp=()=>{Fo&&(Fo=null,gr())},Eh=a=>{let u=Array.isArray(a)?[...a]:[];if(!u.length){xp();return}let m=V?V.getMessages():[];Fo=u,pp=!0,up=fp(m),gp=mp(m),gr(m)},In=!1,_o=Uf(),fr=new Map,$o=new Map,lo=new Map,Tl=0,kh=Jn()!==null,ln=$a(),cn=0,co=null,on=!1,Ei=!1,po=0,Ft=null,zo=null,El=!1,ki=!1,Uo=null,us=!0,Li=!1,mr=null,Pi=!1,jo=()=>{Pi=!0,Rh()},kl=null,Lh=4,Vn=24,Ph=80,Ih=1e3,qn=null,wp=()=>{t.setAttribute("data-persona-scrollbar",fl()),fl()!=="on-scroll"&&(qn!==null&&clearTimeout(qn),qn=null,ce.removeAttribute("data-persona-scrollbar-visible"))},Rh=()=>{fl()==="on-scroll"&&(ce.setAttribute("data-persona-scrollbar-visible",""),qn!==null&&clearTimeout(qn),qn=setTimeout(()=>{qn=null,ro(ce,Vn)&&ce.removeAttribute("data-persona-scrollbar-visible")},Ih))};wp(),Fe.push(()=>{qn!==null&&clearTimeout(qn)});let Ll=new Map,Qe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Cp=o.voiceRecognition?.autoResume??!1,Kn=a=>{d.emit("voice:state",{active:Qe.active,source:a,timestamp:Date.now()})},Rn=()=>{S(a=>({...a,voiceState:{active:Qe.active,timestamp:Date.now(),manuallyDeactivated:Qe.manuallyDeactivated}}))},Wh=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=Id(f.voiceState),u=!!a.active,m=Number(a.timestamp??0);Qe.manuallyDeactivated=!!a.manuallyDeactivated,u&&Date.now()-m<uC&&setTimeout(()=>{Qe.active||(Qe.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?V.toggleVoice().then(()=>{Qe.active=V.isVoiceActive(),Kn("restore"),V.isVoiceActive()&&wr()}):Fi("restore"))},1e3)},Hh=()=>V?nh(V.getMessages()).filter(a=>!a.__skipPersist):[],Ii=null,Ap=(a,u)=>{typeof console<"u"&&console.error(a,u)},Pl=(a,u)=>{let m=()=>{try{let G=a();return!G||typeof G.then!="function"?null:Promise.resolve(G).catch(j=>{Ap(u,j)})}catch(G){return Ap(u,G),null}},x=Ii,A=x?x.then(()=>m()??void 0):m();if(!A)return;let P=A.finally(()=>{Ii===P&&(Ii=null)});Ii=P};function Il(a){if(!b?.save)return;let m={messages:a?nh(a):V?Hh():[],metadata:f,artifacts:Ln.artifacts,selectedArtifactId:Ln.selectedId};Pl(()=>b.save(m),"[AgentWidget] Failed to persist state:")}let hr=null,Sp=()=>Pe.querySelector("#persona-scroll-container")||ce,br=()=>{hr!==null&&(cancelAnimationFrame(hr),hr=null),on=!1},Mp=()=>{co!==null&&(cancelAnimationFrame(co),co=null),Ei=!1,br()},Bh=()=>In&&Wl()&&(an()!=="anchor-top"||Fd()),Rl=()=>{let a=ns()||"Jump to latest",u=Bh();It.toggleAttribute("data-persona-scroll-to-bottom-streaming",u),po>0?(Io.textContent=String(po),Io.style.display="",It.setAttribute("aria-label",`${a} (${po} new)`)):(Io.textContent="",Io.style.display="none",It.setAttribute("aria-label",u?`${a} (response streaming below)`:a))},Tp=()=>{po!==0&&(po=0,Rl())},Dh=()=>{let a=Ft?.spacerHeight??0;return a<=0?ro(ce,Vn):Hi(a)-ce.scrollTop-ce.clientHeight<=Vn},Wl=()=>io()?!ln.isFollowing():!Dh(),Hl=()=>!!V&&V.getMessages().length>0,Vt=()=>{if(!xh()||Ee){It.parentNode&&It.remove(),It.style.display="none";return}It.parentNode!==Ce&&Ce.appendChild(It),Wo();let u=_n(ce)>0&&Wl()&&Hl();u?Rl():Tp(),It.style.display=u?"":"none"},gs=()=>{ln.pause()&&(Mp(),Vt())},uo=()=>{ln.resume(),Tp(),Vt()},go=(a=!1)=>{io()&&Hl()&&ln.isFollowing()&&(!a&&!In||(co!==null&&(cancelAnimationFrame(co),co=null),Ei=!0,co=requestAnimationFrame(()=>{co=null,Ei=!1,ln.isFollowing()&&Oh(Sp(),a?220:140)})))},Ep=(a,u,m,x=()=>!0)=>{let A=a.scrollTop,P=u(),G=P-A;if(br(),Math.abs(G)<1){on=!0,a.scrollTop=P,cn=a.scrollTop,on=!1;return}let j=performance.now();on=!0;let X=he=>1-Math.pow(1-he,3),re=he=>{if(!x()){br();return}let ue=u();ue!==P&&(P=ue,G=P-A);let we=he-j,Xe=Math.min(we/m,1),yt=X(Xe),pt=A+G*yt;a.scrollTop=pt,cn=a.scrollTop,Xe<1?hr=requestAnimationFrame(re):(a.scrollTop=P,cn=a.scrollTop,hr=null,on=!1)};hr=requestAnimationFrame(re)},Oh=(a,u=500)=>{let m=_n(a)-a.scrollTop;if(Math.abs(m)<1){cn=a.scrollTop;return}if(Math.abs(m)>=Ph){br(),on=!0,a.scrollTop=_n(a),cn=a.scrollTop,on=!1;return}Ep(a,()=>_n(a),u,()=>ln.isFollowing())},kp=()=>{if(!Hl()){Vt();return}let a=Sp();on=!0,a.scrollTop=_n(a),cn=a.scrollTop,on=!1,Vt()},Vo=a=>{let u=0,m=a;for(;m&&m!==ce;)u+=m.offsetTop,m=m.offsetParent;return u},Nh=()=>{let a=ce.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??ce.ownerDocument.getSelection()},Ri=()=>Gf(Nh(),ce),Lp=()=>{if(wh()!=="last-user-turn")return!1;let a=V?.getMessages()??[];if(a.length<2)return!1;let u=[...a].reverse().find(P=>P.role==="user");if(!u)return!1;let m=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(u.id):u.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=ce.querySelector(`[data-message-id="${m}"]`);if(!x)return!1;let A=Math.min(Math.max(0,Vo(x)-os()),_n(ce));return on=!0,ce.scrollTop=A,cn=ce.scrollTop,on=!1,an()==="follow"&&!ro(ce,Vn)&&ln.pause(),Vt(),!0},Wi=a=>{let u=Math.max(0,Math.round(a));bn.style.height=`${u}px`,bn.style.display=u>0?"":"none",Ft&&(Ft.spacerHeight=Math.max(0,a))},Hi=a=>{let u=parseFloat(getComputedStyle(ce).paddingBottom)||0,m=0;for(let A of Array.from(ce.children)){if(A===bn||A.offsetHeight===0)continue;let P=Vo(A)+A.offsetHeight;P>m&&(m=P)}let x=ce.scrollHeight-a;return m>0?Math.min(m+u,x):x},Fh=()=>{if(!Ft||Ft.spacerHeight<=0)return;let a=Hi(Ft.spacerHeight),u=Math.max(0,Math.round(ce.scrollTop)+ce.clientHeight-a+Vn);u<Ft.spacerHeight&&(Wi(u),Vt())},fs=()=>{zo!==null&&(cancelAnimationFrame(zo),zo=null),br(),Ft=null,bn.style.height="0px",bn.style.display="none"},Pp=a=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Bl=a=>ce.querySelector(`[data-message-id="${Pp(a)}"]`),Ip=a=>{zo!==null&&cancelAnimationFrame(zo),zo=requestAnimationFrame(()=>{zo=null;let u=Pp(a),m=ce.querySelector(`[data-message-id="${u}"]`);if(!m)return;let x=Vo(m),A=Ft?.spacerHeight??0,P=Hi(A),{targetScrollTop:G,spacerHeight:j}=Xc({anchorOffsetTop:x,topOffset:os(),viewportHeight:ce.clientHeight,contentHeight:P,slack:Vn});Ft={initialSpacerHeight:j,contentHeightAtAnchor:P,spacerHeight:j},Wi(j),Ep(ce,()=>m.isConnected?Math.max(0,Vo(m)-os()):G,220)})},Rp=()=>{if(an()!=="anchor-top"||!Ft||!mr)return;let a=Bl(mr);if(!a)return;br();let u=Ft.spacerHeight,m=Hi(u),{targetScrollTop:x,spacerHeight:A}=Xc({anchorOffsetTop:Vo(a),topOffset:os(),viewportHeight:ce.clientHeight,contentHeight:m,slack:Vn});Ft={initialSpacerHeight:A,contentHeightAtAnchor:m,spacerHeight:A},Wi(A),on=!0,ce.scrollTop=x,cn=ce.scrollTop,on=!1,Vt()},_h=()=>{if(io()){if(!ln.isFollowing()||ro(ce,1))return;go(!In);return}if(Ft&&Ft.initialSpacerHeight>0){let a=ce.scrollHeight-Ft.spacerHeight,u=Qf({initialSpacerHeight:Ft.initialSpacerHeight,contentHeightAtAnchor:Ft.contentHeightAtAnchor,currentContentHeight:a});u!==Ft.spacerHeight&&Wi(u)}Vt()},$h=a=>{let u=an();u==="follow"?(uo(),go(!0)):u==="anchor-top"&&(us=!1,Li=!0,Pi=!1,mr=a,Ip(a))},zh=()=>{if(an()==="anchor-top"){if(Li){us=!1;return}us=!0,fs(),uo(),go(!0)}},Uh=96,jh=a=>{if(Uo===null)return!0;let u=Bl(Uo),m=Bl(a);if(!u||!m)return!0;let x=Vo(m)-Vo(u);return os()+x>ce.clientHeight-Uh},Vh=a=>{if(an()!=="anchor-top"||!Li||Pi||Ri())return;let u=Uo===null;for(let m of a){if(!u){m.id===Uo&&(u=!0);continue}if(Kf(m)){if(m.id===mr||!jh(m.id))return;mr=m.id,Ip(m.id);return}}},qh=a=>{let u=new Map;a.forEach(m=>{let x=Ll.get(m.id);u.set(m.id,{streaming:m.streaming,role:m.role}),!x&&m.role==="assistant"&&(d.emit("assistant:message",m),!ki&&(an()!=="anchor-top"||Fd())&&Wl()&&(po+=1,Rl(),Vt(),$d(po===1?"1 new message below.":`${po} new messages below.`))),m.role==="assistant"&&x?.streaming&&m.streaming===!1&&d.emit("assistant:complete",m),m.variant==="approval"&&m.approval&&(x?m.approval.status!=="pending"&&d.emit("approval:resolved",{approval:m.approval,decision:m.approval.status}):d.emit("approval:requested",{approval:m.approval,message:m}))}),Ll.clear(),u.forEach((m,x)=>{Ll.set(x,m)})},Bi=(a,u)=>{let m=u==="user"?"user":"assistant",x=o.layout?.messages?.[m],A=x?.width??"content",P=x?.maxWidth??(A==="full"?"100%":"85%");a.classList.add("persona-message-row"),a.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),a.classList.add(`persona-message-row-${u}`,`persona-message-width-${A}`),a.classList.toggle("persona-justify-end",u==="user"),a.setAttribute("data-message-role",u),a.setAttribute("data-message-width",A),a.style.setProperty("--persona-message-row-max-width",P)},qo=(a,u)=>{let m=document.createElement("div");return m.className="persona-flex",m.id=`wrapper-${a}`,m.setAttribute("data-wrapper-id",a),Bi(m,u),m},Kh=(a,u,m)=>{let x=document.createElement("div"),P=(()=>{let U=s.find(Re=>Re.renderLoadingIndicator);if(U?.renderLoadingIndicator)return U.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),G=(U,Re)=>Re==null?!1:typeof Re=="string"?(U.textContent=Re,!0):(U.appendChild(Re),!0),j=new Set,X=new Map,re=new Set,he=s.some(U=>U.renderAskUserQuestion),ue=[],we=[],Xe=o.enableComponentStreaming!==!1,yt=o.approval!==!1,pt=[];if(u.forEach(U=>{j.add(U.id),X.set(U.id,U.role);let Re=he&&Yo(U),_e=yt&&U.variant==="approval"&&!!U.approval,Le=!Re&&U.role==="assistant"&&!U.variant&&Xe&&Pd(U);!_e&&lo.has(U.id)&&(a.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime"),lo.delete(U.id)),!Le&&$o.has(U.id)&&(a.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime"),$o.delete(U.id));let Tt=Yo(U)?`:${U.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${U.agentMetadata?.askUserQuestionAnswers?Object.keys(U.agentMetadata.askUserQuestionAnswers).length:0}`:"",ut=zf(U,Tl)+Tt,$t=Re||_e||Le?null:jf(_o,U.id,ut);if($t){x.appendChild($t.cloneNode(!0)),Yo(U)&&U.toolCall?.id&&U.agentMetadata?.awaitingLocalTool===!0&&!U.agentMetadata?.askUserQuestionAnswered&&(re.add(U.toolCall.id),ea(U,o,ke.composerOverlay));return}let gt=null,rn=s.find($e=>!!(U.variant==="reasoning"&&$e.renderReasoning||U.variant==="tool"&&$e.renderToolCall||!U.variant&&$e.renderMessage)),Ht=o.layout?.messages;if(Yo(U)&&U.agentMetadata?.askUserQuestionAnswered===!0){fr.delete(U.id),a.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime");return}if(Rs(U)&&So(o).enabled)return;if(Yo(U)&&o.features?.askUserQuestion?.enabled!==!1){let $e=s.find(qt=>typeof qt.renderAskUserQuestion=="function");if($e&&at.current){let qt=fr.get(U.id),Kt=qt!==ut,St=null;if(Kt){let{payload:Ze,complete:De}=Ir(U),vt=U.id,Gt=()=>at.current?.getMessages().find(xn=>xn.id===vt);St=$e.renderAskUserQuestion({message:U,payload:Ze,complete:De,resolve:xn=>{let Ms=Gt();Ms&&at.current?.resolveAskUserQuestion(Ms,xn)},dismiss:()=>{let xn=Gt();xn?.agentMetadata?.awaitingLocalTool&&(at.current?.markAskUserQuestionResolved(xn),at.current?.resolveAskUserQuestion(xn,"(dismissed)"))},config:o})}let lt=qt!=null;if(Kt&&St===null&&!lt){U.agentMetadata?.awaitingLocalTool===!0&&!U.agentMetadata?.askUserQuestionAnswered&&(re.add(U.toolCall.id),ea(U,o,ke.composerOverlay));return}let ft=qo(U.id,U.role);ft.setAttribute("data-ask-plugin-stub","true"),ft.setAttribute("data-preserve-runtime","true"),x.appendChild(ft),ue.push({messageId:U.id,fingerprint:ut,bubble:St});return}else{U.agentMetadata?.awaitingLocalTool===!0&&!U.agentMetadata?.askUserQuestionAnswered&&(re.add(U.toolCall.id),ea(U,o,ke.composerOverlay));return}}else if(_e){let $e=s.find(lt=>typeof lt.renderApproval=="function")??p,Kt=lo.get(U.id)!==ut,St=null;if(Kt&&$e?.renderApproval){let lt=U.id,ft=(Ze,De)=>{let vt=at.current?.getMessages().find(Gt=>Gt.id===lt);vt?.approval&&(vt.approval.toolType==="webmcp"?at.current?.resolveWebMcpApproval(vt.id,Ze):at.current?.resolveApproval(vt.approval,Ze,De))};St=$e.renderApproval({message:U,defaultRenderer:()=>ll(U,o),config:o,approve:Ze=>ft("approved",Ze),deny:Ze=>ft("denied",Ze)})}if(Kt&&St===null)a.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime"),lo.delete(U.id),gt=ll(U,o);else{let lt=qo(U.id,U.role);lt.setAttribute("data-approval-plugin-stub","true"),lt.setAttribute("data-preserve-runtime","true"),x.appendChild(lt),pt.push({messageId:U.id,fingerprint:ut,bubble:St});return}}else if(rn)if(U.variant==="reasoning"&&U.reasoning&&rn.renderReasoning){if(!pe)return;gt=rn.renderReasoning({message:U,defaultRenderer:()=>ud(U,o),config:o})}else if(U.variant==="tool"&&U.toolCall&&rn.renderToolCall){if(!ne)return;gt=rn.renderToolCall({message:U,defaultRenderer:()=>fd(U,o),config:o})}else rn.renderMessage&&(gt=rn.renderMessage({message:U,defaultRenderer:()=>{let $e=ad(U,m,Ht,o.messageActions,bt,{loadingIndicatorRenderer:P,widgetConfig:o});return U.role!=="user"&&Ad($e,U,o,V),$e},config:o}));if(!gt&&Le){let $e=Zm(U);if($e){let qt=$o.get(U.id),Kt=qt!==ut,St=o.wrapComponentDirectiveInBubble!==!1&&oo.getOptions($e.component)?.bubbleChrome!==!1,lt=null;if(Kt){let ft=Ym($e,{config:o,message:U,transform:m});if(ft&&$e.component==="PersonaArtifactInline"){let Ze=ft.hasAttribute("data-artifact-inline")?ft:ft.querySelector("[data-artifact-inline]"),De=Ze?.getAttribute("data-artifact-inline")??"",vt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(De):De,Gt=De?a.querySelector(`#wrapper-${U.id}`)?.querySelector(`[data-artifact-inline="${vt}"]`)??null:null;Ze&&Gt&&Gt!==Ze&&Df(Gt)&&(Ze===ft?ft=Gt:Ze.replaceWith(Gt))}if(ft)if(St){let Ze=document.createElement("div");if(Ze.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ze.id=`bubble-${U.id}`,Ze.setAttribute("data-message-id",U.id),U.content&&U.content.trim()){let De=document.createElement("div");De.className="persona-mb-3 persona-text-sm persona-leading-relaxed",De.innerHTML=m({text:U.content,message:U,streaming:!!U.streaming,raw:U.rawContent}),Ze.appendChild(De)}Ze.appendChild(ft),lt=Ze}else{let Ze=document.createElement("div");if(Ze.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ze.id=`bubble-${U.id}`,Ze.setAttribute("data-message-id",U.id),Ze.setAttribute("data-persona-component-directive","true"),U.content&&U.content.trim()){let De=document.createElement("div");De.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",De.innerHTML=m({text:U.content,message:U,streaming:!!U.streaming,raw:U.rawContent}),Ze.appendChild(De)}Ze.appendChild(ft),lt=Ze}}if(lt||qt!=null){let ft=qo(U.id,U.role);ft.setAttribute("data-component-directive-stub","true"),ft.setAttribute("data-preserve-runtime","true"),x.appendChild(ft),we.push({messageId:U.id,fingerprint:ut,bubble:lt});return}}}if(!gt)if(U.variant==="reasoning"&&U.reasoning){if(!pe)return;gt=ud(U,o)}else if(U.variant==="tool"&&U.toolCall){if(!ne)return;gt=fd(U,o)}else if(U.variant==="approval"&&U.approval){if(o.approval===!1)return;gt=ll(U,o)}else{let $e=o.layout?.messages;$e?.renderUserMessage&&U.role==="user"?gt=$e.renderUserMessage({message:U,config:o,streaming:!!U.streaming}):$e?.renderAssistantMessage&&U.role==="assistant"?gt=$e.renderAssistantMessage({message:U,config:o,streaming:!!U.streaming}):gt=ad(U,m,$e,o.messageActions,bt,{loadingIndicatorRenderer:P,widgetConfig:o}),U.role!=="user"&&gt&&Ad(gt,U,o,V)}let We=qo(U.id,U.role);We.appendChild(gt),Vf(_o,U.id,ut,We),x.appendChild(We)}),ke.composerOverlay&&ke.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let _e=Re.getAttribute("data-persona-ask-sheet-for");_e&&!re.has(_e)&&Wr(ke.composerOverlay,_e)}),o.features?.toolCallDisplay?.grouped){let U=[],Re=[],_e=o.features.toolCallDisplay.groupedMode==="summary";u.forEach(Le=>{if(Le.variant==="tool"&&Le.toolCall&&ne){Re.push(Le);return}Le.variant==="reasoning"&&!pe||((Re.length>1||_e&&Re.length>0)&&U.push(Re),Re=[])}),(Re.length>1||_e&&Re.length>0)&&U.push(Re),U.forEach(Le=>{let Tt=Le.map($e=>Array.from(x.children).find(qt=>qt instanceof HTMLElement&&qt.getAttribute("data-wrapper-id")===$e.id)).filter($e=>!!$e);if(Tt.length<(_e?1:2))return;let ut=qo(`tool-group-${Le[0].id}`,"assistant");ut.setAttribute("data-persona-tool-group-row","true");let $t=document.createElement("div");$t.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",$t.setAttribute("data-persona-tool-group","true");let gt=document.createElement("div");gt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",gt.id=`tool-group-summary-${Le[0].id}`;let rn=`Called ${Le.length} ${Le.length===1?"tool":"tools"}`,Ht=o.toolCall?.renderGroupedSummary?.({messages:Le,toolCalls:Le.map($e=>$e.toolCall).filter($e=>!!$e),defaultSummary:rn,config:o});G(gt,Ht)||(gt.textContent=rn);let We=document.createElement("div");We.className="persona-tool-group-stack persona-flex persona-flex-col",We.id=`tool-group-stack-${Le[0].id}`,We.setAttribute("data-persona-tool-group-stack","true"),$t.appendChild(gt),_e||$t.appendChild(We),ut.appendChild($t),Tt[0].before(ut),Tt.forEach(($e,qt)=>{if(_e){$e.remove();return}$e.style.setProperty("--persona-message-row-max-width","100%");let Kt=document.createElement("div");Kt.className="persona-tool-group-item persona-relative",Kt.setAttribute("data-persona-tool-group-item","true"),qt<Tt.length-1&&Kt.setAttribute("data-persona-tool-group-connector","true"),Kt.appendChild($e),We.appendChild(Kt)})})}qf(_o,j);let dn=u.some(U=>U.role==="assistant"&&U.streaming),Et=u[u.length-1],Wt=Et?.role==="assistant"&&!Et.streaming&&Et.variant!=="approval";if(In&&u.some(U=>U.role==="user")&&!dn&&!Wt){let U={config:o,streaming:!0,location:"standalone",defaultRenderer:li},Re=s.find(Le=>Le.renderLoadingIndicator),_e=null;if(Re?.renderLoadingIndicator&&(_e=Re.renderLoadingIndicator(U)),_e===null&&o.loadingIndicator?.render&&(_e=o.loadingIndicator.render(U)),_e===null&&(_e=li()),_e){let Le=document.createElement("div"),Tt=o.loadingIndicator?.showBubble!==!1,ut=o.layout?.messages?.layout??"bubble";Le.className=Tt?ci("assistant",ut).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Le.setAttribute("data-typing-indicator","true"),Tt&&(Le.style.color="var(--persona-message-assistant-text, var(--persona-text))",ut!=="flat"&&(Le.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Le.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Le.appendChild(_e);let $t=qo("typing-indicator","assistant");$t.appendChild(Le),x.appendChild($t)}}if(!In&&u.length>0){let U=u[u.length-1],Re={config:o,lastMessage:U,messageCount:u.length},_e=s.find(Tt=>Tt.renderIdleIndicator),Le=null;if(_e?.renderIdleIndicator&&(Le=_e.renderIdleIndicator(Re)),Le===null&&o.loadingIndicator?.renderIdle&&(Le=o.loadingIndicator.renderIdle(Re)),Le){let Tt=document.createElement("div"),ut=o.loadingIndicator?.showBubble!==!1;Tt.className=ut?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Tt.setAttribute("data-idle-indicator","true"),Tt.appendChild(Le);let $t=qo("idle-indicator","assistant");$t.appendChild(Tt),x.appendChild($t)}}if(Pu(x),_a(a,x),ic(a),ue.length>0)for(let{messageId:U,fingerprint:Re,bubble:_e}of ue){let Le=a.querySelector(`#wrapper-${U}`);Le&&(Bi(Le,X.get(U)??"assistant"),_e!==null&&(Le.replaceChildren(_e),Le.setAttribute("data-bubble-fp",Re),fr.set(U,Re)))}if(fr.size>0)for(let U of fr.keys())j.has(U)||fr.delete(U);if(we.length>0)for(let{messageId:U,fingerprint:Re,bubble:_e}of we){let Le=a.querySelector(`#wrapper-${U}`);Le&&(Bi(Le,X.get(U)??"assistant"),_e!==null&&(Le.replaceChildren(_e),Le.setAttribute("data-bubble-fp",Re),$o.set(U,Re)))}if($o.size>0)for(let U of $o.keys())j.has(U)||$o.delete(U);if(pt.length>0)for(let{messageId:U,fingerprint:Re,bubble:_e}of pt){let Le=a.querySelector(`#wrapper-${U}`);Le&&(Bi(Le,X.get(U)??"assistant"),_e!==null&&(Le.replaceChildren(_e),Le.setAttribute("data-bubble-fp",Re),lo.set(U,Re)))}if(lo.size>0)for(let U of lo.keys())j.has(U)||lo.delete(U)},ms=(a,u,m)=>{Kh(a,u,m),tp()},hs=null,Gh=()=>{if(hs)return;let a=m=>{let x=m.composedPath();x.includes(Pe)||ot&&x.includes(ot)||dt(!1,"user")};hs=a,(t.ownerDocument??document).addEventListener("pointerdown",a,!0)},Wp=()=>{if(!hs)return;(t.ownerDocument??document).removeEventListener("pointerdown",hs,!0),hs=null};Fe.push(()=>Wp());let bs=null,Qh=()=>{if(bs)return;let a=m=>{m.key==="Escape"&&(m.isComposing||dt(!1,"user"))};bs=a,(t.ownerDocument??document).addEventListener("keydown",a,!0)},Hp=()=>{if(!bs)return;(t.ownerDocument??document).removeEventListener("keydown",bs,!0),bs=null};Fe.push(()=>Hp());let ys=!1,Bp=new Set,Xh=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},yr=()=>{if(!K())return;let a=ke.peekBanner,u=ke.peekTextNode;if(!a||!u)return;if(Q){a.classList.remove("persona-pill-peek--visible");return}let m=V?.getMessages()??[],x;for(let Et=m.length-1;Et>=0;Et--){let Wt=m[Et];if(Wt.role==="assistant"&&Wt.content){x=Wt;break}}if(!x){a.classList.remove("persona-pill-peek--visible");return}let A=x.content,P=!!x.streaming,G=Xh(),j=ja(G),X=j.type!=="none"?qr(j.type,G?.plugins):null,re=X?.isAnimating?.(x)===!0,he=X!==null&&(P||re);he&&X&&!Bp.has(X.name)&&(Ka(X,t),Bp.add(X.name));let ue=he&&X?.containerClass?X.containerClass:null,we=u.dataset.personaPeekStreamClass??null;we&&we!==ue&&(u.classList.remove(we),delete u.dataset.personaPeekStreamClass),ue&&we!==ue&&(u.classList.add(ue),u.dataset.personaPeekStreamClass=ue),he?(u.style.setProperty("--persona-stream-step",`${j.speed}ms`),u.style.setProperty("--persona-stream-duration",`${j.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let Xe=he?Va(A,j.buffer,X,x,P):A;if(he&&j.placeholder==="skeleton"&&P&&(!Xe||!Xe.trim())){let Et=document.createElement("div"),Wt=ti();Wt.classList.add("persona-pill-peek__skeleton"),Et.appendChild(Wt),_a(u,Et)}else{let Et=Math.max(0,Xe.length-100),Wt=Xe.length>100?Xe.slice(-100):Xe,U=vo(Wt);if(!he||!X){let Re=Xe.length>100?`\u2026${Wt}`:Wt;u.textContent!==Re&&(u.textContent=Re)}else{let Re=U;(X.wrap==="char"||X.wrap==="word")&&(Re=ei(U,X.wrap,`peek-${x.id}`,{skipTags:X.skipTags,startIndex:Et}));let _e=document.createElement("div");if(_e.innerHTML=Re,X.useCaret&&Wt.length>0){let Le=qa(),Tt=_e.querySelectorAll(".persona-stream-char, .persona-stream-word"),ut=Tt[Tt.length-1];ut?.parentNode?ut.parentNode.insertBefore(Le,ut.nextSibling):_e.appendChild(Le)}_a(u,_e),X.onAfterRender?.({container:u,bubble:a,messageId:x.id,message:x,speed:j.speed,duration:j.duration})}}let dn=In||ys;a.classList.toggle("persona-pill-peek--visible",dn)};if(K()){let a=ke.peekBanner;if(a){let x=A=>{A.preventDefault(),A.stopPropagation(),dt(!0,"user")};a.addEventListener("pointerdown",x),Fe.push(()=>{a.removeEventListener("pointerdown",x)})}let u=()=>{ys||(ys=!0,yr())},m=()=>{ys&&(ys=!1,yr())};xe.addEventListener("pointerenter",u),xe.addEventListener("pointerleave",m),Fe.push(()=>{xe.removeEventListener("pointerenter",u),xe.removeEventListener("pointerleave",m)}),ot&&(ot.addEventListener("pointerenter",u),ot.addEventListener("pointerleave",m),Fe.push(()=>{ot.removeEventListener("pointerenter",u),ot.removeEventListener("pointerleave",m)}))}let Yh=a=>{let u=o.launcher?.composerBar??{},m=u.expandedSize??"anchored",x=u.bottomOffset??"16px",A=u.collapsedMaxWidth,P=u.expandedMaxWidth??"880px",G=u.expandedTopOffset??"5vh",j=u.modalMaxWidth??"880px",X=u.modalMaxHeight??"min(90vh, 800px)",re="calc(100vw - 32px)",he="var(--persona-pill-area-height, 80px)",ue=Pe.style;if(ue.left="",ue.right="",ue.top="",ue.bottom="",ue.transform="",ue.width="",ue.maxWidth="",ue.height="",ue.maxHeight="",ot){let we=ot.style;we.bottom=x,we.width=A??""}if(a&&m!=="fullscreen"){if(m==="modal"){ue.top="50%",ue.left="50%",ue.transform="translate(-50%, -50%)",ue.bottom="auto",ue.right="auto",ue.width=j,ue.maxWidth=re,ue.maxHeight=X,ue.height=X;return}ue.left="50%",ue.transform="translateX(-50%)",ue.bottom=`calc(${x} + ${he})`,ue.top=G,ue.width=P,ue.maxWidth=re}},vs=()=>{if(!te())return;if(K()){let re=(o.launcher?.composerBar??{}).expandedSize??"anchored",he=Q?"expanded":"collapsed";Pe.dataset.state=he,Pe.dataset.expandedSize=re,ot&&(ot.dataset.state=he,ot.dataset.expandedSize=re),Pe.style.removeProperty("display"),Pe.classList.remove("persona-pointer-events-none","persona-opacity-0"),xe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Yh(Q),Ce.style.display=Q?"flex":"none",Ho(),Q?(Gh(),Qh()):(Wp(),Hp()),yr();return}let a=Ot(o),u=t.ownerDocument.defaultView??window,m=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,A=u.innerWidth<=m,P=x&&A&&z,G=An(o).reveal;Q?(Pe.style.removeProperty("display"),Pe.style.display=a?"flex":"",Pe.classList.remove("persona-pointer-events-none","persona-opacity-0"),xe.classList.remove("persona-scale-95","persona-opacity-0"),xe.classList.add("persona-scale-100","persona-opacity-100"),Lt?(Lt.setPanelOpen(!0),Lt.element.style.display="none"):en&&(en.style.display="none")):(a?a&&(G==="overlay"||G==="push")&&!P?(Pe.style.removeProperty("display"),Pe.style.display="flex",Pe.classList.remove("persona-pointer-events-none","persona-opacity-0"),xe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Pe.style.setProperty("display","none","important"),Pe.classList.remove("persona-pointer-events-none","persona-opacity-0"),xe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Pe.style.display="",Pe.classList.add("persona-pointer-events-none","persona-opacity-0"),xe.classList.remove("persona-scale-100","persona-opacity-100"),xe.classList.add("persona-scale-95","persona-opacity-0")),Lt?(Lt.setPanelOpen(!1),Lt.element.style.display=a?"none":""):en&&(en.style.display=a?"none":""))},dt=(a,u="user")=>{if(!te()||Q===a)return;let m=Q;Q=a,vs();let x=(()=>{let P=o.launcher?.sidebarMode??!1,G=t.ownerDocument.defaultView??window,j=o.launcher?.mobileFullscreen??!0,X=o.launcher?.mobileBreakpoint??640,re=G.innerWidth<=X,he=Ot(o)&&j&&re,ue=K()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return P||j&&re&&z||he||ue})();if(Q&&x){if(!Dn){let P=t.getRootNode(),G=P instanceof ShadowRoot?P.host:t.closest(".persona-host");G&&(Dn=Zc(G,o.launcher?.zIndex??Ut))}On||(On=ed(t.ownerDocument))}else Q||(Dn?.(),Dn=null,On?.(),On=null);Q&&(As(),Lp()||(an()==="follow"?go(!0):kp()));let A={open:Q,source:u,timestamp:Date.now()};Q&&!m?d.emit("widget:opened",A):!Q&&m&&d.emit("widget:closed",A),d.emit("widget:state",{open:Q,launcherEnabled:z,voiceActive:Qe.active,streaming:V.isStreaming()})},Di=a=>{bi(a?"stop":"send"),le&&(le.disabled=a),Oo.forEach(u=>{u.elements.forEach(m=>{m.toggleAttribute("data-disabled",a),m instanceof HTMLButtonElement||m.setAttribute("aria-disabled",a?"true":"false")}),u.buttons.forEach(m=>{m.disabled=a})}),_l.forEach(u=>{u.toggleAttribute("data-disabled",a),u instanceof HTMLButtonElement?u.disabled=a:u.setAttribute("aria-disabled",a?"true":"false"),u.querySelectorAll("button").forEach(m=>{m.disabled=a})}),Se.dataset.personaComposerStreaming=a?"true":"false",Se.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=a)})},Dl=()=>{Qe.active||W&&W.focus()};d.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Dl(),200)});let Ol=!Z.hidden,fo=null,Dp=!y,Op=null,Np,Fp=null,xs=null,Nl=a=>{let u=rr(o),m=`${u.variant}|${u.dismiss}|${u.title}|${u.subtitle}`;(m!==Op||u.icon!==Np)&&(Op=m,Np=u.icon,sl({host:Z,iconHolder:q,title:ge,subtitle:qe,starterSuggestions:En},u));let x=u.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${u.message}`;x!==Fp&&(Fp=x,il(ee,u.message,o));let A=a??(V?V.getMessages():o.initialMessages),P=Gr(u,A),G=P!==Ol;if(Ol=P,xs){fo?.cancel(),fo=null,Kr(ce,Z,!0);return}if(G&&!P&&u.dismiss==="on-first-message"&&Dp){fo=pm(Z,j=>{fo===j&&(fo=null),!Ol&&!xs&&(Kr(ce,Z,!1),Rp()),j?.cancel()});return}if(fo){if(!P)return;fo.cancel(),fo=null}Kr(ce,Z,P),G&&!P&&Rp()},Fl=[],_l=[],$l=!1,_p=null,$p,zp=()=>{_l.length=0;let a=Fl.splice(0,Fl.length);for(let u of a)try{u()}catch(m){console.warn("[persona] renderWelcome cleanup threw",m)}};Fe.push(zp);let Jh=(a,u)=>{let m=nd(a,u);if(!m)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),v("span");let x=o.suggestions?.starters,A=od({item:{...m,behavior:m.behavior??x?.behavior??"send"},index:u,surface:"starter",source:"config",variant:x?.variant??"card",streaming:i?V.isStreaming():!1,config:o,plugins:s,chipsConfig:o.suggestionChipsConfig,session:V,getTextarea:()=>W,eventTarget:Z});return _l.push(A),A},zl=()=>{if($l)return;$l=!0;let a=rr(o);_p=`${a.variant}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`,$p=a.icon;try{zp(),cm(ce,Z,xs),xs=null;let u=V?V.getMessages():o.initialMessages,m=Gr(a,u),x=0,A=null;for(let P of s)if(P.renderWelcome&&(A=P.renderWelcome({config:a,variant:a.variant,visible:m,defaultRenderer:()=>Z,sendMessage:G=>{if(!V||V.isStreaming())return;let j=G.trim();j&&V.sendMessage(j)},requestRender:()=>zl(),renderStarter:G=>Jh(G,x++),storage:l(P.id),onCleanup:G=>{Fl.push(G)}}),A))break;A&&A!==Z&&(xs=A,lm(ce,Z,A))}finally{$l=!1}Nl()},Zh=()=>{let a=rr(o);`${a.variant}|${a.dismiss}|${a.title}|${a.subtitle}|${a.message??""}`===_p&&a.icon===$p||zl()},Ul=()=>{Nl(),yl||(W.placeholder=o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!V?.isStreaming()&&(h.textContent=o.copy?.sendButtonLabel??"Send")),W.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',W.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let a=f.sessionId;return typeof a=="string"?a:null},setStoredSessionId:a=>{S(u=>({...u,sessionId:a}))}});let Ko=null,eb=()=>{Ko==null&&(Ko=setInterval(()=>{let a=Ae.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(Ko),Ko=null;return}let u=Date.now();a.forEach(m=>{let x=Number(m.getAttribute("data-tool-elapsed"));x&&(m.textContent=oa(u-x))})},100))},jl=(a,u)=>{if(Object.is(a,u))return!0;if(a===null||u===null||typeof a!="object"||typeof u!="object")return!1;if(Array.isArray(a)||Array.isArray(u))return!Array.isArray(a)||!Array.isArray(u)||a.length!==u.length?!1:a.every((G,j)=>jl(G,u[j]));let m=a,x=u,A=Object.keys(m),P=Object.keys(x);return A.length===P.length&&A.every(G=>Object.prototype.hasOwnProperty.call(x,G)&&jl(m[G],x[G]))},Up=a=>{let{content:u,rawContent:m,llmContent:x,...A}=a;return A},Vl=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!Pd(a),tb=(a,u,m)=>{if(a.length!==u.length)return!1;let x=a[m.index],A=u[m.index];return!x||!A||x.id!==m.id||A.id!==m.id?!1:(!Object.is(x.content,A.content)||!Object.is(x.rawContent,A.rawContent)||!Object.is(x.llmContent,A.llmContent))&&Vl(x)&&Vl(A)&&jl(Up(x),Up(A))},jp=null,vr=null,Go=null,Gn=null,Oi=a=>{jp=a;let u,m;vr=null;for(let A=a.length-1;A>=0;A-=1){let P=a[A];if(!u&&P.role==="user"&&(u=P),!m&&P.role==="assistant"&&(m=P),!vr&&Vl(P)&&(vr={index:A,id:P.id}),u&&m&&vr)break}ms(Ae,a,Y),qc(Ae,Ln.artifacts,{suppressTransition:In}),eb(),Nl(a),gr(a),go(!In),qh(a),a.length===0&&(fs(),us=!0,Li=!1,mr=null,Pi=!1),!El||ki?(El=!0,Uo=u?.id??null,kl=m?.id??null):u&&u.id!==Uo?(Uo=u.id,$h(u.id)):m&&m.id!==kl&&zh(),m&&(kl=m.id),Vh(a);let x=Qe.lastUserMessageId;u&&u.id!==x&&(Qe.lastUserMessageId=u.id,d.emit("user:message",u)),Qe.lastUserMessageWasVoice=!!u?.viaVoice,Il(a),yr()},ql=()=>{Gn!==null&&(cancelAnimationFrame(Gn),Gn=null);let a=Go;Go=null,a&&Oi(a)},Vp=()=>{Gn!==null&&cancelAnimationFrame(Gn),Gn=null,Go=null},nb=a=>{let u=Go??jp;if(In&&u&&vr&&tb(u,a,vr)){Go=a,Gn===null&&(Gn=requestAnimationFrame(()=>{Gn=null;let m=Go;Go=null,m&&Oi(m)}));return}if(a.length===0){Vp(),Oi(a);return}ql(),Oi(a)};V=new ga(o,{onMessagesChanged(a){nb(a)},onStatusChanged(a){let u=o.statusIndicator??{};Tn(_,(x=>x==="idle"?u.idleText??Bt.idle:x==="connecting"?u.connectingText??Bt.connecting:x==="connected"?u.connectedText??Bt.connected:x==="error"?u.errorText??Bt.error:x==="paused"?u.pausedText??Bt.paused:x==="resuming"?u.resumingText??Bt.resuming:Bt[x])(a),u,a)},onStreamingChanged(a){a||(V?.getMessages().length===0?Vp():ql()),In=a,Di(a),V&&ms(Ae,V.getMessages(),Y),a||(go(!0),Fh(),yp=!0,V&&vp(V.getMessages(),So(o))),Vt(),$d(a?"Responding\u2026":"Response complete."),yr()},onVoiceStatusChanged(a){if(d.emit("voice:status",{status:a,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(a){case"listening":Qn(),wr();break;case"processing":Qn(),gb();break;case"speaking":Qn(),fb();break;default:a==="idle"&&V.isBargeInActive()?(Qn(),wr(),le?.setAttribute("aria-label","End voice session")):(Qe.active=!1,Qn(),Kn("system"),Rn());break}},onArtifactsState(a){Ln=a,a.artifacts.length===0&&(dr=!1),qc(Ae,a.artifacts,{suppressTransition:In}),Un(),Il()},onReconnect(a){let{executionId:u,lastEventId:m}=a.handle;a.phase==="paused"?d.emit("stream:paused",{executionId:u,after:m}):a.phase==="resuming"?d.emit("stream:resuming",{executionId:u,after:m,attempt:a.attempt??1}):d.emit("stream:resumed",{executionId:u,after:m})}}),at.current=V,Fe.push(()=>V.cancel());let Kl=null;if(V.onReadAloudChange((a,u)=>{Zd=a,ep=u,tp();let m=a??Kl;a&&(Kl=a);let x=m?V.getMessages().find(A=>A.id===m)??null:null;d.emit("message:read-aloud",{messageId:m,message:x,state:u,timestamp:Date.now()}),u==="idle"&&(Kl=null)}),i=!0,El=!0,o.voiceRecognition?.provider?.type==="runtype")try{V.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}o.clientToken&&V.initClientSession().catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)}),(Be||o.onSSEEvent)&&V.setSSEEventCallback((a,u)=>{o.onSSEEvent?.(a,u),Ue?.processEvent(a,u),Be?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(u)})});let qp=()=>{o.resume&&typeof o.reconnectStream=="function"&&V.resumeFromHandle(o.resume)};y?y.then(a=>{if(a){if(a.metadata&&(f=Id(a.metadata),D.syncFromMetadata()),a.messages?.length){ki=!0;try{V.hydrateMessages(a.messages)}finally{ki=!1}}a.artifacts?.length&&V.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>{Dp=!0,qp()}):qp();let Kp=()=>{!K()||Q||!(o.launcher?.composerBar?.expandOnSubmit??!0)||dt(!0,"auto")},ob=(a,u)=>a?u?{refs:[...a.refs,...u.refs],finalize:async()=>{let[m,x]=await Promise.allSettled([a.finalize(),u.finalize()]),A=[];return m.status==="fulfilled"?A.push(m.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",m.reason),x.status==="fulfilled"?A.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),vC(A)}}:a:u,rb=()=>{let u=W.getInlineMessageFields?.();return u&&u.contentSegments.some(x=>x.kind==="mention")?u.contentSegments:void 0},ws=!1,sb=async a=>{let u=W.value.trim(),m=wt?.hasAttachments()??!1,x=u?await(Zt?.takeInlineCommand(u)??Promise.resolve(null)):null;if(x?.kind==="action"){W.value="",W.style.height="auto",Cs(),Zt?.clear();return}let A=Zt?.collectForSubmit()??null,P=x?.kind==="server"?x.mentions:null,G=ob(A,P),j=x?.kind==="prompt"?x.sendText:u,X=!!A&&A.refs.length>0;if(!j&&!m&&!X&&!P)return;Kp();let re;m&&(re=[],re.push(...wt.getContentParts()),j&&re.push(Dr(j)));let he=x?.kind==="prompt"?void 0:rb();W.value="",W.style.height="auto",Cs(),V.sendMessage(j,{contentParts:re,mentions:G??void 0,contentSegments:he,viaVoice:a?.viaVoice}),m&&wt.clearAttachments(),A&&Zt?.clear()},Gl=async a=>{if(!ws){ws=!0;try{await sb(a)}finally{ws=!1}}},Ni=a=>{if(a.preventDefault(),V.isStreaming()){V.cancel(),Ue?.reset(),Me?.update();return}ws||Gl()},ib=()=>o.features?.composerHistory!==!1,Ql={...Qc},Xl=!1,Cs=()=>{Ql={...Qc}},ab=()=>V.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),lb=a=>{if(!W)return;Xl=!0,W.value=a,W.dispatchEvent(new Event("input",{bubbles:!0})),Xl=!1;let u=W.value.length;W.setSelectionRange(u,u)},cb=a=>{Xl||(a.isComposing||Zt?.handleInput(a.inputType??void 0),Cs())},db=a=>{if(W&&!(!a.isComposing&&Zt?.handleKeydown(a))){if(ib()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let u=W.selectionStart===0&&W.selectionEnd===0,m=$f({direction:a.key==="ArrowUp"?"up":"down",history:ab(),currentValue:W.value,atStart:u,state:Ql});if(Ql=m.state,m.handled){a.preventDefault(),m.value!==void 0&&lb(m.value);return}}if(a.key==="Enter"&&!a.shiftKey){if(V.isStreaming()){a.preventDefault();return}if(ws){a.preventDefault();return}Cs(),a.preventDefault(),h.click()}}},Gp=a=>{a.key!=="Escape"||a.isComposing||V.isStreaming()&&a.composedPath().includes(Ce)&&(V.cancel(),Ue?.reset(),Me?.update(),Cs(),a.preventDefault(),a.stopImmediatePropagation())},pb=async a=>{if(o.attachments?.enabled!==!0||!wt)return;let u=mC(a.clipboardData);u.length!==0&&(a.preventDefault(),await wt.handleFiles(u))},yn=null,Nn=!1,xr=null,At=null,Qp=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Fi=(a="user")=>{if(Nn||V.isStreaming())return;let u=Qp();if(!u)return;yn=new u;let x=(o.voiceRecognition??{}).pauseDuration??2e3;yn.continuous=!0,yn.interimResults=!0,yn.lang="en-US";let A=W.value;yn.onresult=P=>{let G="",j="";for(let re=0;re<P.results.length;re++){let he=P.results[re],ue=he[0].transcript;he.isFinal?G+=ue+" ":j=ue}let X=A+G+j;W.value=X,xr&&clearTimeout(xr),(G||j)&&(xr=window.setTimeout(()=>{W.value.trim()&&yn&&Nn&&(mo(),Gl({viaVoice:!0}))},x))},yn.onerror=P=>{P.error!=="no-speech"&&mo()},yn.onend=()=>{if(Nn){let P=W.value.trim();P&&P!==A.trim()&&Gl({viaVoice:!0}),mo()}};try{if(yn.start(),Nn=!0,Qe.active=!0,a!=="system"&&(Qe.manuallyDeactivated=!1),Kn(a),Rn(),le){let P=o.voiceRecognition??{};At={backgroundColor:le.style.backgroundColor,color:le.style.color,borderColor:le.style.borderColor,iconName:P.iconName??"mic",iconSize:parseFloat(P.iconSize??o.sendButton?.size??"40")||24};let G=P.recordingBackgroundColor,j=P.recordingIconColor,X=P.recordingBorderColor;if(le.classList.add("persona-voice-recording"),le.style.backgroundColor=G??"var(--persona-voice-recording-bg, #ef4444)",le.style.color=j??"var(--persona-voice-recording-indicator, #ffffff)",j){let re=le.querySelector("svg");re&&re.setAttribute("stroke",j)}X&&(le.style.borderColor=X),le.setAttribute("aria-label","Stop voice recognition")}}catch{mo("system")}},mo=(a="user")=>{if(Nn){if(Nn=!1,xr&&(clearTimeout(xr),xr=null),yn){try{yn.stop()}catch{}yn=null}if(Qe.active=!1,Kn(a),Rn(),le){if(le.classList.remove("persona-voice-recording"),At){le.style.backgroundColor=At.backgroundColor,le.style.color=At.color,le.style.borderColor=At.borderColor;let u=le.querySelector("svg");u&&u.setAttribute("stroke",At.color||"currentColor"),At=null}le.setAttribute("aria-label","Start voice recognition")}}},ub=(a,u)=>{let m=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=a?.provider?.type==="runtype",A=a?.provider?.type==="custom";if(!(m||x||A))return null;let G=v("div","persona-send-button-wrapper"),j=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");j.type="button";let X=a?.tooltipText??"Start voice recognition";j.setAttribute("aria-label",X);let re=a?.iconName??"mic",he=u?.size??"40px",ue=a?.iconSize??he,we=parseFloat(ue)||24,Xe=a?.backgroundColor??u?.backgroundColor,yt=a?.iconColor??u?.textColor;j.style.width=ue,j.style.height=ue,j.style.minWidth=ue,j.style.minHeight=ue,j.style.fontSize="18px",j.style.lineHeight="1",yt?j.style.color=yt:j.style.color="var(--persona-text, #111827)";let dn=ie(re,we,yt||"currentColor",1.5);dn?j.appendChild(dn):j.textContent="\u{1F3A4}",Xe?j.style.backgroundColor=Xe:j.style.backgroundColor="",a?.borderWidth&&(j.style.borderWidth=a.borderWidth,j.style.borderStyle="solid"),a?.borderColor&&(j.style.borderColor=a.borderColor),a?.paddingX&&(j.style.paddingLeft=a.paddingX,j.style.paddingRight=a.paddingX),a?.paddingY&&(j.style.paddingTop=a.paddingY,j.style.paddingBottom=a.paddingY),G.appendChild(j);let Et=a?.showTooltip??!1;return jt({anchor:j,trigger:G,text:()=>j.getAttribute("aria-label")??X,enabled:Et}),{micButton:j,micButtonWrapper:G}},Yl=()=>{if(!le||At)return;let a=o.voiceRecognition??{};At={backgroundColor:le.style.backgroundColor,color:le.style.color,borderColor:le.style.borderColor,iconName:a.iconName??"mic",iconSize:parseFloat(a.iconSize??o.sendButton?.size??"40")||24}},Jl=(a,u)=>{if(!le)return;let m=le.querySelector("svg");m&&m.remove();let x=At?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),A=ie(a,x,u,1.5);A&&le.appendChild(A)},_i=()=>{le&&le.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},wr=()=>{if(!le)return;Yl();let a=o.voiceRecognition??{},u=a.recordingBackgroundColor,m=a.recordingIconColor,x=a.recordingBorderColor;if(_i(),le.classList.add("persona-voice-recording"),le.style.backgroundColor=u??"var(--persona-voice-recording-bg, #ef4444)",le.style.color=m??"var(--persona-voice-recording-indicator, #ffffff)",m){let A=le.querySelector("svg");A&&A.setAttribute("stroke",m)}x&&(le.style.borderColor=x),le.setAttribute("aria-label","Stop voice recognition")},gb=()=>{if(!le)return;Yl();let a=o.voiceRecognition??{},u=V.getVoiceInterruptionMode(),m=a.processingIconName??"loader",x=a.processingIconColor??At?.color??"",A=a.processingBackgroundColor??At?.backgroundColor??"",P=a.processingBorderColor??At?.borderColor??"";_i(),le.classList.add("persona-voice-processing"),le.style.backgroundColor=A,le.style.borderColor=P;let G=x||"currentColor";le.style.color=G,Jl(m,G),le.setAttribute("aria-label","Processing voice input"),u==="none"&&(le.style.cursor="default")},fb=()=>{if(!le)return;Yl();let a=o.voiceRecognition??{},u=V.getVoiceInterruptionMode(),m=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",x=a.speakingIconName??m,A=a.speakingIconColor??(u==="barge-in"?a.recordingIconColor??At?.color??"":At?.color??""),P=a.speakingBackgroundColor??(u==="barge-in"?a.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":At?.backgroundColor??""),G=a.speakingBorderColor??(u==="barge-in"?a.recordingBorderColor??"":At?.borderColor??"");_i(),le.classList.add("persona-voice-speaking"),le.style.backgroundColor=P,le.style.borderColor=G;let j=A||"currentColor";le.style.color=j,Jl(x,j);let X=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";le.setAttribute("aria-label",X),u==="none"&&(le.style.cursor="default"),u==="barge-in"&&le.classList.add("persona-voice-recording")},Qn=()=>{le&&(_i(),At&&(le.style.backgroundColor=At.backgroundColor??"",le.style.color=At.color??"",le.style.borderColor=At.borderColor??"",Jl(At.iconName,At.color||"currentColor"),At=null),le.style.cursor="",le.setAttribute("aria-label","Start voice recognition"))},Cr=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let a=V.getVoiceStatus(),u=V.getVoiceInterruptionMode();if(u==="none"&&(a==="processing"||a==="speaking"))return;if(u==="cancel"&&(a==="processing"||a==="speaking")){V.stopVoicePlayback();return}if(V.isBargeInActive()){V.stopVoicePlayback(),V.deactivateBargeIn().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,Rn(),Kn("user"),Qn()});return}V.toggleVoice().then(()=>{Qe.active=V.isVoiceActive(),Qe.manuallyDeactivated=!V.isVoiceActive(),Rn(),Kn("user"),V.isVoiceActive()?wr():Qn()});return}if(Nn){let a=W.value.trim();Qe.manuallyDeactivated=!0,Rn(),mo("user"),a&&(W.value="",W.style.height="auto",V.sendMessage(a))}else Qe.manuallyDeactivated=!1,Rn(),Fi("user")};Ud=Cr,le&&(le.addEventListener("click",Cr),Fe.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(V.isVoiceActive()&&V.toggleVoice(),Qn()):mo("system"),le&&le.removeEventListener("click",Cr)}));let mb=d.on("assistant:complete",()=>{Cp&&(Qe.active||Qe.manuallyDeactivated||Cp==="assistant"&&!Qe.lastUserMessageWasVoice||setTimeout(()=>{!Qe.active&&!Qe.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?V.toggleVoice().then(()=>{Qe.active=V.isVoiceActive(),Kn("auto"),V.isVoiceActive()&&wr()}):Fi("auto"))},600))});Fe.push(mb);let hb=d.on("action:resubmit",()=>{setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)});Fe.push(hb);let Xp=()=>{dt(!Q,"user")},Lt=null,en=null;if(z&&!K()){let{instance:a,element:u}=pd({config:o,plugins:s,onToggle:Xp});Lt=a,a||(en=u)}Lt?t.appendChild(Lt.element):en&&t.appendChild(en),vs(),gr(),Ul(),zl(),Di(V.isStreaming()),Lp()||(an()==="follow"?go(!0):kp()),Wh(),F&&(!z||K()?setTimeout(()=>Dl(),0):Q&&setTimeout(()=>Dl(),200));let As=()=>{if(K()){Wo(),vs();return}let a=Ot(o),u=o.launcher?.sidebarMode??!1,m=t.ownerDocument.defaultView??window,x=o.launcher?.mobileFullscreen??!0,A=o.launcher?.mobileBreakpoint??640,P=m.innerWidth<=A,G=x&&P&&z;try{if(G){Ho(),cs=Mi();return}let j=!1;N&&(N=!1,Ho(),j=!0);let X=Mi();if(!j&&X!==cs&&(Ho(),j=!0),cs=X,j&&Cl(),!z&&!a){xe.style.height="",xe.style.width="";return}if(!u&&!a){let he=o?.launcher?.width??o?.launcherWidth??no;xe.style.width=he,xe.style.maxWidth=he}Si(),ap()}finally{if(Wo(),vs(),Q&&z){let X=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),re=o.launcher?.sidebarMode??!1,he=o.launcher?.mobileFullscreen??!0,ue=Ot(o)&&he&&X,we=re||he&&X&&z||ue;if(we&&!On){let Xe=t.getRootNode(),yt=Xe instanceof ShadowRoot?Xe.host:t.closest(".persona-host");yt&&!Dn&&(Dn=Zc(yt,o.launcher?.zIndex??Ut)),On=ed(t.ownerDocument)}else we||(Dn?.(),Dn=null,On?.(),On=null)}}};As();let Yp=t.ownerDocument.defaultView??window;if(Yp.addEventListener("resize",As),Fe.push(()=>Yp.removeEventListener("resize",As)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{Wo()});a.observe(Se),Fe.push(()=>a.disconnect())}cn=ce.scrollTop;let Jp=_n(ce),Zp=()=>{let a=ce.scrollTop,u=_n(ce),m=u<Jp;if(Jp=u,!io()){cn=a,Vt();return}let{action:x,nextLastScrollTop:A}=za({following:ln.isFollowing(),currentScrollTop:a,lastScrollTop:cn,nearBottom:ro(ce,Vn),userScrollThreshold:Lh,isAutoScrolling:on||Ei||m,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(cn=A,x==="resume"){Ri()||uo();return}x==="pause"&&gs()};if(ce.addEventListener("scroll",Zp,{passive:!0}),Fe.push(()=>ce.removeEventListener("scroll",Zp)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{_h(),ic(Ae)});a.observe(Ae),a.observe(ce),Fe.push(()=>a.disconnect())}let eu=()=>{io()&&ln.isFollowing()&&Ri()&&gs()},tu=ce.ownerDocument;tu.addEventListener("selectionchange",eu),Fe.push(()=>{tu.removeEventListener("selectionchange",eu)});let bb=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),nu=a=>{bb.has(a.key)&&(jo(),Nd()&&io()&&ln.isFollowing()&&gs())},ou=a=>{a.target?.closest("a, button, [tabindex], input, textarea, select")&&(jo(),Nd()&&io()&&ln.isFollowing()&&gs())};ce.addEventListener("keydown",nu),ce.addEventListener("focusin",ou),Fe.push(()=>{ce.removeEventListener("keydown",nu),ce.removeEventListener("focusin",ou)});let ru=a=>{if(a.deltaY!==0&&jo(),!io())return;let u=Ua({following:ln.isFollowing(),deltaY:a.deltaY,nearBottom:ro(ce,Vn),resumeWhenNearBottom:!0});u==="pause"?gs():u==="resume"&&!Ri()&&uo()};ce.addEventListener("wheel",ru,{passive:!0}),ce.addEventListener("touchmove",jo,{passive:!0}),ce.addEventListener("pointerdown",jo,{passive:!0}),Fe.push(()=>{ce.removeEventListener("touchmove",jo),ce.removeEventListener("pointerdown",jo)}),Fe.push(()=>ce.removeEventListener("wheel",ru)),It.addEventListener("click",()=>{fs(),ce.scrollTop=ce.scrollHeight,cn=ce.scrollTop,uo(),go(!0),Vt()}),Fe.push(()=>It.remove()),Fe.push(()=>{Mp(),fs()});let su=()=>{fe&&(No&&(fe.removeEventListener("click",No),No=null),te()?(fe.style.display="",No=()=>{dt(!1,"user")},fe.addEventListener("click",No)):fe.style.display="none")};su(),(()=>{let{clearChatButton:a}=ke;a&&a.addEventListener("click",()=>{V.clearMessages(),_o.clear(),uo(),Wr(ke.composerOverlay);try{localStorage.removeItem(es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(u),b?.clear&&Pl(()=>b.clear(),"[AgentWidget] Failed to clear storage adapter:"),f={},D.syncFromMetadata(),Be?.clear(),Ue?.reset(),Me?.update()})})(),R&&R.addEventListener("submit",Ni);let iu=[["keydown",db],["input",cb],["paste",pb],["focus",Ch]],Zl=a=>{if(a)for(let[u,m]of iu)a.addEventListener(u,m)},ec=a=>{if(a)for(let[u,m]of iu)a.removeEventListener(u,m)};Zl(W);let au=()=>{Zt?.onComposerSwap((a,u)=>{ec(u),W=a,Zl(a)})};au();let tc=!1;function yb(){if(!tc){tc=!0;try{let a=W?.value??"",u=Se.ownerDocument??document,m=W?u.activeElement===W:!1;ec(W),R?.removeEventListener("submit",Ni),le?.removeEventListener("click",Cr),Zt?.destroy(),Zt=null;let x=null,A=()=>(x=K()?ol({config:o}):ai({config:o}),x.footer),P=qd(A)??A();nt.replaceComposer(P),Se=nt.composer.footer;let G=x!==null&&P===x.footer;yl=!G,bi=G?x.setSendButtonMode:()=>{},Vd(Se),Gd(Se),Qd(),Xd(),Yd(),au(),R&&R.addEventListener("submit",Ni),Zl(W),le?.addEventListener("click",Cr);let j=Oo.indexOf(jn);jn.destroy(),jn=si(k),j>=0&&(Oo[j]=jn),W&&(W.value=a),Ul(),gr(),Di(V.isStreaming()),Ho(),Wo(),m&&W?.focus()}finally{tc=!1}}}let lu=t.ownerDocument??document;lu.addEventListener("keydown",Gp,!0);let cu="persona-attachment-drop-active",Ss=0,nc=()=>{Ss=0,Ce.classList.remove(cu)},Ar=()=>o.attachments?.enabled===!0&&wt!==null,du=a=>{!ul(a.dataTransfer)||!Ar()||(Ss++,Ss===1&&Ce.classList.add(cu))},pu=a=>{!ul(a.dataTransfer)||!Ar()||(Ss--,Ss<=0&&nc())},uu=a=>{!ul(a.dataTransfer)||!Ar()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},gu=a=>{if(!ul(a.dataTransfer)||!Ar())return;a.preventDefault(),a.stopPropagation(),nc();let u=Array.from(a.dataTransfer.files??[]);u.length!==0&&wt.handleFiles(u)},ho=!0;Ce.addEventListener("dragenter",du,ho),Ce.addEventListener("dragleave",pu,ho),t.addEventListener("dragover",uu,ho),t.addEventListener("drop",gu,ho);let $i=t.ownerDocument,fu=a=>{Ar()&&a.preventDefault()},mu=a=>{Ar()&&a.preventDefault()};$i.addEventListener("dragover",fu),$i.addEventListener("drop",mu),Fe.push(()=>{R&&R.removeEventListener("submit",Ni),ec(W),lu.removeEventListener("keydown",Gp,!0),Zt?.destroy()}),Fe.push(()=>{Ce.removeEventListener("dragenter",du,ho),Ce.removeEventListener("dragleave",pu,ho),t.removeEventListener("dragover",uu,ho),t.removeEventListener("drop",gu,ho),$i.removeEventListener("dragover",fu),$i.removeEventListener("drop",mu),nc()}),Fe.push(()=>{V.cancel()}),Lt?Fe.push(()=>{Lt?.destroy()}):en&&Fe.push(()=>{en?.remove()});let Rt={update(a){let u=o.toolCall,m=o.messageActions,x=o.layout?.messages,A=o.colorScheme,P=o.loadingIndicator,G=o.iterationDisplay,j=o.features?.showReasoning,X=o.features?.showToolCalls,re=o.features?.toolCallDisplay,he=o.features?.reasoningDisplay,ue=o.features?.streamAnimation?.type;o=Km({...o,features:r},a),r=o.features,o=wd(o),Sl(),Qs(t,o),gi(t,o),fi(t,o),Un(),o.colorScheme!==A&&lp();let we=Md.getForInstance(o.plugins);s.length=0,s.push(...we),z=o.launcher?.enabled??!0,$=o.launcher?.autoExpand??!1,pe=o.features?.showReasoning??!0,ne=o.features?.showToolCalls??!0,ve=o.features?.scrollToBottom??{};let Xe=an();be=o.features?.scrollBehavior??{},Xe!==an()&&(fs(),uo()),wp(),zd(),Vt();let yt=me;if(me=o.features?.showEventStreamToggle??!1,me&&!yt){if(Be||(Oe=new pi(ze),Be=new di(Ne,Oe),Ue=Ue??new ui,Oe.open().then(()=>Be?.restore()).catch(()=>{}),V.setSSEEventCallback((de,Ge)=>{o.onSSEEvent?.(de,Ge),Ue?.processEvent(de,Ge),Be.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:de,timestamp:Date.now(),payload:JSON.stringify(Ge)})})),!et&&He){let de=o.features?.eventStream?.classNames,Ge="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"+(de?.toggleButton?" "+de.toggleButton:"");et=v("button",Ge),et.style.width="28px",et.style.height="28px",et.style.color=Yt.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let mt=ie("activity","18px","currentColor",1.5);mt&&et.appendChild(mt);let tt=ke.clearChatButtonWrapper,st=ke.closeButtonWrapper,Qt=tt||st;Qt&&Qt.parentNode===He?He.insertBefore(et,Qt):He.appendChild(et),et.addEventListener("click",()=>{Ee?is():hl()})}}else!me&&yt&&(is(),et&&(et.remove(),et=null),Be?.clear(),Oe?.destroy(),Be=null,Oe=null,Ue?.reset(),Ue=null);if(o.launcher?.enabled===!1&&Lt&&(Lt.destroy(),Lt=null),o.launcher?.enabled===!1&&en&&(en.remove(),en=null),o.launcher?.enabled!==!1&&!Lt&&!en){let{instance:de,element:Ge}=pd({config:o,plugins:s,onToggle:Xp});Lt=de,de||(en=Ge),t.appendChild(Ge)}Lt&&Lt.update(o),Ke&&o.launcher?.title!==void 0&&(Ke.textContent=o.launcher.title),je&&o.launcher?.subtitle!==void 0&&(je.textContent=o.launcher.subtitle);let pt=o.layout?.header;if(pt?.layout!==w&&He){let de=pt?Xa(o,pt,{showClose:te(),onClose:()=>dt(!1,"user")}):or({config:o,showClose:te(),onClose:()=>dt(!1,"user")});nt.replaceHeader(de),He=nt.header.element,Ie=nt.header.iconHolder,Ke=nt.header.headerTitle,je=nt.header.headerSubtitle,fe=nt.header.closeButton,w=pt?.layout}else if(pt){if(Ie&&(Ie.style.display=pt.showIcon===!1?"none":""),Ke&&(Ke.style.display=pt.showTitle===!1?"none":""),je&&(je.style.display=pt.showSubtitle===!1?"none":""),fe){let de=te()&&pt.showCloseButton!==!1;fe.style.display=de?"":"none"}if(ke.clearChatButtonWrapper){let de=pt.showClearChat;if(de!==void 0){ke.clearChatButtonWrapper.style.display=de?"":"none";let{closeButtonWrapper:Ge}=ke;Ge&&!Ge.classList.contains("persona-absolute")&&(de?Ge.classList.remove("persona-ml-auto"):Ge.classList.add("persona-ml-auto"))}}}let Et=o.layout?.showHeader!==!1;He&&(He.style.display=Et?"":"none");let Wt=o.layout?.showFooter!==!1;Se&&(Se.style.display=Wt?"":"none"),Wo(),Vt(),z!==H?z?dt($,"auto"):(Q=!0,vs()):$!==B&&dt($,"auto"),B=$,H=z,As(),su();let _e=JSON.stringify(o.toolCall)!==JSON.stringify(u),Le=JSON.stringify(o.messageActions)!==JSON.stringify(m),Tt=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),ut=o.loadingIndicator?.render!==P?.render||o.loadingIndicator?.renderIdle!==P?.renderIdle||o.loadingIndicator?.showBubble!==P?.showBubble,$t=o.iterationDisplay!==G,gt=(o.features?.showReasoning??!0)!==(j??!0)||(o.features?.showToolCalls??!0)!==(X??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(re)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(he);(_e||Le||Tt||ut||$t||gt)&&V&&(Tl++,ms(Ae,V.getMessages(),Y));let Ht=o.features?.streamAnimation?.type;if(Ht!==ue&&Ht&&Ht!=="none"){let de=qr(Ht,o.features?.streamAnimation?.plugins);de&&Ka(de,t)}let We=o.launcher??{},$e=We.headerIconHidden??!1,qt=o.layout?.header?.showIcon,Kt=$e||qt===!1,St=We.headerIconName,lt=We.headerIconSize??"48px";if(Ie){let de=Ce.querySelector(".persona-border-b-persona-divider"),Ge=de?.querySelector(".persona-flex-col");if(Kt)Ie.style.display="none",de&&Ge&&!de.contains(Ge)&&de.insertBefore(Ge,de.firstChild);else{if(Ie.style.display="",Ie.style.height=lt,Ie.style.width=lt,de&&Ge&&(de.contains(Ie)?Ie.nextSibling!==Ge&&(Ie.remove(),de.insertBefore(Ie,Ge)):de.insertBefore(Ie,Ge)),St){let tt=parseFloat(lt)||24,st=ie(St,tt*.6,"currentColor",1);st?Ie.replaceChildren(st):Ie.textContent=We.agentIconText??"\u{1F4AC}"}else if(We.iconUrl){let tt=Ie.querySelector("img");if(tt)tt.src=We.iconUrl,tt.style.height=lt,tt.style.width=lt;else{let st=document.createElement("img");st.src=We.iconUrl,st.alt="",st.className="persona-rounded-xl persona-object-cover",st.style.height=lt,st.style.width=lt,Ie.replaceChildren(st)}}else{let tt=Ie.querySelector("svg"),st=Ie.querySelector("img");(tt||st)&&Ie.replaceChildren(),Ie.textContent=We.agentIconText??"\u{1F4AC}"}let mt=Ie.querySelector("img");mt&&(mt.style.height=lt,mt.style.width=lt)}}let ft=o.layout?.header?.showTitle,Ze=o.layout?.header?.showSubtitle;if(Ke&&(Ke.style.display=ft===!1?"none":""),je&&(je.style.display=Ze===!1?"none":""),fe){let de=te()&&o.layout?.header?.showCloseButton!==!1;fe.style.display=de?"":"none";let Ge=We.closeButtonSize??"32px",mt=We.closeButtonPlacement??"inline";fe.style.height=Ge,fe.style.width=Ge;let{closeButtonWrapper:tt}=ke,st=mt==="top-right",Qt=tt?.classList.contains("persona-absolute");if(tt&&st!==Qt)if(tt.remove(),st)tt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Ce.style.position="relative",Ce.appendChild(tt);else{let yo=We.clearChat?.placement??"inline",Es=We.clearChat?.enabled??!0;tt.className=Es&&yo==="inline"?"":"persona-ml-auto";let hu=Ce.querySelector(".persona-border-b-persona-divider");hu&&hu.appendChild(tt)}if(fe.style.color=We.closeButtonColor||Yt.actionIconColor,We.closeButtonBackgroundColor?(fe.style.backgroundColor=We.closeButtonBackgroundColor,fe.classList.remove("hover:persona-bg-gray-100")):(fe.style.backgroundColor="",fe.classList.add("hover:persona-bg-gray-100")),We.closeButtonBorderWidth||We.closeButtonBorderColor){let yo=We.closeButtonBorderWidth||"0px",Es=We.closeButtonBorderColor||"transparent";fe.style.border=`${yo} solid ${Es}`,fe.classList.remove("persona-border-none")}else fe.style.border="",fe.classList.add("persona-border-none");We.closeButtonBorderRadius?(fe.style.borderRadius=We.closeButtonBorderRadius,fe.classList.remove("persona-rounded-full")):(fe.style.borderRadius="",fe.classList.add("persona-rounded-full")),We.closeButtonPaddingX?(fe.style.paddingLeft=We.closeButtonPaddingX,fe.style.paddingRight=We.closeButtonPaddingX):(fe.style.paddingLeft="",fe.style.paddingRight=""),We.closeButtonPaddingY?(fe.style.paddingTop=We.closeButtonPaddingY,fe.style.paddingBottom=We.closeButtonPaddingY):(fe.style.paddingTop="",fe.style.paddingBottom="");let pn=We.closeButtonIconName??"x",Wn=We.closeButtonIconText??"\xD7";fe.innerHTML="";let zt=ie(pn,"28px","currentColor",1);zt?(zt.style.display="block",fe.appendChild(zt)):fe.textContent=Wn;let Xt=We.closeButtonTooltipText??"Close chat",Yn=We.closeButtonShowTooltip??!0;fe.setAttribute("aria-label",Xt),tt&&jt({anchor:fe,trigger:tt,text:()=>fe?.getAttribute("aria-label")??Xt,enabled:Yn})}let{clearChatButton:De,clearChatButtonWrapper:vt}=ke;if(De){let de=We.clearChat??{},Ge=de.enabled??!0,mt=o.layout?.header?.showClearChat,tt=mt!==void 0?mt:Ge,st=de.placement??"inline";if(vt){vt.style.display=tt?"":"none";let{closeButtonWrapper:Qt}=ke;!K()&&Qt&&!Qt.classList.contains("persona-absolute")&&(tt?Qt.classList.remove("persona-ml-auto"):Qt.classList.add("persona-ml-auto"));let pn=st==="top-right",Wn=vt.classList.contains("persona-absolute");if(!K()&&pn!==Wn&&tt){if(vt.remove(),pn)vt.className="persona-absolute persona-top-4 persona-z-50",vt.style.right="48px",Ce.style.position="relative",Ce.appendChild(vt);else{vt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",vt.style.right="";let Xt=Ce.querySelector(".persona-border-b-persona-divider"),Yn=ke.closeButtonWrapper;Xt&&Yn&&Yn.parentElement===Xt?Xt.insertBefore(vt,Yn):Xt&&Xt.appendChild(vt)}let zt=ke.closeButtonWrapper;zt&&!zt.classList.contains("persona-absolute")&&(pn?zt.classList.add("persona-ml-auto"):zt.classList.remove("persona-ml-auto"))}}if(tt){if(!K()){let yo=de.size??"32px";De.style.height=yo,De.style.width=yo}let Qt=de.iconName??"refresh-cw",pn=de.iconColor??"";De.style.color=pn||Yt.actionIconColor,De.innerHTML="";let Wn=K()?"14px":"20px",zt=ie(Qt,Wn,"currentColor",1);if(zt&&(zt.style.display="block",De.appendChild(zt)),de.backgroundColor?(De.style.backgroundColor=de.backgroundColor,De.classList.remove("hover:persona-bg-gray-100")):(De.style.backgroundColor="",De.classList.add("hover:persona-bg-gray-100")),de.borderWidth||de.borderColor){let yo=de.borderWidth||"0px",Es=de.borderColor||"transparent";De.style.border=`${yo} solid ${Es}`,De.classList.remove("persona-border-none")}else De.style.border="",De.classList.add("persona-border-none");de.borderRadius?(De.style.borderRadius=de.borderRadius,De.classList.remove("persona-rounded-full")):(De.style.borderRadius="",De.classList.add("persona-rounded-full")),de.paddingX?(De.style.paddingLeft=de.paddingX,De.style.paddingRight=de.paddingX):(De.style.paddingLeft="",De.style.paddingRight=""),de.paddingY?(De.style.paddingTop=de.paddingY,De.style.paddingBottom=de.paddingY):(De.style.paddingTop="",De.style.paddingBottom="");let Xt=de.tooltipText??"Clear chat",Yn=de.showTooltip??!0;De.setAttribute("aria-label",Xt),vt&&jt({anchor:De,trigger:vt,text:()=>De?.getAttribute("aria-label")??Xt,enabled:Yn})}}let Gt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Ed],xn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[mi.message,mi.messageAndClick];D=kd({parsers:Gt,handlers:xn,getSessionMetadata:I,updateSessionMetadata:S,emit:d.emit,documentRef:typeof document<"u"?document:null}),Y=oh(o,D,oe),V.updateConfig(o),ms(Ae,V.getMessages(),Y),gr(),Ul(),Zh(),Di(V.isStreaming());let Ms=o.voiceRecognition?.enabled===!0,zi=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Pt=o.voiceRecognition?.provider?.type==="runtype";if(Ms&&(zi||Pt))if(!le||!mn){let de=ub(o.voiceRecognition,o.sendButton);de&&(le=de.micButton,mn=de.micButtonWrapper,Mt.insertBefore(mn,O),le.addEventListener("click",Cr),le.disabled=V.isStreaming())}else{let de=o.voiceRecognition??{},Ge=o.sendButton??{},mt=de.iconName??"mic",tt=Ge.size??"40px",st=de.iconSize??tt,Qt=parseFloat(st)||24;le.style.width=st,le.style.height=st,le.style.minWidth=st,le.style.minHeight=st;let pn=de.iconColor??Ge.textColor;le.innerHTML="";let Wn=ie(mt,Qt,pn||"currentColor",1.5);Wn?le.appendChild(Wn):le.textContent="\u{1F3A4}";let zt=de.backgroundColor??Ge.backgroundColor;zt?le.style.backgroundColor=zt:le.style.backgroundColor="",pn?le.style.color=pn:le.style.color="var(--persona-text, #111827)",de.borderWidth?(le.style.borderWidth=de.borderWidth,le.style.borderStyle="solid"):(le.style.borderWidth="",le.style.borderStyle=""),de.borderColor?le.style.borderColor=de.borderColor:le.style.borderColor="",de.paddingX?(le.style.paddingLeft=de.paddingX,le.style.paddingRight=de.paddingX):(le.style.paddingLeft="",le.style.paddingRight=""),de.paddingY?(le.style.paddingTop=de.paddingY,le.style.paddingBottom=de.paddingY):(le.style.paddingTop="",le.style.paddingBottom="");let Xt=de.tooltipText??"Start voice recognition",Yn=de.showTooltip??!1;le.setAttribute("aria-label",Xt),mn&&jt({anchor:le,trigger:mn,text:()=>le?.getAttribute("aria-label")??Xt,enabled:Yn}),mn.style.display="",le.disabled=V.isStreaming()}else le&&mn&&(mn.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?V.isVoiceActive()&&V.toggleVoice():Nn&&mo());if(o.attachments?.enabled===!0){if(!hn||!ct){let de=o.attachments??{},mt=(o.sendButton??{}).size??"40px";kn||(kn=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),kn.style.display="none",R.insertBefore(kn,W)),kt||(kt=document.createElement("input"),kt.type="file",kt.accept=(de.allowedTypes??to).join(","),kt.multiple=(de.maxFiles??4)>1,kt.style.display="none",kt.setAttribute("aria-label","Attach files"),R.insertBefore(kt,W)),hn=v("div","persona-send-button-wrapper"),ct=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ct.type="button",ct.setAttribute("aria-label",de.buttonTooltipText??"Attach file");let tt=de.buttonIconName??"paperclip",st=mt,Qt=parseFloat(st)||40,pn=Math.round(Qt*.6);ct.style.width=st,ct.style.height=st,ct.style.minWidth=st,ct.style.minHeight=st,ct.style.fontSize="18px",ct.style.lineHeight="1";let Wn=ie(tt,pn,"currentColor",1.5);Wn?ct.appendChild(Wn):ct.textContent="\u{1F4CE}",ct.addEventListener("click",Xt=>{Xt.preventDefault(),kt?.click()}),hn.appendChild(ct);let zt=de.buttonTooltipText??"Attach file";jt({anchor:ct,trigger:hn,text:()=>ct?.getAttribute("aria-label")??zt}),fn?fn.append(hn):R.appendChild(hn),!wt&&kt&&kn&&(wt=$s.fromConfig(de),wt.setPreviewsContainer(kn),kt.addEventListener("change",async()=>{wt&&kt?.files&&(await wt.handleFileSelect(kt.files),kt.value="")}))}else{hn.style.display="";let de=o.attachments??{};kt&&(kt.accept=(de.allowedTypes??to).join(","),kt.multiple=(de.maxFiles??4)>1),wt&&wt.updateConfig({allowedTypes:de.allowedTypes,maxFileSize:de.maxFileSize,maxFiles:de.maxFiles})}if(Ce.querySelector(".persona-attachment-drop-overlay")?.remove(),Ce.appendChild(rh(o.attachments?.dropOverlay)),ct){let de=o.attachments??{},Ge=de.buttonTooltipText??"Attach file";ct.setAttribute("aria-label",Ge),ct.textContent="";let mt=parseFloat(o.sendButton?.size??"40px")||40,tt=ie(de.buttonIconName??"paperclip",Math.round(mt*.6),"currentColor",1.5);tt?ct.appendChild(tt):ct.textContent="\u{1F4CE}",hn&&jt({anchor:ct,trigger:hn,text:()=>ct?.getAttribute("aria-label")??Ge})}}else hn&&(hn.style.display="none"),wt&&wt.clearAttachments(),Ce.querySelector(".persona-attachment-drop-overlay")?.remove();let _t=o.sendButton??{},Ts=_t.useIcon??!1,ji=_t.iconText??"\u2191",Sr=_t.iconName,Vi=_t.tooltipText??"Send message",oc=_t.showTooltip??!1,Qo=_t.size??"40px",Xn=_t.backgroundColor,Xo=_t.textColor;if(Ts){if(h.style.width=Qo,h.style.height=Qo,h.style.minWidth=Qo,h.style.minHeight=Qo,h.style.fontSize="18px",h.style.lineHeight="1",Xo?h.style.color=Xo:h.style.color="var(--persona-button-primary-fg, #ffffff)",!V.isStreaming())if(h.innerHTML="",Sr){let de=parseFloat(Qo)||24,Ge=Xo?.trim()||"currentColor",mt=ie(Sr,de,Ge,2);mt?h.appendChild(mt):h.textContent=ji}else h.textContent=ji;h.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Xn?(h.style.backgroundColor=Xn,h.classList.remove("persona-bg-persona-primary")):(h.style.backgroundColor="",h.classList.add("persona-bg-persona-primary"))}else h.textContent=o.copy?.sendButtonLabel??"Send",h.style.width="",h.style.height="",h.style.minWidth="",h.style.minHeight="",h.style.fontSize="",h.style.lineHeight="",h.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",Xn?(h.style.backgroundColor=Xn,h.classList.remove("persona-bg-persona-accent")):h.classList.add("persona-bg-persona-accent"),Xo?h.style.color=Xo:h.classList.add("persona-text-white");_t.borderWidth?(h.style.borderWidth=_t.borderWidth,h.style.borderStyle="solid"):(h.style.borderWidth="",h.style.borderStyle=""),_t.borderColor?h.style.borderColor=_t.borderColor:h.style.borderColor="",_t.paddingX?(h.style.paddingLeft=_t.paddingX,h.style.paddingRight=_t.paddingX):(h.style.paddingLeft="",h.style.paddingRight=""),_t.paddingY?(h.style.paddingTop=_t.paddingY,h.style.paddingBottom=_t.paddingY):(h.style.paddingTop="",h.style.paddingBottom=""),V.isStreaming()||h.setAttribute("aria-label",Vi),O&&jt({anchor:h,trigger:O,text:()=>h.getAttribute("aria-label")??Vi,enabled:oc});let Mr=To(o,K());Ml(),Mr?(Ae.style.maxWidth=Mr,Ae.style.marginLeft="auto",Ae.style.marginRight="auto",Ae.style.width="100%",ee.style.maxWidth=Mr,ee.style.marginLeft="auto",ee.style.marginRight="auto",ee.style.width="100%",R&&(R.style.maxWidth=Mr,R.style.marginLeft="auto",R.style.marginRight="auto"),k&&(k.style.maxWidth=Mr,k.style.marginLeft="auto",k.style.marginRight="auto"),_.style.maxWidth=Mr,_.style.marginLeft="auto",_.style.marginRight="auto"):(Ae.style.maxWidth="",Ae.style.marginLeft="",Ae.style.marginRight="",Ae.style.width="",ee.style.maxWidth="",ee.style.marginLeft="",ee.style.marginRight="",ee.style.width="",R&&(R.style.maxWidth="",R.style.marginLeft="",R.style.marginRight=""),k&&(k.style.maxWidth="",k.style.marginLeft="",k.style.marginRight=""),_.style.maxWidth="",_.style.marginLeft="",_.style.marginRight="");let bo=o.statusIndicator??{},vb=bo.visible??!0;if(_.style.display=vb?"":"none",V){let de=V.getStatus();Tn(_,(mt=>mt==="idle"?bo.idleText??Bt.idle:mt==="connecting"?bo.connectingText??Bt.connecting:mt==="connected"?bo.connectedText??Bt.connected:mt==="error"?bo.errorText??Bt.error:Bt[mt])(de),bo,de)}_.classList.remove("persona-text-left","persona-text-center","persona-text-right");let xb=bo.align==="left"?"persona-text-left":bo.align==="center"?"persona-text-center":"persona-text-right";_.classList.add(xb)},open(){te()&&dt(!0,"api")},close(){te()&&dt(!1,"api")},toggle(){te()&&dt(!Q,"api")},reconnect(){V.reconnectNow()},clearChat(){zn=!1,V.clearMessages(),_o.clear(),uo();try{localStorage.removeItem(es),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${es}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==es)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),b?.clear&&Pl(()=>b.clear(),"[AgentWidget] Failed to clear storage adapter:"),f={},D.syncFromMetadata(),Be?.clear(),Ue?.reset(),Me?.update()},setMessage(a){return!W||V.isStreaming()?!1:(!Q&&te()&&dt(!0,"system"),W.value=a,W.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(V.isStreaming())return!1;let u=a?.trim()||W.value.trim();return u?(!Q&&te()&&dt(!0,"system"),W.value="",W.style.height="auto",V.sendMessage(u),!0):!1},startVoiceRecognition(){return V.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(V.isVoiceActive()||(!Q&&te()&&dt(!0,"system"),Qe.manuallyDeactivated=!1,Rn(),V.toggleVoice().then(()=>{Qe.active=V.isVoiceActive(),Kn("user"),V.isVoiceActive()&&wr()})),!0):Nn?!0:Qp()?(!Q&&te()&&dt(!0,"system"),Qe.manuallyDeactivated=!1,Rn(),Fi("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?V.isVoiceActive()?(V.toggleVoice().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,Rn(),Kn("user"),Qn()}),!0):!1:Nn?(Qe.manuallyDeactivated=!0,Rn(),mo("user"),!0):!1},injectMessage(a){return!Q&&te()&&dt(!0,"system"),V.injectMessage(a)},injectAssistantMessage(a){!Q&&te()&&dt(!0,"system");let u=V.injectAssistantMessage(a);return se&&(se=!1,J&&(clearTimeout(J),J=null),setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)),u},injectUserMessage(a){return!Q&&te()&&dt(!0,"system"),V.injectUserMessage(a)},injectSystemMessage(a){return!Q&&te()&&dt(!0,"system"),V.injectSystemMessage(a)},injectMessageBatch(a){return!Q&&te()&&dt(!0,"system"),V.injectMessageBatch(a)},injectComponentDirective(a){return!Q&&te()&&dt(!0,"system"),V.injectComponentDirective(a)},injectTestMessage(a){!Q&&te()&&dt(!0,"system"),V.injectTestEvent(a)},async connectStream(a,u){return V.connectStream(a,u)},__pushEventStreamEvent(a){Be&&(Ue?.processEvent(a.type,a.payload),Be.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a.type,timestamp:Date.now(),payload:JSON.stringify(a.payload)}))},showEventStream(){!me||!Be||hl()},hideEventStream(){Ee&&is()},isEventStreamVisible(){return Ee},showArtifacts(){nn(o)&&(zn=!1,dr=!0,Un(),Je?.setMobileOpen(!0))},hideArtifacts(){nn(o)&&(zn=!0,Un())},upsertArtifact(a){return nn(o)?(xo(o.features?.artifacts,{artifactType:a.artifactType,...a.artifactType==="markdown"&&a.file?{file:a.file}:{},...a.presentation?{presentation:a.presentation}:{}})==="panel"&&(zn=!1,dr=!0),V.upsertArtifact(a)):null},selectArtifact(a){nn(o)&&V.selectArtifact(a)},clearArtifacts(){nn(o)&&V.clearArtifacts()},getArtifacts(){return V?.getArtifacts()??[]},getSelectedArtifactId(){return V?.getSelectedArtifactId()??null},focusInput(){return z&&!Q&&!K()||!W?!1:(W.focus(),!0)},async resolveApproval(a,u,m){let A=V.getMessages().find(P=>P.variant==="approval"&&P.approval?.id===a);if(!A?.approval)throw new Error(`Approval not found: ${a}`);if(A.approval.toolType==="webmcp"){V.resolveWebMcpApproval(A.id,u);return}return V.resolveApproval(A.approval,u,m)},setFollowUpSuggestions(a){Eh(a)},clearFollowUpSuggestions(){xp()},getMessages(){return V.getMessages()},getStatus(){return V.getStatus()},getPersistentMetadata(){return{...f}},updatePersistentMetadata(a){S(a)},on(a,u){return d.on(a,u)},off(a,u){d.off(a,u)},isOpen(){return te()&&Q},isVoiceActive(){return Qe.active},toggleReadAloud(a){V.toggleReadAloud(a)},stopReadAloud(){V.stopSpeaking()},getReadAloudState(a){return V.getReadAloudState(a)},onReadAloudChange(a){return V.onReadAloudChange(a)},getState(){return{open:te()&&Q,launcherEnabled:z,voiceActive:Qe.active,streaming:V.isStreaming()}},showCSATFeedback(a){!Q&&te()&&dt(!0,"system");let u=Ae.querySelector(".persona-feedback-container");u&&u.remove();let m=eh({onSubmit:async(x,A)=>{V.isClientTokenMode()&&await V.submitCSATFeedback(x,A),a?.onSubmit?.(x,A)},onDismiss:a?.onDismiss,...a});Ae.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!Q&&te()&&dt(!0,"system");let u=Ae.querySelector(".persona-feedback-container");u&&u.remove();let m=th({onSubmit:async(x,A)=>{V.isClientTokenMode()&&await V.submitNPSFeedback(x,A),a?.onSubmit?.(x,A)},onDismiss:a?.onDismiss,...a});Ae.appendChild(m),m.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,u){return V.submitCSATFeedback(a,u)},async submitNPSFeedback(a,u){return V.submitNPSFeedback(a,u)},destroy(){ql(),Ko!=null&&(clearInterval(Ko),Ko=null),Fe.forEach(a=>a()),Pe.remove(),ot?.remove(),Lt?.destroy(),en?.remove(),No&&fe.removeEventListener("click",No)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,u={controller:Rt,getMessages:Rt.getMessages,getStatus:Rt.getStatus,getMetadata:Rt.getPersistentMetadata,updateMetadata:Rt.updatePersistentMetadata,clearHistory:()=>Rt.clearChat(),setVoiceActive:m=>m?Rt.startVoiceRecognition():Rt.stopVoiceRecognition()};window.AgentWidgetBrowser=u,Fe.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=a)})}if(typeof window<"u"){let a=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),u=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===a)&&Rt.focusInput()};if(window.addEventListener("persona:focusInput",u),Fe.push(()=>{window.removeEventListener("persona:focusInput",u)}),me){let j=re=>{let he=re.detail;(!he?.instanceId||he.instanceId===a)&&Rt.showEventStream()},X=re=>{let he=re.detail;(!he?.instanceId||he.instanceId===a)&&Rt.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",X),Fe.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",X)})}let m=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===a)&&Rt.showArtifacts()},x=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===a)&&Rt.hideArtifacts()},A=j=>{let X=j.detail;X?.instanceId&&X.instanceId!==a||X?.artifact&&Rt.upsertArtifact(X.artifact)},P=j=>{let X=j.detail;X?.instanceId&&X.instanceId!==a||typeof X?.id=="string"&&Rt.selectArtifact(X.id)},G=j=>{let X=j.detail;(!X?.instanceId||X.instanceId===a)&&Rt.clearArtifacts()};window.addEventListener("persona:showArtifacts",m),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",P),window.addEventListener("persona:clearArtifacts",G),Fe.push(()=>{window.removeEventListener("persona:showArtifacts",m),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",P),window.removeEventListener("persona:clearArtifacts",G)})}let vn=hC(o.persistState);if(vn&&te()){let a=bC(vn.storage),u=`${vn.keyPrefix}widget-open`,m=`${vn.keyPrefix}widget-voice`,x=`${vn.keyPrefix}widget-voice-mode`;if(a){let A=vn.persist?.openState&&a.getItem(u)==="true",P=vn.persist?.voiceState&&a.getItem(m)==="true",G=vn.persist?.voiceState&&a.getItem(x)==="true";if(A&&(Lt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Rt.open(),setTimeout(()=>{if(P||G)Rt.startVoiceRecognition();else if(vn.persist?.focusInput){let j=t.querySelector("textarea");j&&j.focus()}},100)},0)),vn.persist?.openState&&(d.on("widget:opened",()=>{a.setItem(u,"true")}),d.on("widget:closed",()=>{a.setItem(u,"false")})),vn.persist?.voiceState&&(d.on("voice:state",j=>{a.setItem(m,j.active?"true":"false")}),d.on("user:message",j=>{a.setItem(x,j.viaVoice?"true":"false")})),vn.clearOnChatClear){let j=()=>{a.removeItem(u),a.removeItem(m),a.removeItem(x)},X=()=>j();window.addEventListener("persona:clear-chat",X),Fe.push(()=>{window.removeEventListener("persona:clear-chat",X)})}}}if(C&&te()&&(Lt?.setPanelOpen(!0,"auto"),setTimeout(()=>{Rt.open()},0)),yr(),!kh){let a=Gi(()=>{V&&(Tl++,_o.clear(),ms(Ae,V.getMessages(),Y))});Fe.push(a)}return Rt};var ih=(t,e)=>{let n=t.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,e*parseFloat(r[1])/100):420},xC=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},wC=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},CC=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(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.")},ah=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0",t.style.minWidth=n?"":"0"},Bd=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},lh=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Bd(t)},Rd=t=>{t.style.transition=""},Wd=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},Hd=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},gl=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},AC=(t,e,n,o,r)=>{r?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},SC=(t,e,n,o,r,s)=>{let i=s?e:t;r==="left"?i.firstElementChild!==o&&i.replaceChildren(o,n):i.lastElementChild!==o&&i.replaceChildren(n,o)},MC=t=>{let e=$r(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:tn(e,r)??r;return{inset:o(n?.inset,Pa),canvasBackground:o(n?.canvasBackground,Ia)}},ch=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},TC=(t,e,n,o,r,s,i,l)=>{let p=An(s),c=p.reveal==="push",d=l!=null,g=l?.inset??"",b=l?.canvasBackground??"";AC(t,e,n,o,c),SC(t,e,n,o,p.side,c),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=p.side,t.dataset.personaDockOpen=i?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=t.ownerDocument.defaultView,y=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,M=f!=null?f.innerWidth<=C:!1;if(y&&M&&i){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),Wd(e),Rd(o),lh(o),Hd(n),gl(r,o),ch(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Ut),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",c&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),lh(o),xC(o,p.maxHeight),ch(o,d&&i,g,b),p.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",Wd(e),Rd(o),Hd(n),gl(r,o);let S=p.animate?"transform 180ms ease":"none",E=p.side==="right"?"translateX(100%)":"translateX(-100%)",L=i?"translateX(0)":E;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=p.width,o.style.maxWidth=p.width,o.style.minWidth=p.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=S,o.style.transform=L,o.style.pointerEvents=i?"auto":"none",o.style.zIndex="2",p.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(p.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",Rd(o),Bd(o),gl(r,o);let S=ih(p.width,t.clientWidth),E=Math.max(0,t.clientWidth),L=p.animate?"margin-left 180ms ease":"none",D=p.side==="right"?i?-S:0:i?0:-S;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=`${E+S}px`,e.style.transition=L,e.style.marginLeft=`${D}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${E}px`,n.style.maxWidth=`${E}px`,n.style.minWidth=`${E}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=p.width,o.style.minWidth=p.width,o.style.maxWidth=p.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=i?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",Wd(e),Bd(o),Hd(n),gl(r,o);let S=p.reveal==="emerge";S?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let E=i?p.width:"0px",L=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${d?", padding 180ms ease":""}`:"none",D=!i;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${E}`,o.style.width=E,o.style.maxWidth=E,o.style.minWidth=E,o.style.minHeight="0",wC(o,p.maxHeight),o.style.overflow=S||D?"hidden":"visible",o.style.transition=L,S){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let z=d?`calc(${ih(p.width,t.clientWidth)}px - (2 * ${g}))`:p.width;r.style.width=z,r.style.minWidth=z,r.style.maxWidth=z,r.style.boxSizing="border-box"}}},EC=(t,e)=>{let n=t.ownerDocument.createElement("div");return ah(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){ah(n,o)},destroy(){n.remove()}}},kC=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=t.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,i=n.createElement("div"),l=n.createElement("div"),p=n.createElement("div"),c=n.createElement("aside"),d=n.createElement("div"),g=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",d.dataset.personaDockRole="host",c.appendChild(d),o.insertBefore(i,t),p.appendChild(t);let b=null,f=()=>{b?.disconnect(),b=null},y=null,C=()=>{y=e?.launcher?.detachedPanel===!0?MC(e):null};C();let M=()=>{TC(i,l,p,c,d,e,g,y)},I=null,S=()=>{I?.(),I=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(I=Ra(()=>{C(),M()}))},E=()=>{f(),An(e).reveal==="push"&&(typeof ResizeObserver>"u"||(b=new ResizeObserver(()=>{M()}),b.observe(i)))},L=!1,D=()=>{M(),E(),g&&!L&&i.dataset.personaDockMobileFullscreen!=="true"&&(L=!0,CC(i,An(e)))},z=i.ownerDocument.defaultView,$=()=>{D()};return z?.addEventListener("resize",$),An(e).reveal==="push"?(l.appendChild(p),l.appendChild(c),i.appendChild(l)):(i.appendChild(p),i.appendChild(c)),D(),S(),{mode:"docked",host:d,shell:i,syncWidgetState(F){let B=F.launcherEnabled?F.open:!0;g!==B&&(g=B,D())},updateConfig(F){e=F,(e?.launcher?.enabled??!0)===!1&&(g=!0),C(),D(),S()},destroy(){z?.removeEventListener("resize",$),I?.(),I=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),i.remove()}}},dh=(t,e)=>Ot(e)?kC(t,e):EC(t,e);var hi={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ph=.15,uh=1.5,Dd="persona-preview-shell-theme",LC={load:()=>null,save:()=>{},clear:()=>{}},PC=["How do I get started?","Pricing & plans","Talk to support"];function Od(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function IC(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function gh(t){let e=IC(t);return`* { box-sizing: border-box; }
1209
+ ${Re?"background: transparent !important;":""}
1210
+ `)}if(!h&&!i){let qt="max-height: -moz-available !important; max-height: stretch !important;",Tn=c?"":"padding-top: 1.25em !important;",Ki=c?"":`z-index: ${o.launcher?.zIndex??mn} !important;`;R.style.cssText+=qt+Tn+Ki}to()},_d=()=>{t.style.setProperty("--persona-content-max-width",yr(o,oe()))},yf=()=>{if(oe())return;let i=Kt(o),c=o.launcher?.sidebarMode??!1;if(i||c||(o.launcher?.fullHeight??!1)||!P)return;let h=t.ownerDocument.defaultView??window,C=o.launcher?.mobileFullscreen??!0,L=o.launcher?.mobileBreakpoint??640;if(C&&h.innerWidth<=L)return;let X=h.innerHeight,G=64,ie=o.launcher?.heightOffset??0,ne=Math.max(200,X-G),le=Math.min(640,ne);$.style.height=`${Math.max(200,le-ie)}px`};Od(),Ca(t,o),$a(t,o),za(t,o),_d(),Tr=()=>{Od(),yf(),Ca(t,o),$a(t,o),za(t,o),_d(),Ja?t.style.setProperty("--persona-artifact-welded-outer-radius",Ja):t.style.removeProperty("--persona-artifact-welded-outer-radius"),kt(),lt()};let We=[];We.push(()=>{d.forEach(i=>i()),l.destroy()}),We.push(()=>{document.removeEventListener("keydown",ff)}),We.push(()=>{fi!==null&&clearTimeout(fi)});let ho=null,yo=null;We.push(()=>{ho?.(),ho=null,yo?.(),yo=null}),yi&&We.push(()=>{yi?.disconnect(),yi=null}),We.push(()=>{wi?.(),wi=null,Nd(),Lt&&(Lt.remove(),Lt=null),tt?.element.style.removeProperty("width"),tt?.element.style.removeProperty("maxWidth"),tt?.destroy()}),ke&&We.push(()=>{yt!==null&&(cancelAnimationFrame(yt),yt=null),mt?.destroy(),mt=null,Ee?.destroy(),Ee=null,Ue=null});let kr=null,bf=()=>{kr&&(kr(),kr=null),o.colorScheme==="auto"&&(kr=Oc(()=>{Ca(t,o)}))};bf(),We.push(()=>{kr&&(kr(),kr=null)}),We.push(b);let sl=o.features?.streamAnimation;if(sl?.type&&sl.type!=="none"){let i=Zs(sl.type,sl.plugins);i&&(rd(i,t),We.push(()=>iv(t)))}let Io=Ra(Be),vf=Ra(et),wf=Ra(Ye),Pr=[Io,vf,wf];We.push(()=>{Pr.forEach(i=>i.destroy())});let Lr=null,z,Ir=null,Cf=!1,xf=0,Sf=null,Af=i=>i.reduce((c,f)=>f.role==="user"?c+1:c,0),Mf=i=>{for(let c=i.length-1;c>=0;c--)if(ta(i[c]))return i[c].id??null;return null},Tf=!1,sC=()=>{Tf||o.debug!==!0||(Tf=!0,console.warn('[persona] suggestions.starters.placement is pinned to "welcome" but the welcome surface is hidden (welcome.variant: "none" or copy.showWelcomeCard: false), so no starters render. Use "auto" or "composer".'))},Ef=!1,kf=!1,Pf=(i,c)=>{Ef||o.debug!==!0||!c.enabled||c.expose||Cf||kf&&(z.isStreaming()||i.some(ta)||(Ef=!0,console.info("[persona] Follow-up suggestions are enabled but the agent has not called suggest_replies. The model needs the tool declared (runtimeTools server-side, suggestions.followUps.expose: true from the widget, or your own backend's tool definition) and benefits from instructions telling it when to offer follow-ups. See the integration paths table in UI-COMPONENTS.md.")))},fs=i=>{if(!z)return;let c=i??z.getMessages(),f=ne=>{ne.render([],z,ye,c)},h=ne=>{Pr.forEach(le=>{le!==ne&&f(le)})};Ir&&(Af(c)>xf||Mf(c)!==Sf)&&(Ir=null);let C=fr(o);Pf(c,C);let L=C.enabled?$h(c):null,X=Ir??L,G=Ir?"host":"agent";if(X){let ne=o.suggestions?.followUps,le=ne?.placement??(ne?"auto":"composer"),Ae=(le==="auto"?oe()?"composer":"after-message":le)==="after-message"?wf:Io;h(Ae),Ae.render(X,z,ye,c,o.suggestionChipsConfig,{source:G,surface:"followUp",variant:ne?.variant??"chip",behavior:ne?.behavior??"send",overflow:ne?.overflow??"wrap",maxItems:ne?.maxItems??4,config:o,plugins:a});return}if(c.some(ne=>ne.role==="user")){Pr.forEach(f);return}let ie=o.suggestions?.starters;if(ie){let ne=oi(ts(o),c),le=ie.placement??"auto",be=le==="auto"?ne?"welcome":"composer":le;if(be==="welcome"&&!ne){sC(),Pr.forEach(f);return}let Ae=be==="welcome"?vf:Io;h(Ae),Ae.render(ie.items??o.suggestionChips,z,ye,c,o.suggestionChipsConfig,{surface:"starter",variant:ie.variant??"card",behavior:ie.behavior??"send",overflow:ie.overflow??"wrap",maxItems:ie.maxItems??4,config:o,plugins:a});return}h(Io),Io.render(o.suggestionChips,z,ye,c,o.suggestionChipsConfig,{surface:"starter",variant:"chip",behavior:"send",overflow:"wrap",config:o,plugins:a})},Lf=()=>{Ir&&(Ir=null,fs())},iC=i=>{let c=Array.isArray(i)?[...i]:[];if(!c.length){Lf();return}let f=z?z.getMessages():[];Ir=c,Cf=!0,xf=Af(f),Sf=Mf(f),fs(f)},_n=!1,Fn=Qb(),ms=new Map,Hr=new Map,Jo=new Map,Fd=0,aC=zo()!==null,$n=Jc(),zn=0,Zo=null,Hn=!1,il=!1,er=0,nn=null,Rr=null,$d=!1,hs=!1,Wr=null,Ci=!0,al=!1,ys=null,ll=!1,Br=()=>{ll=!0,pC()},zd=null,lC=4,Ho=24,cC=80,dC=1e3,Ro=null,If=()=>{t.setAttribute("data-persona-scrollbar",Pd()),Pd()!=="on-scroll"&&(Ro!==null&&clearTimeout(Ro),Ro=null,Z.removeAttribute("data-persona-scrollbar-visible"))},pC=()=>{Pd()==="on-scroll"&&(Z.setAttribute("data-persona-scrollbar-visible",""),Ro!==null&&clearTimeout(Ro),Ro=setTimeout(()=>{Ro=null,Go(Z,Ho)&&Z.removeAttribute("data-persona-scrollbar-visible")},dC))};If(),We.push(()=>{Ro!==null&&clearTimeout(Ro)});let Vd=new Map,rt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Hf=o.voiceRecognition?.autoResume??!1,Wo=i=>{m.emit("voice:state",{active:rt.active,source:i,timestamp:Date.now()})},po=()=>{I(i=>({...i,voiceState:{active:rt.active,timestamp:Date.now(),manuallyDeactivated:rt.manuallyDeactivated}}))},uC=()=>{if(o.voiceRecognition?.enabled===!1)return;let i=Fg(T.voiceState),c=!!i.active,f=Number(i.timestamp??0);rt.manuallyDeactivated=!!i.manuallyDeactivated,c&&Date.now()-f<kk&&setTimeout(()=>{rt.active||(rt.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?z.toggleVoice().then(()=>{rt.active=z.isVoiceActive(),Wo("restore"),z.isVoiceActive()&&Ps()}):Fl("restore"))},1e3)},gC=()=>z?Ow(z.getMessages()).filter(i=>!i.__skipPersist):[],cl=null,Rf=(i,c)=>{typeof console<"u"&&console.error(i,c)},dl=(i,c)=>{let f=()=>{try{let X=i();return!X||typeof X.then!="function"?null:Promise.resolve(X).catch(G=>{Rf(c,G)})}catch(X){return Rf(c,X),null}},h=cl,C=h?h.then(()=>f()??void 0):f();if(!C)return;let L=C.finally(()=>{cl===L&&(cl=null)});cl=L};function jd(i){if(!w?.save)return;let f={messages:i?Ow(i):z?gC():[],metadata:T,artifacts:lo.artifacts,selectedArtifactId:lo.selectedId};dl(()=>w.save(f),"[AgentWidget] Failed to persist state:")}let bs=null,Wf=()=>R.querySelector("#persona-scroll-container")||Z,vs=()=>{bs!==null&&(cancelAnimationFrame(bs),bs=null),Hn=!1},Bf=()=>{Zo!==null&&(cancelAnimationFrame(Zo),Zo=null),il=!1,vs()},fC=()=>_n&&Ud()&&(Le()!=="anchor-top"||Kg()),qd=()=>{let i=ce()||"Jump to latest",c=fC();Gt.toggleAttribute("data-persona-scroll-to-bottom-streaming",c),er>0?(Ar.textContent=String(er),Ar.style.display="",Gt.setAttribute("aria-label",`${i} (${er} new)`)):(Ar.textContent="",Ar.style.display="none",Gt.setAttribute("aria-label",c?`${i} (response streaming below)`:i))},Df=()=>{er!==0&&(er=0,qd())},mC=()=>{let i=nn?.spacerHeight??0;return i<=0?Go(Z,Ho):fl(i)-Z.scrollTop-Z.clientHeight<=Ho},Ud=()=>Nt()?!$n.isFollowing():!mC(),Kd=()=>!!z&&z.getMessages().length>0,on=()=>{if(!Xe()||Gn()){Gt.parentNode&&Gt.remove(),Gt.style.display="none";return}Gt.parentNode!==Q&&Q.appendChild(Gt),Mr();let c=Mo(Z)>0&&Ud()&&Kd();c?qd():Df(),Gt.style.display=c?"":"none"},xi=()=>{$n.pause()&&(Bf(),on())},Rn=()=>{$n.resume(),Df(),on()},tr=(i=!1)=>{Nt()&&Kd()&&$n.isFollowing()&&(!i&&!_n||(Zo!==null&&(cancelAnimationFrame(Zo),Zo=null),il=!0,Zo=requestAnimationFrame(()=>{Zo=null,il=!1,$n.isFollowing()&&hC(Wf(),i?220:140)})))},Nf=(i,c,f,h=()=>!0)=>{let C=i.scrollTop,L=c(),X=L-C;if(vs(),Math.abs(X)<1){Hn=!0,i.scrollTop=L,zn=i.scrollTop,Hn=!1;return}let G=performance.now();Hn=!0;let ie=le=>1-Math.pow(1-le,3),ne=le=>{if(!h()){vs();return}let be=c();be!==L&&(L=be,X=L-C);let Ae=le-G,gt=Math.min(Ae/f,1),Ht=ie(gt),pn=C+X*Ht;i.scrollTop=pn,zn=i.scrollTop,gt<1?bs=requestAnimationFrame(ne):(i.scrollTop=L,zn=i.scrollTop,bs=null,Hn=!1)};bs=requestAnimationFrame(ne)},hC=(i,c=500)=>{let f=Mo(i)-i.scrollTop;if(Math.abs(f)<1){zn=i.scrollTop;return}if(Math.abs(f)>=cC){vs(),Hn=!0,i.scrollTop=Mo(i),zn=i.scrollTop,Hn=!1;return}Nf(i,()=>Mo(i),c,()=>$n.isFollowing())},pl=()=>{if(!Kd()){on();return}let i=Wf();Hn=!0,i.scrollTop=Mo(i),zn=i.scrollTop,Hn=!1,on()},Dr=i=>{let c=0,f=i;for(;f&&f!==Z;)c+=f.offsetTop,f=f.offsetParent;return c},yC=()=>{let i=Z.getRootNode();return(typeof i.getSelection=="function"?i.getSelection():null)??Z.ownerDocument.getSelection()},ul=()=>nv(yC(),Z),Gd=()=>{if(Qo()!=="last-user-turn")return!1;let i=z?.getMessages()??[];if(i.length<2)return!1;let c=[...i].reverse().find(L=>L.role==="user");if(!c)return!1;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(c.id):c.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=Z.querySelector(`[data-message-id="${f}"]`);if(!h)return!1;let C=Math.min(Math.max(0,Dr(h)-In()),Mo(Z));return Hn=!0,Z.scrollTop=C,zn=Z.scrollTop,Hn=!1,Le()==="follow"&&!Go(Z,Ho)&&$n.pause(),on(),!0},gl=i=>{let c=Math.max(0,Math.round(i));Yn.style.height=`${c}px`,Yn.style.display=c>0?"":"none",nn&&(nn.spacerHeight=Math.max(0,i))},fl=i=>{let c=parseFloat(getComputedStyle(Z).paddingBottom)||0,f=0;for(let C of Array.from(Z.children)){if(C===Yn||C.offsetHeight===0)continue;let L=Dr(C)+C.offsetHeight;L>f&&(f=L)}let h=Z.scrollHeight-i;return f>0?Math.min(f+c,h):h},bC=()=>{if(!nn||nn.spacerHeight<=0)return;let i=fl(nn.spacerHeight),c=Math.max(0,Math.round(Z.scrollTop)+Z.clientHeight-i+Ho);c<nn.spacerHeight&&(gl(c),on())},uo=()=>{Rr!==null&&(cancelAnimationFrame(Rr),Rr=null),vs(),nn=null,Yn.style.height="0px",Yn.style.display="none"},Of=i=>typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(i):i.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),Yd=i=>Z.querySelector(`[data-message-id="${Of(i)}"]`),_f=i=>{Rr!==null&&cancelAnimationFrame(Rr),Rr=requestAnimationFrame(()=>{Rr=null;let c=Of(i),f=Z.querySelector(`[data-message-id="${c}"]`);if(!f)return;let h=Dr(f),C=nn?.spacerHeight??0,L=fl(C),{targetScrollTop:X,spacerHeight:G}=Fu({anchorOffsetTop:h,topOffset:In(),viewportHeight:Z.clientHeight,contentHeight:L,slack:Ho});nn={initialSpacerHeight:G,contentHeightAtAnchor:L,spacerHeight:G},gl(G),Nf(Z,()=>f.isConnected?Math.max(0,Dr(f)-In()):X,220)})},Bo=()=>{if(Le()!=="anchor-top"||!nn||!ys)return;let i=Yd(ys);if(!i)return;vs();let c=nn.spacerHeight,f=fl(c),{targetScrollTop:h,spacerHeight:C}=Fu({anchorOffsetTop:Dr(i),topOffset:In(),viewportHeight:Z.clientHeight,contentHeight:f,slack:Ho});nn={initialSpacerHeight:C,contentHeightAtAnchor:f,spacerHeight:C},gl(C),Hn=!0,Z.scrollTop=h,zn=Z.scrollTop,Hn=!1,on()},vC=()=>{if(Nt()){if(!$n.isFollowing()||Go(Z,1))return;tr(!_n);return}if(nn&&nn.initialSpacerHeight>0){let i=Z.scrollHeight-nn.spacerHeight,c=ov({initialSpacerHeight:nn.initialSpacerHeight,contentHeightAtAnchor:nn.contentHeightAtAnchor,currentContentHeight:i});c!==nn.spacerHeight&&gl(c)}on()},wC=i=>{let c=Le();c==="follow"?(Rn(),tr(!0)):c==="anchor-top"&&(Ci=!1,al=!0,ll=!1,ys=i,_f(i))},CC=()=>{if(Le()==="anchor-top"){if(al){Ci=!1;return}Ci=!0,uo(),Rn(),tr(!0)}},xC=96,SC=i=>{if(Wr===null)return!0;let c=Yd(Wr),f=Yd(i);if(!c||!f)return!0;let h=Dr(f)-Dr(c);return In()+h>Z.clientHeight-xC},AC=i=>{if(Le()!=="anchor-top"||!al||ll||ul())return;let c=Wr===null;for(let f of i){if(!c){f.id===Wr&&(c=!0);continue}if(tv(f)){if(f.id===ys||!SC(f.id))return;ys=f.id,_f(f.id);return}}},MC=i=>{let c=new Map;i.forEach(f=>{let h=Vd.get(f.id);c.set(f.id,{streaming:f.streaming,role:f.role}),!h&&f.role==="assistant"&&(m.emit("assistant:message",f),!hs&&(Le()!=="anchor-top"||Kg())&&Ud()&&(er+=1,qd(),on(),Yg(er===1?"1 new message below.":`${er} new messages below.`))),f.role==="assistant"&&h?.streaming&&f.streaming===!1&&m.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(h?f.approval.status!=="pending"&&m.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):m.emit("approval:requested",{approval:f.approval,message:f}))}),Vd.clear(),c.forEach((f,h)=>{Vd.set(h,f)})},ml=(i,c)=>{let f=c==="user"?"user":"assistant",h=o.layout?.messages?.[f],C=h?.width??"content",L=h?.maxWidth??(C==="full"?"100%":"85%");i.classList.add("persona-message-row"),i.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),i.classList.add(`persona-message-row-${c}`,`persona-message-width-${C}`),i.classList.toggle("persona-justify-end",c==="user"),i.setAttribute("data-message-role",c),i.setAttribute("data-message-width",C),i.style.setProperty("--persona-message-row-max-width",L)},Nr=(i,c)=>{let f=document.createElement("div");return f.className="persona-flex",f.id=`wrapper-${i}`,f.setAttribute("data-wrapper-id",i),ml(f,c),f},TC=(i,c,f)=>{let h=document.createElement("div"),L=(()=>{let U=a.find(Ne=>Ne.renderLoadingIndicator);if(U?.renderLoadingIndicator)return U.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),X=(U,Ne)=>Ne==null?!1:typeof Ne=="string"?(U.textContent=Ne,!0):(U.appendChild(Ne),!0),G=new Set,ie=new Map,ne=new Set,le=a.some(U=>U.renderAskUserQuestion),be=[],Ae=[],gt=o.enableComponentStreaming!==!1,Ht=o.approval!==!1,pn=[];if(c.forEach(U=>{G.add(U.id),ie.set(U.id,U.role);let Ne=le&&Kr(U),Ve=Ht&&U.variant==="approval"&&!!U.approval,Ie=!Ne&&U.role==="assistant"&&!U.variant&&gt&&_g(U);!Ve&&Jo.has(U.id)&&(i.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime"),Jo.delete(U.id)),!Ie&&Hr.has(U.id)&&(i.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime"),Hr.delete(U.id));let $t=Kr(U)?`:${U.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${U.agentMetadata?.askUserQuestionAnswers?Object.keys(U.agentMetadata.askUserQuestionAnswers).length:0}`:"",Mt=Xb(U,Fd)+$t,un=Ne||Ve||Ie?null:Jb(Fn,U.id,Mt);if(un){h.appendChild(un.cloneNode(!0)),Kr(U)&&U.toolCall?.id&&U.agentMetadata?.awaitingLocalTool===!0&&!U.agentMetadata?.askUserQuestionAnswered&&(ne.add(U.toolCall.id),nc(U,o,Y.composerOverlay));return}let St=null,An=a.find(je=>!!(U.variant==="reasoning"&&je.renderReasoning||U.variant==="tool"&&je.renderToolCall||!U.variant&&je.renderMessage)),gn=o.layout?.messages;if(Kr(U)&&U.agentMetadata?.askUserQuestionAnswered===!0){ms.delete(U.id),i.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime");return}if(ta(U)&&fr(o).enabled)return;if(Kr(U)&&o.features?.askUserQuestion?.enabled!==!1){let je=a.find(Mn=>typeof Mn.renderAskUserQuestion=="function");if(je&&wt.current){let Mn=ms.get(U.id),sn=Mn!==Mt,Re=null;if(sn){let{payload:at,complete:Xt}=Ds(U),jt=U.id,bn=()=>wt.current?.getMessages().find(to=>to.id===jt);Re=je.renderAskUserQuestion({message:U,payload:at,complete:Xt,resolve:to=>{let dt=bn();dt&&wt.current?.resolveAskUserQuestion(dt,to)},dismiss:()=>{let to=bn();to?.agentMetadata?.awaitingLocalTool&&(wt.current?.markAskUserQuestionResolved(to),wt.current?.resolveAskUserQuestion(to,"(dismissed)"))},config:o})}let Yt=Mn!=null;if(sn&&Re===null&&!Yt){U.agentMetadata?.awaitingLocalTool===!0&&!U.agentMetadata?.askUserQuestionAnswered&&(ne.add(U.toolCall.id),nc(U,o,Y.composerOverlay));return}let Tt=Nr(U.id,U.role);Tt.setAttribute("data-ask-plugin-stub","true"),Tt.setAttribute("data-preserve-runtime","true"),h.appendChild(Tt),be.push({messageId:U.id,fingerprint:Mt,bubble:Re});return}else{U.agentMetadata?.awaitingLocalTool===!0&&!U.agentMetadata?.askUserQuestionAnswered&&(ne.add(U.toolCall.id),nc(U,o,Y.composerOverlay));return}}else if(Ve){let je=a.find(Yt=>typeof Yt.renderApproval=="function")??g,sn=Jo.get(U.id)!==Mt,Re=null;if(sn&&je?.renderApproval){let Yt=U.id,Tt=(at,Xt)=>{let jt=wt.current?.getMessages().find(bn=>bn.id===Yt);jt?.approval&&(jt.approval.toolType==="webmcp"?wt.current?.resolveWebMcpApproval(jt.id,at):wt.current?.resolveApproval(jt.approval,at,Xt))};Re=je.renderApproval({message:U,defaultRenderer:()=>bd(U,o),config:o,approve:at=>Tt("approved",at),deny:at=>Tt("denied",at)})}if(sn&&Re===null)i.querySelector(`#wrapper-${U.id}`)?.removeAttribute("data-preserve-runtime"),Jo.delete(U.id),St=bd(U,o);else{let Yt=Nr(U.id,U.role);Yt.setAttribute("data-approval-plugin-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),h.appendChild(Yt),pn.push({messageId:U.id,fingerprint:Mt,bubble:Re});return}}else if(An)if(U.variant==="reasoning"&&U.reasoning&&An.renderReasoning){if(!Ce)return;St=An.renderReasoning({message:U,defaultRenderer:()=>ag(U,o),config:o})}else if(U.variant==="tool"&&U.toolCall&&An.renderToolCall){if(!Me)return;St=An.renderToolCall({message:U,defaultRenderer:()=>cg(U,o),config:o})}else An.renderMessage&&(St=An.renderMessage({message:U,defaultRenderer:()=>{let je=Ju(U,f,gn,o.messageActions,j,{loadingIndicatorRenderer:L,widgetConfig:o});return U.role!=="user"&&vg(je,U,o,z),je},config:o}));if(!St&&Ie){let je=Bw(U);if(je){let Mn=Hr.get(U.id),sn=Mn!==Mt,Re=o.wrapComponentDirectiveInBubble!==!1&&Ko.getOptions(je.component)?.bubbleChrome!==!1,Yt=null;if(sn){let Tt=Rw(je,{config:o,message:U,transform:f});if(Tt&&je.component==="PersonaArtifactInline"){let at=Tt.hasAttribute("data-artifact-inline")?Tt:Tt.querySelector("[data-artifact-inline]"),Xt=at?.getAttribute("data-artifact-inline")??"",jt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Xt):Xt,bn=Xt?i.querySelector(`#wrapper-${U.id}`)?.querySelector(`[data-artifact-inline="${jt}"]`)??null:null;at&&bn&&bn!==at&&jb(bn)&&(at===Tt?Tt=bn:at.replaceWith(bn))}if(Tt)if(Re){let at=document.createElement("div");if(at.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),at.id=`bubble-${U.id}`,at.setAttribute("data-message-id",U.id),U.content&&U.content.trim()){let Xt=document.createElement("div");Xt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Xt.innerHTML=f({text:U.content,message:U,streaming:!!U.streaming,raw:U.rawContent}),at.appendChild(Xt)}at.appendChild(Tt),Yt=at}else{let at=document.createElement("div");if(at.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",at.id=`bubble-${U.id}`,at.setAttribute("data-message-id",U.id),at.setAttribute("data-persona-component-directive","true"),U.content&&U.content.trim()){let Xt=document.createElement("div");Xt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Xt.innerHTML=f({text:U.content,message:U,streaming:!!U.streaming,raw:U.rawContent}),at.appendChild(Xt)}at.appendChild(Tt),Yt=at}}if(Yt||Mn!=null){let Tt=Nr(U.id,U.role);Tt.setAttribute("data-component-directive-stub","true"),Tt.setAttribute("data-preserve-runtime","true"),h.appendChild(Tt),Ae.push({messageId:U.id,fingerprint:Mt,bubble:Yt});return}}}if(!St)if(U.variant==="reasoning"&&U.reasoning){if(!Ce)return;St=ag(U,o)}else if(U.variant==="tool"&&U.toolCall){if(!Me)return;St=cg(U,o)}else if(U.variant==="approval"&&U.approval){if(o.approval===!1)return;St=bd(U,o)}else{let je=o.layout?.messages;je?.renderUserMessage&&U.role==="user"?St=je.renderUserMessage({message:U,config:o,streaming:!!U.streaming}):je?.renderAssistantMessage&&U.role==="assistant"?St=je.renderAssistantMessage({message:U,config:o,streaming:!!U.streaming}):St=Ju(U,f,je,o.messageActions,j,{loadingIndicatorRenderer:L,widgetConfig:o}),U.role!=="user"&&St&&vg(St,U,o,z)}let rn=Nr(U.id,U.role);rn.appendChild(St),Zb(Fn,U.id,Mt,rn),h.appendChild(rn)}),Y.composerOverlay&&Y.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Ne=>{let Ve=Ne.getAttribute("data-persona-ask-sheet-for");Ve&&!ne.has(Ve)&&Os(Y.composerOverlay,Ve)}),o.features?.toolCallDisplay?.grouped){let U=[],Ne=[],Ve=o.features.toolCallDisplay.groupedMode==="summary";c.forEach(Ie=>{if(Ie.variant==="tool"&&Ie.toolCall&&Me){Ne.push(Ie);return}Ie.variant==="reasoning"&&!Ce||((Ne.length>1||Ve&&Ne.length>0)&&U.push(Ne),Ne=[])}),(Ne.length>1||Ve&&Ne.length>0)&&U.push(Ne),U.forEach(Ie=>{let $t=Ie.map(je=>Array.from(h.children).find(Mn=>Mn instanceof HTMLElement&&Mn.getAttribute("data-wrapper-id")===je.id)).filter(je=>!!je);if($t.length<(Ve?1:2))return;let Mt=Nr(`tool-group-${Ie[0].id}`,"assistant");Mt.setAttribute("data-persona-tool-group-row","true");let un=document.createElement("div");un.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",un.setAttribute("data-persona-tool-group","true");let St=document.createElement("div");St.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",St.id=`tool-group-summary-${Ie[0].id}`;let An=`Called ${Ie.length} ${Ie.length===1?"tool":"tools"}`,gn=o.toolCall?.renderGroupedSummary?.({messages:Ie,toolCalls:Ie.map(je=>je.toolCall).filter(je=>!!je),defaultSummary:An,config:o});X(St,gn)||(St.textContent=An);let rn=document.createElement("div");rn.className="persona-tool-group-stack persona-flex persona-flex-col",rn.id=`tool-group-stack-${Ie[0].id}`,rn.setAttribute("data-persona-tool-group-stack","true"),un.appendChild(St),Ve||un.appendChild(rn),Mt.appendChild(un),$t[0].before(Mt),$t.forEach((je,Mn)=>{if(Ve){je.remove();return}je.style.setProperty("--persona-message-row-max-width","100%");let sn=document.createElement("div");sn.className="persona-tool-group-item persona-relative",sn.setAttribute("data-persona-tool-group-item","true"),Mn<$t.length-1&&sn.setAttribute("data-persona-tool-group-connector","true"),sn.appendChild(je),rn.appendChild(sn)})})}ev(Fn,G);let Bn=c.some(U=>U.role==="assistant"&&U.streaming),Ft=c[c.length-1],Vt=Ft?.role==="assistant"&&!Ft.streaming&&Ft.variant!=="approval";if(_n&&c.some(U=>U.role==="user")&&!Bn&&!Vt){let U={config:o,streaming:!0,location:"standalone",defaultRenderer:Da},Ne=a.find(Ie=>Ie.renderLoadingIndicator),Ve=null;if(Ne?.renderLoadingIndicator&&(Ve=Ne.renderLoadingIndicator(U)),Ve===null&&o.loadingIndicator?.render&&(Ve=o.loadingIndicator.render(U)),Ve===null&&(Ve=Da()),Ve){let Ie=document.createElement("div"),$t=o.loadingIndicator?.showBubble!==!1,Mt=o.layout?.messages?.layout??"bubble";Ie.className=$t?Na("assistant",Mt).join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-text"].join(" "),Ie.setAttribute("data-typing-indicator","true"),$t&&(Ie.style.color="var(--persona-message-assistant-text, var(--persona-text))",Mt!=="flat"&&(Ie.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-container))",Ie.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))")),Ie.appendChild(Ve);let un=Nr("typing-indicator","assistant");un.appendChild(Ie),h.appendChild(un)}}if(!_n&&c.length>0){let U=c[c.length-1],Ne={config:o,lastMessage:U,messageCount:c.length},Ve=a.find($t=>$t.renderIdleIndicator),Ie=null;if(Ve?.renderIdleIndicator&&(Ie=Ve.renderIdleIndicator(Ne)),Ie===null&&o.loadingIndicator?.renderIdle&&(Ie=o.loadingIndicator.renderIdle(Ne)),Ie){let $t=document.createElement("div"),Mt=o.loadingIndicator?.showBubble!==!1;$t.className=Mt?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),$t.setAttribute("data-idle-indicator","true"),$t.appendChild(Ie);let un=Nr("idle-indicator","assistant");un.appendChild($t),h.appendChild(un)}}if(vh(h),Qc(i,h),Gp(i),be.length>0)for(let{messageId:U,fingerprint:Ne,bubble:Ve}of be){let Ie=i.querySelector(`#wrapper-${U}`);Ie&&(ml(Ie,ie.get(U)??"assistant"),Ve!==null&&(Ie.replaceChildren(Ve),Ie.setAttribute("data-bubble-fp",Ne),ms.set(U,Ne)))}if(ms.size>0)for(let U of ms.keys())G.has(U)||ms.delete(U);if(Ae.length>0)for(let{messageId:U,fingerprint:Ne,bubble:Ve}of Ae){let Ie=i.querySelector(`#wrapper-${U}`);Ie&&(ml(Ie,ie.get(U)??"assistant"),Ve!==null&&(Ie.replaceChildren(Ve),Ie.setAttribute("data-bubble-fp",Ne),Hr.set(U,Ne)))}if(Hr.size>0)for(let U of Hr.keys())G.has(U)||Hr.delete(U);if(pn.length>0)for(let{messageId:U,fingerprint:Ne,bubble:Ve}of pn){let Ie=i.querySelector(`#wrapper-${U}`);Ie&&(ml(Ie,ie.get(U)??"assistant"),Ve!==null&&(Ie.replaceChildren(Ve),Ie.setAttribute("data-bubble-fp",Ne),Jo.set(U,Ne)))}if(Jo.size>0)for(let U of Jo.keys())G.has(U)||Jo.delete(U)},Si=(i,c,f)=>{TC(i,c,f),pf()},Ai=null,EC=()=>{if(Ai)return;let i=f=>{let h=f.composedPath();h.includes(R)||K&&h.includes(K)||xt(!1,"user")};Ai=i,(t.ownerDocument??document).addEventListener("pointerdown",i,!0)},Ff=()=>{if(!Ai)return;(t.ownerDocument??document).removeEventListener("pointerdown",Ai,!0),Ai=null};We.push(()=>Ff());let Mi=null,kC=()=>{if(Mi)return;let i=f=>{f.key==="Escape"&&(f.isComposing||xt(!1,"user"))};Mi=i,(t.ownerDocument??document).addEventListener("keydown",i,!0)},$f=()=>{if(!Mi)return;(t.ownerDocument??document).removeEventListener("keydown",Mi,!0),Mi=null};We.push(()=>$f());let Ti=!1,zf=new Set,PC=()=>{let i=o.launcher?.composerBar?.peek?.streamAnimation;return i||o.features?.streamAnimation},ws=()=>{if(!oe())return;let i=Y.peekBanner,c=Y.peekTextNode;if(!i||!c)return;if(M){i.classList.remove("persona-pill-peek--visible");return}let f=z?.getMessages()??[],h;for(let Ft=f.length-1;Ft>=0;Ft--){let Vt=f[Ft];if(Vt.role==="assistant"&&Vt.content){h=Vt;break}}if(!h){i.classList.remove("persona-pill-peek--visible");return}let C=h.content,L=!!h.streaming,X=PC(),G=td(X),ie=G.type!=="none"?Zs(G.type,X?.plugins):null,ne=ie?.isAnimating?.(h)===!0,le=ie!==null&&(L||ne);le&&ie&&!zf.has(ie.name)&&(rd(ie,t),zf.add(ie.name));let be=le&&ie?.containerClass?ie.containerClass:null,Ae=c.dataset.personaPeekStreamClass??null;Ae&&Ae!==be&&(c.classList.remove(Ae),delete c.dataset.personaPeekStreamClass),be&&Ae!==be&&(c.classList.add(be),c.dataset.personaPeekStreamClass=be),le?(c.style.setProperty("--persona-stream-step",`${G.speed}ms`),c.style.setProperty("--persona-stream-duration",`${G.duration}ms`)):(c.style.removeProperty("--persona-stream-step"),c.style.removeProperty("--persona-stream-duration"));let gt=le?nd(C,G.buffer,ie,h,L):C;if(le&&G.placeholder==="skeleton"&&L&&(!gt||!gt.trim())){let Ft=document.createElement("div"),Vt=Pa();Vt.classList.add("persona-pill-peek__skeleton"),Ft.appendChild(Vt),Qc(c,Ft)}else{let Ft=Math.max(0,gt.length-100),Vt=gt.length>100?gt.slice(-100):gt,U=cr(Vt);if(!le||!ie){let Ne=gt.length>100?`\u2026${Vt}`:Vt;c.textContent!==Ne&&(c.textContent=Ne)}else{let Ne=U;(ie.wrap==="char"||ie.wrap==="word")&&(Ne=ka(U,ie.wrap,`peek-${h.id}`,{skipTags:ie.skipTags,startIndex:Ft}));let Ve=document.createElement("div");if(Ve.innerHTML=Ne,ie.useCaret&&Vt.length>0){let Ie=od(),$t=Ve.querySelectorAll(".persona-stream-char, .persona-stream-word"),Mt=$t[$t.length-1];Mt?.parentNode?Mt.parentNode.insertBefore(Ie,Mt.nextSibling):Ve.appendChild(Ie)}Qc(c,Ve),ie.onAfterRender?.({container:c,bubble:i,messageId:h.id,message:h,speed:G.speed,duration:G.duration})}}let Bn=_n||Ti;i.classList.toggle("persona-pill-peek--visible",Bn)};if(oe()){let i=Y.peekBanner;if(i){let h=C=>{C.preventDefault(),C.stopPropagation(),xt(!0,"user")};i.addEventListener("pointerdown",h),We.push(()=>{i.removeEventListener("pointerdown",h)})}let c=()=>{Ti||(Ti=!0,ws())},f=()=>{Ti&&(Ti=!1,ws())};$.addEventListener("pointerenter",c),$.addEventListener("pointerleave",f),We.push(()=>{$.removeEventListener("pointerenter",c),$.removeEventListener("pointerleave",f)}),K&&(K.addEventListener("pointerenter",c),K.addEventListener("pointerleave",f),We.push(()=>{K.removeEventListener("pointerenter",c),K.removeEventListener("pointerleave",f)}))}let LC=i=>{let c=o.launcher?.composerBar??{},f=c.expandedSize??"anchored",h=c.bottomOffset??"16px",C=c.collapsedMaxWidth,L=c.expandedMaxWidth??"880px",X=c.expandedTopOffset??"5vh",G=c.modalMaxWidth??"880px",ie=c.modalMaxHeight??"min(90vh, 800px)",ne="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",be=R.style;if(be.left="",be.right="",be.top="",be.bottom="",be.transform="",be.width="",be.maxWidth="",be.height="",be.maxHeight="",K){let Ae=K.style;Ae.bottom=h,Ae.width=C??""}if(i&&f!=="fullscreen"){if(f==="modal"){be.top="50%",be.left="50%",be.transform="translate(-50%, -50%)",be.bottom="auto",be.right="auto",be.width=G,be.maxWidth=ne,be.maxHeight=ie,be.height=ie;return}be.left="50%",be.transform="translateX(-50%)",be.bottom=`calc(${h} + ${le})`,be.top=X,be.width=L,be.maxWidth=ne}},Ei=()=>{if(!ee())return;if(oe()){let ne=(o.launcher?.composerBar??{}).expandedSize??"anchored",le=M?"expanded":"collapsed";R.dataset.state=le,R.dataset.expandedSize=ne,K&&(K.dataset.state=le,K.dataset.expandedSize=ne),R.style.removeProperty("display"),R.classList.remove("persona-pointer-events-none","persona-opacity-0"),$.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),LC(M),Q.style.display=M?"flex":"none",Tr(),M?(EC(),kC()):(Ff(),$f()),ws();return}let i=Kt(o),c=t.ownerDocument.defaultView??window,f=o.launcher?.mobileBreakpoint??640,h=o.launcher?.mobileFullscreen??!0,C=c.innerWidth<=f,L=h&&C&&P,X=ro(o).reveal;M?(R.style.removeProperty("display"),R.style.display=i?"flex":"",R.classList.remove("persona-pointer-events-none","persona-opacity-0"),$.classList.remove("persona-scale-95","persona-opacity-0"),$.classList.add("persona-scale-100","persona-opacity-100"),Ot?(Ot.setPanelOpen(!0),Ot.element.style.display="none"):Sn&&(Sn.style.display="none")):(i?i&&(X==="overlay"||X==="push")&&!L?(R.style.removeProperty("display"),R.style.display="flex",R.classList.remove("persona-pointer-events-none","persona-opacity-0"),$.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(R.style.setProperty("display","none","important"),R.classList.remove("persona-pointer-events-none","persona-opacity-0"),$.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(R.style.display="",R.classList.add("persona-pointer-events-none","persona-opacity-0"),$.classList.remove("persona-scale-100","persona-opacity-100"),$.classList.add("persona-scale-95","persona-opacity-0")),Ot?(Ot.setPanelOpen(!1),Ot.element.style.display=i?"none":""):Sn&&(Sn.style.display=i?"none":""))},xt=(i,c="user")=>{if(!ee()||M===i)return;let f=M;M=i,Ei();let h=(()=>{let L=o.launcher?.sidebarMode??!1,X=t.ownerDocument.defaultView??window,G=o.launcher?.mobileFullscreen??!0,ie=o.launcher?.mobileBreakpoint??640,ne=X.innerWidth<=ie,le=Kt(o)&&G&&ne,be=oe()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return L||G&&ne&&P||le||be})();if(M&&h){if(!ho){let L=t.getRootNode(),X=L instanceof ShadowRoot?L.host:t.closest(".persona-host");X&&(ho=ju(X,o.launcher?.zIndex??mn))}yo||(yo=qu(t.ownerDocument))}else M||(ho?.(),ho=null,yo?.(),yo=null);M&&(qi(),Gd()||(Le()==="follow"?tr(!0):pl()));let C={open:M,source:c,timestamp:Date.now()};M&&!f?m.emit("widget:opened",C):!M&&f&&m.emit("widget:closed",C),m.emit("widget:state",{open:M,launcherEnabled:P,voiceActive:rt.active,streaming:z.isStreaming()})},ki=i=>{Sr(i?"stop":"send"),de&&(de.disabled=i),Pr.forEach(c=>{c.elements.forEach(f=>{f.toggleAttribute("data-disabled",i),f instanceof HTMLButtonElement||f.setAttribute("aria-disabled",i?"true":"false")}),c.buttons.forEach(f=>{f.disabled=i})}),Zd.forEach(c=>{c.toggleAttribute("data-disabled",i),c instanceof HTMLButtonElement?c.disabled=i:c.setAttribute("aria-disabled",i?"true":"false"),c.querySelectorAll("button").forEach(f=>{f.disabled=i})}),Je.dataset.personaComposerStreaming=i?"true":"false",Je.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(c=>{(c instanceof HTMLButtonElement||c instanceof HTMLInputElement||c instanceof HTMLTextAreaElement||c instanceof HTMLSelectElement)&&(c.disabled=i)})},Or=()=>{rt.active||ye&&ye.focus()};m.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>Or(),200)});let _r=null,Pi=!1,Xd=!ln.hidden,nr=null,Vf=!W,jf=null,qf,Uf=null,Cs=null,Qd=!1,Li=i=>{let c=ts(o),f=`${c.variant}|${c.dismiss}|${c.title}|${c.subtitle}`;(f!==jf||c.icon!==qf)&&(jf=f,qf=c.icon,md({host:ln,iconHolder:pi,title:ls,subtitle:Xa,starterSuggestions:et},c));let h=c.message===void 0?null:`${o.layout?.messages?.layout??"bubble"}|${c.message}`;h!==Uf&&(Uf=h,hd(cn,c.message,o));let C=i??(z?z.getMessages():o.initialMessages),L=Pi,X=!L&&oi(c,C),G=X!==Xd;if(Xd=X,Cs){nr?.cancel(),nr=null,L!==Qd&&(Qd=L,L?tg(Z,ln,null):eg(Z,ln,Cs)),ni(Z,ln,!L);return}if(G&&!X&&!L&&c.dismiss==="on-first-message"&&Vf){nr=bv(ln,ne=>{nr===ne&&(nr=null),!Xd&&!Cs&&(ni(Z,ln,!1),Bo()),ne?.cancel()});return}if(nr){if(!X&&!L)return;nr.cancel(),nr=null}let ie=!ln.hidden;ni(Z,ln,X),!X&&ie&&Bo()},Jd=[],Zd=[],ep=!1,Kf=null,Gf,Yf=()=>{Zd.length=0;let i=Jd.splice(0,Jd.length);for(let c of i)try{c()}catch(f){console.warn("[persona] renderWelcome cleanup threw",f)}};We.push(Yf);let IC=(i,c)=>{let f=Ku(i,c);if(!f)return o.debug===!0&&console.warn("[persona] renderStarter received a suggestion with no label"),v("span");let h=o.suggestions?.starters,C=Gu({item:{...f,behavior:f.behavior??h?.behavior??"send"},index:c,surface:"starter",source:"config",variant:h?.variant??"card",streaming:p?z.isStreaming():!1,config:o,plugins:a,chipsConfig:o.suggestionChipsConfig,session:z,getTextarea:()=>ye,eventTarget:ln});return Zd.push(C),C},tp=()=>{if(ep)return;ep=!0;let i=ts(o);Kf=`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`,Gf=i.icon;try{Yf(),tg(Z,ln,Cs),Cs=null,Qd=!1;let c=z?z.getMessages():o.initialMessages,f=oi(i,c),h=0,C=null;for(let L of a)if(L.renderWelcome&&(C=L.renderWelcome({config:i,variant:i.variant,visible:f,defaultRenderer:()=>ln,sendMessage:X=>{if(!z||z.isStreaming())return;let G=X.trim();G&&z.sendMessage(G)},requestRender:()=>tp(),renderStarter:X=>IC(X,h++),storage:u(L.id),onCleanup:X=>{Jd.push(X)}}),C))break;C&&C!==ln&&(Cs=C,eg(Z,ln,C))}finally{ep=!1}Li()},HC=()=>{let i=ts(o);`${i.variant}|${i.dismiss}|${i.title}|${i.subtitle}|${i.message??""}`===Kf&&i.icon===Gf||tp()},np=()=>{Li(),mi||(ye.placeholder=o.copy?.inputPlaceholder??"How can I help...",!(o.sendButton?.useIcon??!1)&&!z?.isStreaming()&&(we.textContent=o.copy?.sendButtonLabel??"Send")),ye.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ye.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"},RC=!!o.setStoredConversationId,Ii=i=>I(c=>{let f={...c};return delete f[i],f}),hl=i=>{let c=T[i];return typeof c=="string"?c:null};o.clientToken&&(o={...o,getStoredSessionId:()=>hl("sessionId"),setStoredSessionId:i=>{I(c=>({...c,sessionId:i}))},clearStoredSessionId:o.clearStoredSessionId??(()=>Ii("sessionId")),getStoredConversationId:o.getStoredConversationId??(()=>hl("conversationId")),setStoredConversationId:o.setStoredConversationId??(i=>{I(c=>({...c,conversationId:i}))}),clearStoredConversationId:o.clearStoredConversationId??(()=>Ii("conversationId"))});let Xf=()=>o.features?.history?.enabled===!0?o.clientToken??null:null,Qf=i=>dw(i,qe(),o.persistState===!1),Jf=Xf(),Do=Jf?Qf(Jf):null,Fr={...Do?{visitorStore:Do}:{},historyBootstrapReady:k,getStoredMessageCursor:()=>hl("historyMessageCursor"),setStoredMessageCursor:i=>{if(i===null){Ii("historyMessageCursor");return}I(c=>({...c,historyMessageCursor:i}))},getPendingDisplayProjections:()=>{let i=T.pendingDisplayProjections;if(!i||typeof i!="object")return null;let c=i;return typeof c.conversationId!="string"||!Array.isArray(c.messageIds)?null:{conversationId:c.conversationId,messageIds:c.messageIds.filter(f=>typeof f=="string")}},setPendingDisplayProjections:i=>{if(!i){Ii("pendingDisplayProjections");return}I(c=>({...c,pendingDisplayProjections:i}))},...RC?{}:{getStoredConversationRevision:()=>hl("conversationRevision"),setStoredConversationRevision:i=>{if(i===null){Ii("conversationRevision");return}I(c=>({...c,conversationRevision:i}))}}},WC=()=>{let i=Xf();if(i&&Do?.matches(i,qe(),o.persistState===!1)||!i&&!Do)return;Do?.destroy(),Do=i?Qf(i):null;let c={...Fr};Do?c.visitorStore=Do:delete c.visitorStore,Fr=c,z.setHistoryInternals(Fr)},$r=null,BC=()=>{$r==null&&($r=setInterval(()=>{let i=ue.querySelectorAll("[data-tool-elapsed]");if(i.length===0){clearInterval($r),$r=null;return}let c=Date.now();i.forEach(f=>{let h=Number(f.getAttribute("data-tool-elapsed"));h&&(f.textContent=sc(c-h))})},100))},op=(i,c)=>{if(Object.is(i,c))return!0;if(i===null||c===null||typeof i!="object"||typeof c!="object")return!1;if(Array.isArray(i)||Array.isArray(c))return!Array.isArray(i)||!Array.isArray(c)||i.length!==c.length?!1:i.every((X,G)=>op(X,c[G]));let f=i,h=c,C=Object.keys(f),L=Object.keys(h);return C.length===L.length&&C.every(X=>Object.prototype.hasOwnProperty.call(h,X)&&op(f[X],h[X]))},Zf=i=>{let{content:c,rawContent:f,llmContent:h,...C}=i;return C},rp=i=>i.role==="assistant"&&i.streaming===!0&&!i.variant&&!i.toolCall&&!i.tools&&!i.approval&&!i.reasoning&&!i.contentParts&&!i.stopReason&&!_g(i),DC=(i,c,f)=>{if(i.length!==c.length)return!1;let h=i[f.index],C=c[f.index];return!h||!C||h.id!==f.id||C.id!==f.id?!1:(!Object.is(h.content,C.content)||!Object.is(h.rawContent,C.rawContent)||!Object.is(h.llmContent,C.llmContent))&&rp(h)&&rp(C)&&op(Zf(h),Zf(C))},sp=null,xs=null,zr=null,No=null,yl=i=>{sp=i;let c,f;xs=null;for(let C=i.length-1;C>=0;C-=1){let L=i[C];if(!c&&L.role==="user"&&(c=L),!f&&L.role==="assistant"&&(f=L),!xs&&rp(L)&&(xs={index:C,id:L.id}),c&&f&&xs)break}Si(ue,i,xe),Du(ue,lo.artifacts,{suppressTransition:_n}),BC(),Li(i),fs(i),tr(!_n),MC(i),i.length===0&&(uo(),Ci=!0,al=!1,ys=null,ll=!1),!$d||hs?($d=!0,Wr=c?.id??null,zd=f?.id??null):c&&c.id!==Wr?(Wr=c.id,wC(c.id)):f&&f.id!==zd&&CC(),f&&(zd=f.id),AC(i);let h=rt.lastUserMessageId;c&&c.id!==h&&(rt.lastUserMessageId=c.id,m.emit("user:message",c)),rt.lastUserMessageWasVoice=!!c?.viaVoice,jd(i),ws()},ip=()=>{No!==null&&(cancelAnimationFrame(No),No=null);let i=zr;zr=null,i&&yl(i)},em=()=>{No!==null&&cancelAnimationFrame(No),No=null,zr=null},NC=i=>{let c=zr??sp;if(_n&&c&&xs&&DC(c,i,xs)){zr=i,No===null&&(No=requestAnimationFrame(()=>{No=null;let f=zr;zr=null,f&&yl(f)}));return}if(i.length===0){em(),yl(i);return}ip(),yl(i)};z=new hc(o,{onMessagesChanged(i){NC(i)},onStatusChanged(i){let c=o.statusIndicator??{};S(Bt,(h=>h==="idle"?c.idleText??Zt.idle:h==="connecting"?c.connectingText??Zt.connecting:h==="connected"?c.connectedText??Zt.connected:h==="error"?c.errorText??Zt.error:h==="paused"?c.pausedText??Zt.paused:h==="resuming"?c.resumingText??Zt.resuming:Zt[h])(i),c,i),Ln()},onStreamingChanged(i){i||(z?.getMessages().length===0?em():ip()),_n=i,ki(i),Ln(),z&&Si(ue,z.getMessages(),xe),i||(tr(!0),bC(),kf=!0,z&&Pf(z.getMessages(),fr(o))),on(),Yg(i?"Responding\u2026":"Response complete."),ws()},onVoiceStatusChanged(i){if(m.emit("voice:status",{status:i,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(i){case"listening":$o(),Ps();break;case"processing":$o(),Px();break;case"speaking":$o(),Lx();break;default:i==="idle"&&z.isBargeInActive()?($o(),Ps(),de?.setAttribute("aria-label","End voice session")):(rt.active=!1,$o(),Wo("system"),po());break}},onArtifactsState(i){lo=i,i.artifacts.length===0&&(ps=!1),Du(ue,i.artifacts,{suppressTransition:_n}),Lo(),jd()},onHistoryStateChanged(i){wn(i)},onHistoryNotice(i){Ct(i)},onReconnect(i){let{executionId:c,lastEventId:f}=i.handle;i.phase==="paused"?m.emit("stream:paused",{executionId:c,after:f}):i.phase==="resuming"?m.emit("stream:resuming",{executionId:c,after:f,attempt:i.attempt??1}):m.emit("stream:resumed",{executionId:c,after:f})}},Fr),wt.current=z,We.push(()=>z.cancel()),We.push(()=>{z.destroy(),Do?.destroy()});let ap=null;if(z.onReadAloudChange((i,c)=>{cf=i,df=c,pf();let f=i??ap;i&&(ap=i);let h=f?z.getMessages().find(C=>C.id===f)??null:null;m.emit("message:read-aloud",{messageId:f,message:h,state:c,timestamp:Date.now()}),c==="idle"&&(ap=null)}),p=!0,$d=!0,o.voiceRecognition?.provider?.type==="runtype")try{z.setupVoice()}catch(i){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",i)}let OC=720,_C=250,it=Mg(o.features?.history?.copy),Vn=null,lp=!1,ht=null,bl=null,vl="conversation",cp=null,xn=null,bo=null,wl=z.getHistoryState(),dp=null,Cl=0,pp=null,xl=null,Sl=null,up=`persona-history-${Math.random().toString(36).slice(2,8)}`,gp=()=>o.features?.history?.enabled===!0,vo=()=>gp()&&!!Vn&&!lp,tm=()=>{let i=z.getStatus();return _n||i==="paused"||i==="resuming"},fp=()=>{let i=o.features?.history?.scope;if(i)return i;let c=o.getIdentityProof?"verified-user":"browser",f=Vn?.capabilities.scopes;return!f||f.includes(c)?c:f[0]??c},Ss=()=>bl?.scope??fp(),nm=()=>z.getClientSession()?.targetId??null,om=i=>`${i.state}:${"reason"in i?i.reason:""}`,FC=i=>{let c=om(i);c!==dp&&(dp=c,m.emit("history:identityStatusChanged",{status:i,timestamp:Date.now()}))},Al=i=>{i&&(ko.textContent="",ko.textContent=i)},rm=null,sm=null,$C=()=>{if(!gp())return null;let i=Iw();if(i)return i();let c=o.features?.history?.provider;return c?typeof c!="function"?c:(rm!==c&&(rm=c,sm=c()),sm):z.isClientTokenMode()?Hw({client:z.getClient(),getIdentityProofConfigured:()=>typeof o.getIdentityProof=="function",onActivationCommitted:f=>z.bindActivatedSession(f),getClient:()=>z.getClient()}):null},im=()=>{xl?.(),xl=null,Sl?.(),Sl=null,lp=!1,Vn=$C();let i={...Fr};Vn?i.historyProvider=Vn:delete i.historyProvider,Fr=i,z.setHistoryInternals(Fr),Vn&&(xl=Vn.subscribeAvailability?.(c=>{lp=!c,c||Wn({restoreFocus:!1}),rr()})??null,Sl=Vn.subscribeIdentityStatus(c=>FC(c)),dp=om(Vn.getIdentityStatus()))},mp=()=>{let i=o.features?.history?.presentation??"panel";if(i==="panel"||i==="auto"&&!(!P||Kt(o)))return"panel";let c=mo??Q;return(c.getBoundingClientRect().width||c.clientWidth)>=OC?"rail":"panel"},Xn=(i,c)=>{c?(i.setAttribute("aria-hidden","true"),i.setAttribute("inert","")):(i.removeAttribute("aria-hidden"),i.removeAttribute("inert"))},Ml="data-persona-history-suppressed",jn=null,or=null,Vr=null,Hi=null,hp=null,am="",lm=()=>Pe===hp?am:o.layout?.showHeader===!1?"none":"",zC=()=>ot==="panel"&&!!Vr&&Hi===Vr.element&&o.layout?.showHeader!==!1&&lm()!=="none",VC=()=>{for(let i of Array.from(Pe.children))i!==jn&&i.setAttribute(Ml,"")},jC=()=>{for(let i of Array.from(Q.querySelectorAll(`[${Ml}]`)))i.removeAttribute(Ml)},qC=()=>{let i=Vr;if(!i)return;if(Array.from(Pe.children).some(h=>h!==jn&&!h.hasAttribute(Ml))){or&&or!==Pe&&(or.style.removeProperty("min-height"),or=null);let h=Pe.offsetHeight;h>0&&(Pe.style.minHeight=`${h}px`,or=Pe)}jn||(jn=v("div","persona-history-header-host")),i.setHeaderPlacement("external");let f=i.getHeaderElement();f.parentNode!==jn&&jn.replaceChildren(f),jn.parentNode!==Pe&&Pe.appendChild(jn),VC()},cm=()=>{or&&(or.style.removeProperty("min-height"),or=null),jn&&(Vr?.setHeaderPlacement("inline"),jn.remove(),jn=null,jC())},Tl=null,yp=()=>{if(Tl){if(Z.style.display="none",Xn(Z,!0),Je.hidden=!0,Xn(Je,!0),zC()){qC(),Pe.style.display=lm(),Xn(Pe,!1);return}cm(),Pe.style.display="none",Xn(Pe,!0)}};lt=yp;let UC=i=>{let c=Z.style.display,f=Je.hidden,h=Je,C=Pe,L=Pe.style.display;hp=C,am=L,Tl=()=>{Tl=null,cm(),hp=null,Z.style.display=c,Xn(Z,!1),h.hidden=f,Xn(h,!1),Je!==h&&(Je.hidden=!1,Xn(Je,!1)),C.style.display=L,Xn(C,!1),Pe!==C&&(Pe.style.display=o.layout?.showHeader===!1?"none":"",Xn(Pe,!1))},Je.parentNode?.insertBefore(i,Je),yp()},Ri=null,As=null,Wi=null,dm=()=>[Pe,Y.closeButtonWrapper,Y.clearChatButtonWrapper,Z,Je],KC=52,El=()=>o.features?.history?.rail?.collapsible!==!1,Ms=()=>o.features?.history?.rail?.side==="right"?"right":"left",bp=200,vp=400,wp=i=>Math.min(vp,Math.max(bp,Math.round(i))),GC=()=>o.features?.history?.rail?.resizable===!0,Bi,YC=()=>{if(Bi===void 0&&(Bi=null,o.persistState!==!1))try{let i=Number(window.localStorage.getItem(`${qe()}rail-width`));i&&(Bi=i)}catch{}return Bi},Di=()=>wp(YC()??o.features?.history?.rail?.width??260),XC=i=>{if(Bi=i,o.persistState!==!1)try{window.localStorage.setItem(`${qe()}rail-width`,String(i))}catch{}},kl=()=>El()&&o.features?.history?.rail?.collapsedBehavior==="overlay",dn=!1,pm=i=>{let c=v("img");return c.src=i,c.alt="",c.setAttribute("aria-hidden","true"),c},QC=()=>{let i=o.features?.history?.rail?.brand;if(!i)return;let c=!1,f;return h=>{if(i.render)try{return i.render({collapsed:h})??null}catch(C){return c||(c=!0,console.warn("[persona] history rail brand threw",C)),null}return f===void 0&&(i.iconUrl?f=pm(i.iconUrl):f=i.icon?fe(i.icon,20):null),f?f.cloneNode(!0):null}},JC=()=>o.features?.history?.rail?.sections?.map(i=>{let c=!1,f=h=>{c||(c=!0,console.warn("[persona] history rail section threw",i.id,h))};return{id:i.id,title:i.title,placement:i.placement??"above-conversations",items:i.items.map(h=>{let C;return{id:h.id,label:h.label,badge:h.badge,iconNode:()=>{if(C!==void 0)return C;try{h.renderIcon?C=h.renderIcon()??null:h.iconUrl?C=pm(h.iconUrl):C=h.icon?fe(h.icon,20):null}catch(L){f(L),C=null}return C},onSelect:()=>{try{h.onSelect()}catch(L){f(L)}}}})}})??[],ZC=i=>{let c=JC();for(let f of i)c.some(h=>h.id===f.id)?console.warn("[persona] duplicate history rail section id",f.id):c.push(f);return c.length?c:void 0},Ni=null,um=()=>`${qe()}rail-collapsed`,Cp=()=>{if(Ni===null&&(Ni=o.features?.history?.rail?.defaultCollapsed===!0,o.persistState!==!1))try{let i=window.localStorage.getItem(um());i&&(Ni=i==="1")}catch{}return Ni},xp=i=>{if(Ni=i,o.persistState!==!1)try{window.localStorage.setItem(um(),i?"1":"0")}catch{}},Oi=()=>ot==="rail"&&El()&&!kl()&&Cp(),Sp=()=>{},gm=()=>{if(kl()){Sp();return}xp(!Cp()),ht?.view.setCollapsed(Oi()),kt(),Bo()},Ap=()=>{let i=o.features?.history?.rail?.collapseShortcut;return!i||!Fc(i)?null:{combo:i,hint:$c(i),aria:xa(i)}},fm=()=>{d.forEach(c=>c()),d=[];let i=Ap();i&&d.push(l.register({id:"history-rail-collapse",combo:i.combo,scope:o.features?.history?.rail?.collapseShortcutScope==="page"?"page":"widget",when:()=>Te&&ot==="rail"&&El()||_i(),run:()=>kl()?Sp():gm()}));for(let c of o.layout?.header?.trailingActions??[])c.shortcut&&d.push(l.register({id:`header-action-${c.id}`,combo:c.shortcut,run:()=>{let f=t.querySelector(`[data-persona-header-action="${c.id}"]`);f?f.click():o.layout?.header?.onAction?.(c.id)}}));for(let c of a)for(let f of c.shortcuts??[])d.push(l.register({...f,id:`${c.id}:${f.id}`}))};fm();let ex=300,Pl="var(--persona-history-overlay-margin,8px)",Qn=null,Oo=null,_o=null,Ts=null,jr=!1,Mp=0,mm=()=>window.matchMedia?.("(pointer: coarse)").matches===!0,_i=()=>vo()&&kl()&&(ot??mp())==="rail",tx=()=>Te&&!dn,Fi=()=>{Ts!==null&&clearTimeout(Ts),Ts=null},nx=()=>{Bg().catch(()=>{})},hm=()=>{Fi(),dn&&(Ts=setTimeout(()=>{Ts=null,!(jr||!dn)&&(_o?.contains(document.activeElement)||Wn({restoreFocus:!1}))},ex))},ox=(i,c)=>{let f=_o?.getBoundingClientRect();if(!f)return!1;let h=Qn?.getBoundingClientRect(),C=h?Math.min(h.top,f.top):f.top;return i>=f.left&&i<=f.right&&c>=C&&c<=f.bottom||!!h&&i>=h.left&&i<=h.right&&c>=h.top&&c<=h.bottom},Tp=i=>{dn&&(jr=ox(i.clientX,i.clientY),jr?Fi():Ts===null&&hm())},ym=i=>{Te||!_i()||(dn=!0,$i({invoker:Qn,keyboard:i?.keyboard===!0}).then(()=>{Te?!jr&&document.activeElement!==Qn&&Wn():dn=!1}))},bm=()=>{let i=Hi?.querySelector('[data-persona-history-focus="collapse"]');i&&(i.setAttribute("aria-label",dn?it.expandLabel:it.collapseLabel),i.setAttribute("aria-expanded",dn?"false":"true"))},vm=()=>{xp(!1);let i=ht;if(!dn||!i){$i({invoker:Qn});return}let c=document.activeElement===Qn;dn=!1,Pp(),i.element.remove(),Lp(i.element),bm(),c&&Il(),Bo(),rr()},rx=()=>{xp(!0),Wn()};Sp=()=>{!Te||dn?vm():rx()};let sx=()=>{let i=Ap(),c=Zr({ariaLabel:it.expandLabel,iconName:"panel-left",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-rail-trigger",tooltip:!1,attrs:{"data-persona-rail-trigger":"","aria-controls":up,...i?{"aria-keyshortcuts":i.aria}:{}}}),f=c.button;f.addEventListener("mouseenter",()=>{jr=!0,Fi(),!(mm()||Date.now()<Mp)&&ym()}),f.addEventListener("mouseleave",()=>{jr=!1,Mp=0,hm()}),f.addEventListener("focus",()=>{Te||nx()}),f.addEventListener("click",h=>{vo()&&(h.detail!==0&&mm()&&!Te?ym():vm())}),Qn=f,Oo=c.wrapper},Ep=()=>{if(Oo&&!Oo.isConnected&&(Oo=null,Qn=null),!_i()){Oo?.remove(),Oo=null,Qn=null;return}Qn||sx();let i=Oo,c=Qn;if(!i||!c)return;let f=Ms()!=="right"?Pe.firstChild:null;(f??Pe.lastChild)!==i&&Pe.insertBefore(i,f),i.style.display=tx()?"none":"",c.setAttribute("aria-label",it.expandLabel),c.setAttribute("aria-expanded",Te?"true":"false"),_o&&kt()},wm=i=>{if(!dn)return;let c=i.target;c instanceof Node&&(_o?.contains(c)||Oo?.contains(c)||c instanceof Element&&c.closest('.persona-dropdown-menu,[role="alertdialog"]')||Wn({restoreFocus:!1}))};document.addEventListener("pointerdown",wm,!0),We.push(()=>{document.removeEventListener("pointerdown",wm,!0),document.removeEventListener("pointermove",Tp),Es?.(),Fi()});let kp=null,Es=null,Cm=16,xm=i=>{XC(wp(i)),kt(),Bo()},ix=()=>{let i=v("div","persona-rail-resizer");return i.tabIndex=0,i.setAttribute("role","separator"),i.setAttribute("aria-orientation","vertical"),i.setAttribute("aria-valuemin",String(bp)),i.setAttribute("aria-valuemax",String(vp)),i.addEventListener("pointerdown",c=>{let f=As;if(!f||c.button!==0)return;c.preventDefault(),Es?.();let h=c.clientX,C=f.getBoundingClientRect().width||Di(),L=Ms()==="right"?-1:1,X=C,G=t.ownerDocument;f.style.transition="none";let ie=le=>{X=wp(C+L*(le.clientX-h)),f.style.flex=`0 0 ${X}px`,i.setAttribute("aria-valuenow",String(X))},ne=()=>{Es=null,G.removeEventListener("pointermove",ie),G.removeEventListener("pointerup",ne),G.removeEventListener("pointercancel",ne),f.style.removeProperty("transition");try{i.releasePointerCapture(c.pointerId)}catch{}xm(X)};Es=ne,G.addEventListener("pointermove",ie),G.addEventListener("pointerup",ne),G.addEventListener("pointercancel",ne);try{i.setPointerCapture(c.pointerId)}catch{}}),i.addEventListener("keydown",c=>{let f=Ms()==="right"?-Cm:Cm,h=Di(),C=c.key==="ArrowRight"?h+f:c.key==="ArrowLeft"?h-f:c.key==="Home"?bp:c.key==="End"?vp:null;C!==null&&(c.preventDefault(),xm(C))}),i},ax=(i,c)=>{if(!GC()||Oi()){Es?.(),kp?.remove();return}let f=kp??ix();kp=f,f.setAttribute("aria-label",it.resizeLabel),f.setAttribute("aria-valuenow",String(Di())),f.nextElementSibling!==c&&i.insertBefore(f,c)};kt=()=>{ht?.view.setRailSide(Ms());let i=Ms()==="right",c=_o;if(c){let G=Qn?Qn.getBoundingClientRect().bottom-Q.getBoundingClientRect().top:0;c.style.top=`calc(${Math.max(0,Math.round(G))}px + ${Pl})`,c.style.width=`${Di()}px`,c.style.left=i?"":Pl,c.style.right=i?Pl:""}let f=As,h=Ri,C=Wi;if(!f||!h||!C)return;f.style.flex=`0 0 ${Oi()?KC:Di()}px`;let L="1px solid var(--persona-divider,#e5e7eb)";f.style.borderRight=i?"":L,f.style.borderLeft=i?L:"";let X=i?C:f;h.firstElementChild!==X&&h.append(X,i?f:C),ax(h,i?f:C)};let lx=i=>{let c=v("div","persona-history-rail-shell");c.style.cssText="display:flex;flex-direction:row;flex:1 1 auto;min-height:0";let f=v("div","persona-history-rail-conversation");f.style.cssText="display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";let h=v("div","persona-history-rail-host");h.style.cssText="display:flex;min-height:0;overflow:hidden",Q.insertBefore(c,Pe.parentNode===Q?Pe:Z);for(let C of dm())C?.parentNode===Q&&f.appendChild(C);c.append(h,f),h.appendChild(i),Ri=c,As=h,Wi=f,kt()},cx=i=>{let c=v("div","persona-history-rail-overlay");c.style.cssText=`position:absolute;bottom:${Pl};display:flex;overflow:hidden;z-index:${Us-1};border-radius:var(--persona-history-overlay-radius,16px);background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))`,Q.style.position="relative",Q.appendChild(c),c.appendChild(i),document.addEventListener("pointermove",Tp),_o=c,kt(),bm()},Pp=()=>{Tl?.(),_o&&(jr&&(Mp=Date.now()+150),document.removeEventListener("pointermove",Tp),_o.remove(),_o=null);let i=Ri;if(i){Es?.();for(let c of dm())c&&i.contains(c)&&Q.insertBefore(c,i);i.remove(),Ri=null,As=null,Wi=null}},Sm=i=>{Hi=i,i.id=up,i.style.flex="1 1 auto",i.style.minHeight="0"},Lp=i=>{Sm(i),ot!=="rail"?UC(i):dn?cx(i):lx(i)},Ll=()=>{if(Ep(),Wm(),!Te||!ht)return;let i=mp();if(i===ot)return;let c=document.activeElement,f=c instanceof HTMLElement&&(ht.element.contains(c)||jn?.contains(c)===!0)?c:null;Pp(),ht.element.remove(),ht.view.setHeaderPlacement("inline"),ot=i,ht.view.setPresentation(i),ht.view.setCollapsed(Oi()),ht.requestRender(),ht.element.isConnected||Lp(ht.element),f?.isConnected?f.focus():Il(),on(),Bo(),rr()},Am=(i,c)=>jn?.querySelector(c)??i.querySelector(c),Il=()=>{let i=ht?.element??Hi;if(!i)return;let c=Am(i,'[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]');if(c){c.focus();return}let f=Am(i,".persona-history-title")??i;f.tabIndex=-1,f.focus()},$i=async i=>{if(!vo()||Te)return;let c=Vn;if(!c)return;if(!dn&&_i()&&Cp()){Ep();return}Hl();let f=++Cl;vl=i?.returnSurface??"conversation",cp=i?.invoker??xn;let h;try{h=await Bg()}catch{Al(it.openHistoryLabel);return}if(f!==Cl||Te)return;bl={scope:fp()},ot=mp(),Te=!0;let C=ot==="panel"&&o.layout?.showHeader!==!1&&Pe.style.display!=="none"?"external":"inline",L=o.features?.history?.rowAvatar,X=Ap(),G=X?{hint:X.hint,aria:X.aria}:null,ie={provider:c,context:bl,targetId:nm(),presentation:ot,collapsible:El(),collapsed:Oi(),railSide:Ms(),renderRailHeader:o.features?.history?.rail?.renderHeader,railBrand:QC(),onToggleCollapse:gm,...G?{collapseShortcut:G}:{},headerPlacement:C,showScopeStatus:o.features?.history?.showScopeStatus!==!1,showDelete:o.features?.history?.showDelete!==!1,showDeleteAll:o.features?.history?.showDeleteAll!==!1,...o.features?.history?.listActions?.length?{listActions:o.features.history.listActions}:{},rowAvatar:L===!1?!1:typeof L=="string"?L:o.launcher?.iconUrl,activeConversationId:z.getActiveConversationId(),...o.features?.history?.grouping?{grouping:o.features.history.grouping}:{},...o.features?.history?.copy?{copy:o.features.history.copy}:{},...o.features?.history?.pageSize!==void 0?{pageSize:o.features.history.pageSize}:{},onSelect:ne=>Hp(ne,{focusComposer:!0}).catch(()=>{}),onActiveConversationChange:ne=>qr(ne),attachTooltip:hn,onStartNew:()=>Rp({focusComposer:!0}),onClose:()=>Wn(),onRequestDeleteConversation:ne=>Rm(ne),onRequestClearHistory:()=>mx(),...c.resetDevice?{onRequestResetIdentity:()=>hx()}:{}};ht=Lw({plugins:a,config:o,getPresentation:()=>ot??"panel",getReturnSurface:()=>vl,close:()=>Wn(),createView:({slots:ne,renderDom:le,onModelChange:be,railSections:Ae})=>(Vr=h.createHistoryView({...ie,railSections:ZC(Ae),slots:ne,renderDom:le,onModelChange:be,onAnnounce:Al}),Vr),onElementChanged:(ne,le)=>{if(!le?.isConnected)return Lp(ne);Sm(ne),le.replaceWith(ne),yp()}}),ht.view.setNewConversationRequired(wl.recovery==="new_conversation_required"),i?.focus!==!1&&(ot!=="rail"||i?.keyboard===!0)&&Il(),on(),Bo(),rr(),m.emit("history:opened",{presentation:ot,returnSurface:vl,timestamp:Date.now()})},Hl=()=>{},Wn=i=>{if(!Te)return;Cl+=1;let c=vl,f=cp,h=ht,C=i?.restoreFocus!==!1;Te=!1;let L=!1,X=null,G=()=>{if(!L){if(L=!0,Hl=()=>{},X!==null&&clearTimeout(X),dn=!1,Fi(),Pp(),h?.dispose(),h?.view.destroy(),h?.element.remove(),ht===h&&(ht=null,Vr=null,Hi=null,ot=null,bl=null,cp=null),on(),Bo(),rr(),C){let ne=f??xn;ne?.isConnected?ne.focus():Or()}m.emit("history:closed",{returnSurface:c,timestamp:Date.now()})}},ie=h&&h.element===h.view.element?h.view.playExit():null;if(!ie){G();return}Hl=G,X=setTimeout(G,_C),ie.then(G)},Mm=i=>{if(!(i.key!=="Escape"||!Te||!ht)){if(ot==="rail"){let c=i.target;if(!(c instanceof Node)||!(ht.element.contains(c)||dn&&Oo?.contains(c)===!0))return}i.preventDefault(),i.stopPropagation(),Wn()}};Q.addEventListener("keydown",Mm),We.push(()=>Q.removeEventListener("keydown",Mm));let Rl=null,Tm=!1,zi=()=>{if(!tn)return;let i=o.layout?.header?.titleSource==="conversation",c=i&&Rl?.trim()||null;tn.textContent=c??o.launcher?.title??"Chat Assistant";let f=tn.closest(".persona-combo-btn");if(!f)return;let h=!i||z.getActiveConversationId()!==null;f.setAttribute("data-persona-menu-locked",h?"false":"true"),f.setAttribute("aria-haspopup",h?"true":"false"),h||f.setAttribute("aria-expanded","false"),f.style.cursor=h?"pointer":"default";let C=f.querySelector("svg");C&&(C.style.display=h?"":"none")},dx=i=>{i!==Rl&&(Rl=i,zi())},qr=i=>{Tm=i?.starred===!0,dx(i&&i.title.trim()||null),zi()};zi(),Q.addEventListener("persona:title-menu-builtin",i=>{let c=i.detail?.actionId,f=z.getActiveConversationId();f&&(c==="delete"?Rm(f):c==="star"&&z.canUpdateConversations()&&Wp(f,{starred:!Tm}).catch(()=>{}))});let Wl=0,px=250,Bl=null,Dl=()=>{Bl&&clearTimeout(Bl),Bl=null};We.push(Dl);let Em=()=>{Dl();let i=_r;i&&(Pi=!0,i.hidden=!1,ue.style.display="none",Li())},Nl=()=>{Wl+=1,Dl(),_r&&(_r.remove(),_r=null,Pi=!1,ue.style.removeProperty("display"),Xn(Je,!1),Li())},ux=()=>{try{if(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches)return;ue.animate([{opacity:0},{opacity:1}],{duration:150,easing:"ease-out"})}catch{}},Ip=(i,c)=>J("div",{className:zt("persona-conversation-loading-bubble",c&&"persona-conversation-loading-bubble--trailing"),attrs:{"aria-hidden":"true"},style:{width:i}}),km=()=>J("div",{className:"persona-conversation-loading-body"},Ip("58%",!1),Ip("72%",!0),Ip("44%",!1)),Pm=i=>{_r?.remove(),_r=i,i.hidden=!Pi,Z.insertBefore(i,ue),Dl(),Pi||(Bl=setTimeout(Em,px)),Xn(Je,!0)},gx=()=>{let i={config:o,streaming:!1,location:"conversation-open",defaultRenderer:km},c=null,f=a.find(h=>h.renderLoadingIndicator);f?.renderLoadingIndicator&&(c=f.renderLoadingIndicator(i)),c===null&&o.loadingIndicator?.render&&(c=o.loadingIndicator.render(i)),Pm(J("div",{className:"persona-conversation-loading",attrs:{role:"status","aria-label":it.openConversationLoadingLabel}},c??km()))},fx=i=>{let c=()=>{Hp(i,{focusComposer:!0}).catch(()=>{})},f=vo()?()=>{Nl(),$i()}:void 0,h=(G,ie)=>{let ne=J("button",{className:"persona-conversation-loading-error-action",attrs:{type:"button"},text:G});return ne.addEventListener("click",ie),ne},C=()=>J("div",{className:"persona-conversation-loading-error-body"},J("p",{className:"persona-conversation-loading-error-title",text:it.openConversationErrorTitle}),J("div",{className:"persona-conversation-loading-error-actions"},h(it.openConversationRetryLabel,c),f?h(it.openConversationBackLabel,f):null)),L=Object.freeze({conversationId:i,config:o,copy:Object.freeze({title:it.openConversationErrorTitle,retryLabel:it.openConversationRetryLabel,backLabel:it.openConversationBackLabel}),retry:c,...f?{back:f}:{},defaultRenderer:C}),X=null;for(let G of a)if(G.renderHistoryOpenError){try{X=G.renderHistoryOpenError(L)}catch(ie){console.warn("[persona] renderHistoryOpenError threw",ie),X=null}if(X)break}Pm(J("div",{className:"persona-conversation-loading-error",attrs:{role:"alert"}},X??C())),Em()};m.on("history:closed",()=>{_r&&Xn(Je,!0)});let Hp=async(i,{focusComposer:c=!1}={})=>{let f=Ss(),h=!!ht;ht?.view.setActiveConversationId(i),Nl();let C=Wl;gx(),Te&&(ot==="panel"||dn)&&Wn({restoreFocus:!1}),hs=!0;try{await z.openConversation(i,{scope:f})}catch(L){throw C===Wl&&fx(i),L}finally{hs=!1}C===Wl&&(Nl(),Fn.clear(),uo(),Rn(),Gd()||pl(),ux(),Fo(),h||qr(null),m.emit("history:conversationOpened",{conversationId:i,title:Rl,scope:f,timestamp:Date.now()}),c&&Or())},Rp=async({focusComposer:i=!1}={})=>{Nl(),await z.startNewConversation({scope:Ss()}),qr(null),Fn.clear(),uo(),Rn(),pl(),Fo();let c=z.getActiveConversationId();ht?.view.setActiveConversationId(c),m.emit("history:conversationStarted",{conversationId:c,timestamp:Date.now()}),Te&&(ot==="panel"||dn)&&Wn({restoreFocus:!1}),i&&Or()},Wp=async(i,c)=>{let f=await z.updateConversation(i,{...c,...c.title!==void 0?{title:c.title.trim()}:{}});return ht?.view.applyConversationSummary(f),!ht&&i===z.getActiveConversationId()&&qr(f),f},Lm=async i=>{let c=Ss(),f=z.getActiveConversationId()===i;await z.deleteConversation(i,{scope:c}),ht?.view.removeConversationSummary(i),f&&(qr(null),Fn.clear(),uo(),Rn(),Fo()),m.emit("history:conversationDeleted",{conversationId:i,scope:c,wasActive:f,timestamp:Date.now()})},Im=async i=>{let c=i?.scope??Ss(),f=i?.allTargets?null:i?.targetId??nm(),h=await z.clearConversationHistory({...f?{targetId:f}:{},scope:c});return qr(null),Fn.clear(),uo(),Rn(),Fo(),m.emit("history:cleared",{deleted:h.deleted,scope:c,targetId:f,timestamp:Date.now()}),h},Hm=async()=>{if(!Vn?.resetDevice)throw new Error("[Persona] resetHistoryIdentity() requires a history provider that can reset this device");let i=!1;try{i=(await z.resetHistoryDevice()).remoteRevocationConfirmed}finally{qr(null),z.clearArtifacts(),Fn.clear(),sp=null,o.clearStoredSessionId?.(),o.clearStoredConversationId?.(),T={},F.syncFromMetadata(),w?.clear&&dl(()=>w.clear(),"[AgentWidget] Failed to clear storage adapter:"),uo(),Rn(),Fo(),Wn({restoreFocus:!1}),Or(),M||Ot?.launcher.element.focus()}return Al(i?it.identityResetNotice:it.identityResetUnconfirmedNotice),m.emit("history:identityReset",{remoteRevocationConfirmed:i,timestamp:Date.now()}),{remoteRevocationConfirmed:i}},Bp=()=>mo?$:Q,Rm=async i=>await Td({host:Bp(),title:it.deleteConversationConfirmTitle,description:it.deleteConversationConfirm,confirmLabel:it.deleteConversationConfirmLabel,cancelLabel:it.confirmCancelLabel})?(await Lm(i),"deleted"):"cancelled",mx=async()=>{let i=Ss()==="verified-user";return await Td({host:Bp(),title:it.clearHistoryConfirmTitle,description:i?it.clearHistoryVerifiedConfirm:it.clearHistoryConfirm,confirmLabel:it.clearHistoryConfirmLabel,cancelLabel:it.confirmCancelLabel})?(await Im(),"cleared"):"cancelled"},hx=async()=>{if(!await Td({host:Bp(),title:it.resetIdentityConfirmTitle,description:it.resetIdentityConfirm,confirmLabel:it.resetIdentityConfirmLabel,cancelLabel:it.confirmCancelLabel}))return{outcome:"cancelled"};let{remoteRevocationConfirmed:c}=await Hm();return{outcome:"reset",remoteRevocationConfirmed:c}},Jn=v("button","persona-history-earlier");Jn.type="button",Jn.textContent=it.showEarlierMessagesLabel,Jn.setAttribute("data-persona-history-earlier",""),Object.assign(Jn.style,{alignSelf:"center",minHeight:"44px",padding:"0 16px",borderRadius:"999px",border:"1px solid var(--persona-border, rgba(0,0,0,0.12))",background:"transparent",color:"inherit",font:"inherit",cursor:"pointer",flexShrink:"0"});let Fo=()=>{if(!(vo()&&!!wl.nextMessageCursor&&!!z.getActiveConversationId())){Jn.remove();return}Jn.textContent=it.showEarlierMessagesLabel,Jn.parentNode!==Z&&Z.insertBefore(Jn,Z.firstChild)};Jn.addEventListener("click",()=>{let i=z.getActiveConversationId(),c=wl.nextMessageCursor;if(!i||!c||Jn.disabled)return;Jn.disabled=!0;let f=Z.scrollHeight,h=Z.scrollTop;z.loadOlderMessages(i,c,{scope:Ss()}).then(()=>{Z.scrollTop=h+(Z.scrollHeight-f),Bo()}).catch(()=>{}).finally(()=>{Jn.disabled=!1,Fo()})});let yx=()=>{let i=Zr({ariaLabel:it.openHistoryLabel,iconName:"history",wrapperClassName:"persona-relative persona-inline-flex persona-items-center persona-justify-center",extraClassName:"persona-history-toggle",attrs:{"data-persona-history-toggle":""}});return i.button.addEventListener("click",c=>{if(!(!vo()||tm())){if(Te){Wn();return}$i({invoker:i.button,keyboard:c.detail===0})}}),i},Wm=()=>{if(!vo()){bo?.remove(),xn=null,bo=null;return}if(bo&&!bo.isConnected&&(xn=null,bo=null),!xn&&Pe){let h=yx();xn=h.button,bo=h.wrapper;let C=Y.clearChatButtonWrapper||Y.closeButtonWrapper;C?.parentNode&&Pe.contains(C)?C.parentNode.insertBefore(bo,C):Pe.appendChild(bo)}if(!xn||!bo)return;let i=_i()||Te&&ot==="rail";if(bo.style.display=i?"none":"",i){document.activeElement===xn&&Il();return}let c=tm();xn.disabled=c,xn.setAttribute("aria-disabled",c?"true":"false");let f=c?it.openHistoryBusyLabel:it.openHistoryLabel;xn.setAttribute("aria-label",f),(o.features?.history?.presentation??"panel")==="panel"?(xn.removeAttribute("aria-expanded"),xn.removeAttribute("aria-controls")):(xn.setAttribute("aria-expanded",Te?"true":"false"),xn.setAttribute("aria-controls",up))},Ol=!1,bx=()=>{let i=Y.clearChatButton;if(i){if(vo()){Ol||(pp=i.getAttribute("aria-label")??"",Ol=!0),i.setAttribute("aria-label",it.newConversationLabel),i.removeAttribute("title");return}Ol&&(Ol=!1,pp&&i.setAttribute("aria-label",pp))}},rr=()=>{it=Mg(o.features?.history?.copy),Wm(),Ep(),bx(),Fo()};Ln=rr,wn=i=>{wl=i,ht?.view.setNewConversationRequired(i.recovery==="new_conversation_required"),ki(i.sendBlocked||_n),Fo()},Ct=i=>{(i.code==="history_continuity_reset"||i.code==="conversation_deleted_recovered")&&(Fn.clear(),uo(),Rn()),Al(i.message),ht?.view.refresh()},im(),rr(),We.push(()=>{xl?.(),Sl?.(),Cl+=1,Hl(),ht?.dispose(),ht?.view.destroy(),ht=null}),o.clientToken&&z.initClientSession().then(()=>{if(vo())return z.reconcileBootConversation({scope:fp()})}).then(()=>{Fo()}).catch(i=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",i)}),(Ee||o.onSSEEvent)&&z.setSSEEventCallback((i,c)=>{o.onSSEEvent?.(i,c),$e?.processEvent(i,c),Ee?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i,timestamp:Date.now(),payload:JSON.stringify(c)})});let Bm=()=>{o.resume&&typeof o.reconnectStream=="function"&&z.resumeFromHandle(o.resume)};W?W.then(i=>{if(i){if(i.metadata&&(T=Fg(i.metadata),F.syncFromMetadata()),i.messages?.length){hs=!0;try{z.hydrateMessages(i.messages)}finally{hs=!1}}i.artifacts?.length&&z.hydrateArtifacts(i.artifacts,i.selectedArtifactId??null)}}).catch(i=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",i)}).finally(()=>{Vf=!0,E(),Bm()}):Bm();let Dm=()=>{!oe()||M||!(o.launcher?.composerBar?.expandOnSubmit??!0)||xt(!0,"auto")},vx=(i,c)=>i?c?{refs:[...i.refs,...c.refs],finalize:async()=>{let[f,h]=await Promise.allSettled([i.finalize(),c.finalize()]),C=[];return f.status==="fulfilled"?C.push(f.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",f.reason),h.status==="fulfilled"?C.push(h.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",h.reason),Bk(C)}}:i:c,wx=()=>{let c=ye.getInlineMessageFields?.();return c&&c.contentSegments.some(h=>h.kind==="mention")?c.contentSegments:void 0},Vi=!1,Cx=async i=>{let c=ye.value.trim(),f=Pt?.hasAttachments()??!1,h=c?await(Cn?.takeInlineCommand(c)??Promise.resolve(null)):null;if(h?.kind==="action"){ye.value="",ye.style.height="auto",ji(),Cn?.clear();return}let C=Cn?.collectForSubmit()??null,L=h?.kind==="server"?h.mentions:null,X=vx(C,L),G=h?.kind==="prompt"?h.sendText:c,ie=!!C&&C.refs.length>0;if(!G&&!f&&!ie&&!L)return;Dm();let ne;f&&(ne=[],ne.push(...Pt.getContentParts()),G&&ne.push(hr(G)));let le=h?.kind==="prompt"?void 0:wx();ye.value="",ye.style.height="auto",ji(),z.sendMessage(G,{contentParts:ne,mentions:X??void 0,contentSegments:le,viaVoice:i?.viaVoice}),f&&Pt.clearAttachments(),C&&Cn?.clear()},Dp=async i=>{if(!Vi){Vi=!0;try{await Cx(i)}finally{Vi=!1}}},_l=i=>{if(i.preventDefault(),z.isStreaming()){z.cancel(),$e?.reset(),mt?.update();return}Vi||Dp()},xx=()=>o.features?.composerHistory!==!1,Np={..._u},Op=!1,ji=()=>{Np={..._u}},Sx=()=>z.getMessages().filter(i=>i.role==="user").map(i=>i.content??"").filter(i=>i.length>0),Ax=i=>{if(!ye)return;Op=!0,ye.value=i,ye.dispatchEvent(new Event("input",{bubbles:!0})),Op=!1;let c=ye.value.length;ye.setSelectionRange(c,c)},Mx=i=>{Op||(i.isComposing||Cn?.handleInput(i.inputType??void 0),ji())},Tx=i=>{if(ye&&!(!i.isComposing&&Cn?.handleKeydown(i))){if(xx()&&(i.key==="ArrowUp"||i.key==="ArrowDown")&&!i.shiftKey&&!i.metaKey&&!i.ctrlKey&&!i.altKey&&!i.isComposing){let c=ye.selectionStart===0&&ye.selectionEnd===0,f=Yb({direction:i.key==="ArrowUp"?"up":"down",history:Sx(),currentValue:ye.value,atStart:c,state:Np});if(Np=f.state,f.handled){i.preventDefault(),f.value!==void 0&&Ax(f.value);return}}if(i.key==="Enter"&&!i.shiftKey){if(z.isStreaming()){i.preventDefault();return}if(Vi){i.preventDefault();return}ji(),i.preventDefault(),we.click()}}},Nm=i=>{i.key!=="Escape"||i.isComposing||z.isStreaming()&&i.composedPath().includes(Q)&&(z.cancel(),$e?.reset(),mt?.update(),ji(),i.preventDefault(),i.stopImmediatePropagation())},Ex=async i=>{if(o.attachments?.enabled!==!0||!Pt)return;let c=Ik(i.clipboardData);c.length!==0&&(i.preventDefault(),await Pt.handleFiles(c))},Zn=null,wo=!1,ks=null,It=null,Om=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Fl=(i="user")=>{if(wo||z.isStreaming())return;let c=Om();if(!c)return;Zn=new c;let h=(o.voiceRecognition??{}).pauseDuration??2e3;Zn.continuous=!0,Zn.interimResults=!0,Zn.lang="en-US";let C=ye.value;Zn.onresult=L=>{let X="",G="";for(let ne=0;ne<L.results.length;ne++){let le=L.results[ne],be=le[0].transcript;le.isFinal?X+=be+" ":G=be}let ie=C+X+G;ye.value=ie,ks&&clearTimeout(ks),(X||G)&&(ks=window.setTimeout(()=>{ye.value.trim()&&Zn&&wo&&(sr(),Dp({viaVoice:!0}))},h))},Zn.onerror=L=>{L.error!=="no-speech"&&sr()},Zn.onend=()=>{if(wo){let L=ye.value.trim();L&&L!==C.trim()&&Dp({viaVoice:!0}),sr()}};try{if(Zn.start(),wo=!0,rt.active=!0,i!=="system"&&(rt.manuallyDeactivated=!1),Wo(i),po(),de){let L=o.voiceRecognition??{};It={backgroundColor:de.style.backgroundColor,color:de.style.color,borderColor:de.style.borderColor,iconName:L.iconName??"mic",iconSize:parseFloat(L.iconSize??o.sendButton?.size??"40")||24};let X=L.recordingBackgroundColor,G=L.recordingIconColor,ie=L.recordingBorderColor;if(de.classList.add("persona-voice-recording"),de.style.backgroundColor=X??"var(--persona-voice-recording-bg, #ef4444)",de.style.color=G??"var(--persona-voice-recording-indicator, #ffffff)",G){let ne=de.querySelector("svg");ne&&ne.setAttribute("stroke",G)}ie&&(de.style.borderColor=ie),de.setAttribute("aria-label","Stop voice recognition")}}catch{sr("system")}},sr=(i="user")=>{if(wo){if(wo=!1,ks&&(clearTimeout(ks),ks=null),Zn){try{Zn.stop()}catch{}Zn=null}if(rt.active=!1,Wo(i),po(),de){if(de.classList.remove("persona-voice-recording"),It){de.style.backgroundColor=It.backgroundColor,de.style.color=It.color,de.style.borderColor=It.borderColor;let c=de.querySelector("svg");c&&c.setAttribute("stroke",It.color||"currentColor"),It=null}de.setAttribute("aria-label","Start voice recognition")}}},kx=(i,c)=>{let f=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),h=i?.provider?.type==="runtype",C=i?.provider?.type==="custom";if(!(f||h||C))return null;let X=v("div","persona-send-button-wrapper"),G=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");G.type="button";let ie=i?.tooltipText??"Start voice recognition";G.setAttribute("aria-label",ie);let ne=i?.iconName??"mic",le=c?.size??"40px",be=i?.iconSize??le,Ae=parseFloat(be)||24,gt=i?.backgroundColor??c?.backgroundColor,Ht=i?.iconColor??c?.textColor;G.style.width=be,G.style.height=be,G.style.minWidth=be,G.style.minHeight=be,G.style.fontSize="18px",G.style.lineHeight="1",Ht?G.style.color=Ht:G.style.color="var(--persona-text, #111827)";let Bn=fe(ne,Ae,Ht||"currentColor",1.5);Bn?G.appendChild(Bn):G.textContent="\u{1F3A4}",gt?G.style.backgroundColor=gt:G.style.backgroundColor="",i?.borderWidth&&(G.style.borderWidth=i.borderWidth,G.style.borderStyle="solid"),i?.borderColor&&(G.style.borderColor=i.borderColor),i?.paddingX&&(G.style.paddingLeft=i.paddingX,G.style.paddingRight=i.paddingX),i?.paddingY&&(G.style.paddingTop=i.paddingY,G.style.paddingBottom=i.paddingY),X.appendChild(G);let Ft=i?.showTooltip??!1;return hn({anchor:G,trigger:X,text:()=>G.getAttribute("aria-label")??ie,enabled:Ft}),{micButton:G,micButtonWrapper:X}},_p=()=>{if(!de||It)return;let i=o.voiceRecognition??{};It={backgroundColor:de.style.backgroundColor,color:de.style.color,borderColor:de.style.borderColor,iconName:i.iconName??"mic",iconSize:parseFloat(i.iconSize??o.sendButton?.size??"40")||24}},Fp=(i,c)=>{if(!de)return;let f=de.querySelector("svg");f&&f.remove();let h=It?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),C=fe(i,h,c,1.5);C&&de.appendChild(C)},$l=()=>{de&&de.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ps=()=>{if(!de)return;_p();let i=o.voiceRecognition??{},c=i.recordingBackgroundColor,f=i.recordingIconColor,h=i.recordingBorderColor;if($l(),de.classList.add("persona-voice-recording"),de.style.backgroundColor=c??"var(--persona-voice-recording-bg, #ef4444)",de.style.color=f??"var(--persona-voice-recording-indicator, #ffffff)",f){let C=de.querySelector("svg");C&&C.setAttribute("stroke",f)}h&&(de.style.borderColor=h),de.setAttribute("aria-label","Stop voice recognition")},Px=()=>{if(!de)return;_p();let i=o.voiceRecognition??{},c=z.getVoiceInterruptionMode(),f=i.processingIconName??"loader",h=i.processingIconColor??It?.color??"",C=i.processingBackgroundColor??It?.backgroundColor??"",L=i.processingBorderColor??It?.borderColor??"";$l(),de.classList.add("persona-voice-processing"),de.style.backgroundColor=C,de.style.borderColor=L;let X=h||"currentColor";de.style.color=X,Fp(f,X),de.setAttribute("aria-label","Processing voice input"),c==="none"&&(de.style.cursor="default")},Lx=()=>{if(!de)return;_p();let i=o.voiceRecognition??{},c=z.getVoiceInterruptionMode(),f=c==="cancel"?"square":c==="barge-in"?"mic":"volume-2",h=i.speakingIconName??f,C=i.speakingIconColor??(c==="barge-in"?i.recordingIconColor??It?.color??"":It?.color??""),L=i.speakingBackgroundColor??(c==="barge-in"?i.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":It?.backgroundColor??""),X=i.speakingBorderColor??(c==="barge-in"?i.recordingBorderColor??"":It?.borderColor??"");$l(),de.classList.add("persona-voice-speaking"),de.style.backgroundColor=L,de.style.borderColor=X;let G=C||"currentColor";de.style.color=G,Fp(h,G);let ie=c==="cancel"?"Stop playback and re-record":c==="barge-in"?"Speak to interrupt":"Agent is speaking";de.setAttribute("aria-label",ie),c==="none"&&(de.style.cursor="default"),c==="barge-in"&&de.classList.add("persona-voice-recording")},$o=()=>{de&&($l(),It&&(de.style.backgroundColor=It.backgroundColor??"",de.style.color=It.color??"",de.style.borderColor=It.borderColor??"",Fp(It.iconName,It.color||"currentColor"),It=null),de.style.cursor="",de.setAttribute("aria-label","Start voice recognition"))},Ls=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let i=z.getVoiceStatus(),c=z.getVoiceInterruptionMode();if(c==="none"&&(i==="processing"||i==="speaking"))return;if(c==="cancel"&&(i==="processing"||i==="speaking")){z.stopVoicePlayback();return}if(z.isBargeInActive()){z.stopVoicePlayback(),z.deactivateBargeIn().then(()=>{rt.active=!1,rt.manuallyDeactivated=!0,po(),Wo("user"),$o()});return}z.toggleVoice().then(()=>{rt.active=z.isVoiceActive(),rt.manuallyDeactivated=!z.isVoiceActive(),po(),Wo("user"),z.isVoiceActive()?Ps():$o()});return}if(wo){let i=ye.value.trim();rt.manuallyDeactivated=!0,po(),sr("user"),i&&(ye.value="",ye.style.height="auto",z.sendMessage(i))}else rt.manuallyDeactivated=!1,po(),Fl("user")};Qg=Ls,de&&(de.addEventListener("click",Ls),We.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(z.isVoiceActive()&&z.toggleVoice(),$o()):sr("system"),de&&de.removeEventListener("click",Ls)}));let Ix=m.on("assistant:complete",()=>{Hf&&(rt.active||rt.manuallyDeactivated||Hf==="assistant"&&!rt.lastUserMessageWasVoice||setTimeout(()=>{!rt.active&&!rt.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?z.toggleVoice().then(()=>{rt.active=z.isVoiceActive(),Wo("auto"),z.isVoiceActive()&&Ps()}):Fl("auto"))},600))});We.push(Ix);let Hx=m.on("action:resubmit",()=>{setTimeout(()=>{z&&!z.isStreaming()&&z.continueConversation()},100)});We.push(Hx);let _m=()=>{xt(!M,"user")},Ot=null,Sn=null;if(P&&!oe()){let{instance:i,element:c}=ig({config:o,plugins:a,onToggle:_m});Ot=i,i||(Sn=c)}Ot?t.appendChild(Ot.element):Sn&&t.appendChild(Sn),Ei(),fs(),np(),tp(),ki(z.isStreaming()),Gd()||(Le()==="follow"?tr(!0):pl()),uC(),se&&(!P||oe()?setTimeout(()=>Or(),0):M&&setTimeout(()=>Or(),200));let qi=()=>{if(oe()){Mr(),Ei();return}let i=Kt(o),c=o.launcher?.sidebarMode??!1,f=t.ownerDocument.defaultView??window,h=o.launcher?.mobileFullscreen??!0,C=o.launcher?.mobileBreakpoint??640,L=f.innerWidth<=C,X=h&&L&&P;try{if(X){Tr(),bi=rl();return}let G=!1;re&&(re=!1,Tr(),G=!0);let ie=rl();if(!G&&ie!==bi&&(Tr(),G=!0),bi=ie,G&&Dd(),!P&&!i){$.style.height="",$.style.width="";return}if(!c&&!i){let le=o?.launcher?.width??o?.launcherWidth??Uo;$.style.width=le,$.style.maxWidth=le}ol(),yf()}finally{if(Mr(),Ei(),M&&P){let ie=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ne=o.launcher?.sidebarMode??!1,le=o.launcher?.mobileFullscreen??!0,be=Kt(o)&&le&&ie,Ae=ne||le&&ie&&P||be;if(Ae&&!yo){let gt=t.getRootNode(),Ht=gt instanceof ShadowRoot?gt.host:t.closest(".persona-host");Ht&&!ho&&(ho=ju(Ht,o.launcher?.zIndex??mn)),yo=qu(t.ownerDocument)}else Ae||(ho?.(),ho=null,yo?.(),yo=null)}}};qi();let zl=t.ownerDocument.defaultView??window;if(zl.addEventListener("resize",qi),We.push(()=>zl.removeEventListener("resize",qi)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{Mr()});i.observe(Je),We.push(()=>i.disconnect());let c=new ResizeObserver(()=>{Ll()});c.observe(Q),We.push(()=>c.disconnect())}zl.addEventListener("resize",Ll),We.push(()=>zl.removeEventListener("resize",Ll)),zn=Z.scrollTop;let Fm=Mo(Z),$m=()=>{let i=Z.scrollTop,c=Mo(Z),f=c<Fm;if(Fm=c,!Nt()){zn=i,on();return}let{action:h,nextLastScrollTop:C}=Zc({following:$n.isFollowing(),currentScrollTop:i,lastScrollTop:zn,nearBottom:Go(Z,Ho),userScrollThreshold:lC,isAutoScrolling:Hn||il||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(zn=C,h==="resume"){ul()||Rn();return}h==="pause"&&xi()};if(Z.addEventListener("scroll",$m,{passive:!0}),We.push(()=>Z.removeEventListener("scroll",$m)),typeof ResizeObserver<"u"){let i=new ResizeObserver(()=>{vC(),Gp(ue)});i.observe(ue),i.observe(Z),We.push(()=>i.disconnect())}let zm=()=>{Nt()&&$n.isFollowing()&&ul()&&xi()},Vm=Z.ownerDocument;Vm.addEventListener("selectionchange",zm),We.push(()=>{Vm.removeEventListener("selectionchange",zm)});let Rx=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),jm=i=>{Rx.has(i.key)&&(Br(),cs()&&Nt()&&$n.isFollowing()&&xi())},qm=i=>{i.target?.closest("a, button, [tabindex], input, textarea, select")&&(Br(),cs()&&Nt()&&$n.isFollowing()&&xi())};Z.addEventListener("keydown",jm),Z.addEventListener("focusin",qm),We.push(()=>{Z.removeEventListener("keydown",jm),Z.removeEventListener("focusin",qm)});let Um=i=>{if(i.deltaY!==0&&Br(),!Nt())return;let c=ed({following:$n.isFollowing(),deltaY:i.deltaY,nearBottom:Go(Z,Ho),resumeWhenNearBottom:!0});c==="pause"?xi():c==="resume"&&!ul()&&Rn()};Z.addEventListener("wheel",Um,{passive:!0}),Z.addEventListener("touchmove",Br,{passive:!0}),Z.addEventListener("pointerdown",Br,{passive:!0}),We.push(()=>{Z.removeEventListener("touchmove",Br),Z.removeEventListener("pointerdown",Br)}),We.push(()=>Z.removeEventListener("wheel",Um)),Gt.addEventListener("click",()=>{uo(),Z.scrollTop=Z.scrollHeight,zn=Z.scrollTop,Rn(),tr(!0),on()}),We.push(()=>Gt.remove()),We.push(()=>{Bf(),uo()});let Km=()=>{Ke&&(Lr&&(Ke.removeEventListener("click",Lr),Lr=null),ee()?(Ke.style.display="",Lr=()=>{xt(!1,"user")},Ke.addEventListener("click",Lr)):Ke.style.display="none")};Km(),(()=>{let{clearChatButton:i}=Y;i&&i.addEventListener("click",()=>{if(vo()){Rp({focusComposer:!0}).catch(f=>{o.debug&&console.warn("[AgentWidget] New conversation failed:",f)});return}z.clearMessages(),Fn.clear(),Rn(),Os(Y.composerOverlay);try{localStorage.removeItem(ci),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ci}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ci)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(c),w?.clear&&dl(()=>w.clear(),"[AgentWidget] Failed to clear storage adapter:"),T={},F.syncFromMetadata(),Ee?.clear(),$e?.reset(),mt?.update()})})(),_e&&_e.addEventListener("submit",_l);let Gm=[["keydown",Tx],["input",Mx],["paste",Ex],["focus",eC]],$p=i=>{if(i)for(let[c,f]of Gm)i.addEventListener(c,f)},zp=i=>{if(i)for(let[c,f]of Gm)i.removeEventListener(c,f)};$p(ye);let Ym=()=>{Cn?.onComposerSwap((i,c)=>{zp(c),ye=i,$p(i)})};Ym();let Vp=!1;function Wx(){if(!Vp){Vp=!0;try{let i=ye?.value??"",c=Je.ownerDocument??document,f=ye?c.activeElement===ye:!1;zp(ye),_e?.removeEventListener("submit",_l),de?.removeEventListener("click",Ls),Cn?.destroy(),Cn=null;let h=null,C=()=>(h=oe()?gd({config:o}):Ba({config:o}),h.footer),L=tf(C)??C();O.replaceComposer(L),Je=O.composer.footer;let X=h!==null&&L===h.footer;mi=!X,Sr=X?h.setSendButtonMode:()=>{},ef(Je),of(Je),rf(),sf(),af(),Ym(),_e&&_e.addEventListener("submit",_l),$p(ye),de?.addEventListener("click",Ls);let G=Pr.indexOf(Io);Io.destroy(),Io=Ra(Be),G>=0&&(Pr[G]=Io),ye&&(ye.value=i),np(),fs(),ki(z.isStreaming()),Tr(),Mr(),f&&ye?.focus()}finally{Vp=!1}}}let Xm=t.ownerDocument??document;Xm.addEventListener("keydown",Nm,!0);let Qm="persona-attachment-drop-active",Ui=0,jp=()=>{Ui=0,Q.classList.remove(Qm)},Is=()=>o.attachments?.enabled===!0&&Pt!==null,Jm=i=>{!Ed(i.dataTransfer)||!Is()||(Ui++,Ui===1&&Q.classList.add(Qm))},Zm=i=>{!Ed(i.dataTransfer)||!Is()||(Ui--,Ui<=0&&jp())},eh=i=>{!Ed(i.dataTransfer)||!Is()||(i.preventDefault(),i.dataTransfer.dropEffect="copy")},th=i=>{if(!Ed(i.dataTransfer)||!Is())return;i.preventDefault(),i.stopPropagation(),jp();let c=Array.from(i.dataTransfer.files??[]);c.length!==0&&Pt.handleFiles(c)},ir=!0;Q.addEventListener("dragenter",Jm,ir),Q.addEventListener("dragleave",Zm,ir),t.addEventListener("dragover",eh,ir),t.addEventListener("drop",th,ir);let Vl=t.ownerDocument,nh=i=>{Is()&&i.preventDefault()},oh=i=>{Is()&&i.preventDefault()};Vl.addEventListener("dragover",nh),Vl.addEventListener("drop",oh),We.push(()=>{_e&&_e.removeEventListener("submit",_l),zp(ye),Xm.removeEventListener("keydown",Nm,!0),Cn?.destroy()}),We.push(()=>{Q.removeEventListener("dragenter",Jm,ir),Q.removeEventListener("dragleave",Zm,ir),t.removeEventListener("dragover",eh,ir),t.removeEventListener("drop",th,ir),Vl.removeEventListener("dragover",nh),Vl.removeEventListener("drop",oh),jp()}),We.push(()=>{z.cancel()}),Ot?We.push(()=>{Ot?.destroy()}):Sn&&We.push(()=>{Sn?.remove()});let _t={update(i){let c=o.toolCall,f=o.messageActions,h=o.layout?.messages,C=o.colorScheme,L=o.loadingIndicator,X=o.iterationDisplay,G=o.features?.showReasoning,ie=o.features?.showToolCalls,ne=o.features?.toolCallDisplay,le=o.features?.reasoningDisplay,be=o.features?.streamAnimation?.type,Ae=o.features?.history?.enabled===!0,gt=o.features?.history?.provider,Ht=o.getIdentityProof,pn=o.clientToken;o=sw({...o,features:s},i),s=o.features,o=yg(o),r(),Od(),Ca(t,o),$a(t,o),za(t,o),kt(),Lo(),o.colorScheme!==C&&bf();let Bn=Cg.getForInstance(o.plugins);a.length=0,a.push(...Bn),fm(),P=o.launcher?.enabled??!0,V=o.launcher?.autoExpand??!1,Ce=o.features?.showReasoning??!0,Me=o.features?.showToolCalls??!0,Oe=o.features?.scrollToBottom??{};let Ft=Le();ze=o.features?.scrollBehavior??{},Ft!==Le()&&(uo(),Rn()),If(),Xg(),on();let Vt=ke;if(ke=o.features?.showEventStreamToggle??!1,ke&&!Vt){if(Ee||(Ue=new _a(De),Ee=new Oa(an,Ue),$e=$e??new Fa,Ue.open().then(()=>Ee?.restore()).catch(()=>{}),z.setSSEEventCallback((me,st)=>{o.onSSEEvent?.(me,st),$e?.processEvent(me,st),Ee.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:me,timestamp:Date.now(),payload:JSON.stringify(st)})})),!ut&&Pe){let me=o.features?.eventStream?.classNames,st="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"+(me?.toggleButton?" "+me.toggleButton:"");ut=v("button",st),ut.style.width="28px",ut.style.height="28px",ut.style.color=kn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let pt=fe("activity","18px","currentColor",1.5);pt&&ut.appendChild(pt);let Et=Y.clearChatButtonWrapper,bt=Y.closeButtonWrapper,fn=Et||bt;fn&&fn.parentNode===Pe?Pe.insertBefore(ut,fn):Pe.appendChild(ut),ut.addEventListener("click",()=>{At?ds():Id()})}}else!ke&&Vt&&(ds(),ut&&(ut.remove(),ut=null),Ee?.clear(),Ue?.destroy(),Ee=null,Ue=null,$e?.reset(),$e=null);if(o.launcher?.enabled===!1&&Ot&&(Ot.destroy(),Ot=null),o.launcher?.enabled===!1&&Sn&&(Sn.remove(),Sn=null),o.launcher?.enabled!==!1&&!Ot&&!Sn){let{instance:me,element:st}=ig({config:o,plugins:a,onToggle:_m});Ot=me,me||(Sn=st),t.appendChild(st)}Ot&&Ot.update(o),zi(),fo&&o.launcher?.subtitle!==void 0&&(fo.textContent=o.launcher.subtitle);let U=o.layout?.header;if(U?.layout!==ge&&Pe){let me=U?id(o,U,{showClose:ee(),onClose:()=>xt(!1,"user")}):es({config:o,showClose:ee(),onClose:()=>xt(!1,"user")});O.replaceHeader(me),Pe=O.header.element,Fe=O.header.iconHolder,tn=O.header.headerTitle,fo=O.header.headerSubtitle,Ke=O.header.closeButton,ge=U?.layout,zi()}else if(U){if(Fe&&(Fe.style.display=U.showIcon===!1?"none":""),tn&&(tn.style.display=U.showTitle===!1?"none":""),fo&&(fo.style.display=U.showSubtitle===!1?"none":""),Ke){let me=ee()&&U.showCloseButton!==!1;Ke.style.display=me?"":"none"}if(Y.clearChatButtonWrapper){let me=U.showClearChat;if(me!==void 0){Y.clearChatButtonWrapper.style.display=me?"":"none";let{closeButtonWrapper:st}=Y;st&&!st.classList.contains("persona-absolute")&&(me?st.classList.remove("persona-ml-auto"):st.classList.add("persona-ml-auto"))}}}let Ve=o.layout?.showHeader!==!1;Pe&&(Pe.style.display=Ve?"":"none");let Ie=o.layout?.showFooter!==!1;Je&&(Je.style.display=Ie?"":"none"),Mr(),on(),P!==he?P?xt(V,"auto"):(M=!0,Ei()):V!==ve&&xt(V,"auto"),ve=V,he=P,qi(),Km();let un=JSON.stringify(o.toolCall)!==JSON.stringify(c),St=JSON.stringify(o.messageActions)!==JSON.stringify(f),An=JSON.stringify(o.layout?.messages)!==JSON.stringify(h),gn=o.loadingIndicator?.render!==L?.render||o.loadingIndicator?.renderIdle!==L?.renderIdle||o.loadingIndicator?.showBubble!==L?.showBubble,rn=o.iterationDisplay!==X,je=(o.features?.showReasoning??!0)!==(G??!0)||(o.features?.showToolCalls??!0)!==(ie??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(ne)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(le);(un||St||An||gn||rn||je)&&z&&(Fd++,Si(ue,z.getMessages(),xe));let sn=o.features?.streamAnimation?.type;if(sn!==be&&sn&&sn!=="none"){let me=Zs(sn,o.features?.streamAnimation?.plugins);me&&rd(me,t)}let Re=o.launcher??{},Yt=Re.headerIconHidden??!1,Tt=o.layout?.header?.showIcon,at=Yt||Tt===!1,Xt=Re.headerIconName,jt=Re.headerIconSize??"48px";if(Fe){let me=Pe,st=me?.querySelector(".persona-flex-col");if(at)Fe.style.display="none",me&&st&&!me.contains(st)&&me.insertBefore(st,me.firstChild);else{if(Fe.style.display="",Fe.style.height=jt,Fe.style.width=jt,me&&st&&(me.contains(Fe)?Fe.nextSibling!==st&&(Fe.remove(),me.insertBefore(Fe,st)):me.insertBefore(Fe,st)),Xt){let Et=parseFloat(jt)||24,bt=fe(Xt,Et*.6,"currentColor",1);bt?Fe.replaceChildren(bt):Fe.textContent=Re.agentIconText??"\u{1F4AC}"}else if(Re.iconUrl){let Et=Fe.querySelector("img");if(Et)Et.src=Re.iconUrl,Et.style.height=jt,Et.style.width=jt;else{let bt=document.createElement("img");bt.src=Re.iconUrl,bt.alt="",bt.className="persona-rounded-xl persona-object-cover",bt.style.height=jt,bt.style.width=jt,Fe.replaceChildren(bt)}}else{let Et=Fe.querySelector("svg"),bt=Fe.querySelector("img");(Et||bt)&&Fe.replaceChildren(),Fe.textContent=Re.agentIconText??"\u{1F4AC}"}let pt=Fe.querySelector("img");pt&&(pt.style.height=jt,pt.style.width=jt)}}let bn=o.layout?.header?.showTitle,to=o.layout?.header?.showSubtitle;if(tn&&(tn.style.display=bn===!1?"none":""),fo&&(fo.style.display=to===!1?"none":""),Ke){let me=ee()&&o.layout?.header?.showCloseButton!==!1;if(Ke.style.display=me?"":"none",!oe()){let Ut=Re.closeButtonSize??"";Ke.style.height=Ut,Ke.style.width=Ut,Ke.style.minWidth=Ut,Ke.style.minHeight=Ut}let st=Re.closeButtonPlacement??"inline",{closeButtonWrapper:pt}=Y,Et=st==="top-right",bt=pt?.classList.contains("persona-absolute");if(pt&&Et!==bt)if(pt.remove(),Et){pt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50";let Ut=Wi??Q;Ut.style.position="relative",Ut.appendChild(pt)}else{let Ut=Re.clearChat?.placement??"inline",Jt=Re.clearChat?.enabled??!0;pt.className=Jt&&Ut==="inline"?"":"persona-ml-auto",Pe&&Pe.appendChild(pt)}if(Ke.style.color=Re.closeButtonColor||kn.actionIconColor,Re.closeButtonBackgroundColor?(Ke.style.backgroundColor=Re.closeButtonBackgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),Re.closeButtonBorderWidth||Re.closeButtonBorderColor){let Ut=Re.closeButtonBorderWidth||"0px",Jt=Re.closeButtonBorderColor||"transparent";Ke.style.border=`${Ut} solid ${Jt}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");Re.closeButtonBorderRadius?(Ke.style.borderRadius=Re.closeButtonBorderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),Re.closeButtonPaddingX?(Ke.style.paddingLeft=Re.closeButtonPaddingX,Ke.style.paddingRight=Re.closeButtonPaddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),Re.closeButtonPaddingY?(Ke.style.paddingTop=Re.closeButtonPaddingY,Ke.style.paddingBottom=Re.closeButtonPaddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom=""),sd(Ke,Re.closeButtonIconName??"x",{iconSize:oe()?ng:void 0,iconText:Re.closeButtonIconText??"\xD7"});let fn=Re.closeButtonTooltipText??"Close chat",Dn=Re.closeButtonShowTooltip??!0;Ke.setAttribute("aria-label",fn),pt&&hn({anchor:Ke,trigger:pt,text:()=>Ke?.getAttribute("aria-label")??fn,enabled:Dn})}let{clearChatButton:dt,clearChatButtonWrapper:vn}=Y;if(dt){let me=Re.clearChat??{},st=me.enabled??!0,pt=o.layout?.header?.showClearChat,Et=pt!==void 0?pt:st,bt=me.placement??"inline";if(vn){vn.style.display=Et?"":"none";let{closeButtonWrapper:fn}=Y;!oe()&&fn&&!fn.classList.contains("persona-absolute")&&(Et?fn.classList.remove("persona-ml-auto"):fn.classList.add("persona-ml-auto"));let Dn=bt==="top-right",Ut=vn.classList.contains("persona-absolute");if(!oe()&&Dn!==Ut&&Et){if(vn.remove(),Dn){vn.className="persona-absolute persona-top-4 persona-z-50",vn.style.right="48px";let qn=Wi??Q;qn.style.position="relative",qn.appendChild(vn)}else{vn.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",vn.style.right="";let qn=Y.closeButtonWrapper;Pe&&qn&&qn.parentElement===Pe?Pe.insertBefore(vn,qn):Pe&&Pe.appendChild(vn)}let Jt=Y.closeButtonWrapper;Jt&&!Jt.classList.contains("persona-absolute")&&(Dn?Jt.classList.add("persona-ml-auto"):Jt.classList.remove("persona-ml-auto"))}}if(Et){if(!oe()){let Jt=me.size??"";dt.style.height=Jt,dt.style.width=Jt,dt.style.minWidth=Jt,dt.style.minHeight=Jt}let fn=me.iconColor??"";if(dt.style.color=fn||kn.actionIconColor,sd(dt,me.iconName??"refresh-cw",{iconSize:oe()?og:void 0}),me.backgroundColor?(dt.style.backgroundColor=me.backgroundColor,dt.classList.remove("hover:persona-bg-gray-100")):(dt.style.backgroundColor="",dt.classList.add("hover:persona-bg-gray-100")),me.borderWidth||me.borderColor){let Jt=me.borderWidth||"0px",qn=me.borderColor||"transparent";dt.style.border=`${Jt} solid ${qn}`,dt.classList.remove("persona-border-none")}else dt.style.border="",dt.classList.add("persona-border-none");me.borderRadius?(dt.style.borderRadius=me.borderRadius,dt.classList.remove("persona-rounded-full")):(dt.style.borderRadius="",dt.classList.add("persona-rounded-full")),me.paddingX?(dt.style.paddingLeft=me.paddingX,dt.style.paddingRight=me.paddingX):(dt.style.paddingLeft="",dt.style.paddingRight=""),me.paddingY?(dt.style.paddingTop=me.paddingY,dt.style.paddingBottom=me.paddingY):(dt.style.paddingTop="",dt.style.paddingBottom="");let Dn=me.tooltipText??"Clear chat",Ut=me.showTooltip??!0;dt.setAttribute("aria-label",Dn),vn&&hn({anchor:dt,trigger:vn,text:()=>dt?.getAttribute("aria-label")??Dn,enabled:Ut})}}let qt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[Sg],Tn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Va.message,Va.messageAndClick];F=Ag({parsers:qt,handlers:Tn,getSessionMetadata:B,updateSessionMetadata:I,emit:m.emit,documentRef:typeof document<"u"?document:null}),xe=_w(o,F,Se),WC(),z.updateConfig(o),(o.features?.history?.enabled===!0!==Ae||o.features?.history?.provider!==gt||o.getIdentityProof!==Ht||o.clientToken!==pn)&&(Wn({restoreFocus:!1}),im()),rr(),Ll(),Si(ue,z.getMessages(),xe),fs(),np(),HC(),ki(z.isStreaming());let Ki=o.voiceRecognition?.enabled===!0,rh=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Gi=o.voiceRecognition?.provider?.type==="runtype";if(Ki&&(rh||Gi))if(!de||!Nn){let me=kx(o.voiceRecognition,o.sendButton);me&&(de=me.micButton,Nn=me.micButtonWrapper,ui.insertBefore(Nn,ct),de.addEventListener("click",Ls),de.disabled=z.isStreaming())}else{let me=o.voiceRecognition??{},st=o.sendButton??{},pt=me.iconName??"mic",Et=st.size??"40px",bt=me.iconSize??Et,fn=parseFloat(bt)||24;de.style.width=bt,de.style.height=bt,de.style.minWidth=bt,de.style.minHeight=bt;let Dn=me.iconColor??st.textColor;de.innerHTML="";let Ut=fe(pt,fn,Dn||"currentColor",1.5);Ut?de.appendChild(Ut):de.textContent="\u{1F3A4}";let Jt=me.backgroundColor??st.backgroundColor;Jt?de.style.backgroundColor=Jt:de.style.backgroundColor="",Dn?de.style.color=Dn:de.style.color="var(--persona-text, #111827)",me.borderWidth?(de.style.borderWidth=me.borderWidth,de.style.borderStyle="solid"):(de.style.borderWidth="",de.style.borderStyle=""),me.borderColor?de.style.borderColor=me.borderColor:de.style.borderColor="",me.paddingX?(de.style.paddingLeft=me.paddingX,de.style.paddingRight=me.paddingX):(de.style.paddingLeft="",de.style.paddingRight=""),me.paddingY?(de.style.paddingTop=me.paddingY,de.style.paddingBottom=me.paddingY):(de.style.paddingTop="",de.style.paddingBottom="");let qn=me.tooltipText??"Start voice recognition",Ox=me.showTooltip??!1;de.setAttribute("aria-label",qn),Nn&&hn({anchor:de,trigger:Nn,text:()=>de?.getAttribute("aria-label")??qn,enabled:Ox}),Nn.style.display="",de.disabled=z.isStreaming()}else de&&Nn&&(Nn.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?z.isVoiceActive()&&z.toggleVoice():wo&&sr());if(o.attachments?.enabled===!0){if(!yn||!vt){let me=o.attachments??{},pt=(o.sendButton??{}).size??"40px";On||(On=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),On.style.display="none",_e.insertBefore(On,ye)),Dt||(Dt=document.createElement("input"),Dt.type="file",Dt.accept=(me.allowedTypes??qo).join(","),Dt.multiple=(me.maxFiles??4)>1,Dt.style.display="none",Dt.setAttribute("aria-label","Attach files"),_e.insertBefore(Dt,ye)),yn=v("div","persona-send-button-wrapper"),vt=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),vt.type="button",vt.setAttribute("aria-label",me.buttonTooltipText??"Attach file");let Et=me.buttonIconName??"paperclip",bt=pt,fn=parseFloat(bt)||40,Dn=Math.round(fn*.6);vt.style.width=bt,vt.style.height=bt,vt.style.minWidth=bt,vt.style.minHeight=bt,vt.style.fontSize="18px",vt.style.lineHeight="1";let Ut=fe(Et,Dn,"currentColor",1.5);Ut?vt.appendChild(Ut):vt.textContent="\u{1F4CE}",vt.addEventListener("click",qn=>{qn.preventDefault(),Dt?.click()}),yn.appendChild(vt);let Jt=me.buttonTooltipText??"Attach file";hn({anchor:vt,trigger:yn,text:()=>vt?.getAttribute("aria-label")??Jt}),ao?ao.append(yn):_e.appendChild(yn),!Pt&&Dt&&On&&(Pt=ua.fromConfig(me),Pt.setPreviewsContainer(On),Dt.addEventListener("change",async()=>{Pt&&Dt?.files&&(await Pt.handleFileSelect(Dt.files),Dt.value="")}))}else{yn.style.display="";let me=o.attachments??{};Dt&&(Dt.accept=(me.allowedTypes??qo).join(","),Dt.multiple=(me.maxFiles??4)>1),Pt&&Pt.updateConfig({allowedTypes:me.allowedTypes,maxFileSize:me.maxFileSize,maxFiles:me.maxFiles})}if(Q.querySelector(".persona-attachment-drop-overlay")?.remove(),Q.appendChild(Fw(o.attachments?.dropOverlay)),vt){let me=o.attachments??{},st=me.buttonTooltipText??"Attach file";vt.setAttribute("aria-label",st),vt.textContent="";let pt=parseFloat(o.sendButton?.size??"40px")||40,Et=fe(me.buttonIconName??"paperclip",Math.round(pt*.6),"currentColor",1.5);Et?vt.appendChild(Et):vt.textContent="\u{1F4CE}",yn&&hn({anchor:vt,trigger:yn,text:()=>vt?.getAttribute("aria-label")??st})}}else yn&&(yn.style.display="none"),Pt&&Pt.clearAttachments(),Q.querySelector(".persona-attachment-drop-overlay")?.remove();let Qt=o.sendButton??{},qp=Qt.useIcon??!1,ql=Qt.iconText??"\u2191",Ur=Qt.iconName,Ul=Qt.tooltipText??"Send message",Bx=Qt.showTooltip??!1,Yi=Qt.size??"40px",Kl=Qt.backgroundColor,Xi=Qt.textColor;if(qp){if(we.style.width=Yi,we.style.height=Yi,we.style.minWidth=Yi,we.style.minHeight=Yi,we.style.fontSize="18px",we.style.lineHeight="1",Xi?we.style.color=Xi:we.style.color="var(--persona-button-primary-fg, #ffffff)",!z.isStreaming())if(we.innerHTML="",Ur){let me=parseFloat(Yi)||24,st=Xi?.trim()||"currentColor",pt=fe(Ur,me,st,2);pt?we.appendChild(pt):we.textContent=ql}else we.textContent=ql;we.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Kl?(we.style.backgroundColor=Kl,we.classList.remove("persona-bg-persona-primary")):(we.style.backgroundColor="",we.classList.add("persona-bg-persona-primary"))}else we.textContent=o.copy?.sendButtonLabel??"Send",we.style.width="",we.style.height="",we.style.minWidth="",we.style.minHeight="",we.style.fontSize="",we.style.lineHeight="",we.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",Kl?(we.style.backgroundColor=Kl,we.classList.remove("persona-bg-persona-accent")):we.classList.add("persona-bg-persona-accent"),Xi?we.style.color=Xi:we.classList.add("persona-text-white");Qt.borderWidth?(we.style.borderWidth=Qt.borderWidth,we.style.borderStyle="solid"):(we.style.borderWidth="",we.style.borderStyle=""),Qt.borderColor?we.style.borderColor=Qt.borderColor:we.style.borderColor="",Qt.paddingX?(we.style.paddingLeft=Qt.paddingX,we.style.paddingRight=Qt.paddingX):(we.style.paddingLeft="",we.style.paddingRight=""),Qt.paddingY?(we.style.paddingTop=Qt.paddingY,we.style.paddingBottom=Qt.paddingY):(we.style.paddingTop="",we.style.paddingBottom=""),z.isStreaming()||we.setAttribute("aria-label",Ul),ct&&hn({anchor:we,trigger:ct,text:()=>we.getAttribute("aria-label")??Ul,enabled:Bx});let Hs=yr(o,oe());_d(),Hs?(ue.style.maxWidth=Hs,ue.style.marginLeft="auto",ue.style.marginRight="auto",ue.style.width="100%",cn.style.maxWidth=Hs,cn.style.marginLeft="auto",cn.style.marginRight="auto",cn.style.width="100%",_e&&(_e.style.maxWidth=Hs,_e.style.marginLeft="auto",_e.style.marginRight="auto"),Be&&(Be.style.maxWidth=Hs,Be.style.marginLeft="auto",Be.style.marginRight="auto"),Bt.style.maxWidth=Hs,Bt.style.marginLeft="auto",Bt.style.marginRight="auto"):(ue.style.maxWidth="",ue.style.marginLeft="",ue.style.marginRight="",ue.style.width="",cn.style.maxWidth="",cn.style.marginLeft="",cn.style.marginRight="",cn.style.width="",_e&&(_e.style.maxWidth="",_e.style.marginLeft="",_e.style.marginRight=""),Be&&(Be.style.maxWidth="",Be.style.marginLeft="",Be.style.marginRight=""),Bt.style.maxWidth="",Bt.style.marginLeft="",Bt.style.marginRight="");let ar=o.statusIndicator??{},Dx=ar.visible??!0;if(Bt.style.display=Dx?"":"none",z){let me=z.getStatus();S(Bt,(pt=>pt==="idle"?ar.idleText??Zt.idle:pt==="connecting"?ar.connectingText??Zt.connecting:pt==="connected"?ar.connectedText??Zt.connected:pt==="error"?ar.errorText??Zt.error:Zt[pt])(me),ar,me)}Bt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Nx=ar.align==="left"?"persona-text-left":ar.align==="center"?"persona-text-center":"persona-text-right";Bt.classList.add(Nx),lt()},open(){ee()&&xt(!0,"api")},close(){ee()&&xt(!1,"api")},toggle(){ee()&&xt(!M,"api")},reconnect(){z.reconnectNow()},clearChat(){Po=!1,z.clearMessages(),Fn.clear(),Rn();try{localStorage.removeItem(ci),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ci}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==ci)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let i=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(i),w?.clear&&dl(()=>w.clear(),"[AgentWidget] Failed to clear storage adapter:"),T={},F.syncFromMetadata(),Ee?.clear(),$e?.reset(),mt?.update()},setMessage(i){return!ye||z.isStreaming()?!1:(!M&&ee()&&xt(!0,"system"),ye.value=i,ye.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(i){if(z.isStreaming())return!1;let c=i?.trim()||ye.value.trim();return c?(!M&&ee()&&xt(!0,"system"),ye.value="",ye.style.height="auto",z.sendMessage(c),!0):!1},startVoiceRecognition(){return z.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(z.isVoiceActive()||(!M&&ee()&&xt(!0,"system"),rt.manuallyDeactivated=!1,po(),z.toggleVoice().then(()=>{rt.active=z.isVoiceActive(),Wo("user"),z.isVoiceActive()&&Ps()})),!0):wo?!0:Om()?(!M&&ee()&&xt(!0,"system"),rt.manuallyDeactivated=!1,po(),Fl("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?z.isVoiceActive()?(z.toggleVoice().then(()=>{rt.active=!1,rt.manuallyDeactivated=!0,po(),Wo("user"),$o()}),!0):!1:wo?(rt.manuallyDeactivated=!0,po(),sr("user"),!0):!1},injectMessage(i){return!M&&ee()&&xt(!0,"system"),z.injectMessage(i)},injectAssistantMessage(i){!M&&ee()&&xt(!0,"system");let c=z.injectAssistantMessage(i);return te&&(te=!1,pe&&(clearTimeout(pe),pe=null),setTimeout(()=>{z&&!z.isStreaming()&&z.continueConversation()},100)),c},injectUserMessage(i){return!M&&ee()&&xt(!0,"system"),z.injectUserMessage(i)},injectSystemMessage(i){return!M&&ee()&&xt(!0,"system"),z.injectSystemMessage(i)},injectMessageBatch(i){return!M&&ee()&&xt(!0,"system"),z.injectMessageBatch(i)},injectComponentDirective(i){return!M&&ee()&&xt(!0,"system"),z.injectComponentDirective(i)},injectTestMessage(i){!M&&ee()&&xt(!0,"system"),z.injectTestEvent(i)},async connectStream(i,c){return z.connectStream(i,c)},__pushEventStreamEvent(i){Ee&&($e?.processEvent(i.type,i.payload),Ee.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:i.type,timestamp:Date.now(),payload:JSON.stringify(i.payload)}))},showEventStream(){!ke||!Ee||Id()},hideEventStream(){At&&ds()},isEventStreamVisible(){return At},listConversations(i){return z.listConversations(i)},getActiveConversationId(){return z.getActiveConversationId()},openConversation(i,c){return Hp(i,{focusComposer:c?.focus===!0})},startNewConversation(i){return Rp({focusComposer:i?.focus===!0})},deleteConversation(i){return Lm(i)},renameConversation(i,c){return Wp(i,{title:c})},setConversationStarred(i,c){return Wp(i,{starred:c})},clearConversationHistory(i){return Im(i)},resetHistoryIdentity(){return Hm()},getHistoryIdentityStatus(){return Vn?Vn.getIdentityStatus():gp()?{state:"unavailable",reason:"ineligible_mode"}:{state:"unavailable",reason:"history_disabled"}},showHistory(i){return $i({...i?.returnSurface?{returnSurface:i.returnSurface}:{},...i?.focus!==void 0?{focus:i.focus}:{}})},hideHistory(i){Wn(i?.restoreFocus!==void 0?{restoreFocus:i.restoreFocus}:void 0)},isHistoryVisible(){return Te},showArtifacts(){Pn(o)&&(Po=!1,ps=!0,Lo(),tt?.setMobileOpen(!0))},hideArtifacts(){Pn(o)&&(Po=!0,Lo())},upsertArtifact(i){return Pn(o)?(dr(o.features?.artifacts,{artifactType:i.artifactType,...i.artifactType==="markdown"&&i.file?{file:i.file}:{},...i.presentation?{presentation:i.presentation}:{}})==="panel"&&(Po=!1,ps=!0),z.upsertArtifact(i)):null},selectArtifact(i){Pn(o)&&z.selectArtifact(i)},clearArtifacts(){Pn(o)&&z.clearArtifacts()},getArtifacts(){return z?.getArtifacts()??[]},getSelectedArtifactId(){return z?.getSelectedArtifactId()??null},focusInput(){return P&&!M&&!oe()||!ye?!1:(ye.focus(),!0)},async resolveApproval(i,c,f){let C=z.getMessages().find(L=>L.variant==="approval"&&L.approval?.id===i);if(!C?.approval)throw new Error(`Approval not found: ${i}`);if(C.approval.toolType==="webmcp"){z.resolveWebMcpApproval(C.id,c);return}return z.resolveApproval(C.approval,c,f)},setFollowUpSuggestions(i){iC(i)},clearFollowUpSuggestions(){Lf()},getMessages(){return z.getMessages()},getStatus(){return z.getStatus()},getPersistentMetadata(){return{...T}},updatePersistentMetadata(i){I(i)},on(i,c){return m.on(i,c)},off(i,c){m.off(i,c)},isOpen(){return ee()&&M},isVoiceActive(){return rt.active},toggleReadAloud(i){z.toggleReadAloud(i)},stopReadAloud(){z.stopSpeaking()},getReadAloudState(i){return z.getReadAloudState(i)},onReadAloudChange(i){return z.onReadAloudChange(i)},getState(){return{open:ee()&&M,launcherEnabled:P,voiceActive:rt.active,streaming:z.isStreaming()}},showCSATFeedback(i){!M&&ee()&&xt(!0,"system");let c=ue.querySelector(".persona-feedback-container");c&&c.remove();let f=Dw({onSubmit:async(h,C)=>{z.isClientTokenMode()&&await z.submitCSATFeedback(h,C),i?.onSubmit?.(h,C)},onDismiss:i?.onDismiss,...i});ue.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(i){!M&&ee()&&xt(!0,"system");let c=ue.querySelector(".persona-feedback-container");c&&c.remove();let f=Nw({onSubmit:async(h,C)=>{z.isClientTokenMode()&&await z.submitNPSFeedback(h,C),i?.onSubmit?.(h,C)},onDismiss:i?.onDismiss,...i});ue.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(i,c){return z.submitCSATFeedback(i,c)},async submitNPSFeedback(i,c){return z.submitNPSFeedback(i,c)},destroy(){ip(),$r!=null&&(clearInterval($r),$r=null),We.forEach(i=>i()),R.remove(),K?.remove(),Ot?.destroy(),Sn?.remove(),Lr&&Ke.removeEventListener("click",Lr)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let i=window.AgentWidgetBrowser,c={controller:_t,getMessages:_t.getMessages,getStatus:_t.getStatus,getMetadata:_t.getPersistentMetadata,updateMetadata:_t.updatePersistentMetadata,clearHistory:()=>_t.clearChat(),setVoiceActive:f=>f?_t.startVoiceRecognition():_t.stopVoiceRecognition()};window.AgentWidgetBrowser=c,We.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=i)})}if(typeof window<"u"){let i=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),c=ne=>{let le=ne.detail;(!le?.instanceId||le.instanceId===i)&&_t.focusInput()};if(window.addEventListener("persona:focusInput",c),We.push(()=>{window.removeEventListener("persona:focusInput",c)}),ke){let ne=be=>{let Ae=be.detail;(!Ae?.instanceId||Ae.instanceId===i)&&_t.showEventStream()},le=be=>{let Ae=be.detail;(!Ae?.instanceId||Ae.instanceId===i)&&_t.hideEventStream()};window.addEventListener("persona:showEventStream",ne),window.addEventListener("persona:hideEventStream",le),We.push(()=>{window.removeEventListener("persona:showEventStream",ne),window.removeEventListener("persona:hideEventStream",le)})}let f=ne=>{let le=ne.detail;(!le?.instanceId||le.instanceId===i)&&_t.showHistory()},h=ne=>{let le=ne.detail;(!le?.instanceId||le.instanceId===i)&&_t.hideHistory()};window.addEventListener("persona:showHistory",f),window.addEventListener("persona:hideHistory",h),We.push(()=>{window.removeEventListener("persona:showHistory",f),window.removeEventListener("persona:hideHistory",h)});let C=ne=>{let le=ne.detail;(!le?.instanceId||le.instanceId===i)&&_t.showArtifacts()},L=ne=>{let le=ne.detail;(!le?.instanceId||le.instanceId===i)&&_t.hideArtifacts()},X=ne=>{let le=ne.detail;le?.instanceId&&le.instanceId!==i||le?.artifact&&_t.upsertArtifact(le.artifact)},G=ne=>{let le=ne.detail;le?.instanceId&&le.instanceId!==i||typeof le?.id=="string"&&_t.selectArtifact(le.id)},ie=ne=>{let le=ne.detail;(!le?.instanceId||le.instanceId===i)&&_t.clearArtifacts()};window.addEventListener("persona:showArtifacts",C),window.addEventListener("persona:hideArtifacts",L),window.addEventListener("persona:upsertArtifact",X),window.addEventListener("persona:selectArtifact",G),window.addEventListener("persona:clearArtifacts",ie),We.push(()=>{window.removeEventListener("persona:showArtifacts",C),window.removeEventListener("persona:hideArtifacts",L),window.removeEventListener("persona:upsertArtifact",X),window.removeEventListener("persona:selectArtifact",G),window.removeEventListener("persona:clearArtifacts",ie)})}let eo=Hk(o.persistState);if(eo&&ee()){let i=Rk(eo.storage),c=`${eo.keyPrefix}widget-open`,f=`${eo.keyPrefix}widget-voice`,h=`${eo.keyPrefix}widget-voice-mode`;if(i){let C=eo.persist?.openState&&i.getItem(c)==="true",L=eo.persist?.voiceState&&i.getItem(f)==="true",X=eo.persist?.voiceState&&i.getItem(h)==="true";if(C&&(Ot?.setPanelOpen(!0,"auto"),setTimeout(()=>{_t.open(),setTimeout(()=>{if(L||X)_t.startVoiceRecognition();else if(eo.persist?.focusInput){let G=t.querySelector("textarea");G&&G.focus()}},100)},0)),eo.persist?.openState&&(m.on("widget:opened",()=>{i.setItem(c,"true")}),m.on("widget:closed",()=>{i.setItem(c,"false")})),eo.persist?.voiceState&&(m.on("voice:state",G=>{i.setItem(f,G.active?"true":"false")}),m.on("user:message",G=>{i.setItem(h,G.viaVoice?"true":"false")})),eo.clearOnChatClear){let G=()=>{i.removeItem(c),i.removeItem(f),i.removeItem(h)},ie=()=>G();window.addEventListener("persona:clear-chat",ie),We.push(()=>{window.removeEventListener("persona:clear-chat",ie)})}}}if(A&&ee()&&(Ot?.setPanelOpen(!0,"auto"),setTimeout(()=>{_t.open()},0)),ws(),!aC){let i=Xl(()=>{z&&(Fd++,Fn.clear(),Si(ue,z.getMessages(),xe))});We.push(i)}return _t};var zw=(t,e)=>{let n=t.trim(),o=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(o)return Math.max(0,parseFloat(o[1]));let r=/^(\d+(?:\.\d+)?)%$/i.exec(n);return r?Math.max(0,e*parseFloat(r[1])/100):420},Dk=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},Nk=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},Ok=(t,e)=>{let n=t.parentElement;if(!n)return;let o=t.ownerDocument.createElement("div");o.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(o);let r=o.offsetHeight>0;o.style.height="100%";let s=o.offsetHeight>0;o.remove(),!(!r||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(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.")},Vw=(t,e)=>{let n=e?.launcher?.enabled??!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0",t.style.minWidth=n?"":"0"},jg=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},jw=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",jg(t)},$g=t=>{t.style.transition=""},zg=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},Vg=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},kd=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},_k=(t,e,n,o,r)=>{r?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,o),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(o))},Fk=(t,e,n,o,r,s)=>{let a=s?e:t;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},$k=t=>{let e=Ys(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:En(e,r)??r;return{inset:o(n?.inset,Dc),canvasBackground:o(n?.canvasBackground,Nc)}},qw=(t,e,n,o)=>{if(!e){t.style.padding="",t.style.background="",t.style.boxSizing="";return}t.style.boxSizing="border-box",t.style.padding=n,t.style.background=o},zk=(t,e,n,o,r,s,a,l)=>{let d=ro(s),p=d.reveal==="push",u=l!=null,g=l?.inset??"",b=l?.canvasBackground??"";_k(t,e,n,o,p),Fk(t,e,n,o,d.side,p),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=d.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let m=t.ownerDocument.defaultView,y=s?.launcher?.mobileFullscreen??!0,w=s?.launcher?.mobileBreakpoint??640,T=m!=null?m.innerWidth<=w:!1;if(y&&T&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),zg(e),$g(o),jw(o),Vg(n),kd(r,o),qw(o,!1,"",""),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??mn),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",p&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),jw(o),Dk(o,d.maxHeight),qw(o,u&&a,g,b),d.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",zg(e),$g(o),Vg(n),kd(r,o);let E=d.animate?"transform 180ms ease":"none",k=d.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":k;o.style.display="flex",o.style.flexDirection="column",o.style.flex="none",o.style.position="absolute",o.style.top="0",o.style.bottom="0",o.style.width=d.width,o.style.maxWidth=d.width,o.style.minWidth=d.width,o.style.minHeight="0",o.style.overflow="hidden",o.style.transition=E,o.style.transform=A,o.style.pointerEvents=a?"auto":"none",o.style.zIndex="2",d.side==="right"?(o.style.right="0",o.style.left=""):(o.style.left="0",o.style.right="")}else if(d.reveal==="push"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",$g(o),jg(o),kd(r,o);let E=zw(d.width,t.clientWidth),k=Math.max(0,t.clientWidth),A=d.animate?"margin-left 180ms ease":"none",D=d.side==="right"?a?-E:0:a?0:-E;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=`${k+E}px`,e.style.transition=A,e.style.marginLeft=`${D}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${k}px`,n.style.maxWidth=`${k}px`,n.style.minWidth=`${k}px`,o.style.display="flex",o.style.flexDirection="column",o.style.flex="0 0 auto",o.style.flexShrink="0",o.style.width=d.width,o.style.minWidth=d.width,o.style.maxWidth=d.width,o.style.position="relative",o.style.top="",o.style.overflow="hidden",o.style.transition="none",o.style.pointerEvents=a?"auto":"none"}else{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",zg(e),jg(o),Vg(n),kd(r,o);let E=d.reveal==="emerge";E?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let k=a?d.width:"0px",A=d.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${u?", padding 180ms ease":""}`:"none",D=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${k}`,o.style.width=k,o.style.maxWidth=k,o.style.minWidth=k,o.style.minHeight="0",Nk(o,d.maxHeight),o.style.overflow=E||D?"hidden":"visible",o.style.transition=A,E){o.style.alignItems=d.side==="right"?"flex-start":"flex-end";let B=u?`calc(${zw(d.width,t.clientWidth)}px - (2 * ${g}))`:d.width;r.style.width=B,r.style.minWidth=B,r.style.maxWidth=B,r.style.boxSizing="border-box"}}},Vk=(t,e)=>{let n=t.ownerDocument.createElement("div");return Vw(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Vw(n,o)},destroy(){n.remove()}}},jk=(t,e)=>{let{ownerDocument:n}=t,o=t.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=t.tagName.toUpperCase();if(r==="BODY"||r==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=t.nextSibling,a=n.createElement("div"),l=n.createElement("div"),d=n.createElement("div"),p=n.createElement("aside"),u=n.createElement("div"),g=e?.launcher?.enabled??!0?e?.launcher?.autoExpand??!1:!0;l.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",p.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",p.appendChild(u),o.insertBefore(a,t),d.appendChild(t);let b=null,m=()=>{b?.disconnect(),b=null},y=null,w=()=>{y=e?.launcher?.detachedPanel===!0?$k(e):null};w();let T=()=>{zk(a,l,d,p,u,e,g,y)},W=null,E=()=>{W?.(),W=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(W=Oc(()=>{w(),T()}))},k=()=>{m(),ro(e).reveal==="push"&&(typeof ResizeObserver>"u"||(b=new ResizeObserver(()=>{T()}),b.observe(a)))},A=!1,D=()=>{T(),k(),g&&!A&&a.dataset.personaDockMobileFullscreen!=="true"&&(A=!0,Ok(a,ro(e)))},B=a.ownerDocument.defaultView,I=()=>{D()};return B?.addEventListener("resize",I),ro(e).reveal==="push"?(l.appendChild(d),l.appendChild(p),a.appendChild(l)):(a.appendChild(d),a.appendChild(p)),D(),E(),{mode:"docked",host:u,shell:a,syncWidgetState(N){let _=N.launcherEnabled?N.open:!0;g!==_&&(g=_,D())},updateConfig(N){e=N,(e?.launcher?.enabled??!0)===!1&&(g=!0),w(),D(),E()},destroy(){B?.removeEventListener("resize",I),W?.(),W=null,m(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),a.remove()}}},Uw=(t,e)=>Kt(e)?jk(t,e):Vk(t,e);var Ya={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Kw=.15,Gw=1.5,qg="persona-preview-shell-theme",qk={load:()=>null,save:()=>{},clear:()=>{}},Uk=["How do I get started?","Pricing & plans","Talk to support"];function Ug(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Kk(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function Yw(t){let e=Kk(t);return`* { box-sizing: border-box; }
314
1211
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
315
1212
  html { color-scheme: ${t}; }
316
1213
  body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
@@ -334,7 +1231,7 @@ _Details: ${n.message}_`:o}var _s=t=>({isError:!0,content:[{type:"text",text:t}]
334
1231
  .preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
335
1232
  .preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
336
1233
  .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}; }
337
- .preview-workspace-card.short { height: 96px; }`}function fh(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Dd);o||(o=n.createElement("style"),o.id=Dd,n.head.appendChild(o)),o.textContent=gh(e)}var RC=`
1234
+ .preview-workspace-card.short { height: 96px; }`}function Xw(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(qg);o||(o=n.createElement("style"),o.id=qg,n.head.appendChild(o)),o.textContent=Yw(e)}var Gk=`
338
1235
  <div class="preview-iframe-mock" aria-hidden="true">
339
1236
  <div class="preview-iframe-chrome">
340
1237
  <span class="preview-iframe-dot"></span>
@@ -353,7 +1250,7 @@ _Details: ${n.message}_`:o}var _s=t=>({isError:!0,content:[{type:"text",text:t}]
353
1250
  <div class="preview-iframe-line body"></div>
354
1251
  <div class="preview-iframe-line body"></div>
355
1252
  </div>
356
- </div>`,WC=`
1253
+ </div>`,Yk=`
357
1254
  <div class="preview-workspace-content-shell" aria-hidden="true">
358
1255
  <div class="preview-iframe-line hero"></div>
359
1256
  <div class="preview-iframe-line body"></div>
@@ -366,8 +1263,8 @@ _Details: ${n.message}_`:o}var _s=t=>({isError:!0,content:[{type:"text",text:t}]
366
1263
  <div class="preview-workspace-card short"></div>
367
1264
  <div class="preview-workspace-card short"></div>
368
1265
  </div>
369
- </div>`;function mh(t,e,n,o){let r=`
370
- ${RC}
1266
+ </div>`;function Qw(t,e,n,o){let r=`
1267
+ ${Gk}
371
1268
  <div style="position:fixed;inset:0;z-index:9999;"><div id="${t}" data-mount-id="${t}"></div></div>`,s=`
372
1269
  <div class="preview-workspace-shell">
373
1270
  <div class="preview-workspace-topbar">
@@ -379,7 +1276,7 @@ _Details: ${n.message}_`:o}var _s=t=>({isError:!0,content:[{type:"text",text:t}]
379
1276
  </div>
380
1277
  <div class="preview-workspace-body">
381
1278
  <div id="preview-content-${t}" class="preview-workspace-content" data-mount-id="${t}">
382
- ${WC}
1279
+ ${Yk}
383
1280
  </div>
384
1281
  </div>
385
1282
  </div>`;return`<!DOCTYPE html>
@@ -387,16 +1284,16 @@ _Details: ${n.message}_`:o}var _s=t=>({isError:!0,content:[{type:"text",text:t}]
387
1284
  <head>
388
1285
  <meta charset="UTF-8">
389
1286
  <meta name="viewport" content="width=device-width, initial-scale=1">
390
- <link rel="stylesheet" href="${Od(o)}">
391
- <style id="${Dd}">${gh(e)}</style>
1287
+ <link rel="stylesheet" href="${Ug(o)}">
1288
+ <style id="${qg}">${Yw(e)}</style>
392
1289
  </head>
393
1290
  <body>
394
1291
  ${n?s:r}
395
1292
  </body>
396
- </html>`}var HC=()=>[{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()}],BC=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function DC(t,e,n=[]){if(t==="follow-ups"){let o=Date.now();return[{id:"preview-follow-up-user",role:"user",content:"What can Persona help me build?",createdAt:new Date(o-12e4).toISOString()},{id:"preview-follow-up-assistant",role:"assistant",content:"Persona gives you a themeable streaming chat interface with flexible integrations and interaction patterns. Where would you like to go next?",createdAt:new Date(o-6e4).toISOString()},{id:"preview-follow-up-suggestions",role:"assistant",content:"",createdAt:new Date(o-59e3).toISOString(),streaming:!1,variant:"tool",toolCall:{id:"preview-follow-up-suggestions",name:"suggest_replies",status:"complete",args:{suggestions:[{id:"preview-implementation",label:"Show me an implementation",prompt:"Show me a practical implementation",description:"See a complete integration example",icon:"code-2",emphasis:"primary"},{id:"preview-theming",label:"Explore theming",prompt:"Tell me how theming works",description:"Customize colors, type, and component styles",icon:"palette"},{id:"preview-security",label:"Review security",prompt:"Explain the security model",description:"Learn about isolation and safe rendering",icon:"shield-check"},{id:"preview-support",label:"Talk to support",prompt:"Help me contact support",description:"Get help choosing the right approach",icon:"messages-square"}]},chunks:[]}},...n]}return t==="home"?[]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:t==="conversation"&&BC(e)?[...HC(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function OC(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:PC:t.suggestionChips,initialMessages:DC(e,t,n),storageAdapter:LC};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),r}function NC(t,e){let n=t.theme?_r(t.theme,{validate:!1}):_r();return{...it,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function ts(t,e){let n=t.scene??"conversation";return OC(NC(t,e),n,t.appendedMessages??[])}function hh(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:ts(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:ts(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let o={...t,config:t.baselineConfig??t.config,theme:t.baselineTheme??t.theme,darkTheme:t.baselineDarkTheme??t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:ts(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:ts(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:ts(t,n),shellMode:n}]}function bh(t,e){let n={...e},o=[],r=[],s=null,i=!1,l=1,p=1,c=0;function d(){return n.device??"desktop"}function g(){return n.zoom??l}function b(){let S=getComputedStyle(t),E=parseFloat(S.paddingLeft)+parseFloat(S.paddingRight),L=parseFloat(S.paddingTop)+parseFloat(S.paddingBottom),D=40,z=(n.compareMode??"off")!=="off",$=(t.clientWidth-E-D)/(z?2:1),F=t.clientHeight-L-D;if($<=0||F<=0)return 1;let B=hi[d()]??hi.desktop;return Math.min($/B.w,F/B.h,1)}function f(){l=b();let S=Math.max(ph,Math.min(uh,g()));p=S;let E=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let L of E){let D=L.dataset.device??"desktop",z=hi[D]??hi.desktop;L.style.width=`${z.w*S}px`,L.style.height=`${z.h*S}px`,D==="mobile"&&(L.style.borderRadius=`${32*S}px`);let $=L.querySelector("iframe");$&&($.style.width=`${z.w}px`,$.style.height=`${z.h}px`,$.style.transformOrigin="top left",$.style.transition="none",$.style.transform=`scale(${S})`)}n.onScaleChange?.(S)}function y(){n.onBeforeDestroy?.();for(let S of o)S.destroy();for(let S of r)S();o=[],r=[]}function C(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function M(){if(i)return;y();let S=++c,E=hh(n),L=d(),D=(n.compareMode??"off")!=="off",z=(n.scene??"conversation")==="minimized",$=n.widgetCssPath??"/widget-dist/widget.css",F=n.buildSrcdoc??mh,B=L==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",H=se=>`<div class="${B}" data-mount-id="${se.mountId}" data-device="${L}" data-shell-mode="${se.shellMode}">
397
- ${D?`<div class="preview-frame-meta"><span class="preview-frame-label">${Od(se.label)}</span></div>`:""}
398
- <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${se.mountId}"></iframe>
399
- </div>`,w=D?`<div class="preview-compare-grid">${E.map(se=>`<div class="preview-compare-cell">${H(se)}</div>`).join("")}</div>`:`<div class="preview-single">${H(E[0])}</div>`;n.morphContainer?n.morphContainer(t,w):t.innerHTML=w,f();let N=C(),K=0,te=N.length,Q=()=>{if(i||S!==c)return;for(let J of N){let oe=J.dataset.mountId;if(!oe||!J.contentDocument)continue;let Y=E.find(be=>be.mountId===oe);if(!Y)continue;let pe=()=>{},ne=Ot(Y.config),me=ne?(()=>{let be=J.contentDocument?.getElementById(`preview-content-${oe}`);if(!be)return null;let Te=dh(be,Y.config),ze=J.contentDocument.createElement("div");ze.id=oe,ze.style.height="100%",ze.style.display="flex",ze.style.flexDirection="column",ze.style.flex="1",ze.style.minHeight="0",Te.host.appendChild(ze);let Oe=()=>Te.syncWidgetState(ve.getState()),Ne=pe;return pe=()=>{Te.destroy(),Ne()},ze.__syncDock=Oe,ze.__hostLayout=Te,ze})():J.contentDocument.getElementById(oe);if(!me)continue;let ve=sh(me,Y.config);if(o.push(ve),ne&&me.__syncDock){let be=me.__syncDock,Te=ve.on("widget:opened",be),ze=ve.on("widget:closed",be),Oe=pe;pe=()=>{Te(),ze(),Oe()},be()}r.push(pe),z&&ve.close()}if((n.scene??"conversation")==="artifact"||n.config?.features?.artifacts?.enabled)for(let J of o)J.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
1293
+ </html>`}var Xk=()=>[{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()}],Qk=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function Jk(t,e,n=[]){if(t==="follow-ups"){let o=Date.now();return[{id:"preview-follow-up-user",role:"user",content:"What can Persona help me build?",createdAt:new Date(o-12e4).toISOString()},{id:"preview-follow-up-assistant",role:"assistant",content:"Persona gives you a themeable streaming chat interface with flexible integrations and interaction patterns. Where would you like to go next?",createdAt:new Date(o-6e4).toISOString()},{id:"preview-follow-up-suggestions",role:"assistant",content:"",createdAt:new Date(o-59e3).toISOString(),streaming:!1,variant:"tool",toolCall:{id:"preview-follow-up-suggestions",name:"suggest_replies",status:"complete",args:{suggestions:[{id:"preview-implementation",label:"Show me an implementation",prompt:"Show me a practical implementation",description:"See a complete integration example",icon:"code-2",emphasis:"primary"},{id:"preview-theming",label:"Explore theming",prompt:"Tell me how theming works",description:"Customize colors, type, and component styles",icon:"palette"},{id:"preview-security",label:"Review security",prompt:"Explain the security model",description:"Learn about isolation and safe rendering",icon:"shield-check"},{id:"preview-support",label:"Talk to support",prompt:"Help me contact support",description:"Get help choosing the right approach",icon:"messages-square"}]},chunks:[]}},...n]}return t==="home"?[]:t==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:t==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:t==="conversation"&&Qk(e)?[...Xk(),...n]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...n]}function Zk(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:Uk:t.suggestionChips,initialMessages:Jk(e,t,n),storageAdapter:qk};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),e==="messages"&&(r.features={...r.features,history:{presentation:"panel",...r.features?.history,enabled:!0}}),r}function e0(t,e){let n=t.theme?Gs(t.theme,{validate:!1}):Gs();return{...ft,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function di(t,e){let n=t.scene??"conversation";return Zk(e0(t,e),n,t.appendedMessages??[])}function Jw(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:di(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:di(t,"dark"),shellMode:"dark"}];if(e==="baseline"&&(t.baselineConfig||t.baselineTheme)){let o={...t,config:t.baselineConfig??t.config,theme:t.baselineTheme??t.theme,darkTheme:t.baselineDarkTheme??t.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:di(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:di(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:di(t,n),shellMode:n}]}function Zw(t,e){let n={...e},o=[],r=[],s=null,a=!1,l=1,d=1,p=0;function u(){return n.device??"desktop"}function g(){return n.zoom??l}function b(){let E=getComputedStyle(t),k=parseFloat(E.paddingLeft)+parseFloat(E.paddingRight),A=parseFloat(E.paddingTop)+parseFloat(E.paddingBottom),D=40,B=(n.compareMode??"off")!=="off",I=(t.clientWidth-k-D)/(B?2:1),N=t.clientHeight-A-D;if(I<=0||N<=0)return 1;let _=Ya[u()]??Ya.desktop;return Math.min(I/_.w,N/_.h,1)}function m(){l=b();let E=Math.max(Kw,Math.min(Gw,g()));d=E;let k=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let A of k){let D=A.dataset.device??"desktop",B=Ya[D]??Ya.desktop;A.style.width=`${B.w*E}px`,A.style.height=`${B.h*E}px`,D==="mobile"&&(A.style.borderRadius=`${32*E}px`);let I=A.querySelector("iframe");I&&(I.style.width=`${B.w}px`,I.style.height=`${B.h}px`,I.style.transformOrigin="top left",I.style.transition="none",I.style.transform=`scale(${E})`)}n.onScaleChange?.(E)}function y(){n.onBeforeDestroy?.();for(let E of o)E.destroy();for(let E of r)E();o=[],r=[]}function w(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function T(){if(a)return;y();let E=++p,k=Jw(n),A=u(),D=(n.compareMode??"off")!=="off",B=(n.scene??"conversation")==="minimized",I=n.widgetCssPath??"/widget-dist/widget.css",N=n.buildSrcdoc??Qw,_=A==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",F=ge=>`<div class="${_}" data-mount-id="${ge.mountId}" data-device="${A}" data-shell-mode="${ge.shellMode}">
1294
+ ${D?`<div class="preview-frame-meta"><span class="preview-frame-label">${Ug(ge.label)}</span></div>`:""}
1295
+ <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${ge.mountId}"></iframe>
1296
+ </div>`,P=D?`<div class="preview-compare-grid">${k.map(ge=>`<div class="preview-compare-cell">${F(ge)}</div>`).join("")}</div>`:`<div class="preview-single">${F(k[0])}</div>`;n.morphContainer?n.morphContainer(t,P):t.innerHTML=P,m();let V=w(),se=0,ve=V.length,he=()=>{if(a||E!==p)return;for(let re of V){let oe=re.dataset.mountId;if(!oe||!re.contentDocument)continue;let ee=k.find(xe=>xe.mountId===oe);if(!ee)continue;let M=()=>{},te=Kt(ee.config),pe=te?(()=>{let xe=re.contentDocument?.getElementById(`preview-content-${oe}`);if(!xe)return null;let Ce=Uw(xe,ee.config),Me=re.contentDocument.createElement("div");Me.id=oe,Me.style.height="100%",Me.style.display="flex",Me.style.flexDirection="column",Me.style.flex="1",Me.style.minHeight="0",Ce.host.appendChild(Me);let ke=()=>Ce.syncWidgetState(Se.getState()),Oe=M;return M=()=>{Ce.destroy(),Oe()},Me.__syncDock=ke,Me.__hostLayout=Ce,Me})():re.contentDocument.getElementById(oe);if(!pe)continue;let Se=$w(pe,ee.config);if(o.push(Se),te&&pe.__syncDock){let xe=pe.__syncDock,Ce=Se.on("widget:opened",xe),Me=Se.on("widget:closed",xe),ke=M;M=()=>{Ce(),Me(),ke()},xe()}r.push(M),B&&Se.close()}let ge=n.scene??"conversation";if(ge==="messages")for(let re of o)re.showHistory({focus:!1});if(ge==="artifact"||n.config?.features?.artifacts?.enabled)for(let re of o)re.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
400
1297
 
401
1298
  This is a preview of the artifact sidebar.
402
1299
 
@@ -404,4 +1301,4 @@ This is a preview of the artifact sidebar.
404
1301
 
405
1302
  - Markdown rendering
406
1303
  - Document toolbar
407
- - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:N,controllers:[...o]})};for(let se of N){let J=se.dataset.mountId;if(!J)continue;let oe=E.find(Y=>Y.mountId===J);oe&&(se.addEventListener("load",()=>{K++,K>=te&&Q()},{once:!0}),se.srcdoc=F(J,oe.shellMode,Ot(oe.config),$))}te===0&&Q()}function I(){if(i)return;let S=hh(n);if(o.length!==S.length){M();return}if(S.some(L=>{let D=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${L.mountId}"]`);return!D||D.dataset.shellMode!==L.shellMode})){M();return}o.forEach((L,D)=>{L.update(S[D].config),(n.scene??"conversation")==="minimized"&&L.close()});for(let L of S){let D=t.querySelector(`iframe[data-mount-id="${L.mountId}"]`);D&&fh(D,L.shellMode)}n.onAfterUpdate?.({iframes:C(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{i||f()}),s.observe(t)),M(),{update(S){if(i)return;let E=S.device!==void 0&&S.device!==n.device||S.scene!==void 0&&S.scene!==n.scene||S.compareMode!==void 0&&S.compareMode!==n.compareMode||S.widgetCssPath!==void 0&&S.widgetCssPath!==n.widgetCssPath;n={...n,...S},E?M():I()},destroy(){i||(i=!0,y(),s?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){i||(n={...n,zoom:void 0},f())},getIframes(){return C()},getScale(){return p},setZoom(S){i||(n={...n,zoom:S},f())}}}0&&(module.exports={createThemePreview});
1304
+ - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:V,controllers:[...o]})};for(let ge of V){let re=ge.dataset.mountId;if(!re)continue;let oe=k.find(ee=>ee.mountId===re);oe&&(ge.addEventListener("load",()=>{se++,se>=ve&&he()},{once:!0}),ge.srcdoc=N(re,oe.shellMode,Kt(oe.config),I))}ve===0&&he()}function W(){if(a)return;let E=Jw(n);if(o.length!==E.length){T();return}if(E.some(A=>{let D=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${A.mountId}"]`);return!D||D.dataset.shellMode!==A.shellMode})){T();return}o.forEach((A,D)=>{A.update(E[D].config),(n.scene??"conversation")==="minimized"&&A.close()});for(let A of E){let D=t.querySelector(`iframe[data-mount-id="${A.mountId}"]`);D&&Xw(D,A.shellMode)}n.onAfterUpdate?.({iframes:w(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(t)),T(),{update(E){if(a)return;let k=E.device!==void 0&&E.device!==n.device||E.scene!==void 0&&E.scene!==n.scene||E.compareMode!==void 0&&E.compareMode!==n.compareMode||E.widgetCssPath!==void 0&&E.widgetCssPath!==n.widgetCssPath;n={...n,...E},k?T():W()},destroy(){a||(a=!0,y(),s?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){a||(n={...n,zoom:void 0},m())},getIframes(){return w()},getScale(){return d},setZoom(E){a||(n={...n,zoom:E},m())}}}0&&(module.exports={createThemePreview});