@runtypelabs/persona 4.11.0 → 4.12.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.
@@ -1,6 +1,6 @@
1
- "use strict";var um=Object.create;var ri=Object.defineProperty;var gm=Object.getOwnPropertyDescriptor;var fm=Object.getOwnPropertyNames;var mm=Object.getPrototypeOf,hm=Object.prototype.hasOwnProperty;var yt=(t,e)=>()=>(t&&(e=t(t=0)),e);var Jo=(t,e)=>{for(var n in e)ri(t,n,{get:e[n],enumerable:!0})},Dd=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of fm(e))!hm.call(t,r)&&r!==n&&ri(t,r,{get:()=>e[r],enumerable:!(o=gm(e,r))||o.enumerable});return t};var Nd=(t,e,n)=>(n=t!=null?um(mm(t)):{},Dd(e||!t||!t.__esModule?ri(n,"default",{value:t,enumerable:!0}):n,t)),bm=t=>Dd(ri({},"__esModule",{value:!0}),t);var _d={};Jo(_d,{DOMPurify:()=>Fd.default,Marked:()=>Od.Marked});var Od,Fd,$d=yt(()=>{"use strict";Od=require("marked"),Fd=Nd(require("dompurify"),1)});var h,op,xe,Fn,tt=yt(()=>{"use strict";h=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},op=()=>document.createDocumentFragment(),xe=(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},Fn=(...t)=>t.filter(Boolean).join(" ")});var ar,hl=yt(()=>{"use strict";ar=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 Eh(t){return t.replace(/\/+$/,"")}async function kh(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 Si,Bp=yt(()=>{"use strict";hl();Si=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 ar(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=`${Eh(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 kh(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 Mi,Dp=yt(()=>{"use strict";Mi=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 Np={};Jo(Np,{FallbackSpeechEngine:()=>Mi,RuntypeSpeechEngine:()=>Si});var Op=yt(()=>{"use strict";Bp();Dp()});var _p={};Jo(_p,{createReconnectController:()=>Ph});function Ph(t){let e=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let m=n;n=null,m()}},i=()=>{let m=t.getStatus();m!=="resuming"&&m!=="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)},u=m=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},m)}),y=()=>{let m=t.getResumable();t.clearResumable(),t.setReconnecting(!1),e=0,d(),t.setAbortController(null);let C=!1;for(let B of t.getMessages())B.streaming&&(B.streaming=!1,C=!0);let D=t.buildErrorContent("Connection lost and the response could not be resumed.");D?t.appendMessage({id:`reconnect-failed-${m?.executionId??t.nextSequence()}`,role:"assistant",content:D,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."))},g=async()=>{let m=t.config.reconnect?.backoffMs??Lh,C=t.config.reconnect?.maxAttempts??m.length,D=t.config.reconnectStream;if(!D){t.setReconnecting(!1);return}for(;t.getResumable()&&e<C;){e+=1,t.setStatus("resuming");let B=t.getResumable(),E=B.lastEventId,A=new AbortController;t.setAbortController(A),t.emitReconnect({phase:"resuming",handle:B,attempt:e});let W=null;try{let z=await D({executionId:B.executionId,after:B.lastEventId,signal:A.signal});z&&z.ok&&z.body&&(W=z.body)}catch{W=null}if(A.signal.aborted)return;if(W){let z=t.getMessages().find(w=>w.id===B.assistantMessageId)?.content,G=typeof z=="string"?z:"";try{await t.resumeConnect(W,B.assistantMessageId,G)}catch{}if(A.signal.aborted)return;if(!t.getResumable()){t.setReconnecting(!1),e=0,d(),t.emitReconnect({phase:"resumed",handle:B});return}t.getResumable().lastEventId!==E&&(e=0)}if(t.getResumable()&&e<C&&(t.setStatus("paused"),await u(m[Math.min(e-1,m.length-1)]??1e3),A.signal.aborted))return}t.getResumable()&&y()};return{begin(){e=0,c(),g()},teardown(){o&&(clearTimeout(o),o=null),n=null,e=0,d()},wake:s}}var Lh,$p=yt(()=>{"use strict";Lh=[1e3,2e3,4e3,8e3,8e3]});function Hh(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 M,Wh,se,Mt=yt(()=>{"use strict";M=require("lucide"),Wh={activity:M.Activity,"arrow-down":M.ArrowDown,"arrow-up":M.ArrowUp,"arrow-up-right":M.ArrowUpRight,bot:M.Bot,"chevron-down":M.ChevronDown,"chevron-up":M.ChevronUp,"chevron-right":M.ChevronRight,"chevron-left":M.ChevronLeft,check:M.Check,clipboard:M.Clipboard,"clipboard-copy":M.ClipboardCopy,"code-xml":M.CodeXml,copy:M.Copy,file:M.File,"file-code":M.FileCode,"file-spreadsheet":M.FileSpreadsheet,"file-text":M.FileText,"image-plus":M.ImagePlus,loader:M.Loader,"loader-circle":M.LoaderCircle,mic:M.Mic,paperclip:M.Paperclip,"refresh-cw":M.RefreshCw,search:M.Search,send:M.Send,"shield-alert":M.ShieldAlert,"shield-check":M.ShieldCheck,"shield-x":M.ShieldX,square:M.Square,"thumbs-down":M.ThumbsDown,"thumbs-up":M.ThumbsUp,upload:M.Upload,"volume-2":M.Volume2,x:M.X,user:M.User,mail:M.Mail,phone:M.Phone,calendar:M.Calendar,clock:M.Clock,building:M.Building,"map-pin":M.MapPin,lock:M.Lock,key:M.Key,"credit-card":M.CreditCard,"at-sign":M.AtSign,hash:M.Hash,globe:M.Globe,link:M.Link,"circle-check":M.CircleCheck,"circle-x":M.CircleX,"triangle-alert":M.TriangleAlert,info:M.Info,ban:M.Ban,shield:M.Shield,"arrow-left":M.ArrowLeft,"arrow-right":M.ArrowRight,"external-link":M.ExternalLink,ellipsis:M.Ellipsis,"ellipsis-vertical":M.EllipsisVertical,menu:M.Menu,house:M.House,plus:M.Plus,minus:M.Minus,pencil:M.Pencil,trash:M.Trash,"trash-2":M.Trash2,save:M.Save,download:M.Download,share:M.Share,funnel:M.Funnel,settings:M.Settings,"rotate-cw":M.RotateCw,maximize:M.Maximize,minimize:M.Minimize,"shopping-cart":M.ShoppingCart,"shopping-bag":M.ShoppingBag,package:M.Package,truck:M.Truck,tag:M.Tag,gift:M.Gift,receipt:M.Receipt,wallet:M.Wallet,store:M.Store,"dollar-sign":M.DollarSign,percent:M.Percent,play:M.Play,pause:M.Pause,"volume-x":M.VolumeX,camera:M.Camera,image:M.Image,film:M.Film,headphones:M.Headphones,"message-circle":M.MessageCircle,"message-square":M.MessageSquare,bell:M.Bell,heart:M.Heart,star:M.Star,eye:M.Eye,"eye-off":M.EyeOff,bookmark:M.Bookmark,"calendar-days":M.CalendarDays,history:M.History,timer:M.Timer,folder:M.Folder,"folder-open":M.FolderOpen,files:M.Files,sparkles:M.Sparkles,zap:M.Zap,sun:M.Sun,moon:M.Moon,flag:M.Flag,monitor:M.Monitor,smartphone:M.Smartphone},se=(t,e=24,n="currentColor",o=2)=>{let r=Wh[t];return r?Hh(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 Nh(t,e,n){if(n==="input-start")return e===0;let o=e>0?t[e-1]:"";return n==="line-start"?o===""||o===`
1
+ "use strict";var um=Object.create;var ri=Object.defineProperty;var gm=Object.getOwnPropertyDescriptor;var fm=Object.getOwnPropertyNames;var mm=Object.getPrototypeOf,hm=Object.prototype.hasOwnProperty;var bt=(t,e)=>()=>(t&&(e=t(t=0)),e);var Jo=(t,e)=>{for(var n in e)ri(t,n,{get:e[n],enumerable:!0})},Dd=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of fm(e))!hm.call(t,r)&&r!==n&&ri(t,r,{get:()=>e[r],enumerable:!(o=gm(e,r))||o.enumerable});return t};var Nd=(t,e,n)=>(n=t!=null?um(mm(t)):{},Dd(e||!t||!t.__esModule?ri(n,"default",{value:t,enumerable:!0}):n,t)),bm=t=>Dd(ri({},"__esModule",{value:!0}),t);var _d={};Jo(_d,{DOMPurify:()=>Fd.default,Marked:()=>Od.Marked});var Od,Fd,$d=bt(()=>{"use strict";Od=require("marked"),Fd=Nd(require("dompurify"),1)});var h,op,xe,Fn,nt=bt(()=>{"use strict";h=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},op=()=>document.createDocumentFragment(),xe=(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},Fn=(...t)=>t.filter(Boolean).join(" ")});var ar,hl=bt(()=>{"use strict";ar=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 Eh(t){return t.replace(/\/+$/,"")}async function kh(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 Si,Bp=bt(()=>{"use strict";hl();Si=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 ar(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=`${Eh(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 kh(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 Mi,Dp=bt(()=>{"use strict";Mi=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 Np={};Jo(Np,{FallbackSpeechEngine:()=>Mi,RuntypeSpeechEngine:()=>Si});var Op=bt(()=>{"use strict";Bp();Dp()});var _p={};Jo(_p,{createReconnectController:()=>Ph});function Ph(t){let e=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let m=n;n=null,m()}},i=()=>{let m=t.getStatus();m!=="resuming"&&m!=="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)},u=m=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},m)}),y=()=>{let m=t.getResumable();t.clearResumable(),t.setReconnecting(!1),e=0,d(),t.setAbortController(null);let C=!1;for(let B of t.getMessages())B.streaming&&(B.streaming=!1,C=!0);let D=t.buildErrorContent("Connection lost and the response could not be resumed.");D?t.appendMessage({id:`reconnect-failed-${m?.executionId??t.nextSequence()}`,role:"assistant",content:D,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."))},g=async()=>{let m=t.config.reconnect?.backoffMs??Lh,C=t.config.reconnect?.maxAttempts??m.length,D=t.config.reconnectStream;if(!D){t.setReconnecting(!1);return}for(;t.getResumable()&&e<C;){e+=1,t.setStatus("resuming");let B=t.getResumable(),E=B.lastEventId,A=new AbortController;t.setAbortController(A),t.emitReconnect({phase:"resuming",handle:B,attempt:e});let W=null;try{let z=await D({executionId:B.executionId,after:B.lastEventId,signal:A.signal});z&&z.ok&&z.body&&(W=z.body)}catch{W=null}if(A.signal.aborted)return;if(W){let z=t.getMessages().find(w=>w.id===B.assistantMessageId)?.content,G=typeof z=="string"?z:"";try{await t.resumeConnect(W,B.assistantMessageId,G)}catch{}if(A.signal.aborted)return;if(!t.getResumable()){t.setReconnecting(!1),e=0,d(),t.emitReconnect({phase:"resumed",handle:B});return}t.getResumable().lastEventId!==E&&(e=0)}if(t.getResumable()&&e<C&&(t.setStatus("paused"),await u(m[Math.min(e-1,m.length-1)]??1e3),A.signal.aborted))return}t.getResumable()&&y()};return{begin(){e=0,c(),g()},teardown(){o&&(clearTimeout(o),o=null),n=null,e=0,d()},wake:s}}var Lh,$p=bt(()=>{"use strict";Lh=[1e3,2e3,4e3,8e3,8e3]});function Hh(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 M,Wh,se,St=bt(()=>{"use strict";M=require("lucide"),Wh={activity:M.Activity,"arrow-down":M.ArrowDown,"arrow-up":M.ArrowUp,"arrow-up-right":M.ArrowUpRight,bot:M.Bot,"chevron-down":M.ChevronDown,"chevron-up":M.ChevronUp,"chevron-right":M.ChevronRight,"chevron-left":M.ChevronLeft,check:M.Check,clipboard:M.Clipboard,"clipboard-copy":M.ClipboardCopy,"code-xml":M.CodeXml,copy:M.Copy,file:M.File,"file-code":M.FileCode,"file-spreadsheet":M.FileSpreadsheet,"file-text":M.FileText,"image-plus":M.ImagePlus,loader:M.Loader,"loader-circle":M.LoaderCircle,mic:M.Mic,paperclip:M.Paperclip,"refresh-cw":M.RefreshCw,search:M.Search,send:M.Send,"shield-alert":M.ShieldAlert,"shield-check":M.ShieldCheck,"shield-x":M.ShieldX,square:M.Square,"thumbs-down":M.ThumbsDown,"thumbs-up":M.ThumbsUp,upload:M.Upload,"volume-2":M.Volume2,x:M.X,user:M.User,mail:M.Mail,phone:M.Phone,calendar:M.Calendar,clock:M.Clock,building:M.Building,"map-pin":M.MapPin,lock:M.Lock,key:M.Key,"credit-card":M.CreditCard,"at-sign":M.AtSign,hash:M.Hash,globe:M.Globe,link:M.Link,"circle-check":M.CircleCheck,"circle-x":M.CircleX,"triangle-alert":M.TriangleAlert,info:M.Info,ban:M.Ban,shield:M.Shield,"arrow-left":M.ArrowLeft,"arrow-right":M.ArrowRight,"external-link":M.ExternalLink,ellipsis:M.Ellipsis,"ellipsis-vertical":M.EllipsisVertical,menu:M.Menu,house:M.House,plus:M.Plus,minus:M.Minus,pencil:M.Pencil,trash:M.Trash,"trash-2":M.Trash2,save:M.Save,download:M.Download,share:M.Share,funnel:M.Funnel,settings:M.Settings,"rotate-cw":M.RotateCw,maximize:M.Maximize,minimize:M.Minimize,"shopping-cart":M.ShoppingCart,"shopping-bag":M.ShoppingBag,package:M.Package,truck:M.Truck,tag:M.Tag,gift:M.Gift,receipt:M.Receipt,wallet:M.Wallet,store:M.Store,"dollar-sign":M.DollarSign,percent:M.Percent,play:M.Play,pause:M.Pause,"volume-x":M.VolumeX,camera:M.Camera,image:M.Image,film:M.Film,headphones:M.Headphones,"message-circle":M.MessageCircle,"message-square":M.MessageSquare,bell:M.Bell,heart:M.Heart,star:M.Star,eye:M.Eye,"eye-off":M.EyeOff,bookmark:M.Bookmark,"calendar-days":M.CalendarDays,history:M.History,timer:M.Timer,folder:M.Folder,"folder-open":M.FolderOpen,files:M.Files,sparkles:M.Sparkles,zap:M.Zap,sun:M.Sun,moon:M.Moon,flag:M.Flag,monitor:M.Monitor,smartphone:M.Smartphone},se=(t,e=24,n="currentColor",o=2)=>{let r=Wh[t];return r?Hh(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 Nh(t,e,n){if(n==="input-start")return e===0;let o=e>0?t[e-1]:"";return n==="line-start"?o===""||o===`
2
2
  `:o===""||jp.test(o)}function Oh(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 Nh(t,s,o)?{triggerIndex:s,query:t.slice(s+1,e)}:null;if(i===`
3
- `||i==="\uFFFC"||!r&&jp.test(i))return null;s--}return null}function rs(t,e,n){for(let o of n){let r=Oh(t,e,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function qp(t){return t?t!=="insertFromPaste"&&t!=="insertFromDrop":!0}function Vp(t,e,n){return{value:t.slice(0,e.triggerIndex)+t.slice(n),caret:e.triggerIndex}}var jp,ki=yt(()=>{"use strict";jp=/\s/});function Li(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 Cl=yt(()=>{"use strict"});function Qp(t){let{ref:e,config:n,onRemove:o}=t;if(n.renderMentionChip){let g="resolving",m,C=n.renderMentionChip({ref:e,status:g,payload:m,remove:o});return{get el(){return C},setStatus:(B,E)=>{if(B===g&&E===m)return;g=B,m=E;let A=n.renderMentionChip({ref:e,status:g,payload:m,remove:o});C.replaceWith(A),C=A}}}let r=e.iconName??n.chipIconName??"at-sign",s=xe("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:e.label}}),i=h("span","persona-mention-chip-icon"),l=g=>{i.replaceChildren();let m=se(g,13,"currentColor",2);m&&i.appendChild(m)};l(r);let p=h("span","persona-mention-chip-spinner"),c=xe("span",{className:"persona-mention-chip-label",text:e.label}),d=xe("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${e.label} context`}}),u=se("x",11,"currentColor",2.5);return u?d.appendChild(u):d.textContent="\xD7",d.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),o()}),s.appendChild(p),s.appendChild(c),s.appendChild(d),{el:s,setStatus:g=>{s.setAttribute("data-status",g),g==="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),g==="error"?(l("triangle-alert"),s.setAttribute("title",`Couldn't add ${e.label} to context`)):(l(r),s.setAttribute("title",e.label)))}}}var Xp=yt(()=>{"use strict";tt();Mt()});function zh(t){let e=0;for(let n of t.split(`
3
+ `||i==="\uFFFC"||!r&&jp.test(i))return null;s--}return null}function rs(t,e,n){for(let o of n){let r=Oh(t,e,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function qp(t){return t?t!=="insertFromPaste"&&t!=="insertFromDrop":!0}function Vp(t,e,n){return{value:t.slice(0,e.triggerIndex)+t.slice(n),caret:e.triggerIndex}}var jp,ki=bt(()=>{"use strict";jp=/\s/});function Li(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 Cl=bt(()=>{"use strict"});function Qp(t){let{ref:e,config:n,onRemove:o}=t;if(n.renderMentionChip){let g="resolving",m,C=n.renderMentionChip({ref:e,status:g,payload:m,remove:o});return{get el(){return C},setStatus:(B,E)=>{if(B===g&&E===m)return;g=B,m=E;let A=n.renderMentionChip({ref:e,status:g,payload:m,remove:o});C.replaceWith(A),C=A}}}let r=e.iconName??n.chipIconName??"at-sign",s=xe("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:e.label}}),i=h("span","persona-mention-chip-icon"),l=g=>{i.replaceChildren();let m=se(g,13,"currentColor",2);m&&i.appendChild(m)};l(r);let p=h("span","persona-mention-chip-spinner"),c=xe("span",{className:"persona-mention-chip-label",text:e.label}),d=xe("button",{className:"persona-mention-chip-remove",attrs:{type:"button","aria-label":`Remove ${e.label} context`}}),u=se("x",11,"currentColor",2.5);return u?d.appendChild(u):d.textContent="\xD7",d.addEventListener("click",g=>{g.preventDefault(),g.stopPropagation(),o()}),s.appendChild(p),s.appendChild(c),s.appendChild(d),{el:s,setStatus:g=>{s.setAttribute("data-status",g),g==="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),g==="error"?(l("triangle-alert"),s.setAttribute("title",`Couldn't add ${e.label} to context`)):(l(r),s.setAttribute("title",e.label)))}}}var Xp=bt(()=>{"use strict";nt();St()});function zh(t){let e=0;for(let n of t.split(`
4
4
  `)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>e&&(e=o[1].length)}return e}function Ml(t,e){let n="`".repeat(Math.max(3,zh(e)+1));return`${n}${t}
5
5
  ${e}
6
6
  ${n}`}function Uh(t,e,n){return e.includes("</document_content>")?Ml(t,e):`<document index="${n+1}">
@@ -8,7 +8,7 @@ ${n}`}function Uh(t,e,n){return e.includes("</document_content>")?Ml(t,e):`<docu
8
8
  <document_content>
9
9
  ${e}
10
10
  </document_content>
11
- </document>`}function Jp(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),Ml(t.label,t.text)}return n==="document"?Uh(t.label,t.text,e):Ml(t.label,t.text)}var Yp=yt(()=>{"use strict"});function Ii(t,e){return{sourceId:t.id,itemId:e.id,label:e.label,iconName:e.iconName,color:e.color}}var Zp,Ri,Tl=yt(()=>{"use strict";Xp();Yp();Zp=(t,e)=>`${t}\0${e}`,Ri=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=Zp(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=Ii(e,n),i={key:r,source:e,item:n,ref:s,status:"resolving",args:o};return i.chip=Qp({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:Ii(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 u=>{try{return u.source.resolveOn==="submit"?await u.source.resolve(u.item,this.buildResolveContext(new AbortController().signal,u.args,o)):(u.resolvePromise&&await u.resolvePromise,u.payload??null)}catch(y){try{this.opts.mentionConfig.onMentionResolveError?.(u.item,y)}catch(g){typeof console<"u"&&console.warn("[Persona] onMentionResolveError callback threw",g)}return this.opts.emit?.("resolve-error",{sourceId:u.source.id,itemId:u.item.id}),null}})),i=[],l=[],p={},c=new Set;for(let u=0;u<e.length;u++){let y=e[u],g=s[u];if(!g)continue;let m=Zp(y.source.id,y.item.id);if(!c.has(m)){if(c.add(m),g.llmAppend&&g.llmAppend.trim())try{i.push(Jp({label:y.ref.label,text:g.llmAppend,ref:y.ref,item:y.item},i.length,this.opts.mentionConfig.llmFormat))}catch(C){typeof console<"u"&&console.warn("[Persona] context-mention llmFormat threw",C)}g.contentParts?.length&&l.push(...g.contentParts),g.context&&((p[d=y.source.id]??(p[d]={}))[y.item.id]=g.context)}}return{blocks:i,contentParts:l,context:p}}}}updateRowVisibility(){this.opts.contextRow.style.display=this.mentions.length>0?"flex":"none"}}});function eu(t){let e=t.getRootNode?.();return e instanceof ShadowRoot||e instanceof Document?e:t.ownerDocument??document}function Wi(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 tu(t,e,n){if(t instanceof Document||t instanceof ShadowRoot){Wi(t,e,n);return}let o=t;if(o.isConnected){Wi(eu(o),e,n);return}let r=o.ownerDocument??document;Wi(r,e,n),queueMicrotask(()=>{let s=eu(o);s!==r&&Wi(s,e,n)})}function jh(t){let e=t.getRootNode?.();return e instanceof ShadowRoot?e:(t.ownerDocument??document).body}function Hi(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,u=t.container??jh(e),y=!1,g=null,m=()=>{if(!y)return;let B=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${B.width}px`),i&&(n.style.maxWidth=`${B.width}px`);let E=n.getBoundingClientRect(),A=l?.()??null,W=A!=null?B.top+A:B.top,z=o==="top-start"||o==="top-end"?W-r-E.height:B.bottom+r,w=o==="bottom-end"||o==="top-end"?B.right-E.width:B.left,O=i?.()??null;if(O!=null){let N=Math.max(B.left,B.right-E.width);w=Math.min(Math.max(B.left+O,B.left),N)}n.style.top=`${z}px`,n.style.left=`${w}px`},C=()=>{y&&(y=!1,g&&(g(),g=null),n.remove())},D=()=>{if(y)return;y=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),m();let B=(e.ownerDocument??document).defaultView??window,E=e.ownerDocument??document,A=()=>{if(!e.isConnected){C(),d?.("anchor-removed");return}m()},W=G=>{let w=typeof G.composedPath=="function"?G.composedPath():[];w.includes(n)||w.includes(e)||(C(),d?.("outside"))},z=B.setTimeout(()=>{E.addEventListener("pointerdown",W,!0)},0);B.addEventListener("scroll",A,!0),B.addEventListener("resize",A),g=()=>{B.clearTimeout(z),E.removeEventListener("pointerdown",W,!0),B.removeEventListener("scroll",A,!0),B.removeEventListener("resize",A)},c?.()};return{get isOpen(){return y},open:D,close:C,toggle:()=>y?C():D(),reposition:m,destroy:C}}function nu(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var El=yt(()=>{"use strict"});var ou,ru=yt(()=>{"use strict";ou=`
11
+ </document>`}function Jp(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),Ml(t.label,t.text)}return n==="document"?Uh(t.label,t.text,e):Ml(t.label,t.text)}var Yp=bt(()=>{"use strict"});function Ii(t,e){return{sourceId:t.id,itemId:e.id,label:e.label,iconName:e.iconName,color:e.color}}var Zp,Ri,Tl=bt(()=>{"use strict";Xp();Yp();Zp=(t,e)=>`${t}\0${e}`,Ri=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=Zp(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=Ii(e,n),i={key:r,source:e,item:n,ref:s,status:"resolving",args:o};return i.chip=Qp({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:Ii(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 u=>{try{return u.source.resolveOn==="submit"?await u.source.resolve(u.item,this.buildResolveContext(new AbortController().signal,u.args,o)):(u.resolvePromise&&await u.resolvePromise,u.payload??null)}catch(y){try{this.opts.mentionConfig.onMentionResolveError?.(u.item,y)}catch(g){typeof console<"u"&&console.warn("[Persona] onMentionResolveError callback threw",g)}return this.opts.emit?.("resolve-error",{sourceId:u.source.id,itemId:u.item.id}),null}})),i=[],l=[],p={},c=new Set;for(let u=0;u<e.length;u++){let y=e[u],g=s[u];if(!g)continue;let m=Zp(y.source.id,y.item.id);if(!c.has(m)){if(c.add(m),g.llmAppend&&g.llmAppend.trim())try{i.push(Jp({label:y.ref.label,text:g.llmAppend,ref:y.ref,item:y.item},i.length,this.opts.mentionConfig.llmFormat))}catch(C){typeof console<"u"&&console.warn("[Persona] context-mention llmFormat threw",C)}g.contentParts?.length&&l.push(...g.contentParts),g.context&&((p[d=y.source.id]??(p[d]={}))[y.item.id]=g.context)}}return{blocks:i,contentParts:l,context:p}}}}updateRowVisibility(){this.opts.contextRow.style.display=this.mentions.length>0?"flex":"none"}}});function eu(t){let e=t.getRootNode?.();return e instanceof ShadowRoot||e instanceof Document?e:t.ownerDocument??document}function Wi(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 tu(t,e,n){if(t instanceof Document||t instanceof ShadowRoot){Wi(t,e,n);return}let o=t;if(o.isConnected){Wi(eu(o),e,n);return}let r=o.ownerDocument??document;Wi(r,e,n),queueMicrotask(()=>{let s=eu(o);s!==r&&Wi(s,e,n)})}function jh(t){let e=t.getRootNode?.();return e instanceof ShadowRoot?e:(t.ownerDocument??document).body}function Hi(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,u=t.container??jh(e),y=!1,g=null,m=()=>{if(!y)return;let B=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${B.width}px`),i&&(n.style.maxWidth=`${B.width}px`);let E=n.getBoundingClientRect(),A=l?.()??null,W=A!=null?B.top+A:B.top,z=o==="top-start"||o==="top-end"?W-r-E.height:B.bottom+r,w=o==="bottom-end"||o==="top-end"?B.right-E.width:B.left,O=i?.()??null;if(O!=null){let N=Math.max(B.left,B.right-E.width);w=Math.min(Math.max(B.left+O,B.left),N)}n.style.top=`${z}px`,n.style.left=`${w}px`},C=()=>{y&&(y=!1,g&&(g(),g=null),n.remove())},D=()=>{if(y)return;y=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),m();let B=(e.ownerDocument??document).defaultView??window,E=e.ownerDocument??document,A=()=>{if(!e.isConnected){C(),d?.("anchor-removed");return}m()},W=G=>{let w=typeof G.composedPath=="function"?G.composedPath():[];w.includes(n)||w.includes(e)||(C(),d?.("outside"))},z=B.setTimeout(()=>{E.addEventListener("pointerdown",W,!0)},0);B.addEventListener("scroll",A,!0),B.addEventListener("resize",A),g=()=>{B.clearTimeout(z),E.removeEventListener("pointerdown",W,!0),B.removeEventListener("scroll",A,!0),B.removeEventListener("resize",A)},c?.()};return{get isOpen(){return y},open:D,close:C,toggle:()=>y?C():D(),reposition:m,destroy:C}}function nu(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var El=bt(()=>{"use strict"});var ou,ru=bt(()=>{"use strict";ou=`
12
12
  .persona-mention-menu {
13
13
  box-sizing: border-box;
14
14
  display: flex;
@@ -166,25 +166,25 @@ ${e}
166
166
  min-height: 36px;
167
167
  }
168
168
  }
169
- `});function Bi(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 su=yt(()=>{"use strict"});function au(t){let{config:e,listboxId:n}=t,o=xe("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=xe("div",{className:"persona-mention-search",style:{display:"none"}}),s=h("span","persona-mention-search-icon"),i=se("search",15,"currentColor",2);i&&s.appendChild(i);let l=xe("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",L=>t.onSearchKeydown?.(L));let p=xe("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,p);let c=[],d=[],u=-1,y=new Map,g=(L,P)=>`${L}\0${P}`,m=L=>`${n}-opt-${L}`,C=L=>`${n}-grp-${L}`,D=(L,P)=>{let I=c[L];I&&(P?I.setAttribute("data-active","true"):I.removeAttribute("data-active"),I.setAttribute("aria-selected",P?"true":"false"),d[L]?.(P))},B=(L,P=!0)=>{u>=0&&u!==L&&D(u,!1),u=L;let I=c[L];I?(D(L,!0),P&&I.scrollIntoView?.({block:"nearest"}),p.setAttribute("aria-activedescendant",I.id),l.setAttribute("aria-activedescendant",I.id)):(p.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},E=(L,P)=>{let I=C(P),Y=xe("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":I}});return Y.appendChild(xe("div",{className:"persona-mention-group-header",attrs:{id:I},text:L})),Y},A=()=>{let L=xe("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),P=h("span","persona-mention-option-icon");L.appendChild(P);let I="",Y=h("span","persona-mention-option-text"),de=h("span","persona-mention-option-labelline"),ue=h("span","persona-mention-option-label");de.appendChild(ue),Y.appendChild(de),L.appendChild(Y);let pe=null,ee=null,oe={el:L,index:0,update:(V,ae,ne)=>{oe.index=ae,L.id=m(ae),L.setAttribute("aria-setsize",String(ne)),L.setAttribute("aria-posinset",String(ae+1)),L.removeAttribute("data-active"),L.setAttribute("aria-selected","false");let me=V.iconName??e.chipIconName??"at-sign";if(me!==I){I=me;let fe=qh(me,15,2);P.replaceChildren(...fe?[fe]:[])}ue.textContent!==V.label&&(ue.textContent=V.label);let be=V.commandArgsPlaceholder?`\u2039${V.commandArgsPlaceholder}\u203A`:null;be?(pe||(pe=h("span","persona-mention-option-arghint"),de.appendChild(pe)),pe.textContent!==be&&(pe.textContent=be)):pe&&(pe.remove(),pe=null),V.description?(ee||(ee=h("span","persona-mention-option-desc"),Y.appendChild(ee)),ee.textContent!==V.description&&(ee.textContent=V.description)):ee&&(ee.remove(),ee=null)}};return L.addEventListener("mousedown",V=>{V.button===0&&(V.preventDefault(),t.onSelectIndex(oe.index))}),L.addEventListener("mouseenter",()=>t.onHoverIndex(oe.index)),oe},W=(L,P,I,Y,de)=>{let ue=xe("div",{className:"persona-mention-option",attrs:{role:"option",id:m(Y),"aria-selected":"false","aria-setsize":String(de),"aria-posinset":String(Y+1)}}),pe=ee=>{ue.replaceChildren(e.renderMentionItem({item:L,source:P,query:I,active:ee,index:Y}))};return pe(!1),ue.addEventListener("mousedown",ee=>{ee.button===0&&(ee.preventDefault(),t.onSelectIndex(Y))}),ue.addEventListener("mouseenter",()=>t.onHoverIndex(Y)),{el:ue,paint:pe}},z=L=>{let P=xe("div",{className:"persona-mention-status persona-mention-error"});if(P.appendChild(xe("span",{className:"persona-mention-error-text",text:`Couldn't load ${L.label}`})),t.onRetry){let I=xe("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});I.addEventListener("mousedown",Y=>Y.preventDefault()),I.addEventListener("click",Y=>{Y.preventDefault(),t.onRetry(L.id)}),P.appendChild(I)}return P};return{el:o,render:L=>{p.replaceChildren(),c=[],d=[],u=-1;let P=new Set,I=0,Y=0,de=0,ue=0,pe=0,ee=L.groups.reduce((oe,V)=>V.status==="ready"?oe+V.items.length:oe,0);for(let oe of L.groups)if(oe.status==="loading"){de++;let V=E(oe.source.label,pe++);V.appendChild(xe("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),p.appendChild(V)}else if(oe.status==="error"){ue++;let V=E(oe.source.label,pe++);V.appendChild(z(oe.source)),p.appendChild(V)}else if(oe.status==="ready"&&oe.items.length>0){let V=new Map;for(let ne of oe.items){let me=ne.group??oe.source.label,be=V.get(me);be?be.push(ne):V.set(me,[ne])}let ae=Array.from(V.entries());ae.forEach(([ne,me],be)=>{let fe=E(ne,pe++);for(let Te of me){let Se=I++,Fe;if(e.renderMentionItem){let ke=W(Te,oe.source,L.query,Se,ee);Fe=ke.el,d.push(ke.paint)}else{let ke=g(oe.source.id,Te.id),qe=P.has(ke)?void 0:y.get(ke);qe||(qe=A(),P.has(ke)||y.set(ke,qe)),P.add(ke),qe.update(Te,Se,ee),Fe=qe.el,d.push(null)}c.push(Fe),fe.appendChild(Fe),Y++}oe.truncated&&be===ae.length-1&&fe.appendChild(xe("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),p.appendChild(fe)})}for(let oe of y.keys())P.has(oe)||y.delete(oe);Y===0&&de===0&&ue===0&&p.appendChild(xe("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),c.length>0?B(Math.min(Math.max(0,L.activeIndex),c.length-1)):(p.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:B,destroy:()=>{p.replaceChildren(),c=[],y.clear(),o.remove()},showSearch:(L,P)=>{l.value=L,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 iu,qh,lu=yt(()=>{"use strict";tt();Mt();iu=new Map,qh=(t,e,n)=>{let o=`${t}|${e}|${n}`,r=iu.get(o);return r===void 0&&(r=se(t,e,"currentColor",n),iu.set(o,r)),r?r.cloneNode(!0):null}});var Vh,Kh,Di,cu=yt(()=>{"use strict";El();ru();ki();Cl();su();lu();Tl();Vh=t=>!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function",Kh=0,Di=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=Li(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-${++Kh}`,this.menu=e.mentionConfig.renderMentionMenu?this.createHostMenu():au({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=rs(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=rs(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=Hi({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(),tu(this.menu.el,"persona-mention-menu",ou),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}Vh(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 Bi(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=Ii(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}=Bi(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 Bi(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 su=bt(()=>{"use strict"});function au(t){let{config:e,listboxId:n}=t,o=xe("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=xe("div",{className:"persona-mention-search",style:{display:"none"}}),s=h("span","persona-mention-search-icon"),i=se("search",15,"currentColor",2);i&&s.appendChild(i);let l=xe("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",L=>t.onSearchKeydown?.(L));let p=xe("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,p);let c=[],d=[],u=-1,y=new Map,g=(L,P)=>`${L}\0${P}`,m=L=>`${n}-opt-${L}`,C=L=>`${n}-grp-${L}`,D=(L,P)=>{let I=c[L];I&&(P?I.setAttribute("data-active","true"):I.removeAttribute("data-active"),I.setAttribute("aria-selected",P?"true":"false"),d[L]?.(P))},B=(L,P=!0)=>{u>=0&&u!==L&&D(u,!1),u=L;let I=c[L];I?(D(L,!0),P&&I.scrollIntoView?.({block:"nearest"}),p.setAttribute("aria-activedescendant",I.id),l.setAttribute("aria-activedescendant",I.id)):(p.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},E=(L,P)=>{let I=C(P),Y=xe("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":I}});return Y.appendChild(xe("div",{className:"persona-mention-group-header",attrs:{id:I},text:L})),Y},A=()=>{let L=xe("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),P=h("span","persona-mention-option-icon");L.appendChild(P);let I="",Y=h("span","persona-mention-option-text"),de=h("span","persona-mention-option-labelline"),ue=h("span","persona-mention-option-label");de.appendChild(ue),Y.appendChild(de),L.appendChild(Y);let pe=null,ee=null,oe={el:L,index:0,update:(V,ae,ne)=>{oe.index=ae,L.id=m(ae),L.setAttribute("aria-setsize",String(ne)),L.setAttribute("aria-posinset",String(ae+1)),L.removeAttribute("data-active"),L.setAttribute("aria-selected","false");let me=V.iconName??e.chipIconName??"at-sign";if(me!==I){I=me;let fe=qh(me,15,2);P.replaceChildren(...fe?[fe]:[])}ue.textContent!==V.label&&(ue.textContent=V.label);let be=V.commandArgsPlaceholder?`\u2039${V.commandArgsPlaceholder}\u203A`:null;be?(pe||(pe=h("span","persona-mention-option-arghint"),de.appendChild(pe)),pe.textContent!==be&&(pe.textContent=be)):pe&&(pe.remove(),pe=null),V.description?(ee||(ee=h("span","persona-mention-option-desc"),Y.appendChild(ee)),ee.textContent!==V.description&&(ee.textContent=V.description)):ee&&(ee.remove(),ee=null)}};return L.addEventListener("mousedown",V=>{V.button===0&&(V.preventDefault(),t.onSelectIndex(oe.index))}),L.addEventListener("mouseenter",()=>t.onHoverIndex(oe.index)),oe},W=(L,P,I,Y,de)=>{let ue=xe("div",{className:"persona-mention-option",attrs:{role:"option",id:m(Y),"aria-selected":"false","aria-setsize":String(de),"aria-posinset":String(Y+1)}}),pe=ee=>{ue.replaceChildren(e.renderMentionItem({item:L,source:P,query:I,active:ee,index:Y}))};return pe(!1),ue.addEventListener("mousedown",ee=>{ee.button===0&&(ee.preventDefault(),t.onSelectIndex(Y))}),ue.addEventListener("mouseenter",()=>t.onHoverIndex(Y)),{el:ue,paint:pe}},z=L=>{let P=xe("div",{className:"persona-mention-status persona-mention-error"});if(P.appendChild(xe("span",{className:"persona-mention-error-text",text:`Couldn't load ${L.label}`})),t.onRetry){let I=xe("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});I.addEventListener("mousedown",Y=>Y.preventDefault()),I.addEventListener("click",Y=>{Y.preventDefault(),t.onRetry(L.id)}),P.appendChild(I)}return P};return{el:o,render:L=>{p.replaceChildren(),c=[],d=[],u=-1;let P=new Set,I=0,Y=0,de=0,ue=0,pe=0,ee=L.groups.reduce((oe,V)=>V.status==="ready"?oe+V.items.length:oe,0);for(let oe of L.groups)if(oe.status==="loading"){de++;let V=E(oe.source.label,pe++);V.appendChild(xe("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),p.appendChild(V)}else if(oe.status==="error"){ue++;let V=E(oe.source.label,pe++);V.appendChild(z(oe.source)),p.appendChild(V)}else if(oe.status==="ready"&&oe.items.length>0){let V=new Map;for(let ne of oe.items){let me=ne.group??oe.source.label,be=V.get(me);be?be.push(ne):V.set(me,[ne])}let ae=Array.from(V.entries());ae.forEach(([ne,me],be)=>{let fe=E(ne,pe++);for(let Te of me){let Se=I++,Fe;if(e.renderMentionItem){let ke=W(Te,oe.source,L.query,Se,ee);Fe=ke.el,d.push(ke.paint)}else{let ke=g(oe.source.id,Te.id),Ve=P.has(ke)?void 0:y.get(ke);Ve||(Ve=A(),P.has(ke)||y.set(ke,Ve)),P.add(ke),Ve.update(Te,Se,ee),Fe=Ve.el,d.push(null)}c.push(Fe),fe.appendChild(Fe),Y++}oe.truncated&&be===ae.length-1&&fe.appendChild(xe("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),p.appendChild(fe)})}for(let oe of y.keys())P.has(oe)||y.delete(oe);Y===0&&de===0&&ue===0&&p.appendChild(xe("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),c.length>0?B(Math.min(Math.max(0,L.activeIndex),c.length-1)):(p.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:B,destroy:()=>{p.replaceChildren(),c=[],y.clear(),o.remove()},showSearch:(L,P)=>{l.value=L,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 iu,qh,lu=bt(()=>{"use strict";nt();St();iu=new Map,qh=(t,e,n)=>{let o=`${t}|${e}|${n}`,r=iu.get(o);return r===void 0&&(r=se(t,e,"currentColor",n),iu.set(o,r)),r?r.cloneNode(!0):null}});var Vh,Kh,Di,cu=bt(()=>{"use strict";El();ru();ki();Cl();su();lu();Tl();Vh=t=>!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function",Kh=0,Di=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=Li(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-${++Kh}`,this.menu=e.mentionConfig.renderMentionMenu?this.createHostMenu():au({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=rs(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=rs(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=Hi({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(),tu(this.menu.el,"persona-mention-menu",ou),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}Vh(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 Bi(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=Ii(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}=Bi(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}=Bi(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=Vp(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 kl(t){t&&(typeof t.requestSubmit=="function"?t.requestSubmit():t.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function du(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:()=>kl(t.form),dispatchInput:e,focus:()=>t.focus()}}var Ll=yt(()=>{"use strict"});function Pl(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,Gh),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 Gh,pu=yt(()=>{"use strict";Gh={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 uu(t){let e=t.composerInput??du(t.textarea),n=Pl("polite",t.liveRegionHost),o=Pl("assertive",t.liveRegionHost),r=c=>n.announce(c),s=c=>o.announce(c),i=new Ri({mentionConfig:t.mentionConfig,contextRow:t.contextRow,getMessages:t.getMessages,getConfig:t.getConfig,getComposerText:()=>e.getValue(),announce:r,announceError:s,emit:t.emit}),l=()=>new Di({mentionConfig:t.mentionConfig,composerInput:e,anchor:t.anchor,getMessages:t.getMessages,getConfig:t.getConfig,onSelect:(c,d,u)=>i.add(c,d,u),onInsertMention:(c,d,u,y)=>i.track(c,d,u,y,g=>e.setMentionStatus?.(c,g)),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 gu=yt(()=>{"use strict";Tl();cu();Ll();pu()});var fu={};Jo(fu,{mountContextMentions:()=>uu});var mu=yt(()=>{"use strict";gu()});function Wl(t){return t.kind==="text"?t.value.length:1}function Hl(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 hu(){return{blocks:[{kind:"text",value:""}]}}function Bl(t){return{blocks:[{kind:"text",value:t}]}}function Dl(t){return t.blocks.map(e=>e.kind==="text"?e.value:`${Xh}${e.ref.label}`).join("")}function Oi(t){return t.blocks.map(e=>e.kind==="text"?e.value:"\uFFFC").join("")}function Fi(t){return t.blocks.reduce((e,n)=>e+Wl(n),0)}function Jh(t){let e=[];for(let n of t.blocks)n.kind==="mention"&&e.push({id:n.id,ref:n.ref});return e}function Ni(t,e){let n=[],o=[],r=0;for(let s of t){let i=Wl(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 Nl(t,e,n,o){let r=Ni(t.blocks,e.start).left,s=Ni(t.blocks,e.end).right,i=s[0],l=i?.kind==="text"?i.value.charAt(0):"",p=l!==" "&&l!==" "&&l!==`
171
+ `)[0]];for(let r of o){if(!r.startsWith(n.trigger))continue;let{name:s,args:i}=Bi(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=Vp(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 kl(t){t&&(typeof t.requestSubmit=="function"?t.requestSubmit():t.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function du(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:()=>kl(t.form),dispatchInput:e,focus:()=>t.focus()}}var Ll=bt(()=>{"use strict"});function Pl(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,Gh),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 Gh,pu=bt(()=>{"use strict";Gh={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 uu(t){let e=t.composerInput??du(t.textarea),n=Pl("polite",t.liveRegionHost),o=Pl("assertive",t.liveRegionHost),r=c=>n.announce(c),s=c=>o.announce(c),i=new Ri({mentionConfig:t.mentionConfig,contextRow:t.contextRow,getMessages:t.getMessages,getConfig:t.getConfig,getComposerText:()=>e.getValue(),announce:r,announceError:s,emit:t.emit}),l=()=>new Di({mentionConfig:t.mentionConfig,composerInput:e,anchor:t.anchor,getMessages:t.getMessages,getConfig:t.getConfig,onSelect:(c,d,u)=>i.add(c,d,u),onInsertMention:(c,d,u,y)=>i.track(c,d,u,y,g=>e.setMentionStatus?.(c,g)),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 gu=bt(()=>{"use strict";Tl();cu();Ll();pu()});var fu={};Jo(fu,{mountContextMentions:()=>uu});var mu=bt(()=>{"use strict";gu()});function Wl(t){return t.kind==="text"?t.value.length:1}function Hl(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 hu(){return{blocks:[{kind:"text",value:""}]}}function Bl(t){return{blocks:[{kind:"text",value:t}]}}function Dl(t){return t.blocks.map(e=>e.kind==="text"?e.value:`${Xh}${e.ref.label}`).join("")}function Oi(t){return t.blocks.map(e=>e.kind==="text"?e.value:"\uFFFC").join("")}function Fi(t){return t.blocks.reduce((e,n)=>e+Wl(n),0)}function Jh(t){let e=[];for(let n of t.blocks)n.kind==="mention"&&e.push({id:n.id,ref:n.ref});return e}function Ni(t,e){let n=[],o=[],r=0;for(let s of t){let i=Wl(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 Nl(t,e,n,o){let r=Ni(t.blocks,e.start).left,s=Ni(t.blocks,e.end).right,i=s[0],l=i?.kind==="text"?i.value.charAt(0):"",p=l!==" "&&l!==" "&&l!==`
172
172
  `,c=Hl([...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 bu(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+=Wl(i);return r?{doc:{blocks:Hl(t.blocks.filter(i=>!(i.kind==="mention"&&i.id===e)))},caret:n}:{doc:t,caret:o}}function _i(t,e,n,o){let r=Fi(t),s=Math.max(0,Math.min(e,n,r)),i=Math.min(r,Math.max(e,n,0)),l=Ni(t.blocks,s).left,p=Ni(t.blocks,i).right;return{doc:{blocks:Hl([...l,{kind:"text",value:o},...p])},caret:s+o.length}}function yu(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:Dl(t),contextMentions:Jh(t).map(n=>n.ref),contentSegments:e}}var Xh,Ol=yt(()=>{"use strict";ki();Xh="@"});function ls(t){return t.nodeType===1&&t.hasAttribute(as)}function Cu(t){return t.nodeType===1&&t.tagName==="BR"}function $i(t){return t.nodeType===3?t.data.length:ls(t)||Cu(t)?1:t.textContent?.length??0}function vu(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?$i(r):0);if(r.contains(e))return ls(r)?o+1:o+Zh(r,e,n);o+=$i(r)}if(e===t){let r=0,s=Array.from(t.childNodes);for(let i=0;i<Math.min(n,s.length);i++)r+=$i(s[i]);return r}return o}function Zh(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 is(t,e){let n=0,o=Array.from(t.childNodes);for(let r=0;r<o.length;r++){let s=o[r],i=$i(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 eb(t,e){let n=[];for(let o of Array.from(t.childNodes))if(ls(o)){let r=o.getAttribute(as),s=e.get(r);s&&n.push({kind:"mention",id:r,ref:s})}else if(Cu(o))n.push({kind:"text",value:xu});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 wu(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=()=>eb(o,n),l=O=>{o.replaceChildren();for(let N of O.blocks)if(N.kind==="text")N.value.length>0&&o.appendChild(document.createTextNode(N.value));else{n.set(N.id,N.ref);let L=e(N.ref);L.setAttribute("contenteditable","false"),L.setAttribute(as,N.id),o.appendChild(L)}},p=()=>{let N=o.getRootNode().activeElement;return N===o||N!=null&&o.contains(N)},c=(O,N)=>{if(s=O,!N?.focus&&!p())return;let L=typeof window<"u"?window.getSelection():null;if(!L)return;let P=is(o,O);try{let I=document.createRange();I.setStart(P.node,P.offset),I.collapse(!0),L.removeAllRanges(),L.addRange(I)}catch{}},d=()=>{o.dispatchEvent(new Event("input",{bubbles:!0}))},u=()=>{let O={start:s,end:s},N=typeof window<"u"?window.getSelection():null;if(!N||N.rangeCount===0)return O;let L=N.getRangeAt(0);if(!o.contains(L.startContainer))return O;let P=vu(o,L.startContainer,L.startOffset),I=L.collapsed?P:vu(o,L.endContainer,L.endOffset);return{start:Math.min(P,I),end:Math.max(P,I)}},y=()=>{let O=new Set;for(let N of Array.from(o.childNodes))ls(N)&&O.add(N.getAttribute(as));for(let N of Array.from(n.keys()))O.has(N)||(n.delete(N),t.onMentionRemoved?.(N))},g=()=>{r||n.size!==0&&y()},m=()=>{r=!0},C=()=>{r=!1,y()},D=O=>{O.preventDefault();let N=O.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,N);else{let{start:L,end:P}=u(),I=_i(i(),L,P,N);l(I.doc),c(I.caret,{focus:!0}),y()}d()},B=O=>{if(r)return;let N=O.inputType;if(N==="insertParagraph"){O.preventDefault();let{start:oe,end:V}=u(),ae=_i(i(),oe,V,xu);l(ae.doc),c(ae.caret,{focus:!0}),n.size>0&&y(),d();return}if(N!=="deleteContentBackward"&&N!=="deleteContentForward"||n.size===0)return;let{start:L,end:P}=u();if(L!==P)return;let I=i(),Y=Oi(I),de=N==="deleteContentBackward"?L-1:L;if(de<0||de>=Y.length||Y[de]!=="\uFFFC")return;let ue=0,pe=null;for(let oe of I.blocks){let V=oe.kind==="text"?oe.value.length:1;if(oe.kind==="mention"&&de>=ue&&de<ue+V){pe=oe.id;break}ue+=V}if(!pe)return;O.preventDefault();let ee=bu(I,pe);l(ee.doc),c(ee.caret,{focus:!0}),y(),d()},E=(O,N)=>{l(Bl(O)),c(N)},A=(O,N)=>{if(!Number.isFinite(O)||!Number.isFinite(N)||N<=O)return null;try{let L=is(o,O),P=is(o,N),I=document.createRange();I.setStart(L.node,L.offset),I.setEnd(P.node,P.offset);let Y=I.getBoundingClientRect();return Y.width===0&&Y.height===0?null:Y}catch{return null}},W=(O,N,L)=>{let P=_i(i(),O,N,L);l(P.doc),c(P.caret,{focus:!0})},z=(O,N)=>{let L=i(),P=Oi(L),I=N.triggerIndex,Y=N.triggerIndex+1+N.query.length;if(I<0||Y>P.length||P.slice(I+1,Y)!==N.query)return null;let de=t.generateId(),ue=Nl(L,{start:I,end:Y},O,de);return l(ue.doc),c(ue.caret,{focus:!0}),t.onMentionInserted?.(de,O),d(),de},G=O=>{let N=i(),L=u(),I=typeof window<"u"&&!!window.getSelection()?.rangeCount&&o.contains(window.getSelection().getRangeAt(0).startContainer)?{start:L.start,end:L.end}:{start:Fi(N),end:Fi(N)},Y=t.generateId(),de=Nl(N,I,O,Y);return l(de.doc),c(de.caret,{focus:!0}),t.onMentionInserted?.(Y,O),d(),Y},w=(O,N)=>{for(let L of Array.from(o.childNodes))if(ls(L)&&L.getAttribute(as)===O){let P=N==="error";if(L.classList.toggle(Yh,P),P){L.hasAttribute(ss)||(L.setAttribute(ss,L.getAttribute("aria-label")??""),L.setAttribute(Fl,L.getAttribute("title")??""));let I=n.get(O)?.label??"";L.setAttribute("title",`${I}: failed to attach context`),L.setAttribute("aria-label",`${I}, failed to attach context`)}else if(L.hasAttribute(ss)){let I=L.getAttribute(ss),Y=L.getAttribute(Fl);I?L.setAttribute("aria-label",I):L.removeAttribute("aria-label"),Y?L.setAttribute("title",Y):L.removeAttribute("title"),L.removeAttribute(ss),L.removeAttribute(Fl)}return}};return o.addEventListener("input",g),o.addEventListener("compositionstart",m),o.addEventListener("compositionend",C),o.addEventListener("paste",D),o.addEventListener("beforeinput",B),l(hu()),{element:o,getValue:()=>Dl(i()),getLogicalText:()=>Oi(i()),getDocument:i,getSelection:u,setSelection:(O,N=O)=>{let L=typeof window<"u"?window.getSelection():null;if(L)try{let P=is(o,O),I=is(o,N),Y=document.createRange();Y.setStart(P.node,P.offset),Y.setEnd(I.node,I.offset),L.removeAllRanges(),L.addRange(Y)}catch{}},setValueWithCaret:E,getLogicalRangeRect:A,setValue:O=>{l(Bl(O)),o.focus(),c(O.length,{focus:!0}),d()},replaceLogicalRange:W,insertMentionAtTrigger:z,insertMentionAtSelection:G,setMentionStatus:w,submit:()=>kl(o.closest("form")),dispatchInput:d,focus:()=>o.focus(),destroy:()=>{o.removeEventListener("input",g),o.removeEventListener("compositionstart",m),o.removeEventListener("compositionend",C),o.removeEventListener("paste",D),o.removeEventListener("beforeinput",B)}}}var Yh,as,ss,Fl,xu,Au=yt(()=>{"use strict";Ol();Ll();Yh="persona-mention-token-error",as="data-mention-id",ss="data-mention-prev-label",Fl="data-mention-prev-title",xu=`
174
- `});function ob(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 rb(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 Su(t){let{textarea:e}=t,n={generateId:nb,renderToken:t.renderToken,onMentionRemoved:t.onMentionRemoved,placeholder:e.getAttribute("placeholder")??void 0},o=wu(n),r=o.element,s=e.getAttribute("aria-label")!=null;ob(e,r),rb(r,o,s),r.getInlineMessageFields=()=>yu(o.getDocument?.()??{blocks:[]});let i=e.selectionStart??e.value.length;return o.setValueWithCaret(e.value,i),{input:o,element:r,destroy:o.destroy}}var tb,nb,Mu=yt(()=>{"use strict";Au();Ol();tb=0,nb=()=>`pmention-${++tb}`});var Tu={};Jo(Tu,{mountInlineComposer:()=>Su});var Eu=yt(()=>{"use strict";Mu()});var Yv={};Jo(Yv,{createThemePreview:()=>xf});module.exports=bm(Yv);var Yo=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(u=>(r=u,u)).catch(u=>{throw s=null,u}),s),provide:d=>{r=d},getSync:()=>r}};var{setLoader:sx,load:ym,provide:ix,getSync:tl}=Yo({fallbackImport:()=>Promise.resolve().then(()=>($d(),_d))}),si=new Set,vm=()=>{let t=[...si];si.clear();for(let e of t)try{e()}catch{}};var xm=()=>{let t=tl();return t?Promise.resolve(t):ym().then(e=>(vm(),e))},ii=t=>tl()?()=>{}:(si.add(t),xm().catch(()=>{}),()=>{si.delete(t)});var Nn=tl;var Cm=t=>{if(t)return t},nl=t=>{let e=null;return n=>{let o=Nn();if(!o)return oo(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=Cm(t?.renderer);i&&e.use({renderer:i})}return e.parse(n)}},ai=t=>t?nl({markedOptions:t.options,renderer:t.renderer}):nl(),cx=nl();var oo=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var wm={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"]},Am=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Sm=()=>{let t=null;return e=>{let n=Nn();if(!n)return oo(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:")&&!Am.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,wm)}},li=t=>t===!1?null:typeof t=="function"?t:Sm();var zd=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Ud=t=>t.includes("|"),jd=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())},Mm=t=>`| ${t.join(" | ")} |`,Tm=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,Em=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),qd=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
173
+ `?0:1);return{doc:{blocks:c},caret:d}}function bu(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+=Wl(i);return r?{doc:{blocks:Hl(t.blocks.filter(i=>!(i.kind==="mention"&&i.id===e)))},caret:n}:{doc:t,caret:o}}function _i(t,e,n,o){let r=Fi(t),s=Math.max(0,Math.min(e,n,r)),i=Math.min(r,Math.max(e,n,0)),l=Ni(t.blocks,s).left,p=Ni(t.blocks,i).right;return{doc:{blocks:Hl([...l,{kind:"text",value:o},...p])},caret:s+o.length}}function yu(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:Dl(t),contextMentions:Jh(t).map(n=>n.ref),contentSegments:e}}var Xh,Ol=bt(()=>{"use strict";ki();Xh="@"});function ls(t){return t.nodeType===1&&t.hasAttribute(as)}function Cu(t){return t.nodeType===1&&t.tagName==="BR"}function $i(t){return t.nodeType===3?t.data.length:ls(t)||Cu(t)?1:t.textContent?.length??0}function vu(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?$i(r):0);if(r.contains(e))return ls(r)?o+1:o+Zh(r,e,n);o+=$i(r)}if(e===t){let r=0,s=Array.from(t.childNodes);for(let i=0;i<Math.min(n,s.length);i++)r+=$i(s[i]);return r}return o}function Zh(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 is(t,e){let n=0,o=Array.from(t.childNodes);for(let r=0;r<o.length;r++){let s=o[r],i=$i(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 eb(t,e){let n=[];for(let o of Array.from(t.childNodes))if(ls(o)){let r=o.getAttribute(as),s=e.get(r);s&&n.push({kind:"mention",id:r,ref:s})}else if(Cu(o))n.push({kind:"text",value:xu});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 wu(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=()=>eb(o,n),l=O=>{o.replaceChildren();for(let N of O.blocks)if(N.kind==="text")N.value.length>0&&o.appendChild(document.createTextNode(N.value));else{n.set(N.id,N.ref);let L=e(N.ref);L.setAttribute("contenteditable","false"),L.setAttribute(as,N.id),o.appendChild(L)}},p=()=>{let N=o.getRootNode().activeElement;return N===o||N!=null&&o.contains(N)},c=(O,N)=>{if(s=O,!N?.focus&&!p())return;let L=typeof window<"u"?window.getSelection():null;if(!L)return;let P=is(o,O);try{let I=document.createRange();I.setStart(P.node,P.offset),I.collapse(!0),L.removeAllRanges(),L.addRange(I)}catch{}},d=()=>{o.dispatchEvent(new Event("input",{bubbles:!0}))},u=()=>{let O={start:s,end:s},N=typeof window<"u"?window.getSelection():null;if(!N||N.rangeCount===0)return O;let L=N.getRangeAt(0);if(!o.contains(L.startContainer))return O;let P=vu(o,L.startContainer,L.startOffset),I=L.collapsed?P:vu(o,L.endContainer,L.endOffset);return{start:Math.min(P,I),end:Math.max(P,I)}},y=()=>{let O=new Set;for(let N of Array.from(o.childNodes))ls(N)&&O.add(N.getAttribute(as));for(let N of Array.from(n.keys()))O.has(N)||(n.delete(N),t.onMentionRemoved?.(N))},g=()=>{r||n.size!==0&&y()},m=()=>{r=!0},C=()=>{r=!1,y()},D=O=>{O.preventDefault();let N=O.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,N);else{let{start:L,end:P}=u(),I=_i(i(),L,P,N);l(I.doc),c(I.caret,{focus:!0}),y()}d()},B=O=>{if(r)return;let N=O.inputType;if(N==="insertParagraph"){O.preventDefault();let{start:oe,end:V}=u(),ae=_i(i(),oe,V,xu);l(ae.doc),c(ae.caret,{focus:!0}),n.size>0&&y(),d();return}if(N!=="deleteContentBackward"&&N!=="deleteContentForward"||n.size===0)return;let{start:L,end:P}=u();if(L!==P)return;let I=i(),Y=Oi(I),de=N==="deleteContentBackward"?L-1:L;if(de<0||de>=Y.length||Y[de]!=="\uFFFC")return;let ue=0,pe=null;for(let oe of I.blocks){let V=oe.kind==="text"?oe.value.length:1;if(oe.kind==="mention"&&de>=ue&&de<ue+V){pe=oe.id;break}ue+=V}if(!pe)return;O.preventDefault();let ee=bu(I,pe);l(ee.doc),c(ee.caret,{focus:!0}),y(),d()},E=(O,N)=>{l(Bl(O)),c(N)},A=(O,N)=>{if(!Number.isFinite(O)||!Number.isFinite(N)||N<=O)return null;try{let L=is(o,O),P=is(o,N),I=document.createRange();I.setStart(L.node,L.offset),I.setEnd(P.node,P.offset);let Y=I.getBoundingClientRect();return Y.width===0&&Y.height===0?null:Y}catch{return null}},W=(O,N,L)=>{let P=_i(i(),O,N,L);l(P.doc),c(P.caret,{focus:!0})},z=(O,N)=>{let L=i(),P=Oi(L),I=N.triggerIndex,Y=N.triggerIndex+1+N.query.length;if(I<0||Y>P.length||P.slice(I+1,Y)!==N.query)return null;let de=t.generateId(),ue=Nl(L,{start:I,end:Y},O,de);return l(ue.doc),c(ue.caret,{focus:!0}),t.onMentionInserted?.(de,O),d(),de},G=O=>{let N=i(),L=u(),I=typeof window<"u"&&!!window.getSelection()?.rangeCount&&o.contains(window.getSelection().getRangeAt(0).startContainer)?{start:L.start,end:L.end}:{start:Fi(N),end:Fi(N)},Y=t.generateId(),de=Nl(N,I,O,Y);return l(de.doc),c(de.caret,{focus:!0}),t.onMentionInserted?.(Y,O),d(),Y},w=(O,N)=>{for(let L of Array.from(o.childNodes))if(ls(L)&&L.getAttribute(as)===O){let P=N==="error";if(L.classList.toggle(Yh,P),P){L.hasAttribute(ss)||(L.setAttribute(ss,L.getAttribute("aria-label")??""),L.setAttribute(Fl,L.getAttribute("title")??""));let I=n.get(O)?.label??"";L.setAttribute("title",`${I}: failed to attach context`),L.setAttribute("aria-label",`${I}, failed to attach context`)}else if(L.hasAttribute(ss)){let I=L.getAttribute(ss),Y=L.getAttribute(Fl);I?L.setAttribute("aria-label",I):L.removeAttribute("aria-label"),Y?L.setAttribute("title",Y):L.removeAttribute("title"),L.removeAttribute(ss),L.removeAttribute(Fl)}return}};return o.addEventListener("input",g),o.addEventListener("compositionstart",m),o.addEventListener("compositionend",C),o.addEventListener("paste",D),o.addEventListener("beforeinput",B),l(hu()),{element:o,getValue:()=>Dl(i()),getLogicalText:()=>Oi(i()),getDocument:i,getSelection:u,setSelection:(O,N=O)=>{let L=typeof window<"u"?window.getSelection():null;if(L)try{let P=is(o,O),I=is(o,N),Y=document.createRange();Y.setStart(P.node,P.offset),Y.setEnd(I.node,I.offset),L.removeAllRanges(),L.addRange(Y)}catch{}},setValueWithCaret:E,getLogicalRangeRect:A,setValue:O=>{l(Bl(O)),o.focus(),c(O.length,{focus:!0}),d()},replaceLogicalRange:W,insertMentionAtTrigger:z,insertMentionAtSelection:G,setMentionStatus:w,submit:()=>kl(o.closest("form")),dispatchInput:d,focus:()=>o.focus(),destroy:()=>{o.removeEventListener("input",g),o.removeEventListener("compositionstart",m),o.removeEventListener("compositionend",C),o.removeEventListener("paste",D),o.removeEventListener("beforeinput",B)}}}var Yh,as,ss,Fl,xu,Au=bt(()=>{"use strict";Ol();Ll();Yh="persona-mention-token-error",as="data-mention-id",ss="data-mention-prev-label",Fl="data-mention-prev-title",xu=`
174
+ `});function ob(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 rb(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 Su(t){let{textarea:e}=t,n={generateId:nb,renderToken:t.renderToken,onMentionRemoved:t.onMentionRemoved,placeholder:e.getAttribute("placeholder")??void 0},o=wu(n),r=o.element,s=e.getAttribute("aria-label")!=null;ob(e,r),rb(r,o,s),r.getInlineMessageFields=()=>yu(o.getDocument?.()??{blocks:[]});let i=e.selectionStart??e.value.length;return o.setValueWithCaret(e.value,i),{input:o,element:r,destroy:o.destroy}}var tb,nb,Mu=bt(()=>{"use strict";Au();Ol();tb=0,nb=()=>`pmention-${++tb}`});var Tu={};Jo(Tu,{mountInlineComposer:()=>Su});var Eu=bt(()=>{"use strict";Mu()});var Yv={};Jo(Yv,{createThemePreview:()=>xf});module.exports=bm(Yv);var Yo=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(u=>(r=u,u)).catch(u=>{throw s=null,u}),s),provide:d=>{r=d},getSync:()=>r}};var{setLoader:sx,load:ym,provide:ix,getSync:tl}=Yo({fallbackImport:()=>Promise.resolve().then(()=>($d(),_d))}),si=new Set,vm=()=>{let t=[...si];si.clear();for(let e of t)try{e()}catch{}};var xm=()=>{let t=tl();return t?Promise.resolve(t):ym().then(e=>(vm(),e))},ii=t=>tl()?()=>{}:(si.add(t),xm().catch(()=>{}),()=>{si.delete(t)});var Nn=tl;var Cm=t=>{if(t)return t},nl=t=>{let e=null;return n=>{let o=Nn();if(!o)return oo(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=Cm(t?.renderer);i&&e.use({renderer:i})}return e.parse(n)}},ai=t=>t?nl({markedOptions:t.options,renderer:t.renderer}):nl(),cx=nl();var oo=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");var wm={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"]},Am=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Sm=()=>{let t=null;return e=>{let n=Nn();if(!n)return oo(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:")&&!Am.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,wm)}},li=t=>t===!1?null:typeof t=="function"?t:Sm();var zd=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Ud=t=>t.includes("|"),jd=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())},Mm=t=>`| ${t.join(" | ")} |`,Tm=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,Em=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),qd=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
175
175
  `),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!Ud(r)||zd.test(r)||!zd.test(s))continue;let i=jd(r).length;if(i<1)continue;let l=Tm(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()===""||!Ud(c))break;let d=Mm(Em(jd(c),i));e[p]!==d&&(e[p]=d,n=!0)}o=p-1}return n?e.join(`
176
176
  `):t};var Vd="var(--persona-md-table-scroll-fade, 24px)",Kd=new WeakSet;function Qd(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 Gd(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":Vd),t.style.setProperty("--persona-fade-r",r<=1?"0px":Vd)}function ol(t){Kd.has(t)||(Kd.add(t),t.addEventListener("scroll",e=>{let n=e.target;n?.classList?.contains("persona-table-scroll")&&Gd(n)},!0)),t.querySelectorAll(".persona-table-scroll").forEach(Gd)}var On="webmcp:",rl=new Map,Xd=t=>{rl.clear();for(let e of t){let n=e.title?.trim();n&&rl.set(e.name,n)}},Vr=t=>rl.get(ep(t)),ci={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},Jd=null;function Zd(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}:${km(e.join(""))}`}function Yd(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 km(t){let e=Yd(t,0).toString(36),n=Yd(t,2654435761).toString(36);return`${e}.${n}`}var di=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 ci.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}Xd(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=Pm(r.inputSchema);return i&&(s.parametersSchema=i),s})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return An("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let m=typeof document<"u"&&!!document.modelContext;return An(m?"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=ep(e),i;try{i=await r.getTools()}catch(m){let C=m instanceof Error?m.message:String(m);return An(`Failed to read WebMCP registry: ${C}`)}Xd(i);let l=i.find(m=>m.name===s);if(!l)return An(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return An(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return An("Aborted by cancel()");let p=Vr(s),c={toolName:s,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(c))return An("User declined the tool call.");if(o?.aborted)return An("Aborted by cancel()");let d=new AbortController,u=!1,y=setTimeout(()=>{u=!0,d.abort()},this.timeoutMs),g=()=>d.abort();o&&(o.aborted?d.abort():o.addEventListener("abort",g,{once:!0}));try{let m=await r.executeTool(l,Hm(n),{signal:d.signal});return Im(m)}catch(m){if(u)return An(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return An("Aborted by cancel()");let C=m instanceof Error?m.message:String(m);return An(C)}finally{clearTimeout(y),o&&o.removeEventListener("abort",g)}}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}(Jd?await Jd():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){ci.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,ci.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??Rm;try{return await n(e)}catch(o){return ci.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=>Lm(e,o))}},ep=t=>t.startsWith(On)?t.slice(On.length):t,Zo=t=>t.startsWith(On),Lm=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},Pm=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Im=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:Bm(e)}]}},An=t=>({isError:!0,content:[{type:"text",text:t}]}),Rm=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=Wm(t.args),n=`Allow the AI to call ${t.toolName}`+(e?`
177
177
 
178
178
  Arguments:
179
179
  ${e}`:"")+(t.description?`
180
180
 
181
- ${t.description}`:"");return window.confirm(n)},Wm=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)}},Hm=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},Bm=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};function Lo(t,e){let n=t?.display;return n?typeof n=="string"?n:n.byType?.[e]??n.default??"panel":"panel"}function pi(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}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var Dm="agent_",Nm="flow_";function tp(t){return t.startsWith(Dm)?{kind:"agentId",agentId:t}:t.startsWith(Nm)?{kind:"flowId",flowId:t}:null}function np(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=tp(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=tp(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 ro=require("partial-json");tt();var sl="ask_user_question",Kr=8,er="data-persona-ask-sheet-for",Om="Other",Fm="Other\u2026",sp="Type your own answer here",ip="Send",_m="Next",$m="Back",zm="Submit all",Um="Skip",jm=3,il="data-ask-current-index",al="data-ask-question-count",ap="data-ask-answers",ll="data-ask-grouped",lp="data-ask-layout",qm=t=>t.layout==="pills"?"pills":"rows",Vm=t=>t.getAttribute(lp)==="pills"?"pills":"rows",rp=!1,cp=t=>t.replace(/["\\]/g,"\\$&"),Po=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===sl,cl=t=>t?.features?.askUserQuestion??{},tr=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,ro.parse)(r,ro.STR|ro.OBJ|ro.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Gr=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>Kr&&!rp&&(rp=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Kr}.`)),e.slice(0,Kr)},Km=t=>Gr(t)[0]??null,Gm=(t,e)=>Gr(t)[e]??null,Qm=(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))},dp=(t,e,n)=>{if(t!=="rows")return null;let o=h("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=h("span","persona-ask-row-check");o.appendChild(r)}else{let r=h("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Xm=(t,e,n,o)=>{let s=h("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=h("span","persona-ask-row-content"),l=h("span","persona-ask-row-label");if(l.textContent=t.label,i.appendChild(l),t.description){let c=h("span","persona-ask-row-description");c.textContent=t.description,i.appendChild(c)}s.appendChild(i);let p=dp(n,o,e);p&&s.appendChild(p)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},Jm=t=>{let n=h("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},Ym=(t,e,n,o)=>{let s=h("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<jm;d++)s.appendChild(Jm(o));return s}if(p.forEach((d,u)=>{s.appendChild(Xm(d,u,o,i))}),t?.allowFreeText!==!1){let d=o==="rows"?Om:Fm;if(o==="rows"){let u=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let y=h("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=e.freeTextPlaceholder??sp,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",e.freeTextLabel??d),y.appendChild(g),u.appendChild(y);let m=dp(o,i,p.length);m&&u.appendChild(m),s.appendChild(u)}else{let u=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=e.freeTextLabel??d,s.appendChild(u)}}return s},pp=(t,e)=>{let o=h("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??sp,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=h("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??ip,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},Zm=t=>{let e=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=h("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??ip,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},eh=(t,e,n)=>{let o=h("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=h("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??$m,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=h("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=n.skipLabel??Um,i.setAttribute("data-ask-user-action","skip"),s.appendChild(i);let l=h("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=t===e-1;return l.textContent=p?n.submitAllLabel??zm:n.nextLabel??_m,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Io=t=>{let e=t.getAttribute(ap);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},up=(t,e)=>{t.setAttribute(ap,JSON.stringify(e))},fn=t=>{let e=Number(t.getAttribute(il)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},th=(t,e)=>{t.setAttribute(il,String(Math.max(0,Math.floor(e))))},nr=t=>{let e=Number(t.getAttribute(al)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},so=t=>t.getAttribute(ll)==="true",nh=(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},oh=(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)))},ui=(t,e)=>{let{payload:n}=tr(e),o=Gr(n),r=Io(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},gp=t=>{let e=Io(t),n=fn(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="")},fp=t=>{if(!so(t))return;let e=Io(t),n=fn(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}},dl=(t,e,n)=>{let o=cl(n),r=Vm(t),{payload:s,complete:i}=tr(e),l=so(t),p=fn(t),c=nr(t),d=l?Gm(s,p):Km(s),u=!!d?.multiSelect,y=t.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=l?`${p+1}/${c}`:"");let g=t.querySelector('[data-ask-stepper="true"]');g&&g.remove();let m=t.querySelector('[data-ask-question="true"]');if(m){let E=typeof d?.question=="string"?d.question:"";m.textContent=E,m.classList.toggle("persona-ask-question-skeleton",!E&&!i)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let E=Ym(d,o,i,r);C.replaceWith(E)}if(r!=="rows"){let E=t.querySelector('[data-ask-free-text-row="true"]');E&&E.replaceWith(pp(o,r))}let D=t.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!D?t.appendChild(Zm(o)):(!u||l)&&D&&D.remove(),t.setAttribute("data-multi-select",u?"true":"false");let B=t.querySelector('[data-ask-nav-row="true"]');if(l){let E=eh(p,c,o);B?B.replaceWith(E):t.appendChild(E)}else B&&B.remove();gp(t),fp(t)},rh=(t,e,n)=>{let o=cl(e),r=qm(o),s=t.toolCall.id,i=Gr(n),l=Math.max(1,i.length),p=l>1,c=nh(t,i),d=p?oh(t,l):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(er,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",t.id),u.setAttribute(al,String(l)),u.setAttribute(il,String(d)),u.setAttribute(ll,p?"true":"false"),u.setAttribute(lp,r),up(u,c),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Qm(u,o);let y=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=h("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",y.appendChild(g);let m=h("span","persona-ask-sheet-step-inline");m.setAttribute("data-ask-step-inline","true"),m.textContent="",y.appendChild(m),u.appendChild(y);let D=h("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 D.setAttribute("data-ask-pill-list","true"),D.setAttribute("role","group"),u.appendChild(D),r!=="rows"&&u.appendChild(pp(o,r)),dl(u,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},sh=(t,e,n)=>{let{payload:o}=tr(e),r=Math.max(1,Gr(o).length);r>nr(t)&&(t.setAttribute(al,String(r)),r>1&&!so(t)&&t.setAttribute(ll,"true")),dl(t,e,n)};var gi=(t,e,n)=>{if(!n||!Po(t)||cl(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${er}]`).forEach(c=>{c.getAttribute(er)!==r&&c.remove()});let i=n.querySelector(`[${er}="${cp(r)}"]`);if(i){sh(i,t,e);return}let{payload:l}=tr(t),p=rh(t,e,l);n.appendChild(p)},or=(t,e)=>{if(!t)return;let n=e?`[${er}="${cp(e)}"]`:`[${er}]`;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)})},pl=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),io=(t,e)=>{let n=Io(t),o=fn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,up(t,n),gp(t),fp(t)},fi=(t,e,n,o)=>{let r=nr(t),s=Math.max(0,Math.min(r-1,o));th(t,s),dl(t,e,n)};var _n="suggest_replies";var ih={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},mp={name:_n,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:ih,origin:"sdk",annotations:{readOnlyHint:!0}},ul=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),gl=t=>t.variant==="tool"&&t.toolCall?.name===_n,ah=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.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},hp=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!gl(n))continue;let o=ah(n.toolCall?.args);return o.length>0?o:null}return null},bp=t=>{let e=t?.features?.suggestReplies;return e?.expose===!0&&e.enabled!==!1};var lh={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Kr,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},ch={name:sl,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:lh,origin:"sdk",annotations:{readOnlyHint:!0}},mi=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(ch),bp(t)&&e.push(mp),e};var rr=require("partial-json"),yp=t=>t.replace(/\\n/g,`
181
+ ${t.description}`:"");return window.confirm(n)},Wm=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)}},Hm=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},Bm=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};function Lo(t,e){let n=t?.display;return n?typeof n=="string"?n:n.byType?.[e]??n.default??"panel":"panel"}function pi(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}:{},...t==="inline"&&e.component?{component:e.component}:{},...t==="inline"&&e.componentProps?{componentProps:e.componentProps}:{},...e.markdown!==void 0?{markdown:e.markdown}:{}}})}var Dm="agent_",Nm="flow_";function tp(t){return t.startsWith(Dm)?{kind:"agentId",agentId:t}:t.startsWith(Nm)?{kind:"flowId",flowId:t}:null}function np(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=tp(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=tp(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 ro=require("partial-json");nt();var sl="ask_user_question",Kr=8,er="data-persona-ask-sheet-for",Om="Other",Fm="Other\u2026",sp="Type your own answer here",ip="Send",_m="Next",$m="Back",zm="Submit all",Um="Skip",jm=3,il="data-ask-current-index",al="data-ask-question-count",ap="data-ask-answers",ll="data-ask-grouped",lp="data-ask-layout",qm=t=>t.layout==="pills"?"pills":"rows",Vm=t=>t.getAttribute(lp)==="pills"?"pills":"rows",rp=!1,cp=t=>t.replace(/["\\]/g,"\\$&"),Po=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===sl,cl=t=>t?.features?.askUserQuestion??{},tr=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,ro.parse)(r,ro.STR|ro.OBJ|ro.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Gr=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>Kr&&!rp&&(rp=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Kr}.`)),e.slice(0,Kr)},Km=t=>Gr(t)[0]??null,Gm=(t,e)=>Gr(t)[e]??null,Qm=(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))},dp=(t,e,n)=>{if(t!=="rows")return null;let o=h("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),e){let r=h("span","persona-ask-row-check");o.appendChild(r)}else{let r=h("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},Xm=(t,e,n,o)=>{let s=h("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=h("span","persona-ask-row-content"),l=h("span","persona-ask-row-label");if(l.textContent=t.label,i.appendChild(l),t.description){let c=h("span","persona-ask-row-description");c.textContent=t.description,i.appendChild(c)}s.appendChild(i);let p=dp(n,o,e);p&&s.appendChild(p)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},Jm=t=>{let n=h("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},Ym=(t,e,n,o)=>{let s=h("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<jm;d++)s.appendChild(Jm(o));return s}if(p.forEach((d,u)=>{s.appendChild(Xm(d,u,o,i))}),t?.allowFreeText!==!1){let d=o==="rows"?Om:Fm;if(o==="rows"){let u=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");u.setAttribute("data-ask-user-action","focus-free-text"),u.setAttribute("data-option-index",String(p.length)),u.setAttribute("data-ask-other-row","true");let y=h("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=e.freeTextPlaceholder??sp,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",e.freeTextLabel??d),y.appendChild(g),u.appendChild(y);let m=dp(o,i,p.length);m&&u.appendChild(m),s.appendChild(u)}else{let u=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");u.type="button",u.setAttribute("data-ask-user-action","open-free-text"),u.textContent=e.freeTextLabel??d,s.appendChild(u)}}return s},pp=(t,e)=>{let o=h("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??sp,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),e!=="rows"){let s=h("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=t.submitLabel??ip,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},Zm=t=>{let e=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let n=h("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=t.submitLabel??ip,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},eh=(t,e,n)=>{let o=h("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=h("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??$m,r.setAttribute("data-ask-user-action","back"),r.disabled=t===0,o.appendChild(r);let s=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),i=h("button","persona-ask-nav-skip persona-pointer-events-auto");i.type="button",i.textContent=n.skipLabel??Um,i.setAttribute("data-ask-user-action","skip"),s.appendChild(i);let l=h("button","persona-ask-nav-next persona-pointer-events-auto");l.type="button";let p=t===e-1;return l.textContent=p?n.submitAllLabel??zm:n.nextLabel??_m,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Io=t=>{let e=t.getAttribute(ap);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},up=(t,e)=>{t.setAttribute(ap,JSON.stringify(e))},fn=t=>{let e=Number(t.getAttribute(il)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},th=(t,e)=>{t.setAttribute(il,String(Math.max(0,Math.floor(e))))},nr=t=>{let e=Number(t.getAttribute(al)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},so=t=>t.getAttribute(ll)==="true",nh=(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},oh=(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)))},ui=(t,e)=>{let{payload:n}=tr(e),o=Gr(n),r=Io(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},gp=t=>{let e=Io(t),n=fn(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="")},fp=t=>{if(!so(t))return;let e=Io(t),n=fn(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}},dl=(t,e,n)=>{let o=cl(n),r=Vm(t),{payload:s,complete:i}=tr(e),l=so(t),p=fn(t),c=nr(t),d=l?Gm(s,p):Km(s),u=!!d?.multiSelect,y=t.querySelector('[data-ask-step-inline="true"]');y&&(y.textContent=l?`${p+1}/${c}`:"");let g=t.querySelector('[data-ask-stepper="true"]');g&&g.remove();let m=t.querySelector('[data-ask-question="true"]');if(m){let E=typeof d?.question=="string"?d.question:"";m.textContent=E,m.classList.toggle("persona-ask-question-skeleton",!E&&!i)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let E=Ym(d,o,i,r);C.replaceWith(E)}if(r!=="rows"){let E=t.querySelector('[data-ask-free-text-row="true"]');E&&E.replaceWith(pp(o,r))}let D=t.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!D?t.appendChild(Zm(o)):(!u||l)&&D&&D.remove(),t.setAttribute("data-multi-select",u?"true":"false");let B=t.querySelector('[data-ask-nav-row="true"]');if(l){let E=eh(p,c,o);B?B.replaceWith(E):t.appendChild(E)}else B&&B.remove();gp(t),fp(t)},rh=(t,e,n)=>{let o=cl(e),r=qm(o),s=t.toolCall.id,i=Gr(n),l=Math.max(1,i.length),p=l>1,c=nh(t,i),d=p?oh(t,l):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(er,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",t.id),u.setAttribute(al,String(l)),u.setAttribute(il,String(d)),u.setAttribute(ll,p?"true":"false"),u.setAttribute(lp,r),up(u,c),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Qm(u,o);let y=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=h("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",y.appendChild(g);let m=h("span","persona-ask-sheet-step-inline");m.setAttribute("data-ask-step-inline","true"),m.textContent="",y.appendChild(m),u.appendChild(y);let D=h("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 D.setAttribute("data-ask-pill-list","true"),D.setAttribute("role","group"),u.appendChild(D),r!=="rows"&&u.appendChild(pp(o,r)),dl(u,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},sh=(t,e,n)=>{let{payload:o}=tr(e),r=Math.max(1,Gr(o).length);r>nr(t)&&(t.setAttribute(al,String(r)),r>1&&!so(t)&&t.setAttribute(ll,"true")),dl(t,e,n)};var gi=(t,e,n)=>{if(!n||!Po(t)||cl(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${er}]`).forEach(c=>{c.getAttribute(er)!==r&&c.remove()});let i=n.querySelector(`[${er}="${cp(r)}"]`);if(i){sh(i,t,e);return}let{payload:l}=tr(t),p=rh(t,e,l);n.appendChild(p)},or=(t,e)=>{if(!t)return;let n=e?`[${er}="${cp(e)}"]`:`[${er}]`;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)})},pl=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),io=(t,e)=>{let n=Io(t),o=fn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,up(t,n),gp(t),fp(t)},fi=(t,e,n,o)=>{let r=nr(t),s=Math.max(0,Math.min(r-1,o));th(t,s),dl(t,e,n)};var _n="suggest_replies";var ih={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},mp={name:_n,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:ih,origin:"sdk",annotations:{readOnlyHint:!0}},ul=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),gl=t=>t.variant==="tool"&&t.toolCall?.name===_n,ah=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.filter(r=>typeof r=="string").map(r=>r.trim()).filter(r=>r.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},hp=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!gl(n))continue;let o=ah(n.toolCall?.args);return o.length>0?o:null}return null},bp=t=>{let e=t?.features?.suggestReplies;return e?.expose===!0&&e.enabled!==!1};var lh={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Kr,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},ch={name:sl,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:lh,origin:"sdk",annotations:{readOnlyHint:!0}},mi=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(ch),bp(t)&&e.push(mp),e};var rr=require("partial-json"),yp=t=>t.replace(/\\n/g,`
182
182
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ao=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)}},dh=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`},vp=t=>t.status==="complete"?dh(t):t.status==="pending"?"Waiting":"",ph=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 xp=t=>t.status==="complete"?ph(t):"Using tool...",hi=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Xr=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 hi(e)},bi=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return hi(e)},fl=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=Xr(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},yi=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,i;for(;(i=r.exec(n))!==null;)i.index>s&&Qr(o,n.slice(s,i.index),[]),i[1]!==void 0?Qr(o,i[1],["bold"]):i[2]!==void 0?Qr(o,i[2],["italic"]):i[3]!==void 0&&Qr(o,i[3],["dim"]),s=i.index+i[0].length;return s<n.length&&Qr(o,n.slice(s),[]),o},Qr=(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})},uh=()=>{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
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()=>{}}},Jr=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Cp=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},wp=()=>{let t=uh();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)}},Ap=()=>{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,rr.parse)(n,rr.STR|rr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?yp(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=yp(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var Sp=()=>{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 Mp="4.11.0";var Yr=Mp;var fh="https://api.runtype.com/v1/dispatch",vi="https://api.runtype.com";function mh(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 ml=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 hh(t){switch(t){case"json":return Ap;case"regex-json":return wp;case"xml":return Sp;default:return Cp}}var Tp=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function bh(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=Tp(n);if(!Tp(o))return t;if(!r||o===n||o.startsWith(n))return e;let i=Jr(t);return Jr(e)!==null&&i===null?e:t}var Zr=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??fh,this.headers={"Content-Type":"application/json","X-Persona-Version":Yr,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??hh(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 di(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=np(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$/,"")||vi}/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":Yr},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$/,"")||vi}/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":Yr},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(ml).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":Yr},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 u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(c.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}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$/,"")||vi}/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?Zd(n):void 0,l=this.clientToolsFingerprintSessionId===e,p=s&&l&&this.lastSentClientToolsFingerprint===i,c=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,d=!1,u;for(let y=0;;y++){if(u=await o({...s&&(d||!p)&&n?{clientTools:n}:{},...c?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),u.status===409&&y===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){d=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,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(/\/+$/,"")||vi}/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=[...mi(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:d,commit:u}=await this.sendWithClientToolsDiff(i,c,y=>{let g={...p,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:l,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return d.ok&&u(),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(ml).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=[...mi(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(ml).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=[...mi(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 u={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=u,r(u),u},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++,u=k=>{let j=k.reasoning?{...k.reasoning,chunks:[...k.reasoning.chunks]}:void 0,v=k.toolCall?{...k.toolCall,chunks:k.toolCall.chunks?[...k.toolCall.chunks]:void 0}:void 0,T=k.tools?k.tools.map(R=>({...R,chunks:R.chunks?[...R.chunks]:void 0})):void 0;return{...k,reasoning:j,toolCall:v,tools:T}},y=k=>{if(k.role!=="assistant"||k.variant)return!0;let j=Array.isArray(k.contentParts)&&k.contentParts.length>0,v=typeof k.rawContent=="string"&&k.rawContent.trim()!=="";return typeof k.content=="string"&&k.content.trim()!==""||j||v||!!k.stopReason},g=k=>{y(k)&&n({type:"message",message:u(k)})},m=null,C=null,D={current:null},B={current:null},E=null,A="",W=new Map,z=new Map,G=new Map,w=new Map,O=new Map,N={lastId:null,byStep:new Map},L={lastId:null,byCall:new Map},P=k=>{if(k==null)return null;try{return String(k)}catch{return null}},I=k=>P(k.stepId??k.step_id??k.step??k.parentId??k.flowStepId??k.flow_step_id),Y=k=>P(k.callId??k.call_id??k.requestId??k.request_id??k.toolCallId??k.tool_call_id??k.stepId??k.step_id),de=o,ue=!1,pe=()=>{if(m)return m;let k,j="",v=E;return!ue&&de?(k=de,ue=!0,j=r??""):de&&v?k=`${de}_${v}`:k=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:k,role:"assistant",content:j,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},g(m),m},ee=(k,j)=>{N.lastId=j,k&&N.byStep.set(k,j)},oe=(k,j)=>{let v=k.reasoningId??k.id,T=I(k);if(v){let _=String(v);return ee(T,_),_}if(T){let _=N.byStep.get(T);if(_)return N.lastId=_,_}if(N.lastId&&!j)return N.lastId;if(!j)return null;let R=`reason-${d()}`;return ee(T,R),R},V=k=>{let j=w.get(k);if(j)return j;let v={id:`reason-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:k,status:"streaming",chunks:[]}};return w.set(k,v),g(v),v},ae=(k,j)=>{L.lastId=j,k&&L.byCall.set(k,j)},ne=new Set,me=new Map,be=new Set,fe=new Map,Te=k=>{if(!k)return!1;let j=k.replace(/_+/g,"_").replace(/^_|_$/g,"");return j==="emit_artifact_markdown"||j==="emit_artifact_component"},Se=(k,j)=>{let v=k.toolId??k.id,T=Y(k);if(v){let _=String(v);return ae(T,_),_}if(T){let _=L.byCall.get(T);if(_)return L.lastId=_,_}if(L.lastId&&!j)return L.lastId;if(!j)return null;let R=`tool-${d()}`;return ae(T,R),R},Fe=k=>{let j=O.get(k);if(j)return j;let v={id:`tool-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:k,status:"pending"}};return O.set(k,v),g(v),v},ke=k=>{if(typeof k=="number"&&Number.isFinite(k))return k;if(typeof k=="string"){let j=Number(k);if(!Number.isNaN(j)&&Number.isFinite(j))return j;let v=Date.parse(k);if(!Number.isNaN(v))return v}return Date.now()},qe=k=>{if(typeof k=="string")return k;if(k==null)return"";try{return JSON.stringify(k)}catch{return String(k)}},Xe=new Map,He=new Map,Le=new Map,Je=(k,j,v)=>{let T=Le.get(k);T||(T=[],Le.set(k,T));let R=0,_=T.length;for(;R<_;){let $=R+_>>>1;T[$].seq<j?R=$+1:_=$}T[R]?.seq===j?T[R]={seq:j,text:v}:T.splice(R,0,{seq:j,text:v});let Q="";for(let $=0;$<T.length;$++)Q+=T[$].text;return Q},ln=(k,j)=>{let v=qe(j),T=He.get(k.id),R=bh(T,v);k.rawContent=R;let _=Xe.get(k.id),Q=Pe=>{let it=k.content??"";Pe.trim()!==""&&(it.trim().length===0||Pe.startsWith(it)||Pe.trimStart().startsWith(it.trim()))&&(k.content=Pe)},$=()=>{if(_){let Pe=_.close?.();Pe instanceof Promise&&Pe.catch(()=>{})}Xe.delete(k.id),He.delete(k.id),k.streaming=!1,g(k)};if(!_){Q(v),$();return}let K=Jr(R);if(K!==null&&K.trim()!==""){Q(K),$();return}let ce=Pe=>{let it=typeof Pe=="string"?Pe:Pe?.text??null;if(it!==null&&it.trim()!=="")return it;let X=_.getExtractedText();return X!==null&&X.trim()!==""?X:v},Ve;try{Ve=_.processChunk(R)}catch{Q(v),$();return}if(Ve instanceof Promise){Ve.then(Pe=>{Q(ce(Pe)),$()}).catch(()=>{Q(v),$()});return}Q(ce(Ve)),$()},Lt=null,xt=(k,j,v,T)=>{k.rawContent=j,Xe.has(k.id)||Xe.set(k.id,this.createStreamParser());let R=Xe.get(k.id),_=j.trim().startsWith("{")||j.trim().startsWith("[");if(_&&He.set(k.id,j),R.__isPlainTextParser===!0){k.content=T!==void 0?j:k.content+v,He.delete(k.id),Xe.delete(k.id),k.rawContent=void 0,g(k);return}let $=R.processChunk(j);if($ instanceof Promise)$.then(K=>{let ce=typeof K=="string"?K:K?.text??null;ce!==null&&ce.trim()!==""?(k.content=ce,g(k)):!_&&!j.trim().startsWith("<")&&(k.content=T!==void 0?j:k.content+v,He.delete(k.id),Xe.delete(k.id),k.rawContent=void 0,g(k))}).catch(()=>{k.content=T!==void 0?j:k.content+v,He.delete(k.id),Xe.delete(k.id),k.rawContent=void 0,g(k)});else{let K=typeof $=="string"?$:$?.text??null;K!==null&&K.trim()!==""?(k.content=K,g(k)):!_&&!j.trim().startsWith("<")&&(k.content=T!==void 0?j:k.content+v,He.delete(k.id),Xe.delete(k.id),k.rawContent=void 0,g(k))}},Be=(k,j)=>{let v=j??k.content;if(v==null||v===""){k.streaming=!1,g(k);return}let R=He.get(k.id)??qe(v);k.rawContent=R;let _=Xe.get(k.id),Q=null,$=!1;if(_&&(Q=_.getExtractedText(),Q===null&&(Q=Jr(R)),Q===null)){let K=_.processChunk(R);K instanceof Promise?($=!0,K.then(ce=>{let Ve=typeof ce=="string"?ce:ce?.text??null;Ve!==null&&(k.content=Ve,k.streaming=!1,Xe.delete(k.id),He.delete(k.id),g(k))}).catch(()=>{})):Q=typeof K=="string"?K:K?.text??null}if(!$){Q!==null&&Q.trim()!==""?k.content=Q:He.has(k.id)||(k.content=qe(v));let K=Xe.get(k.id);if(K){let ce=K.close?.();ce instanceof Promise&&ce.catch(()=>{}),Xe.delete(k.id)}He.delete(k.id),k.streaming=!1,g(k)}},Ce=(k,j,v)=>{let T=z.get(k);if(T)return T;let R={id:`nested-${j}-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:k,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:j}};return z.set(k,R),g(R),R},Ge=[],Ie,ye=new Map,ge=0,we="agent",Ct=!1,Ae=null,he=null,hn=new Map,te=this.config.iterationDisplay??"separate";for(Ie=()=>{for(let k=0;k<Ge.length;k++){let j=Ge[k].payloadType,v=Ge[k].payload;if(!Ct&&we!=="flow"&&typeof v.stepType=="string"&&(we="flow"),j==="reasoning_start"){let T=typeof v.id=="string"?v.id:null,R=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(T&&R){W.set(T,R),Ce(T,R,"reasoning");continue}let _=oe(v,!0)??`reason-${d()}`,Q=V(_);Q.reasoning=Q.reasoning??{id:_,status:"streaming",chunks:[]},Q.reasoning.startedAt=Q.reasoning.startedAt??ke(v.startedAt??v.timestamp),Q.reasoning.completedAt=void 0,Q.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(Q.reasoning.scope=v.scope),Q.streaming=!0,Q.reasoning.status="streaming",g(Q)}else if(j==="reasoning_delta"){let T=typeof v.id=="string"?v.id:null;if(T&&W.has(T)&&z.has(T)){let $=z.get(T),K=v.reasoningText??v.text??v.delta??"";K&&v.hidden!==!0&&$.reasoning&&($.reasoning.chunks.push(String(K)),g($));continue}let R=oe(v,!1)??oe(v,!0)??`reason-${d()}`,_=V(R);_.reasoning=_.reasoning??{id:R,status:"streaming",chunks:[]},_.reasoning.startedAt=_.reasoning.startedAt??ke(v.startedAt??v.timestamp);let Q=v.reasoningText??v.text??v.delta??"";if(Q&&v.hidden!==!0){let $=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if($!==void 0){let K=Je(R,$,String(Q));_.reasoning.chunks=[K]}else _.reasoning.chunks.push(String(Q))}if(_.reasoning.status=v.done?"complete":"streaming",v.done){_.reasoning.completedAt=ke(v.completedAt??v.timestamp);let $=_.reasoning.startedAt??Date.now();_.reasoning.durationMs=Math.max(0,(_.reasoning.completedAt??Date.now())-$)}_.streaming=_.reasoning.status!=="complete",g(_)}else if(j==="reasoning_complete"){let T=typeof v.id=="string"?v.id:null;if(T&&W.has(T)&&z.has(T)){let K=z.get(T);if(K.reasoning){let ce=typeof v.text=="string"?v.text:"";ce&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(ce),K.reasoning.status="complete",K.streaming=!1,g(K)}W.delete(T),z.delete(T);continue}let R=oe(v,!1)??oe(v,!0)??`reason-${d()}`,_=typeof v.text=="string"?v.text:"";!w.get(R)&&(_||v.scope==="loop")&&V(R);let Q=w.get(R);if(Q?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(Q.reasoning.scope=v.scope),_&&Q.reasoning.chunks.length===0&&Q.reasoning.chunks.push(_),Q.reasoning.status="complete",Q.reasoning.completedAt=ke(v.completedAt??v.timestamp);let K=Q.reasoning.startedAt??Date.now();Q.reasoning.durationMs=Math.max(0,(Q.reasoning.completedAt??Date.now())-K),Q.streaming=!1,g(Q)}let $=I(v);$&&N.byStep.delete($)}else if(j==="tool_start"){m&&(m.streaming=!1,g(m),m=null),typeof v.iteration=="number"&&(ge=v.iteration);let T=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??Se(v,!0)??`tool-${d()}`,R=v.toolName??v.name;if(Te(R)){ne.add(T);continue}ae(Y(v),T);let _=Fe(T),Q=_.toolCall??{id:T,status:"pending"};Q.name=R??Q.name,Q.status="running",v.parameters!==void 0?Q.args=v.parameters:v.args!==void 0&&(Q.args=v.args),Q.startedAt=Q.startedAt??ke(v.startedAt??v.timestamp),Q.completedAt=void 0,Q.durationMs=void 0,_.toolCall=Q,_.streaming=!0,v.executionId&&(_.agentMetadata={executionId:v.executionId,iteration:v.iteration}),g(_)}else if(j==="tool_output_delta"){let T=Se(v,!1)??Se(v,!0)??`tool-${d()}`;if(ne.has(T))continue;let R=Fe(T),_=R.toolCall??{id:T,status:"running"};_.startedAt=_.startedAt??ke(v.startedAt??v.timestamp);let Q=v.text??v.delta??v.message??"";Q&&(_.chunks=_.chunks??[],_.chunks.push(String(Q))),_.status="running",R.toolCall=_,R.streaming=!0;let $=v.agentContext;($||v.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:$?.executionId??v.executionId,iteration:$?.iteration??v.iteration}),g(R)}else if(j==="tool_complete"){let T=Se(v,!1)??Se(v,!0)??`tool-${d()}`;if(ne.has(T)){ne.delete(T);continue}let R=Fe(T),_=R.toolCall??{id:T,status:"running"};_.status="complete",v.result!==void 0&&(_.result=v.result),typeof v.duration=="number"&&(_.duration=v.duration),_.completedAt=ke(v.completedAt??v.timestamp);let Q=v.duration??v.executionTime;if(typeof Q=="number")_.durationMs=Q;else{let ce=_.startedAt??Date.now();_.durationMs=Math.max(0,(_.completedAt??Date.now())-ce)}R.toolCall=_,R.streaming=!1;let $=v.agentContext;($||v.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:$?.executionId??v.executionId,iteration:$?.iteration??v.iteration}),g(R);let K=Y(v);K&&L.byCall.delete(K)}else if(j==="await"&&v.toolName){let T=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,R=T??v.toolId??`local-${d()}`,_=Fe(R),Q=v.toolName,$=v.origin==="webmcp"&&!Zo(Q)?`webmcp:${Q}`:Q,K=Zo($),ce=_.toolCall??{id:R,status:"pending"};ce.name=$,ce.args=v.parameters,ce.status=K?"running":"complete",ce.chunks=ce.chunks??[],ce.startedAt=ce.startedAt??ke(v.startedAt??v.timestamp??v.awaitedAt),K?(ce.completedAt=void 0,ce.duration=void 0,ce.durationMs=void 0):ce.completedAt=ce.completedAt??ce.startedAt,_.toolCall=ce,_.streaming=!1,_.agentMetadata={..._.agentMetadata,executionId:v.executionId??_.agentMetadata?.executionId,awaitingLocalTool:!0,...T?{webMcpToolCallId:T}:{}},g(_)}else if(j==="text_start"){let T=typeof v.id=="string"?v.id:null,R=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(T&&R){W.set(T,R);continue}let _=m;_&&(we==="flow"?(Be(_),Lt=_):(_.streaming=!1,g(_)),m=null),E=typeof v.id=="string"?v.id:E,A=""}else if(j==="text_delta"){let T=typeof v.id=="string"?v.id:null,R=T?W.get(T):void 0;if(T&&R){let Q=typeof v.delta=="string"?v.delta:"",$=(G.get(T)??"")+Q;if(G.set(T,$),$.trim()==="")continue;let K=Ce(T,R);K.agentMetadata={...K.agentMetadata,executionId:v.executionId,parentToolId:R},xt(K,$,Q,void 0);continue}if(E=typeof v.id=="string"?v.id:E,we==="flow"){let Q=typeof v.delta=="string"?v.delta:"";if(A+=Q,A.trim()==="")continue;let $=pe();$.agentMetadata={executionId:v.executionId,iteration:v.iteration},xt($,A,Q,void 0),C=$;continue}let _=pe();_.content+=v.delta??"",_.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:Ae??void 0,agentName:he?.agentName},C=_,g(_)}else if(j==="text_complete"){let T=typeof v.id=="string"?v.id:null;if(T&&W.has(T)){let _=z.get(T);_&&Be(_),W.delete(T),G.delete(T),z.delete(T);continue}let R=m;R&&(we==="flow"?(Be(R),Lt=R):((R.content??"")===""&&typeof v.text=="string"&&(R.content=v.text),R.streaming=!1,g(R)),m=null),E=null,A=""}else if(j==="step_complete"){let T=v.stepType,R=v.executionType;if(T==="tool"||R==="context")continue;if(v.success===!1){let _=v.error,Q=typeof _=="string"&&_!==""?_:_!=null&&typeof _=="object"&&Reflect.has(_,"message")?String(_.message??"Step failed"):"Step failed";n({type:"error",error:new Error(Q)});let $=m;$&&$.streaming&&($.streaming=!1,g($)),n({type:"status",status:"idle"});continue}{let _=Lt;Lt=null;let Q=v.stopReason,$=v.result?.response;if(_)Q&&(_.stopReason=Q),$!=null?ln(_,$):_.streaming!==!1&&(Xe.delete(_.id),He.delete(_.id),_.streaming=!1,g(_));else{let K=$!=null&&$!=="";if(K||Q){let ce=pe();Q&&(ce.stopReason=Q),K?Be(ce,$):(ce.streaming=!1,g(ce))}}continue}}else if(j==="execution_start")we=v.kind==="flow"?"flow":"agent",Ct=!0,we==="agent"&&(he={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:ke(v.startedAt)});else if(j==="turn_start"){let T=typeof v.iteration=="number"?v.iteration:ge;if(T!==ge){if(he&&(he.currentIteration=T),te==="separate"&&T>1){let R=m;R&&(R.streaming=!1,g(R),hn.set(T-1,R),m=null)}ge=T}Ae=typeof v.id=="string"?v.id:null,C=null}else if(j==="tool_input_delta"){let T=v.toolCallId??L.lastId;if(T){let R=O.get(T);R?.toolCall&&(R.toolCall.chunks=R.toolCall.chunks??[],R.toolCall.chunks.push(v.delta??""),g(R))}}else{if(j==="tool_input_complete")continue;if(j==="turn_complete"){let T=v.stopReason,R=m??C;if(T&&R!==null){let _=v.id;(!_||R.agentMetadata?.turnId===_)&&(R.stopReason=T,g(R))}Ae===v.id&&(Ae=null)}else if(j==="media_start"){let T=String(v.id);ye.set(T,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(j==="media_delta"){let T=ye.get(String(v.id));T&&typeof v.delta=="string"&&T.parts.push(v.delta)}else if(j==="media_complete"){let T=String(v.id),R=ye.get(T);ye.delete(T);let _=(typeof v.mediaType=="string"?v.mediaType:void 0)??R?.mediaType??"application/octet-stream",Q=typeof v.data=="string"?v.data:void 0,$=typeof v.url=="string"?v.url:R&&R.parts.length>0?R.parts.join(""):void 0,K=null;if(Q)K={type:"media",data:Q,mediaType:_};else if($){let it=_.toLowerCase();K={type:it==="image"||it.startsWith("image/")?"image-url":"file-url",url:$,mediaType:_}}let ce=v.toolCallId??R?.toolCallId,Ve=K?[K]:[],Pe=[];for(let it of Ve){if(!it||typeof it!="object")continue;let X=it,ze=typeof X.type=="string"?X.type:void 0,Ee=typeof X.mediaType=="string"?X.mediaType.toLowerCase():"",We=null,Re="";if(ze==="media"){let Ye=typeof X.data=="string"?X.data:void 0;if(!Ye)continue;Re=Ee.length>0?Ee:"application/octet-stream",We=`data:${Re};base64,${Ye}`}else if(ze==="image-url"){let Ye=typeof X.url=="string"?X.url:void 0;if(!Ye)continue;Re=Ee,We=Ye}else if(ze==="file-url"){let Ye=typeof X.url=="string"?X.url:void 0;if(!Ye)continue;Re=Ee,We=Ye}else continue;if(We)if(ze==="image-url"||Re.startsWith("image/"))Pe.push({type:"image",image:We,...Re.includes("/")?{mimeType:Re}:{}});else if(Re.startsWith("audio/"))Pe.push({type:"audio",audio:We,mimeType:Re});else if(Re.startsWith("video/"))Pe.push({type:"video",video:We,mimeType:Re});else{let Ye=Re||"application/octet-stream";Pe.push({type:"file",data:We,mimeType:Ye,filename:mh(Ye)})}}if(Pe.length>0){let it=d(),X=ce,Ee={id:`agent-media-${typeof X=="string"&&X.length>0?`${X}-${it}`:String(it)}`,role:"assistant",content:"",contentParts:Pe,createdAt:new Date().toISOString(),streaming:!1,sequence:it,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:ge}};g(Ee);let We=m;We&&(We.streaming=!1,g(We)),m=null,D.current=null}}else if(j==="execution_complete"){let T=v.kind??we;T==="agent"&&he&&(he.status=v.success?"complete":"error",he.completedAt=ke(v.completedAt),he.stopReason=v.stopReason);let R=m;R&&(T==="flow"&&R.streaming!==!1?Be(R):(R.streaming=!1,g(R)),m=null),E=null,A="",Lt=null,n({type:"status",status:"idle",terminal:!0})}else if(j==="execution_error"){let T=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(T)})}else if(j!=="ping"){if(j==="approval_start"){let T=v.approvalId??`approval-${d()}`,R={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:T,status:"pending",agentId:he?.agentId??"virtual",executionId:v.executionId??he?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};g(R)}else if(j==="step_await"&&v.awaitReason==="approval_required"){let T=v.approvalId??`approval-${d()}`,R={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:T,status:"pending",agentId:he?.agentId??"virtual",executionId:v.executionId??he?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};g(R)}else if(j==="approval_complete"){let T=v.approvalId;if(T){let _={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:T,status:v.decision??"approved",agentId:he?.agentId??"virtual",executionId:v.executionId??he?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};g(_)}}else if(j==="artifact_start"||j==="artifact_delta"||j==="artifact_update"||j==="artifact_complete"){if(j==="artifact_start"){let T=v.artifactType,R=String(v.id),_=typeof v.title=="string"?v.title:void 0,Q=v.file,$;Q&&typeof Q=="object"&&!Array.isArray(Q)&&typeof Q.path=="string"&&typeof Q.mimeType=="string"&&($={path:Q.path,mimeType:Q.mimeType,...typeof Q.language=="string"?{language:Q.language}:{}}),n({type:"artifact_start",id:R,artifactType:T,title:_,component:typeof v.component=="string"?v.component:void 0,...$?{file:$}:{}});let K=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(fe.set(R,{markdown:"",title:_,file:$,...K?{props:K}:{}}),!be.has(R)){be.add(R);let ce=Lo(this.config.features?.artifacts,T),Ve=typeof v.component=="string"?v.component:void 0,Pe={id:`artifact-ref-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:pi(ce,{artifactId:R,title:_,artifactType:T,status:"streaming",...$?{file:$}:{},...Ve?{component:Ve}:{}})};me.set(R,Pe),g(Pe)}}else if(j==="artifact_delta"){let T=String(v.id),R=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:T,artDelta:R});let _=fe.get(T);_&&(_.markdown+=R)}else if(j==="artifact_update"){let T=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:T,component:typeof v.component=="string"?v.component:void 0});let R=fe.get(String(v.id));R&&(R.props={...R.props??{},...T})}else if(j==="artifact_complete"){let T=String(v.id);n({type:"artifact_complete",id:T});let R=me.get(T);if(R){R.streaming=!1;try{let _=JSON.parse(R.rawContent??"{}");if(_.props){_.props.status="complete";let Q=fe.get(T);Q?.markdown&&(_.props.markdown=Q.markdown),Q?.file&&(_.props.file=Q.file),_.component==="PersonaArtifactInline"&&Q?.props&&Object.keys(Q.props).length>0&&(_.props.componentProps=Q.props)}R.rawContent=JSON.stringify(_)}catch{}fe.delete(T),g(R),me.delete(T)}}}else if(j==="transcript_insert"){let T=v.message;if(!T||typeof T!="object")continue;let R=String(T.id??`msg-${d()}`),_=T.role,$={id:R,role:_==="user"?"user":_==="system"?"system":"assistant",content:typeof T.content=="string"?T.content:"",rawContent:typeof T.rawContent=="string"?T.rawContent:void 0,createdAt:typeof T.createdAt=="string"?T.createdAt:new Date().toISOString(),streaming:T.streaming===!0,...typeof T.variant=="string"?{variant:T.variant}:{},sequence:d()};if(g($),$.rawContent)try{let ce=JSON.parse($.rawContent)?.props?.artifactId;typeof ce=="string"&&be.add(ce)}catch{}m=null,D.current=null,Xe.delete(R),He.delete(R)}else if(j==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let T=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(T)});let R=m;R&&R.streaming&&(R.streaming=!1,g(R)),n({type:"status",status:"idle"})}}else if(j==="step_error"||j==="dispatch_error"||j==="flow_error"){let T=null;if(v.error instanceof Error)T=v.error;else if(j==="dispatch_error"){let R=v.message??v.error;R!=null&&R!==""&&(T=new Error(String(R)))}else{let R=v.error;typeof R=="string"&&R!==""?T=new Error(R):R!=null&&typeof R=="object"&&Reflect.has(R,"message")&&(T=new Error(String(R.message??R)))}if(T){n({type:"error",error:T});let R=m;R&&R.streaming&&(R.streaming=!1,g(R)),n({type:"status",status:"idle"})}}}}}Ge.length=0};;){let{done:k,value:j}=await s.read();if(k)break;l+=i.decode(j,{stream:!0});let v=l.split(`
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()=>{}}},Jr=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Cp=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},wp=()=>{let t=uh();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)}},Ap=()=>{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,rr.parse)(n,rr.STR|rr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?yp(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=yp(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var Sp=()=>{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 Mp="4.12.0";var Yr=Mp;var fh="https://api.runtype.com/v1/dispatch",vi="https://api.runtype.com";function mh(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 ml=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 hh(t){switch(t){case"json":return Ap;case"regex-json":return wp;case"xml":return Sp;default:return Cp}}var Tp=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function bh(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=Tp(n);if(!Tp(o))return t;if(!r||o===n||o.startsWith(n))return e;let i=Jr(t);return Jr(e)!==null&&i===null?e:t}var Zr=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??fh,this.headers={"Content-Type":"application/json","X-Persona-Version":Yr,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??hh(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 di(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=np(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$/,"")||vi}/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":Yr},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$/,"")||vi}/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":Yr},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(ml).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":Yr},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 u=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:u}),u}if(l.status===429){let u=new Error(c.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}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$/,"")||vi}/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?Zd(n):void 0,l=this.clientToolsFingerprintSessionId===e,p=s&&l&&this.lastSentClientToolsFingerprint===i,c=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===e,d=!1,u;for(let y=0;;y++){if(u=await o({...s&&(d||!p)&&n?{clientTools:n}:{},...c?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),u.status===409&&y===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){d=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,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(/\/+$/,"")||vi}/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=[...mi(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:d,commit:u}=await this.sendWithClientToolsDiff(i,c,y=>{let g={...p,...y};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:l,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return d.ok&&u(),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(ml).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=[...mi(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(ml).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=[...mi(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 u={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=u,r(u),u},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++,u=k=>{let j=k.reasoning?{...k.reasoning,chunks:[...k.reasoning.chunks]}:void 0,v=k.toolCall?{...k.toolCall,chunks:k.toolCall.chunks?[...k.toolCall.chunks]:void 0}:void 0,T=k.tools?k.tools.map(R=>({...R,chunks:R.chunks?[...R.chunks]:void 0})):void 0;return{...k,reasoning:j,toolCall:v,tools:T}},y=k=>{if(k.role!=="assistant"||k.variant)return!0;let j=Array.isArray(k.contentParts)&&k.contentParts.length>0,v=typeof k.rawContent=="string"&&k.rawContent.trim()!=="";return typeof k.content=="string"&&k.content.trim()!==""||j||v||!!k.stopReason},g=k=>{y(k)&&n({type:"message",message:u(k)})},m=null,C=null,D={current:null},B={current:null},E=null,A="",W=new Map,z=new Map,G=new Map,w=new Map,O=new Map,N={lastId:null,byStep:new Map},L={lastId:null,byCall:new Map},P=k=>{if(k==null)return null;try{return String(k)}catch{return null}},I=k=>P(k.stepId??k.step_id??k.step??k.parentId??k.flowStepId??k.flow_step_id),Y=k=>P(k.callId??k.call_id??k.requestId??k.request_id??k.toolCallId??k.tool_call_id??k.stepId??k.step_id),de=o,ue=!1,pe=()=>{if(m)return m;let k,j="",v=E;return!ue&&de?(k=de,ue=!0,j=r??""):de&&v?k=`${de}_${v}`:k=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:k,role:"assistant",content:j,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},g(m),m},ee=(k,j)=>{N.lastId=j,k&&N.byStep.set(k,j)},oe=(k,j)=>{let v=k.reasoningId??k.id,T=I(k);if(v){let _=String(v);return ee(T,_),_}if(T){let _=N.byStep.get(T);if(_)return N.lastId=_,_}if(N.lastId&&!j)return N.lastId;if(!j)return null;let R=`reason-${d()}`;return ee(T,R),R},V=k=>{let j=w.get(k);if(j)return j;let v={id:`reason-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:k,status:"streaming",chunks:[]}};return w.set(k,v),g(v),v},ae=(k,j)=>{L.lastId=j,k&&L.byCall.set(k,j)},ne=new Set,me=new Map,be=new Set,fe=new Map,Te=k=>{if(!k)return!1;let j=k.replace(/_+/g,"_").replace(/^_|_$/g,"");return j==="emit_artifact_markdown"||j==="emit_artifact_component"},Se=(k,j)=>{let v=k.toolId??k.id,T=Y(k);if(v){let _=String(v);return ae(T,_),_}if(T){let _=L.byCall.get(T);if(_)return L.lastId=_,_}if(L.lastId&&!j)return L.lastId;if(!j)return null;let R=`tool-${d()}`;return ae(T,R),R},Fe=k=>{let j=O.get(k);if(j)return j;let v={id:`tool-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:k,status:"pending"}};return O.set(k,v),g(v),v},ke=k=>{if(typeof k=="number"&&Number.isFinite(k))return k;if(typeof k=="string"){let j=Number(k);if(!Number.isNaN(j)&&Number.isFinite(j))return j;let v=Date.parse(k);if(!Number.isNaN(v))return v}return Date.now()},Ve=k=>{if(typeof k=="string")return k;if(k==null)return"";try{return JSON.stringify(k)}catch{return String(k)}},Je=new Map,Ne=new Map,Pe=new Map,Ye=(k,j,v)=>{let T=Pe.get(k);T||(T=[],Pe.set(k,T));let R=0,_=T.length;for(;R<_;){let $=R+_>>>1;T[$].seq<j?R=$+1:_=$}T[R]?.seq===j?T[R]={seq:j,text:v}:T.splice(R,0,{seq:j,text:v});let Q="";for(let $=0;$<T.length;$++)Q+=T[$].text;return Q},ln=(k,j)=>{let v=Ve(j),T=Ne.get(k.id),R=bh(T,v);k.rawContent=R;let _=Je.get(k.id),Q=Ie=>{let it=k.content??"";Ie.trim()!==""&&(it.trim().length===0||Ie.startsWith(it)||Ie.trimStart().startsWith(it.trim()))&&(k.content=Ie)},$=()=>{if(_){let Ie=_.close?.();Ie instanceof Promise&&Ie.catch(()=>{})}Je.delete(k.id),Ne.delete(k.id),k.streaming=!1,g(k)};if(!_){Q(v),$();return}let K=Jr(R);if(K!==null&&K.trim()!==""){Q(K),$();return}let ce=Ie=>{let it=typeof Ie=="string"?Ie:Ie?.text??null;if(it!==null&&it.trim()!=="")return it;let X=_.getExtractedText();return X!==null&&X.trim()!==""?X:v},Ke;try{Ke=_.processChunk(R)}catch{Q(v),$();return}if(Ke instanceof Promise){Ke.then(Ie=>{Q(ce(Ie)),$()}).catch(()=>{Q(v),$()});return}Q(ce(Ke)),$()},kt=null,vt=(k,j,v,T)=>{k.rawContent=j,Je.has(k.id)||Je.set(k.id,this.createStreamParser());let R=Je.get(k.id),_=j.trim().startsWith("{")||j.trim().startsWith("[");if(_&&Ne.set(k.id,j),R.__isPlainTextParser===!0){k.content=T!==void 0?j:k.content+v,Ne.delete(k.id),Je.delete(k.id),k.rawContent=void 0,g(k);return}let $=R.processChunk(j);if($ instanceof Promise)$.then(K=>{let ce=typeof K=="string"?K:K?.text??null;ce!==null&&ce.trim()!==""?(k.content=ce,g(k)):!_&&!j.trim().startsWith("<")&&(k.content=T!==void 0?j:k.content+v,Ne.delete(k.id),Je.delete(k.id),k.rawContent=void 0,g(k))}).catch(()=>{k.content=T!==void 0?j:k.content+v,Ne.delete(k.id),Je.delete(k.id),k.rawContent=void 0,g(k)});else{let K=typeof $=="string"?$:$?.text??null;K!==null&&K.trim()!==""?(k.content=K,g(k)):!_&&!j.trim().startsWith("<")&&(k.content=T!==void 0?j:k.content+v,Ne.delete(k.id),Je.delete(k.id),k.rawContent=void 0,g(k))}},Oe=(k,j)=>{let v=j??k.content;if(v==null||v===""){k.streaming=!1,g(k);return}let R=Ne.get(k.id)??Ve(v);k.rawContent=R;let _=Je.get(k.id),Q=null,$=!1;if(_&&(Q=_.getExtractedText(),Q===null&&(Q=Jr(R)),Q===null)){let K=_.processChunk(R);K instanceof Promise?($=!0,K.then(ce=>{let Ke=typeof ce=="string"?ce:ce?.text??null;Ke!==null&&(k.content=Ke,k.streaming=!1,Je.delete(k.id),Ne.delete(k.id),g(k))}).catch(()=>{})):Q=typeof K=="string"?K:K?.text??null}if(!$){Q!==null&&Q.trim()!==""?k.content=Q:Ne.has(k.id)||(k.content=Ve(v));let K=Je.get(k.id);if(K){let ce=K.close?.();ce instanceof Promise&&ce.catch(()=>{}),Je.delete(k.id)}Ne.delete(k.id),k.streaming=!1,g(k)}},Ce=(k,j,v)=>{let T=z.get(k);if(T)return T;let R={id:`nested-${j}-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:k,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:j}};return z.set(k,R),g(R),R},Qe=[],Re,ye=new Map,ge=0,we="agent",xt=!1,Ae=null,he=null,hn=new Map,te=this.config.iterationDisplay??"separate";for(Re=()=>{for(let k=0;k<Qe.length;k++){let j=Qe[k].payloadType,v=Qe[k].payload;if(!xt&&we!=="flow"&&typeof v.stepType=="string"&&(we="flow"),j==="reasoning_start"){let T=typeof v.id=="string"?v.id:null,R=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(T&&R){W.set(T,R),Ce(T,R,"reasoning");continue}let _=oe(v,!0)??`reason-${d()}`,Q=V(_);Q.reasoning=Q.reasoning??{id:_,status:"streaming",chunks:[]},Q.reasoning.startedAt=Q.reasoning.startedAt??ke(v.startedAt??v.timestamp),Q.reasoning.completedAt=void 0,Q.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(Q.reasoning.scope=v.scope),Q.streaming=!0,Q.reasoning.status="streaming",g(Q)}else if(j==="reasoning_delta"){let T=typeof v.id=="string"?v.id:null;if(T&&W.has(T)&&z.has(T)){let $=z.get(T),K=v.reasoningText??v.text??v.delta??"";K&&v.hidden!==!0&&$.reasoning&&($.reasoning.chunks.push(String(K)),g($));continue}let R=oe(v,!1)??oe(v,!0)??`reason-${d()}`,_=V(R);_.reasoning=_.reasoning??{id:R,status:"streaming",chunks:[]},_.reasoning.startedAt=_.reasoning.startedAt??ke(v.startedAt??v.timestamp);let Q=v.reasoningText??v.text??v.delta??"";if(Q&&v.hidden!==!0){let $=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if($!==void 0){let K=Ye(R,$,String(Q));_.reasoning.chunks=[K]}else _.reasoning.chunks.push(String(Q))}if(_.reasoning.status=v.done?"complete":"streaming",v.done){_.reasoning.completedAt=ke(v.completedAt??v.timestamp);let $=_.reasoning.startedAt??Date.now();_.reasoning.durationMs=Math.max(0,(_.reasoning.completedAt??Date.now())-$)}_.streaming=_.reasoning.status!=="complete",g(_)}else if(j==="reasoning_complete"){let T=typeof v.id=="string"?v.id:null;if(T&&W.has(T)&&z.has(T)){let K=z.get(T);if(K.reasoning){let ce=typeof v.text=="string"?v.text:"";ce&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(ce),K.reasoning.status="complete",K.streaming=!1,g(K)}W.delete(T),z.delete(T);continue}let R=oe(v,!1)??oe(v,!0)??`reason-${d()}`,_=typeof v.text=="string"?v.text:"";!w.get(R)&&(_||v.scope==="loop")&&V(R);let Q=w.get(R);if(Q?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(Q.reasoning.scope=v.scope),_&&Q.reasoning.chunks.length===0&&Q.reasoning.chunks.push(_),Q.reasoning.status="complete",Q.reasoning.completedAt=ke(v.completedAt??v.timestamp);let K=Q.reasoning.startedAt??Date.now();Q.reasoning.durationMs=Math.max(0,(Q.reasoning.completedAt??Date.now())-K),Q.streaming=!1,g(Q)}let $=I(v);$&&N.byStep.delete($)}else if(j==="tool_start"){m&&(m.streaming=!1,g(m),m=null),typeof v.iteration=="number"&&(ge=v.iteration);let T=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??Se(v,!0)??`tool-${d()}`,R=v.toolName??v.name;if(Te(R)){ne.add(T);continue}ae(Y(v),T);let _=Fe(T),Q=_.toolCall??{id:T,status:"pending"};Q.name=R??Q.name,Q.status="running",v.parameters!==void 0?Q.args=v.parameters:v.args!==void 0&&(Q.args=v.args),Q.startedAt=Q.startedAt??ke(v.startedAt??v.timestamp),Q.completedAt=void 0,Q.durationMs=void 0,_.toolCall=Q,_.streaming=!0,v.executionId&&(_.agentMetadata={executionId:v.executionId,iteration:v.iteration}),g(_)}else if(j==="tool_output_delta"){let T=Se(v,!1)??Se(v,!0)??`tool-${d()}`;if(ne.has(T))continue;let R=Fe(T),_=R.toolCall??{id:T,status:"running"};_.startedAt=_.startedAt??ke(v.startedAt??v.timestamp);let Q=v.text??v.delta??v.message??"";Q&&(_.chunks=_.chunks??[],_.chunks.push(String(Q))),_.status="running",R.toolCall=_,R.streaming=!0;let $=v.agentContext;($||v.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:$?.executionId??v.executionId,iteration:$?.iteration??v.iteration}),g(R)}else if(j==="tool_complete"){let T=Se(v,!1)??Se(v,!0)??`tool-${d()}`;if(ne.has(T)){ne.delete(T);continue}let R=Fe(T),_=R.toolCall??{id:T,status:"running"};_.status="complete",v.result!==void 0&&(_.result=v.result),typeof v.duration=="number"&&(_.duration=v.duration),_.completedAt=ke(v.completedAt??v.timestamp);let Q=v.duration??v.executionTime;if(typeof Q=="number")_.durationMs=Q;else{let ce=_.startedAt??Date.now();_.durationMs=Math.max(0,(_.completedAt??Date.now())-ce)}R.toolCall=_,R.streaming=!1;let $=v.agentContext;($||v.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:$?.executionId??v.executionId,iteration:$?.iteration??v.iteration}),g(R);let K=Y(v);K&&L.byCall.delete(K)}else if(j==="await"&&v.toolName){let T=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,R=T??v.toolId??`local-${d()}`,_=Fe(R),Q=v.toolName,$=v.origin==="webmcp"&&!Zo(Q)?`webmcp:${Q}`:Q,K=Zo($),ce=_.toolCall??{id:R,status:"pending"};ce.name=$,ce.args=v.parameters,ce.status=K?"running":"complete",ce.chunks=ce.chunks??[],ce.startedAt=ce.startedAt??ke(v.startedAt??v.timestamp??v.awaitedAt),K?(ce.completedAt=void 0,ce.duration=void 0,ce.durationMs=void 0):ce.completedAt=ce.completedAt??ce.startedAt,_.toolCall=ce,_.streaming=!1,_.agentMetadata={..._.agentMetadata,executionId:v.executionId??_.agentMetadata?.executionId,awaitingLocalTool:!0,...T?{webMcpToolCallId:T}:{}},g(_)}else if(j==="text_start"){let T=typeof v.id=="string"?v.id:null,R=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(T&&R){W.set(T,R);continue}let _=m;_&&(we==="flow"?(Oe(_),kt=_):(_.streaming=!1,g(_)),m=null),E=typeof v.id=="string"?v.id:E,A=""}else if(j==="text_delta"){let T=typeof v.id=="string"?v.id:null,R=T?W.get(T):void 0;if(T&&R){let Q=typeof v.delta=="string"?v.delta:"",$=(G.get(T)??"")+Q;if(G.set(T,$),$.trim()==="")continue;let K=Ce(T,R);K.agentMetadata={...K.agentMetadata,executionId:v.executionId,parentToolId:R},vt(K,$,Q,void 0);continue}if(E=typeof v.id=="string"?v.id:E,we==="flow"){let Q=typeof v.delta=="string"?v.delta:"";if(A+=Q,A.trim()==="")continue;let $=pe();$.agentMetadata={executionId:v.executionId,iteration:v.iteration},vt($,A,Q,void 0),C=$;continue}let _=pe();_.content+=v.delta??"",_.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:Ae??void 0,agentName:he?.agentName},C=_,g(_)}else if(j==="text_complete"){let T=typeof v.id=="string"?v.id:null;if(T&&W.has(T)){let _=z.get(T);_&&Oe(_),W.delete(T),G.delete(T),z.delete(T);continue}let R=m;R&&(we==="flow"?(Oe(R),kt=R):((R.content??"")===""&&typeof v.text=="string"&&(R.content=v.text),R.streaming=!1,g(R)),m=null),E=null,A=""}else if(j==="step_complete"){let T=v.stepType,R=v.executionType;if(T==="tool"||R==="context")continue;if(v.success===!1){let _=v.error,Q=typeof _=="string"&&_!==""?_:_!=null&&typeof _=="object"&&Reflect.has(_,"message")?String(_.message??"Step failed"):"Step failed";n({type:"error",error:new Error(Q)});let $=m;$&&$.streaming&&($.streaming=!1,g($)),n({type:"status",status:"idle"});continue}{let _=kt;kt=null;let Q=v.stopReason,$=v.result?.response;if(_)Q&&(_.stopReason=Q),$!=null?ln(_,$):_.streaming!==!1&&(Je.delete(_.id),Ne.delete(_.id),_.streaming=!1,g(_));else{let K=$!=null&&$!=="";if(K||Q){let ce=pe();Q&&(ce.stopReason=Q),K?Oe(ce,$):(ce.streaming=!1,g(ce))}}continue}}else if(j==="execution_start")we=v.kind==="flow"?"flow":"agent",xt=!0,we==="agent"&&(he={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:ke(v.startedAt)});else if(j==="turn_start"){let T=typeof v.iteration=="number"?v.iteration:ge;if(T!==ge){if(he&&(he.currentIteration=T),te==="separate"&&T>1){let R=m;R&&(R.streaming=!1,g(R),hn.set(T-1,R),m=null)}ge=T}Ae=typeof v.id=="string"?v.id:null,C=null}else if(j==="tool_input_delta"){let T=v.toolCallId??L.lastId;if(T){let R=O.get(T);R?.toolCall&&(R.toolCall.chunks=R.toolCall.chunks??[],R.toolCall.chunks.push(v.delta??""),g(R))}}else{if(j==="tool_input_complete")continue;if(j==="turn_complete"){let T=v.stopReason,R=m??C;if(T&&R!==null){let _=v.id;(!_||R.agentMetadata?.turnId===_)&&(R.stopReason=T,g(R))}Ae===v.id&&(Ae=null)}else if(j==="media_start"){let T=String(v.id);ye.set(T,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(j==="media_delta"){let T=ye.get(String(v.id));T&&typeof v.delta=="string"&&T.parts.push(v.delta)}else if(j==="media_complete"){let T=String(v.id),R=ye.get(T);ye.delete(T);let _=(typeof v.mediaType=="string"?v.mediaType:void 0)??R?.mediaType??"application/octet-stream",Q=typeof v.data=="string"?v.data:void 0,$=typeof v.url=="string"?v.url:R&&R.parts.length>0?R.parts.join(""):void 0,K=null;if(Q)K={type:"media",data:Q,mediaType:_};else if($){let it=_.toLowerCase();K={type:it==="image"||it.startsWith("image/")?"image-url":"file-url",url:$,mediaType:_}}let ce=v.toolCallId??R?.toolCallId,Ke=K?[K]:[],Ie=[];for(let it of Ke){if(!it||typeof it!="object")continue;let X=it,Ue=typeof X.type=="string"?X.type:void 0,Ee=typeof X.mediaType=="string"?X.mediaType.toLowerCase():"",De=null,We="";if(Ue==="media"){let Ze=typeof X.data=="string"?X.data:void 0;if(!Ze)continue;We=Ee.length>0?Ee:"application/octet-stream",De=`data:${We};base64,${Ze}`}else if(Ue==="image-url"){let Ze=typeof X.url=="string"?X.url:void 0;if(!Ze)continue;We=Ee,De=Ze}else if(Ue==="file-url"){let Ze=typeof X.url=="string"?X.url:void 0;if(!Ze)continue;We=Ee,De=Ze}else continue;if(De)if(Ue==="image-url"||We.startsWith("image/"))Ie.push({type:"image",image:De,...We.includes("/")?{mimeType:We}:{}});else if(We.startsWith("audio/"))Ie.push({type:"audio",audio:De,mimeType:We});else if(We.startsWith("video/"))Ie.push({type:"video",video:De,mimeType:We});else{let Ze=We||"application/octet-stream";Ie.push({type:"file",data:De,mimeType:Ze,filename:mh(Ze)})}}if(Ie.length>0){let it=d(),X=ce,Ee={id:`agent-media-${typeof X=="string"&&X.length>0?`${X}-${it}`:String(it)}`,role:"assistant",content:"",contentParts:Ie,createdAt:new Date().toISOString(),streaming:!1,sequence:it,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:ge}};g(Ee);let De=m;De&&(De.streaming=!1,g(De)),m=null,D.current=null}}else if(j==="execution_complete"){let T=v.kind??we;T==="agent"&&he&&(he.status=v.success?"complete":"error",he.completedAt=ke(v.completedAt),he.stopReason=v.stopReason);let R=m;R&&(T==="flow"&&R.streaming!==!1?Oe(R):(R.streaming=!1,g(R)),m=null),E=null,A="",kt=null,n({type:"status",status:"idle",terminal:!0})}else if(j==="execution_error"){let T=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(T)})}else if(j!=="ping"){if(j==="approval_start"){let T=v.approvalId??`approval-${d()}`,R={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:T,status:"pending",agentId:he?.agentId??"virtual",executionId:v.executionId??he?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};g(R)}else if(j==="step_await"&&v.awaitReason==="approval_required"){let T=v.approvalId??`approval-${d()}`,R={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:T,status:"pending",agentId:he?.agentId??"virtual",executionId:v.executionId??he?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};g(R)}else if(j==="approval_complete"){let T=v.approvalId;if(T){let _={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:T,status:v.decision??"approved",agentId:he?.agentId??"virtual",executionId:v.executionId??he?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};g(_)}}else if(j==="artifact_start"||j==="artifact_delta"||j==="artifact_update"||j==="artifact_complete"){if(j==="artifact_start"){let T=v.artifactType,R=String(v.id),_=typeof v.title=="string"?v.title:void 0,Q=v.file,$;Q&&typeof Q=="object"&&!Array.isArray(Q)&&typeof Q.path=="string"&&typeof Q.mimeType=="string"&&($={path:Q.path,mimeType:Q.mimeType,...typeof Q.language=="string"?{language:Q.language}:{}}),n({type:"artifact_start",id:R,artifactType:T,title:_,component:typeof v.component=="string"?v.component:void 0,...$?{file:$}:{}});let K=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(fe.set(R,{markdown:"",title:_,file:$,...K?{props:K}:{}}),!be.has(R)){be.add(R);let ce=Lo(this.config.features?.artifacts,T),Ke=typeof v.component=="string"?v.component:void 0,Ie={id:`artifact-ref-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:pi(ce,{artifactId:R,title:_,artifactType:T,status:"streaming",...$?{file:$}:{},...Ke?{component:Ke}:{}})};me.set(R,Ie),g(Ie)}}else if(j==="artifact_delta"){let T=String(v.id),R=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:T,artDelta:R});let _=fe.get(T);_&&(_.markdown+=R)}else if(j==="artifact_update"){let T=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:T,component:typeof v.component=="string"?v.component:void 0});let R=fe.get(String(v.id));R&&(R.props={...R.props??{},...T})}else if(j==="artifact_complete"){let T=String(v.id);n({type:"artifact_complete",id:T});let R=me.get(T);if(R){R.streaming=!1;try{let _=JSON.parse(R.rawContent??"{}");if(_.props){_.props.status="complete";let Q=fe.get(T);Q?.markdown&&(_.props.markdown=Q.markdown),Q?.file&&(_.props.file=Q.file),_.component==="PersonaArtifactInline"&&Q?.props&&Object.keys(Q.props).length>0&&(_.props.componentProps=Q.props)}R.rawContent=JSON.stringify(_)}catch{}fe.delete(T),g(R),me.delete(T)}}}else if(j==="transcript_insert"){let T=v.message;if(!T||typeof T!="object")continue;let R=String(T.id??`msg-${d()}`),_=T.role,$={id:R,role:_==="user"?"user":_==="system"?"system":"assistant",content:typeof T.content=="string"?T.content:"",rawContent:typeof T.rawContent=="string"?T.rawContent:void 0,createdAt:typeof T.createdAt=="string"?T.createdAt:new Date().toISOString(),streaming:T.streaming===!0,...typeof T.variant=="string"?{variant:T.variant}:{},sequence:d()};if(g($),$.rawContent)try{let ce=JSON.parse($.rawContent)?.props?.artifactId;typeof ce=="string"&&be.add(ce)}catch{}m=null,D.current=null,Je.delete(R),Ne.delete(R)}else if(j==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let T=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(T)});let R=m;R&&R.streaming&&(R.streaming=!1,g(R)),n({type:"status",status:"idle"})}}else if(j==="step_error"||j==="dispatch_error"||j==="flow_error"){let T=null;if(v.error instanceof Error)T=v.error;else if(j==="dispatch_error"){let R=v.message??v.error;R!=null&&R!==""&&(T=new Error(String(R)))}else{let R=v.error;typeof R=="string"&&R!==""?T=new Error(R):R!=null&&typeof R=="object"&&Reflect.has(R,"message")&&(T=new Error(String(R.message??R)))}if(T){n({type:"error",error:T});let R=m;R&&R.streaming&&(R.streaming=!1,g(R)),n({type:"status",status:"idle"})}}}}}Qe.length=0};;){let{done:k,value:j}=await s.read();if(k)break;l+=i.decode(j,{stream:!0});let v=l.split(`
185
185
 
186
186
  `);l=v.pop()??"";for(let T of v){let R=T.split(`
187
- `),_="message",Q="",$=null;for(let Pe of R)Pe.startsWith("event:")?_=Pe.replace("event:","").trim():Pe.startsWith("data:")?Q+=Pe.replace("data:","").trim():Pe.startsWith("id:")&&($=Pe.slice(3).trim());let K=()=>{$!==null&&$!==""&&n({type:"cursor",id:$})};if(!Q){K();continue}let ce;try{ce=JSON.parse(Q)}catch(Pe){n({type:"error",error:Pe instanceof Error?Pe:new Error("Failed to parse chat stream payload")});continue}let Ve=_!=="message"?_:ce.type??"message";if(this.onSSEEvent?.(Ve,ce),this.parseSSEEvent){D.current=m;let Pe=await this.handleCustomSSEEvent(ce,n,D,g,d,B);if(D.current&&D.current!==m&&(m=D.current),Pe){K();continue}}Ge.push({payloadType:Ve,payload:ce}),Ie(),K()}}Ie()}};function xi(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function sr(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var Ci="[Image]";function Ep(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function ir(t){return{type:"text",text:t}}var kp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],yh=["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"],$n=[...kp,...yh];function vh(t){return kp.includes(t)||t.startsWith("image/")}function wi(t){return vh(t.type)}async function Lp(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;wi(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 Pp(t,e=$n,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 xh(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Ip(t,e){let n=xh(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"}hl();var Rp=16e3,Ch=24e3,wh=4096,Ah=1380533830;function Sh(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===Ah?new Uint8Array(t,44):new Uint8Array(t)}function Mh(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 es=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:Rp,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let i=window.AudioContext||window.webkitAudioContext,l=new i({sampleRate:Rp});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new ar(Ch);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(u=>u.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=`${Mh(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=u=>this.handleMessage(u,r),d.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},d.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let y=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${y}`)),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(wh,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 u=Math.max(-1,Math.min(1,p[d]));c[d]=u<0?u*32768:u*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=Sh(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 Ro=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 lr(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new es(t.runtype);case"browser":if(!Ro.isSupported())throw new Error("Browser speech recognition not supported");return new Ro(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 Wp(t){if(t?.type==="custom"&&t.custom)return lr({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return lr({type:"runtype",runtype:t.runtype});if(Ro.isSupported())return lr({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function bl(t){try{return Wp(t),!0}catch{return!1}}function Ai(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 cr=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):Ai(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 ts=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 yl(t){if(!t)return"";let e=Th(t);return Hp(e!==null?e:t)}function Th(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 Hp(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,`
187
+ `),_="message",Q="",$=null;for(let Ie of R)Ie.startsWith("event:")?_=Ie.replace("event:","").trim():Ie.startsWith("data:")?Q+=Ie.replace("data:","").trim():Ie.startsWith("id:")&&($=Ie.slice(3).trim());let K=()=>{$!==null&&$!==""&&n({type:"cursor",id:$})};if(!Q){K();continue}let ce;try{ce=JSON.parse(Q)}catch(Ie){n({type:"error",error:Ie instanceof Error?Ie:new Error("Failed to parse chat stream payload")});continue}let Ke=_!=="message"?_:ce.type??"message";if(this.onSSEEvent?.(Ke,ce),this.parseSSEEvent){D.current=m;let Ie=await this.handleCustomSSEEvent(ce,n,D,g,d,B);if(D.current&&D.current!==m&&(m=D.current),Ie){K();continue}}Qe.push({payloadType:Ke,payload:ce}),Re(),K()}}Re()}};function xi(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function sr(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var Ci="[Image]";function Ep(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function ir(t){return{type:"text",text:t}}var kp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],yh=["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"],$n=[...kp,...yh];function vh(t){return kp.includes(t)||t.startsWith("image/")}function wi(t){return vh(t.type)}async function Lp(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;wi(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 Pp(t,e=$n,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 xh(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Ip(t,e){let n=xh(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"}hl();var Rp=16e3,Ch=24e3,wh=4096,Ah=1380533830;function Sh(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===Ah?new Uint8Array(t,44):new Uint8Array(t)}function Mh(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 es=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:Rp,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let i=window.AudioContext||window.webkitAudioContext,l=new i({sampleRate:Rp});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new ar(Ch);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(u=>u.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=`${Mh(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=u=>this.handleMessage(u,r),d.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},d.onclose=u=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(r===this.callGeneration){if(u.code!==1e3){let y=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${y}`)),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(wh,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 u=Math.max(-1,Math.min(1,p[d]));c[d]=u<0?u*32768:u*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=Sh(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 Ro=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 lr(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new es(t.runtype);case"browser":if(!Ro.isSupported())throw new Error("Browser speech recognition not supported");return new Ro(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 Wp(t){if(t?.type==="custom"&&t.custom)return lr({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return lr({type:"runtype",runtype:t.runtype});if(Ro.isSupported())return lr({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function bl(t){try{return Wp(t),!0}catch{return!1}}function Ai(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 cr=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):Ai(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 ts=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 yl(t){if(!t)return"";let e=Th(t);return Hp(e!==null?e:t)}function Th(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 Hp(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
188
  `),e=e.replace(/\n{2,}/g,`
189
189
  `),e.trim()}var Fp=null;var vl=()=>Fp?Fp():Promise.resolve().then(()=>(Op(),Np));var Ih=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Rh(t,e){return Ih.some(n=>t[n]!==e[n])}function xl(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
190
 
@@ -192,16 +192,16 @@ _Details: ${n.message}_`:o}var ns=t=>({isError:!0,content:[{type:"text",text:t}]
192
192
 
193
193
  `),i=[s,n].filter(Boolean).join(`
194
194
 
195
- `),l=Array.isArray(e.contentParts)&&e.contentParts.length>0,p=r.contentParts.length>0;if(l){let c=[];s&&c.push(ir(s)),c.push(...r.contentParts),c.push(...e.contentParts),e.contentParts=c}else if(p){let c=[];i&&c.push(ir(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=xi(),s=sr();this.activeAssistantMessageId=null;let i=n?.contentParts&&Ep(n.contentParts)?Ci:"",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(u=>u.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 u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!u){let y=xl(d,this.config.errorMessage);if(y){let g={id:s,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(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=sr();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=xl(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 u=null;if(d instanceof Response){if(!d.ok){let y=await d.json().catch(()=>null);throw new Error(y?.error??`Approval request failed: ${d.status}`)}u=d.body}else d instanceof ReadableStream&&(u=d);u?await this.connectStream(u,{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 u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||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,u=Array.isArray(d?.questions)?d.questions:[];if(u.length===1){let y=typeof u[0]?.question=="string"?u[0].question:"";y&&(i={[y]: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(([u,y])=>`${u}: ${Array.isArray(y)?y.join(", "):y}`).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((u,y)=>{let g=typeof u?.question=="string"?u.question:"";if(!g)return;let m=d[g],C=Array.isArray(m)?m.join(", "):typeof m=="string"?m:"";this.appendMessage({id:`ask-user-q-${l}-${y}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${y}`,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 u=await d.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${d.status}`)}d.body?await this.connectStream(d.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||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!==_n?!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 u=`${e}:${d}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let y=this.markWebMcpToolRunning(p),g=p.agentMetadata?.webMcpToolCallId??c;if(c===_n)return{dedupeKey:u,resumeKey:g,output:ul(),toolMessage:p,startedAt:y,completedAt:Date.now()};let m=new AbortController;this.webMcpResolveControllers.add(m),r.push(m);let C=this.client.executeWebMcpToolCall(c,p.toolCall?.args,m.signal),D;if(!C)D={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{D=await C}catch(B){let E=B instanceof Error&&(B.name==="AbortError"||B.message.includes("aborted")||B.message.includes("abort"));return E||this.callbacks.onError?.(B instanceof Error?B:new Error(String(B))),this.markWebMcpToolComplete(p,ns(E?"Aborted by cancel()":zp(B)),y),this.webMcpInflightKeys.delete(u),null}return m.signal.aborted?(this.markWebMcpToolComplete(p,ns("Aborted by cancel()"),y),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:g,output:D,toolMessage:p,startedAt:y,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===_n?{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,ns("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 m=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m))return;this.webMcpInflightKeys.add(m);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(m)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(m)}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===_n,d=e.toolCall?.args,u=c?null:this.client.executeWebMcpToolCall(o,d,p),y="execute",g=i;try{let m;if(c?m=ul():u?m=await u:m={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),p.aborted){this.markWebMcpToolComplete(e,ns("Aborted by cancel()"),i);return}let C=e.agentMetadata?.webMcpToolCallId??o;y="resume",await this.resumeWithToolOutput(n,C,m,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,m,i,g,c?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(m){let C=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));(y==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(e,ns(C||p.aborted?"Aborted by cancel()":zp(m)),i),C||this.callbacks.onError?.(m instanceof Error?m:new Error(String(m)))}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}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{}};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=Lo(this.config.features?.artifacts,e.artifactType),r=pi(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...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})}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(()=>($p(),_p)).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=>xl(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=sr(),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=yl(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Ai(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=yl(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,u=n.approval;i.approval={...d,...u,executionId:u.executionId||d.executionId,toolName:u.toolName||d.toolName,description:u.description||d.description,toolType:u.toolType??d.toolType,reason:u.reason??d.reason,parameters:u.parameters??d.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,c=n.toolCall?.id;if(l&&Up(l)&&p&&c&&n.agentMetadata?.awaitingLocalTool===!0){let d=`${p}:${c}`,u=this.webMcpInflightKeys.has(d),y=this.webMcpResolvedKeys.has(d),g=r.toolCall?.name,m=r.agentMetadata?.executionId===p&&r.toolCall?.id===c&&g!==void 0&&Up(g)&&r.toolCall?.status==="complete";(u||y||m)&&(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)})}};tt();Mt();var Ei={allowedTypes:$n,maxFileSize:10*1024*1024,maxFiles:4};function Bh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Dh(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 os=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:e.allowedTypes??Ei.allowedTypes,maxFileSize:e.maxFileSize??Ei.maxFileSize,maxFiles:e.maxFiles??Ei.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Ei.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=Pp(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 Lp(n),s=wi(n)?URL.createObjectURL(n):null,i={id:Bh(),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=wi(e.file),o=h("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=h("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=h("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=Dh(e.file.type),p=se(l,20,"var(--persona-muted, #6b7280)",1.5);p&&i.appendChild(p);let c=h("span");c.textContent=Ip(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=h("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=se("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})}};tt();ki();Cl();tt();Mt();var Bt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},qt=1e5,Pi=qt+1;var Fh=8,_h=8,wl=10,Al=new WeakMap,Kp=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,$h=t=>{let e=t.getRootNode?.();return Kp(e)?e:t.ownerDocument.body},Sl=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n));function $t(t){Al.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,enabled:r=!0,gap:s=Fh,viewportPadding:i=_h}=t,l=()=>e.ownerDocument,p=()=>l().defaultView??window,c=null,d=null,u=null,y=!1,g=!1,m=!1,C=()=>(typeof o=="function"?o():o).trim(),D=()=>{u?.(),u=null,c?.remove(),c=null,d=null},B=()=>{if(!c)return;let L=l(),P=p(),I=e.getBoundingClientRect(),Y=c.getBoundingClientRect(),de=L.documentElement.clientWidth||P.innerWidth,ue=L.documentElement.clientHeight||P.innerHeight,pe=de-i-Y.width,ee=I.left+I.width/2-Y.width/2,oe=Sl(ee,i,pe),V=I.top-i,ae=ue-i-I.bottom,ne=Y.height+s,me=V>=ne||V>=ae?"top":"bottom",be=me==="top"?I.top-s-Y.height:I.bottom+s,fe=ue-i-Y.height,Te=Sl(be,i,fe),Se=I.left+I.width/2,Fe=Math.max(wl,Y.width-wl),ke=Sl(Se-oe,wl,Fe);c.dataset.placement=me,c.style.left=`${oe}px`,c.style.top=`${Te}px`,c.style.setProperty("--persona-tooltip-arrow-x",`${ke}px`)},E=()=>{if(m||!r||c||!e.isConnected)return;let L=C(),P=$h(e);if(!L||!P)return;let I=l(),Y=p();c=I.createElement("div"),c.className="persona-control-tooltip",c.setAttribute("role","tooltip"),c.dataset.state="measuring",c.style.zIndex=String(Pi),d=I.createElement("span"),d.className="persona-control-tooltip__label",d.textContent=L,c.appendChild(d);let de=I.createElement("span");de.className="persona-control-tooltip__arrow",c.appendChild(de),P.appendChild(c),B(),c.dataset.state="open";let ue=()=>{if(!e.isConnected){D();return}d&&(d.textContent=C()),B()};Y.addEventListener("scroll",ue,!0),Y.addEventListener("resize",ue);let pe=e.getRootNode(),ee=Kp(pe)?pe:I.documentElement,oe=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||D()});oe?.observe(ee,{childList:!0,subtree:!0}),u=()=>{Y.removeEventListener("scroll",ue,!0),Y.removeEventListener("resize",ue),oe?.disconnect()}},A=()=>{y||g?E():D()},W=()=>{let L=p();(!L.matchMedia||!L.matchMedia("(hover: none)").matches)&&(y=!0,A())},z=()=>{y=!1,A()},G=()=>{g=!0,A()},w=()=>{g=!1,A()},O=L=>{L.key==="Escape"&&(y=!1,g=!1,D())};n.addEventListener("mouseenter",W),n.addEventListener("mouseleave",z),e.addEventListener("focus",G),e.addEventListener("blur",w),e.addEventListener("keydown",O);let N={get isOpen(){return c!==null},show:E,hide:D,reposition:B,destroy:()=>{m||(m=!0,D(),n.removeEventListener("mouseenter",W),n.removeEventListener("mouseleave",z),e.removeEventListener("focus",G),e.removeEventListener("blur",w),e.removeEventListener("keydown",O),Al.delete(e))}};return Al.set(e,N),N}function Gp(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=h("div","persona-send-button-wrapper"),c=xe("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=se(i,s,"currentColor",1.5);return d?c.appendChild(d):c.textContent="+",c.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(c),$t({anchor:c,trigger:p,text:()=>c.getAttribute("aria-label")??l}),{button:c,wrapper:p}}var{setLoader:aw,load:Qh}=Yo({fallbackImport:()=>Promise.resolve().then(()=>(mu(),fu))});var Il=Qh;var{setLoader:vw,load:sb}=Yo({fallbackImport:()=>Promise.resolve().then(()=>(Eu(),Tu)),resetOnSetLoader:!0});var ku=sb;tt();Mt();function cs(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=xe("span",{className:Fn("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=se(t.iconName??"at-sign",13,"currentColor",2);if(o){let r=h("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(xe("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function Lu(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=Li(e).filter(A=>A.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(A=>A.sources.some(W=>typeof W.matchCommand=="function")),r=A=>o.some(W=>W.trigger?W.position==="line-start"?A.split(`
195
+ `),l=Array.isArray(e.contentParts)&&e.contentParts.length>0,p=r.contentParts.length>0;if(l){let c=[];s&&c.push(ir(s)),c.push(...r.contentParts),c.push(...e.contentParts),e.contentParts=c}else if(p){let c=[];i&&c.push(ir(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=xi(),s=sr();this.activeAssistantMessageId=null;let i=n?.contentParts&&Ep(n.contentParts)?Ci:"",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(u=>u.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 u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!u){let y=xl(d,this.config.errorMessage);if(y){let g={id:s,role:"assistant",createdAt:new Date().toISOString(),content:y,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(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=sr();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=xl(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 u=null;if(d instanceof Response){if(!d.ok){let y=await d.json().catch(()=>null);throw new Error(y?.error??`Approval request failed: ${d.status}`)}u=d.body}else d instanceof ReadableStream&&(u=d);u?await this.connectStream(u,{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 u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||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,u=Array.isArray(d?.questions)?d.questions:[];if(u.length===1){let y=typeof u[0]?.question=="string"?u[0].question:"";y&&(i={[y]: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(([u,y])=>`${u}: ${Array.isArray(y)?y.join(", "):y}`).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((u,y)=>{let g=typeof u?.question=="string"?u.question:"";if(!g)return;let m=d[g],C=Array.isArray(m)?m.join(", "):typeof m=="string"?m:"";this.appendMessage({id:`ask-user-q-${l}-${y}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${y}`,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 u=await d.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${d.status}`)}d.body?await this.connectStream(d.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(d){let u=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||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!==_n?!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 u=`${e}:${d}`;if(this.webMcpInflightKeys.has(u)||this.webMcpResolvedKeys.has(u)||this.isSuggestRepliesAlreadyResolved(p))return null;this.webMcpInflightKeys.add(u),o.push(u);let y=this.markWebMcpToolRunning(p),g=p.agentMetadata?.webMcpToolCallId??c;if(c===_n)return{dedupeKey:u,resumeKey:g,output:ul(),toolMessage:p,startedAt:y,completedAt:Date.now()};let m=new AbortController;this.webMcpResolveControllers.add(m),r.push(m);let C=this.client.executeWebMcpToolCall(c,p.toolCall?.args,m.signal),D;if(!C)D={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{D=await C}catch(B){let E=B instanceof Error&&(B.name==="AbortError"||B.message.includes("aborted")||B.message.includes("abort"));return E||this.callbacks.onError?.(B instanceof Error?B:new Error(String(B))),this.markWebMcpToolComplete(p,ns(E?"Aborted by cancel()":zp(B)),y),this.webMcpInflightKeys.delete(u),null}return m.signal.aborted?(this.markWebMcpToolComplete(p,ns("Aborted by cancel()"),y),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:g,output:D,toolMessage:p,startedAt:y,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===_n?{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,ns("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 m=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(m)||this.webMcpResolvedKeys.has(m))return;this.webMcpInflightKeys.add(m);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(m)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(m)}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===_n,d=e.toolCall?.args,u=c?null:this.client.executeWebMcpToolCall(o,d,p),y="execute",g=i;try{let m;if(c?m=ul():u?m=await u:m={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),p.aborted){this.markWebMcpToolComplete(e,ns("Aborted by cancel()"),i);return}let C=e.agentMetadata?.webMcpToolCallId??o;y="resume",await this.resumeWithToolOutput(n,C,m,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,m,i,g,c?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(m){let C=m instanceof Error&&(m.name==="AbortError"||m.message.includes("aborted")||m.message.includes("abort"));(y==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(e,ns(C||p.aborted?"Aborted by cancel()":zp(m)),i),C||this.callbacks.onError?.(m instanceof Error?m:new Error(String(m)))}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}:{}}:{id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:e.props??{}};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=Lo(this.config.features?.artifacts,e.artifactType),r=pi(o,{artifactId:e.id,title:e.title,artifactType:e.artifactType,status:"complete",...e.file?{file:e.file}:{},...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})}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(()=>($p(),_p)).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=>xl(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=sr(),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=yl(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Ai(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=yl(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,u=n.approval;i.approval={...d,...u,executionId:u.executionId||d.executionId,toolName:u.toolName||d.toolName,description:u.description||d.description,toolType:u.toolType??d.toolType,reason:u.reason??d.reason,parameters:u.parameters??d.parameters}}let l=n.toolCall?.name,p=n.agentMetadata?.executionId,c=n.toolCall?.id;if(l&&Up(l)&&p&&c&&n.agentMetadata?.awaitingLocalTool===!0){let d=`${p}:${c}`,u=this.webMcpInflightKeys.has(d),y=this.webMcpResolvedKeys.has(d),g=r.toolCall?.name,m=r.agentMetadata?.executionId===p&&r.toolCall?.id===c&&g!==void 0&&Up(g)&&r.toolCall?.status==="complete";(u||y||m)&&(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)})}};nt();St();var Ei={allowedTypes:$n,maxFileSize:10*1024*1024,maxFiles:4};function Bh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Dh(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 os=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:e.allowedTypes??Ei.allowedTypes,maxFileSize:e.maxFileSize??Ei.maxFileSize,maxFiles:e.maxFiles??Ei.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Ei.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=Pp(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 Lp(n),s=wi(n)?URL.createObjectURL(n):null,i={id:Bh(),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=wi(e.file),o=h("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=h("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=h("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=Dh(e.file.type),p=se(l,20,"var(--persona-muted, #6b7280)",1.5);p&&i.appendChild(p);let c=h("span");c.textContent=Ip(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=h("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=se("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})}};nt();ki();Cl();nt();St();var Ht={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Vt=1e5,Pi=Vt+1;var Fh=8,_h=8,wl=10,Al=new WeakMap,Kp=t=>t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t,$h=t=>{let e=t.getRootNode?.();return Kp(e)?e:t.ownerDocument.body},Sl=(t,e,n)=>Math.min(Math.max(t,e),Math.max(e,n));function _t(t){Al.get(t.anchor)?.destroy();let{anchor:e,trigger:n=e,text:o,enabled:r=!0,gap:s=Fh,viewportPadding:i=_h}=t,l=()=>e.ownerDocument,p=()=>l().defaultView??window,c=null,d=null,u=null,y=!1,g=!1,m=!1,C=()=>(typeof o=="function"?o():o).trim(),D=()=>{u?.(),u=null,c?.remove(),c=null,d=null},B=()=>{if(!c)return;let L=l(),P=p(),I=e.getBoundingClientRect(),Y=c.getBoundingClientRect(),de=L.documentElement.clientWidth||P.innerWidth,ue=L.documentElement.clientHeight||P.innerHeight,pe=de-i-Y.width,ee=I.left+I.width/2-Y.width/2,oe=Sl(ee,i,pe),V=I.top-i,ae=ue-i-I.bottom,ne=Y.height+s,me=V>=ne||V>=ae?"top":"bottom",be=me==="top"?I.top-s-Y.height:I.bottom+s,fe=ue-i-Y.height,Te=Sl(be,i,fe),Se=I.left+I.width/2,Fe=Math.max(wl,Y.width-wl),ke=Sl(Se-oe,wl,Fe);c.dataset.placement=me,c.style.left=`${oe}px`,c.style.top=`${Te}px`,c.style.setProperty("--persona-tooltip-arrow-x",`${ke}px`)},E=()=>{if(m||!r||c||!e.isConnected)return;let L=C(),P=$h(e);if(!L||!P)return;let I=l(),Y=p();c=I.createElement("div"),c.className="persona-control-tooltip",c.setAttribute("role","tooltip"),c.dataset.state="measuring",c.style.zIndex=String(Pi),d=I.createElement("span"),d.className="persona-control-tooltip__label",d.textContent=L,c.appendChild(d);let de=I.createElement("span");de.className="persona-control-tooltip__arrow",c.appendChild(de),P.appendChild(c),B(),c.dataset.state="open";let ue=()=>{if(!e.isConnected){D();return}d&&(d.textContent=C()),B()};Y.addEventListener("scroll",ue,!0),Y.addEventListener("resize",ue);let pe=e.getRootNode(),ee=Kp(pe)?pe:I.documentElement,oe=typeof MutationObserver>"u"?null:new MutationObserver(()=>{e.isConnected||D()});oe?.observe(ee,{childList:!0,subtree:!0}),u=()=>{Y.removeEventListener("scroll",ue,!0),Y.removeEventListener("resize",ue),oe?.disconnect()}},A=()=>{y||g?E():D()},W=()=>{let L=p();(!L.matchMedia||!L.matchMedia("(hover: none)").matches)&&(y=!0,A())},z=()=>{y=!1,A()},G=()=>{g=!0,A()},w=()=>{g=!1,A()},O=L=>{L.key==="Escape"&&(y=!1,g=!1,D())};n.addEventListener("mouseenter",W),n.addEventListener("mouseleave",z),e.addEventListener("focus",G),e.addEventListener("blur",w),e.addEventListener("keydown",O);let N={get isOpen(){return c!==null},show:E,hide:D,reposition:B,destroy:()=>{m||(m=!0,D(),n.removeEventListener("mouseenter",W),n.removeEventListener("mouseleave",z),e.removeEventListener("focus",G),e.removeEventListener("blur",w),e.removeEventListener("keydown",O),Al.delete(e))}};return Al.set(e,N),N}function Gp(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=h("div","persona-send-button-wrapper"),c=xe("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=se(i,s,"currentColor",1.5);return d?c.appendChild(d):c.textContent="+",c.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(c),_t({anchor:c,trigger:p,text:()=>c.getAttribute("aria-label")??l}),{button:c,wrapper:p}}var{setLoader:aw,load:Qh}=Yo({fallbackImport:()=>Promise.resolve().then(()=>(mu(),fu))});var Il=Qh;var{setLoader:vw,load:sb}=Yo({fallbackImport:()=>Promise.resolve().then(()=>(Eu(),Tu)),resetOnSetLoader:!0});var ku=sb;nt();St();function cs(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=xe("span",{className:Fn("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=se(t.iconName??"at-sign",13,"currentColor",2);if(o){let r=h("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(xe("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function Lu(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=Li(e).filter(A=>A.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(A=>A.sources.some(W=>typeof W.matchCommand=="function")),r=A=>o.some(W=>W.trigger?W.position==="line-start"?A.split(`
196
196
  `).some(G=>G.startsWith(W.trigger)):(W.position==="anywhere"?A:A.split(`
197
- `)[0]).startsWith(W.trigger):!1),s=(A,W)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:W}))}catch{}},i=xe("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,c=t.textarea,d=null,u=null,y=null,g=null,m=()=>{if(l)return Promise.resolve(l);if(p)return p;let A=Il().then(W=>(l=W.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:E,emit:s}),l)).catch(W=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",W),p===A&&(p=null),null));return p=A,A},C=()=>{ku().then(A=>{let W=A.mountInlineComposer({textarea:t.textarea,renderToken:G=>cs(G,{render:e.renderMentionToken}),onMentionRemoved:G=>l?.untrackMention(G)});d=W.input,u=W.destroy;let z=c;z.replaceWith(W.element),c=W.element,g={next:W.element,prev:z},y?.(W.element,z),l?l.rebindComposer(W.input):p&&p.then(G=>G?.rebindComposer(W.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};e.display==="inline"&&C();let D=[],B=new Map;for(let A of n){if(!A.showButton)continue;let W=Gp({config:{...e,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},buttonSize:t.config.sendButton?.size,onOpen:()=>{m().then(z=>z?.openMenu(A.trigger))}});D.push(W),B.set(A.trigger,W.button)}let E=(A,W,z)=>{let G=B.get(W);G&&(G.setAttribute("aria-expanded",A?"true":"false"),A?G.setAttribute("aria-controls",z):G.removeAttribute("aria-controls"))};return{affordanceButtons:D.map(A=>A.wrapper),contextRow:i,handleInput:A=>{if(l){l.handleInput();return}if(!qp(A))return;let W=c,z=W.selectionStart??0;rs(W.value,z,n)&&m().then(G=>G?.handleInput())},handleKeydown:A=>{if(l?.isMenuOpen())return l.handleKeydown(A);if(A.key==="Backspace"&&l?.hasMentions()&&!g){let W=c,z=W.selectionStart===0&&W.selectionEnd===0;if((W.value.length===0||z)&&l.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async A=>r(A)?(l??await m())?.dispatchInlineCommand(A)??null:null,clear:()=>l?.clear(),prefetch:()=>{Il().catch(()=>{})},onComposerSwap:A=>{y=A,g&&A(g.next,g.prev)},destroy:()=>{l?.destroy(),u?.();for(let A of D)A.wrapper.remove();i.remove()}}}var Pu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function ds(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];Pu(s)&&Pu(r)?n[o]=ds(s,r):n[o]=r}return n}var zn="min(440px, calc(100vw - 24px))",Ru="440px",ib={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:zn,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)"},ct={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:ib,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"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:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Iu(t,e){if(!(!t&&!e))return t?e?ds(t,e):t:e}function zi(t){return t?{...ct,...t,theme:Iu(ct.theme,t.theme),darkTheme:Iu(ct.darkTheme,t.darkTheme),launcher:{...ct.launcher,...t.launcher,dock:{...ct.launcher?.dock,...t.launcher?.dock},clearChat:{...ct.launcher?.clearChat,...t.launcher?.clearChat}},copy:{...ct.copy,...t.copy},sendButton:{...ct.sendButton,...t.sendButton},statusIndicator:{...ct.statusIndicator,...t.statusIndicator},voiceRecognition:{...ct.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=ct.features?.artifacts,n=t.features?.artifacts,o=ct.features?.scrollToBottom,r=t.features?.scrollToBottom,s=ct.features?.scrollBehavior,i=t.features?.scrollBehavior,l=ct.features?.streamAnimation,p=t.features?.streamAnimation,c=ct.features?.askUserQuestion,d=t.features?.askUserQuestion,u=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},g=s===void 0&&i===void 0?void 0:{...s,...i},m=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{...ct.features,...t.features,...y!==void 0?{scrollToBottom:y}:{},...g!==void 0?{scrollBehavior:g}:{},...u!==void 0?{artifacts:u}:{},...m!==void 0?{streamAnimation:m}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:t.suggestionChips??ct.suggestionChips,suggestionChipsConfig:{...ct.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...ct.layout,...t.layout,header:{...ct.layout?.header,...t.layout?.header},messages:{...ct.layout?.messages,...t.layout?.messages,avatar:{...ct.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...ct.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...ct.layout?.slots,...t.layout?.slots}},markdown:{...ct.markdown,...t.markdown,options:{...ct.markdown?.options,...t.markdown?.options}},messageActions:{...ct.messageActions,...t.messageActions}}:ct}var Ui="16px",ji="transparent",ab={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"}},lb={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"}},cb={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:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:zn,maxWidth:Ru,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Ui,canvasBackground:ji},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"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 Qt(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."))?Qt(t,o):o}function Wu(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=Qt(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 db(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 Hu(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]=Hu(s,r):n[o]=r}return n}function pb(t,e){return e?Hu(t,e):t}function dr(t,e={}){let n={palette:ab,semantic:lb,components:cb},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:pb(n.components,t?.components)};if(e.validate!==!1){let r=db(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 Bu(t){let e=Wu(t),n={};for(let[w,O]of Object.entries(e)){let N=w.replace(/\./g,"-");n[`--persona-${N}`]=O.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"]??Ui,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??ji,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-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=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",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"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-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 r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let s=n["--persona-components-markdown-heading-h1-fontWeight"];s&&(n["--persona-md-h1-weight"]=s);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let l=n["--persona-components-markdown-heading-h2-fontWeight"];l&&(n["--persona-md-h2-weight"]=l);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),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-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 c=t.components,d=c?.iconButton;d&&(d.background&&(n["--persona-icon-btn-bg"]=d.background),d.border&&(n["--persona-icon-btn-border"]=d.border),d.color&&(n["--persona-icon-btn-color"]=d.color),d.padding&&(n["--persona-icon-btn-padding"]=d.padding),d.borderRadius&&(n["--persona-icon-btn-radius"]=d.borderRadius),d.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=d.hoverBackground),d.hoverColor&&(n["--persona-icon-btn-hover-color"]=d.hoverColor),d.activeBackground&&(n["--persona-icon-btn-active-bg"]=d.activeBackground),d.activeBorder&&(n["--persona-icon-btn-active-border"]=d.activeBorder));let u=c?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let y=c?.toggleGroup;y&&(y.gap&&(n["--persona-toggle-group-gap"]=y.gap),y.borderRadius&&(n["--persona-toggle-group-radius"]=y.borderRadius));let g=c?.artifact;if(g?.toolbar){let w=g.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"]=Qt(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(g?.tab){let w=g.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(g?.pane){let w=g.pane;if(w.toolbarBackground){let O=Qt(t,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=O}}if(g?.card){let w=g.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(g?.inline){let w=g.inline;w.background&&(n["--persona-artifact-inline-bg"]=Qt(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"]=Qt(t,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Qt(t,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Qt(t,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Qt(t,w.mutedColor)??w.mutedColor),w.frameHeight&&(n["--persona-artifact-inline-frame-height"]=w.frameHeight)}let m=c?.code;m&&(m.keywordColor&&(n["--persona-code-keyword-color"]=m.keywordColor),m.stringColor&&(n["--persona-code-string-color"]=m.stringColor),m.commentColor&&(n["--persona-code-comment-color"]=m.commentColor),m.numberColor&&(n["--persona-code-number-color"]=m.numberColor),m.tagColor&&(n["--persona-code-tag-color"]=m.tagColor),m.attrColor&&(n["--persona-code-attr-color"]=m.attrColor),m.propertyColor&&(n["--persona-code-property-color"]=m.propertyColor),m.lineNumberColor&&(n["--persona-code-line-number-color"]=m.lineNumberColor),m.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=m.gutterBorderColor),m.background&&(n["--persona-code-bg"]=Qt(t,m.background)??m.background));let C=n["--persona-surface"],D=n["--persona-container"],B=n["--persona-palette-colors-gray-100"]??"#f3f4f6",E=n["--persona-palette-colors-gray-200"]??"#e5e7eb",A=n["--persona-palette-colors-gray-300"]??"#d1d5db",W=!D||D===C,z=W?B:D,G=W?E:D;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??z,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??G,W&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??A),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??z,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??z,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??z,n}var ub={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"}}},Du=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},_l=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",gb=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":_l()},Nu=t=>gb(t),fb=t=>dr(t),mb=t=>dr({...t,palette:{...t?.palette,colors:{...ub.colors,...t?.palette?.colors}}},{validate:!1}),pr=t=>{let e=Nu(t),n=Du(t?.theme),o=Du(t?.darkTheme);return e==="dark"?mb(ds(n??{},o??{})):fb(n)},hb=t=>Bu(t),ps=(t,e)=>{let n=pr(e),o=hb(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",Nu(e))},qi=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(_l())});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(_l());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())}};Mt();tt();function kn(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function Ou(t){let e=kn(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function Vi(t){if(typeof t!="string")return"";let e=t.indexOf(`
197
+ `)[0]).startsWith(W.trigger):!1),s=(A,W)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${A}`,{detail:W}))}catch{}},i=xe("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,c=t.textarea,d=null,u=null,y=null,g=null,m=()=>{if(l)return Promise.resolve(l);if(p)return p;let A=Il().then(W=>(l=W.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:E,emit:s}),l)).catch(W=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",W),p===A&&(p=null),null));return p=A,A},C=()=>{ku().then(A=>{let W=A.mountInlineComposer({textarea:t.textarea,renderToken:G=>cs(G,{render:e.renderMentionToken}),onMentionRemoved:G=>l?.untrackMention(G)});d=W.input,u=W.destroy;let z=c;z.replaceWith(W.element),c=W.element,g={next:W.element,prev:z},y?.(W.element,z),l?l.rebindComposer(W.input):p&&p.then(G=>G?.rebindComposer(W.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};e.display==="inline"&&C();let D=[],B=new Map;for(let A of n){if(!A.showButton)continue;let W=Gp({config:{...e,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},buttonSize:t.config.sendButton?.size,onOpen:()=>{m().then(z=>z?.openMenu(A.trigger))}});D.push(W),B.set(A.trigger,W.button)}let E=(A,W,z)=>{let G=B.get(W);G&&(G.setAttribute("aria-expanded",A?"true":"false"),A?G.setAttribute("aria-controls",z):G.removeAttribute("aria-controls"))};return{affordanceButtons:D.map(A=>A.wrapper),contextRow:i,handleInput:A=>{if(l){l.handleInput();return}if(!qp(A))return;let W=c,z=W.selectionStart??0;rs(W.value,z,n)&&m().then(G=>G?.handleInput())},handleKeydown:A=>{if(l?.isMenuOpen())return l.handleKeydown(A);if(A.key==="Backspace"&&l?.hasMentions()&&!g){let W=c,z=W.selectionStart===0&&W.selectionEnd===0;if((W.value.length===0||z)&&l.removeLastChip())return A.preventDefault(),!0}return!1},isMenuOpen:()=>l?.isMenuOpen()??!1,hasMentions:()=>l?.hasMentions()??!1,collectForSubmit:()=>l?.collectForSubmit()??null,takeInlineCommand:async A=>r(A)?(l??await m())?.dispatchInlineCommand(A)??null:null,clear:()=>l?.clear(),prefetch:()=>{Il().catch(()=>{})},onComposerSwap:A=>{y=A,g&&A(g.next,g.prev)},destroy:()=>{l?.destroy(),u?.();for(let A of D)A.wrapper.remove();i.remove()}}}var Pu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function ds(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];Pu(s)&&Pu(r)?n[o]=ds(s,r):n[o]=r}return n}var zn="min(440px, calc(100vw - 24px))",Ru="440px",ib={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:zn,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)"},lt={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:ib,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"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:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Iu(t,e){if(!(!t&&!e))return t?e?ds(t,e):t:e}function zi(t){return t?{...lt,...t,theme:Iu(lt.theme,t.theme),darkTheme:Iu(lt.darkTheme,t.darkTheme),launcher:{...lt.launcher,...t.launcher,dock:{...lt.launcher?.dock,...t.launcher?.dock},clearChat:{...lt.launcher?.clearChat,...t.launcher?.clearChat}},copy:{...lt.copy,...t.copy},sendButton:{...lt.sendButton,...t.sendButton},statusIndicator:{...lt.statusIndicator,...t.statusIndicator},voiceRecognition:{...lt.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=lt.features?.artifacts,n=t.features?.artifacts,o=lt.features?.scrollToBottom,r=t.features?.scrollToBottom,s=lt.features?.scrollBehavior,i=t.features?.scrollBehavior,l=lt.features?.streamAnimation,p=t.features?.streamAnimation,c=lt.features?.askUserQuestion,d=t.features?.askUserQuestion,u=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},g=s===void 0&&i===void 0?void 0:{...s,...i},m=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{...lt.features,...t.features,...y!==void 0?{scrollToBottom:y}:{},...g!==void 0?{scrollBehavior:g}:{},...u!==void 0?{artifacts:u}:{},...m!==void 0?{streamAnimation:m}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:t.suggestionChips??lt.suggestionChips,suggestionChipsConfig:{...lt.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...lt.layout,...t.layout,header:{...lt.layout?.header,...t.layout?.header},messages:{...lt.layout?.messages,...t.layout?.messages,avatar:{...lt.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...lt.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...lt.layout?.slots,...t.layout?.slots}},markdown:{...lt.markdown,...t.markdown,options:{...lt.markdown?.options,...t.markdown?.options}},messageActions:{...lt.messageActions,...t.messageActions}}:lt}var Ui="16px",ji="transparent",ab={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"}},lb={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"}},cb={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:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:zn,maxWidth:Ru,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Ui,canvasBackground:ji},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"transparent",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"palette.shadows.none"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"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 Qt(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."))?Qt(t,o):o}function Wu(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=Qt(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 db(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 Hu(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]=Hu(s,r):n[o]=r}return n}function pb(t,e){return e?Hu(t,e):t}function dr(t,e={}){let n={palette:ab,semantic:lb,components:cb},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:pb(n.components,t?.components)};if(e.validate!==!1){let r=db(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 Bu(t){let e=Wu(t),n={};for(let[w,O]of Object.entries(e)){let N=w.replace(/\./g,"-");n[`--persona-${N}`]=O.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"]??Ui,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??ji,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-titleForeground"]??n["--persona-primary"],n["--persona-header-subtitle-fg"]=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",n["--persona-intro-card-padding"]=n["--persona-components-introCard-padding"]??"1.5rem",n["--persona-intro-card-shadow"]=n["--persona-components-introCard-shadow"]??"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-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 r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let s=n["--persona-components-markdown-heading-h1-fontWeight"];s&&(n["--persona-md-h1-weight"]=s);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let l=n["--persona-components-markdown-heading-h2-fontWeight"];l&&(n["--persona-md-h2-weight"]=l);let p=n["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(n["--persona-md-prose-font-family"]=p),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-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 c=t.components,d=c?.iconButton;d&&(d.background&&(n["--persona-icon-btn-bg"]=d.background),d.border&&(n["--persona-icon-btn-border"]=d.border),d.color&&(n["--persona-icon-btn-color"]=d.color),d.padding&&(n["--persona-icon-btn-padding"]=d.padding),d.borderRadius&&(n["--persona-icon-btn-radius"]=d.borderRadius),d.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=d.hoverBackground),d.hoverColor&&(n["--persona-icon-btn-hover-color"]=d.hoverColor),d.activeBackground&&(n["--persona-icon-btn-active-bg"]=d.activeBackground),d.activeBorder&&(n["--persona-icon-btn-active-border"]=d.activeBorder));let u=c?.labelButton;u&&(u.background&&(n["--persona-label-btn-bg"]=u.background),u.border&&(n["--persona-label-btn-border"]=u.border),u.color&&(n["--persona-label-btn-color"]=u.color),u.padding&&(n["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(n["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(n["--persona-label-btn-gap"]=u.gap));let y=c?.toggleGroup;y&&(y.gap&&(n["--persona-toggle-group-gap"]=y.gap),y.borderRadius&&(n["--persona-toggle-group-radius"]=y.borderRadius));let g=c?.artifact;if(g?.toolbar){let w=g.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"]=Qt(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(g?.tab){let w=g.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(g?.pane){let w=g.pane;if(w.toolbarBackground){let O=Qt(t,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=O}}if(g?.card){let w=g.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(g?.inline){let w=g.inline;w.background&&(n["--persona-artifact-inline-bg"]=Qt(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"]=Qt(t,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Qt(t,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Qt(t,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Qt(t,w.mutedColor)??w.mutedColor),w.frameHeight&&(n["--persona-artifact-inline-frame-height"]=w.frameHeight)}let m=c?.code;m&&(m.keywordColor&&(n["--persona-code-keyword-color"]=m.keywordColor),m.stringColor&&(n["--persona-code-string-color"]=m.stringColor),m.commentColor&&(n["--persona-code-comment-color"]=m.commentColor),m.numberColor&&(n["--persona-code-number-color"]=m.numberColor),m.tagColor&&(n["--persona-code-tag-color"]=m.tagColor),m.attrColor&&(n["--persona-code-attr-color"]=m.attrColor),m.propertyColor&&(n["--persona-code-property-color"]=m.propertyColor),m.lineNumberColor&&(n["--persona-code-line-number-color"]=m.lineNumberColor),m.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=m.gutterBorderColor),m.background&&(n["--persona-code-bg"]=Qt(t,m.background)??m.background));let C=n["--persona-surface"],D=n["--persona-container"],B=n["--persona-palette-colors-gray-100"]??"#f3f4f6",E=n["--persona-palette-colors-gray-200"]??"#e5e7eb",A=n["--persona-palette-colors-gray-300"]??"#d1d5db",W=!D||D===C,z=W?B:D,G=W?E:D;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??z,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??G,W&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??A),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??z,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??z,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??z,n}var ub={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"}}},Du=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},_l=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",gb=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":_l()},Nu=t=>gb(t),fb=t=>dr(t),mb=t=>dr({...t,palette:{...t?.palette,colors:{...ub.colors,...t?.palette?.colors}}},{validate:!1}),pr=t=>{let e=Nu(t),n=Du(t?.theme),o=Du(t?.darkTheme);return e==="dark"?mb(ds(n??{},o??{})):fb(n)},hb=t=>Bu(t),ps=(t,e)=>{let n=pr(e),o=hb(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",Nu(e))},qi=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(_l())});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(_l());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())}};St();nt();function kn(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function Ou(t){let e=kn(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function Vi(t){if(typeof t!="string")return"";let e=t.indexOf(`
198
198
  `);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 us(t){let e=Ou(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 lo(t){switch(us(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=Ou(t.path);return e?e.toUpperCase():"File"}}}function Fu(t){let e=t.markdown??"";return t.file?{filename:kn(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:Vi(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}tt();tt();var $l="http://www.w3.org/2000/svg";function _u(t){let e=document.createElementNS($l,"svg");e.setAttribute("class",Fn("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS($l,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS($l,"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}tt();tt();var co=(t,e,n)=>{let o=n;for(let r of e){let s=h("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,t.appendChild(s),o++}return o};function $u(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)),co(t,e,0)}var zl="persona-artifact-status-label",zu="persona-artifact-status-detail",Uu="data-artifact-status-label",Ul=new Map,ju=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function ur(t){t&&Ul.delete(t)}function bb(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?lo(e):t.artifactType==="component"?"Component":"Document"}function gr(t,e,n){let o=bb(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=Ul.get(i);t.status!=="complete"&&l===void 0&&(l=ju(),Ul.set(i,l));let p=l===void 0?0:Math.max(0,ju()-l),c=t.artifactType==="component",d=!c&&typeof t.markdown=="string"?t.markdown:"",u=c?0:d.length,y=c||d===""?0:d.split(`
200
- `).length,g=t.artifactType==="markdown"?t.file:void 0,m={artifactId:i,artifactType:t.artifactType,title:t.title,typeLabel:o,file:g,chars:u,lines:y,elapsedMs:p,content:()=>c?"":d,surface:n};try{let C=s(m);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 yb(t){t.className=zl,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 Wo(t,e,n){let o=t.querySelector(`:scope > .${zl}`);o||(o=h("span",zl),t.appendChild(o)),o.getAttribute(Uu)!==e.label&&(yb(o),$u(o,e.label,n),o.setAttribute(Uu,e.label));let r=t.querySelector(`:scope > .${zu}`),s=e.detail;s?(r||(r=h("span",zu),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}tt();var vb={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"},xb=15e4,Ki={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 Cb(t,e){let n=(t||"").trim().toLowerCase();if(n&&Ki[n])return Ki[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(Ki[r])return Ki[r]}}return null}function Gi(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 wb=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"]),Ab=[{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=>wb.has(t)?"keyword":"plain"}];function qu(t){return Gi(t,Ab)}var Sb=[{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 Mb(t){let e=Gi(t,Sb);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 Tb=[{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 Vu(t){let e=Gi(t,Tb),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 Eb=[{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 kb(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 Gi(p,Eb))e.push(d);r=l;let c=/^<\s*(script|style)\b/i.exec(p);if(c&&!/\/>\s*$/.test(p)){let d=c[1].toLowerCase(),y=new RegExp("</\\s*"+d+"\\s*>","i").exec(t.slice(r)),g=y?r+y.index:o,m=t.slice(r,g),C=d==="script"?qu(m):Vu(m);for(let D of C)e.push(D);r=g}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 Lb(t,e){switch(e){case"html":return kb(t);case"css":return Vu(t);case"js":return qu(t);case"json":return Mb(t)}}function Pb(t){let e=op(),n=h("span","persona-code-line"),o=(r,s)=>{if(!s)return;let i=vb[r];if(i){let l=h("span",i);l.textContent=s,n.appendChild(l)}else n.appendChild(document.createTextNode(s))};for(let r of t){let s=r.value.split(`
199
+ `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function us(t){let e=Ou(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 lo(t){switch(us(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=Ou(t.path);return e?e.toUpperCase():"File"}}}function Fu(t){let e=t.markdown??"";return t.file?{filename:kn(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:Vi(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}nt();nt();var $l="http://www.w3.org/2000/svg";function _u(t){let e=document.createElementNS($l,"svg");e.setAttribute("class",Fn("persona-spinner",t)),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let n=document.createElementNS($l,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS($l,"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}nt();nt();var co=(t,e,n)=>{let o=n;for(let r of e){let s=h("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,t.appendChild(s),o++}return o};function $u(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)),co(t,e,0)}var zl="persona-artifact-status-label",zu="persona-artifact-status-detail",Uu="data-artifact-status-label",Ul=new Map,ju=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function ur(t){t&&Ul.delete(t)}function bb(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?lo(e):t.artifactType==="component"?"Component":"Document"}function gr(t,e,n){let o=bb(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=Ul.get(i);t.status!=="complete"&&l===void 0&&(l=ju(),Ul.set(i,l));let p=l===void 0?0:Math.max(0,ju()-l),c=t.artifactType==="component",d=!c&&typeof t.markdown=="string"?t.markdown:"",u=c?0:d.length,y=c||d===""?0:d.split(`
200
+ `).length,g=t.artifactType==="markdown"?t.file:void 0,m={artifactId:i,artifactType:t.artifactType,title:t.title,typeLabel:o,file:g,chars:u,lines:y,elapsedMs:p,content:()=>c?"":d,surface:n};try{let C=s(m);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 yb(t){t.className=zl,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 Wo(t,e,n){let o=t.querySelector(`:scope > .${zl}`);o||(o=h("span",zl),t.appendChild(o)),o.getAttribute(Uu)!==e.label&&(yb(o),$u(o,e.label,n),o.setAttribute(Uu,e.label));let r=t.querySelector(`:scope > .${zu}`),s=e.detail;s?(r||(r=h("span",zu),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}nt();var vb={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"},xb=15e4,Ki={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 Cb(t,e){let n=(t||"").trim().toLowerCase();if(n&&Ki[n])return Ki[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(Ki[r])return Ki[r]}}return null}function Gi(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 wb=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"]),Ab=[{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=>wb.has(t)?"keyword":"plain"}];function qu(t){return Gi(t,Ab)}var Sb=[{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 Mb(t){let e=Gi(t,Sb);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 Tb=[{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 Vu(t){let e=Gi(t,Tb),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 Eb=[{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 kb(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 Gi(p,Eb))e.push(d);r=l;let c=/^<\s*(script|style)\b/i.exec(p);if(c&&!/\/>\s*$/.test(p)){let d=c[1].toLowerCase(),y=new RegExp("</\\s*"+d+"\\s*>","i").exec(t.slice(r)),g=y?r+y.index:o,m=t.slice(r,g),C=d==="script"?qu(m):Vu(m);for(let D of C)e.push(D);r=g}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 Lb(t,e){switch(e){case"html":return kb(t);case"css":return Vu(t);case"js":return qu(t);case"json":return Mb(t)}}function Pb(t){let e=op(),n=h("span","persona-code-line"),o=(r,s)=>{if(!s)return;let i=vb[r];if(i){let l=h("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
201
  `);for(let i=0;i<s.length;i+=1)i>0&&(e.appendChild(n),e.appendChild(document.createTextNode(`
202
- `)),n=h("span","persona-code-line")),o(r.type,s[i])}return n.childNodes.length>0?e.appendChild(n):e.lastChild||e.appendChild(n),e}function Ku(t,e,n){let o=t.length<=xb?Cb(e,n):null,r=o?Lb(t,o):[{type:"plain",value:t}];return Pb(r)}tt();Mt();tt();Mt();function fr(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=t,i=h("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(Pi)):(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 g of e){if(g.dividerBefore){let D=document.createElement("hr");i.appendChild(D)}let m=document.createElement("button");if(m.type="button",m.setAttribute("role","menuitem"),m.setAttribute("data-dropdown-item-id",g.id),g.destructive&&m.setAttribute("data-destructive",""),g.icon){let D=se(g.icon,16,"currentColor",1.5);D&&m.appendChild(D)}let C=document.createElement("span");C.textContent=g.label,m.appendChild(C),m.addEventListener("click",D=>{D.stopPropagation(),d(),n(g.id)}),i.appendChild(m)}let l=null;function p(){if(!s)return;let g=o.getBoundingClientRect();i.style.top=`${g.bottom+4}px`,r==="bottom-right"?(i.style.right=`${window.innerWidth-g.right}px`,i.style.left="auto"):(i.style.left=`${g.left}px`,i.style.right="auto")}function c(){p(),i.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=m=>{!i.contains(m.target)&&!o.contains(m.target)&&d()};document.addEventListener("click",g,!0),l=()=>document.removeEventListener("click",g,!0)})}function d(){i.classList.add("persona-hidden"),l?.(),l=null}function u(){i.classList.contains("persona-hidden")?c():d()}function y(){d(),i.remove()}return s&&s.appendChild(i),{element:i,show:c,hide:d,toggle:u,destroy:y}}function Dt(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,onClick:i,aria:l}=t,p=h("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let c=se(e,o??16,"currentColor",r??2);if(c&&p.appendChild(c),i&&p.addEventListener("click",i),l)for(let[d,u]of Object.entries(l))p.setAttribute(d,u);return p}function Ho(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=h("button",c);if(d.type="button",d.setAttribute("aria-label",n),e){let y=se(e,s??14,"currentColor",2);y&&d.appendChild(y)}let u=h("span");if(u.textContent=n,d.appendChild(u),l&&d.addEventListener("click",l),p)for(let[y,g]of Object.entries(p))d.setAttribute(y,g);return d}function Qi(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,s=h("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 u;d.icon?u=Dt({icon:d.icon,label:d.label,className:d.className,onClick:()=>{i=d.id,p(),o(d.id)}}):(u=h("button","persona-icon-btn"+(d.className?" "+d.className:"")),u.type="button",u.setAttribute("aria-label",d.label),u.title=d.label,u.textContent=d.label,u.addEventListener("click",()=>{i=d.id,p(),o(d.id)})),u.setAttribute("aria-pressed",d.id===i?"true":"false"),l.push({id:d.id,btn:u}),s.appendChild(u)}function c(d){i=d,p()}return{element:s,setSelected:c}}function Gu(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:i,className:l,hover:p}=t,c=h("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=h("span","persona-combo-btn-label");d.textContent=e,c.appendChild(d);let u=se(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),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 y=fr({items:o,onSelect:g=>{c.setAttribute("aria-expanded","false"),r(g)},anchor:c,position:s,portal:i});return i||c.appendChild(y.element),c.addEventListener("click",g=>{g.stopPropagation();let m=!y.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",m?"false":"true"),y.toggle()}),c.addEventListener("keydown",g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),c.click())}),{element:c,setLabel:g=>{d.textContent=g,c.setAttribute("aria-label",g)},open:()=>{c.setAttribute("aria-expanded","true"),y.show()},close:()=>{c.setAttribute("aria-expanded","false"),y.hide()},toggle:()=>{let g=!y.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",g?"false":"true"),y.toggle()},destroy:()=>{y.destroy(),c.remove()}}}tt();var Xi="persona-artifact-custom-action-btn";function mr(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 "+Xi+(n?" persona-artifact-doc-copy-btn":"");o=h("button",r)}else{let r="persona-icon-btn "+Xi+(n?" persona-artifact-doc-icon-btn":"");o=h("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=h("span");r.textContent=t.label,o.appendChild(r)}}else t.showLabel||!t.icon?o=Ho({icon:t.icon,label:t.label,className:Xi+(n?" persona-artifact-doc-copy-btn":"")}):o=Dt({icon:t.icon,label:t.label,className:Xi+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function gs(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 Qu(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?kn(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=n?lo(n):l==="component"?"Component":"Document",c=document.createElement("div");c.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",c.tabIndex=0,c.setAttribute("role","button"),c.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&c.setAttribute("data-open-artifact",s);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let u=document.createElement("div");u.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let y=document.createElement("div");y.className="persona-truncate persona-text-sm persona-font-medium",y.style.color="var(--persona-text, #1f2937)",y.textContent=r;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",i==="streaming"){let m=e?.config?.features?.artifacts,C={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{}},D=gr(C,m,"card");Wo(g,D,m)}else s&&ur(s),g.textContent=p;if(u.append(y,g),c.append(d,u),i==="complete"){let m=e?.config?.features?.artifacts?.cardActions;if(m&&m.length>0){let D={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let B of m)try{if(B.visible===void 0||B.visible(D)){let E=mr(B);E.setAttribute("data-artifact-custom-action",B.id),E.className=`${E.className} persona-flex-shrink-0`,c.append(E)}}catch{}}let C=Ho({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${r}`,C.setAttribute("data-download-artifact",s),c.append(C)}return c}var Ji=(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:()=>Qu(t,e)});if(l)return l}return Qu(t,e)};tt();Mt();var po=new WeakMap;function jl(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=po.get(r);if(!s)return;let i=o.get(r.getAttribute("data-artifact-inline")??"");i&&s(i,n)})}function eg(t){return po.has(t)}function Ib(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";if(t.artifactType==="component"){let s=t.componentProps,i=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:i}}let r=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:"",...r?{file:r}:{}}}function Xu(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?kn(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?lo(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Rb(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 Ju=180,Wb=240,Hb=.8,Bb=300,Db=500,Nb="cubic-bezier(0.2, 0, 0, 1)",Yu=240,Ob=.35;function Fb(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:Ju,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let B of i)B.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(Db,Math.max(Bb,Wb+c*Hb))),u=Math.round(d*Ob),y=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,g=y?y.animate([{opacity:0},{opacity:1}],{duration:Yu,delay:u,easing:"ease-out",fill:"backwards"}):null,m=t.animate([{height:`${e}px`},{height:`${p}px`}],{duration:d,easing:Nb});t.style.height=`${p}px`;let C=!1,D=()=>{C||(C=!0,l(),r())};Promise.allSettled([m.finished,g?.finished].filter(Boolean)).then(D),window.setTimeout(D,Math.max(d,u+Yu)+120)},Ju)}function _b(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 fs="--persona-artifact-inline-body-height";function $b(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,u=e?.fadeMask;u===!0?(c=!0,d=!0):u===!1?(c=!1,d=!1):u&&typeof u=="object"?(c=u.top===!0,d=u.bottom===!0):l==="clip"?(c=!1,d=!0):(c=!0,d=!0);let y=e?.transition==="none"?"none":"auto",g=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:l,fadeTop:c,fadeBottom:d,transition:y,completeDisplay:g}}function Zu(t,e){let n=Ib(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:i,showViewToggle:l}=_b(o),p=o?.inlineActions??[],c=$b(o),d=c.completeDisplay==="card",u=null,y=n,g=h("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let m=V=>Ji(Rb(V),e),C=V=>{g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(fs),g.replaceChildren(m(V)),po.set(g,ae=>{g.replaceChildren(m(ae))})};if(d&&n.status==="complete")return C(n),g;let D=Yi(n,{config:e.config,bodyLayout:c,resolveViewMode:()=>u??c.viewMode}),B=h("div","persona-artifact-inline-body");B.appendChild(D.el);let E=V=>{let ae=V.status!=="complete",ne=ae?c.streamingHeight:c.completeHeight,me=typeof ne=="number";me?g.style.setProperty(fs,`${ne}px`):g.style.removeProperty(fs);let be=!!D.el.querySelector(".persona-code-pre"),fe=!!D.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");B.classList.toggle("persona-artifact-content-flush",be),B.classList.toggle("persona-artifact-inline-body--sized",me&&fe),B.classList.toggle("persona-artifact-inline-body--cap",!ae&&!fe&&typeof c.completeHeight=="number")},A=n.status,W=(V,ae)=>{A!=="complete"&&V.status==="complete"?(typeof c.completeHeight=="number"?g.style.setProperty(fs,`${c.completeHeight}px`):g.style.removeProperty(fs),ng(B,ae?.suppressTransition?"none":c.transition,V.id,()=>{D.update(V),E(V)})):D.update(V),E(V),A=V.status};E(n);let z=c.overflow==="clip"&&i&&!!n.id;if(z&&(B.setAttribute("data-expand-artifact-inline",n.id),B.setAttribute("role","button"),B.setAttribute("tabindex","0"),B.classList.add("persona-cursor-pointer"),B.setAttribute("aria-label",`Open ${Xu(n).title} in panel`)),!r)return g.appendChild(B),po.set(g,W),g;let G=h("div","persona-artifact-inline-chrome");G.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let w=h("div","persona-artifact-inline-chrome-lead"),O=h("span","persona-flex persona-items-center persona-flex-shrink-0"),N=se("file-text",16,"currentColor",2);N&&O.appendChild(N);let L=h("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),P=h("span","persona-artifact-inline-type");w.append(O,L,P);let I=h("div","persona-artifact-inline-chrome-actions"),Y=h("span","persona-flex persona-items-center persona-gap-1"),de=()=>u??c.viewMode,ue=l?Qi({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:de(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:V=>{let ae=V==="source"?"source":"rendered";ae!==de()&&(u=ae,D.update(y),E(y))}}):null,pe=s?Dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;pe&&n.id&&pe.setAttribute("data-copy-artifact",n.id);let ee=i?Dt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ee&&n.id&&ee.setAttribute("data-expand-artifact-inline",n.id),I.appendChild(Y),ue&&I.appendChild(ue.element),pe&&I.appendChild(pe),ee&&I.appendChild(ee),G.append(w,I),g.append(G,B);let oe=V=>{let{title:ae,typeLabel:ne}=Xu(V);L.textContent=ae,L.title=ae,z&&B.setAttribute("aria-label",`Open ${ae} in panel`);let me=V.status!=="complete";if(me){P.classList.contains("persona-artifact-inline-status")||(P.className="persona-artifact-inline-status",P.removeAttribute("data-preserve-animation"),P.replaceChildren());let be=gr(V,o,"inline-chrome");Wo(P,be,o)}else ur(V.id),P.className="persona-artifact-inline-type",P.removeAttribute("data-preserve-animation"),P.replaceChildren(),P.textContent=ne;if(pe&&pe.classList.toggle("persona-hidden",me),ue){let be=V.artifactType==="markdown"?V.file:void 0,fe=!1;if(!me&&be&&c.viewMode!=="source"){let Te=us(be);Te==="markdown"?fe=!0:(Te==="html"||Te==="svg")&&(fe=o?.filePreview?.enabled!==!1)}ue.element.classList.toggle("persona-hidden",!fe),ue.setSelected(de())}if(Y.replaceChildren(),!me&&p.length>0){let be=gs(V);if(be)for(let fe of p)try{if(fe.visible===void 0||fe.visible(be)){let Te=mr(fe,{documentChrome:!0});Te.setAttribute("data-artifact-custom-action",fe.id),Te.classList.add("persona-flex-shrink-0"),Y.appendChild(Te)}}catch{}}};return oe(n),po.set(g,(V,ae)=>{if(d&&A!=="complete"&&V.status==="complete"){let ne=g.isConnected?g.getBoundingClientRect().height:0;A="complete";let me=V,be=!1,fe=Te=>{me=Te,be=!0};po.set(g,fe),Fb(g,ne,{swap:()=>{C(me),be=!1,po.set(g,fe)},onSettled:()=>{be?C(me):po.set(g,Te=>{g.replaceChildren(m(Te))})}});return}(V.status!=="complete"||V.id!==y.id)&&(u=null),y=V,W(V,ae),oe(V)}),g}var tg=(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:()=>Zu(t,e)});if(l)return l}return Zu(t,e)};var ql=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)})}},Un=new ql;Un.register("PersonaArtifactCard",Ji,{bubbleChrome:!1});Un.register("PersonaArtifactInline",tg,{bubbleChrome:!1});function ms(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?Vi(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}var Vl=!1;function zb(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function ng(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"||Vl||s){o();return}Vl=!0;let i=zb(n);t.style.setProperty("view-transition-name",i);let l=()=>{Vl=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Ub="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",jb="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function qb(t){let e=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=h("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=t.component?`Component: ${t.component}`:"Component";let o=h("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 Vb(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 Kb=220;function Gb(){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 Qb(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 Xb(t,e,n){let o=h("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=h("div","persona-artifact-frame-loading-indicator");r.appendChild(_u());let s=null;return n.label!==!1&&(s=h("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 Jb(t,e,n,o,r,s){let i=null,l=0,p=!1,c=new Set,d=()=>{c.forEach(A=>clearTimeout(A)),c.clear()},u=(A,W)=>{let z=setTimeout(()=>{c.delete(z),A()},W);c.add(z)},y=()=>{i&&i.parentElement&&i.remove(),i=null},g=()=>{if(i||p)return;let A=Xb(r,s,o);i=A.el,t.appendChild(i),l=Date.now(),o.label!==!1&&u(A.revealLabel,o.labelDelayMs)},m=()=>{i&&(i.classList.add("persona-artifact-frame-loading--out"),u(y,Kb))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",B):e.removeEventListener("load",E)},D=()=>{if(p||(p=!0,C(),d(),!i))return;let A=Math.max(0,o.minVisibleMs-(Date.now()-l));A>0?u(m,A):m()};function B(A){if(n===null)return;let W=A.data;!W||W.persona!=="artifact-preview-ready"||W.token!==n||A.source===e.contentWindow&&D()}function E(){let A=W=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>W()):setTimeout(W,0)};A(()=>A(()=>D()))}return u(g,o.delayMs),u(D,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",B):e.addEventListener("load",E),()=>{p=!0,d(),C(),y()}}function Yi(t,e){let{config:n}=e,o=e.registry??Un,r=e.bodyLayout,s=n.markdown?ai(n.markdown):null,i=li(n.sanitize),l=t,p=!1,c=ee=>{let oe=Nn()!==null;s&&!oe&&!p&&(p=!0,ii(()=>pe(l)));let V=s?s(ee):oo(ee);return s&&oe&&i?i(V):V},d=h("div","persona-artifact-preview-body"),u=null,y=null,g=null,m=()=>{g&&(g(),g=null),u=null,y=null},C=null,D=null,B=null,E=!1,A=()=>{C=null,D=null,B=null,E=!1},W=null,z=null,G=()=>{W=null,z=null},w=40,O=0,N=ee=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ee()):setTimeout(ee,0),L=ee=>ee.scrollHeight-ee.clientHeight-ee.scrollTop<=w,P=ee=>{if(!r)return;let oe=ee.scrollHeight-ee.clientHeight>1,V=ee.scrollHeight-ee.clientHeight-ee.scrollTop;ee.classList.toggle("persona-artifact-fade-top",r.fadeTop&&oe&&ee.scrollTop>1),ee.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&oe&&V>1)},I=ee=>{O||(O=N(()=>{O=0,ee.scrollTop=ee.scrollHeight,P(ee)}))},Y=(ee,oe,V,ae)=>{let ne=!!r,me=V.id+"|"+(ne?"w":"p");if(!C||B!==me||C.parentElement!==d){m(),G(),d.replaceChildren();let Te=h("pre",Ub+" persona-code-pre"),Se=h("code","persona-code");if(Te.appendChild(Se),ne){let Fe=h("div","persona-artifact-source-window");if(Fe.appendChild(Te),d.appendChild(Fe),!(r?.overflow==="clip")&&typeof Fe.addEventListener=="function"){let qe=()=>Fe.scrollHeight-Fe.clientHeight>1;Fe.addEventListener("scroll",()=>{L(Fe)&&(E=!1),P(Fe)},{passive:!0}),Fe.addEventListener("wheel",Xe=>{qe()&&Xe.deltaY<0&&(E=!0)},{passive:!0}),Fe.addEventListener("touchmove",()=>{qe()&&(E=!0)},{passive:!0})}C=Fe}else d.appendChild(Te),C=Te;D=Se,B=me}let be=ne?C:null;be&&(be.classList.toggle("persona-artifact-source-window--fixed",ae),be.classList.toggle("persona-artifact-source-window--clip",ae&&r?.overflow==="clip"));let fe=be?L(be):!0;if(D.replaceChildren(Ku(ee,oe?.language,oe?.path)),be){let Te=V.status!=="complete";ae&&Te&&r?.followOutput&&!E&&fe?I(be):Te||(E=!1),P(be)}},de=ee=>{m(),A(),G(),d.replaceChildren();let oe=h("div",jb);oe.innerHTML=c(ee),d.appendChild(oe)},ue=ee=>{let oe=ee.id,V=n.features?.artifacts,ae=gr(ee,V,"status-body");if(W&&z===oe&&W.parentElement===d){let be=W.querySelector(".persona-artifact-status-view-text");be&&Wo(be,ae,V);return}m(),A(),d.replaceChildren();let ne=h("div","persona-artifact-status-view"),me=h("div","persona-artifact-status-view-text");Wo(me,ae,V),ne.appendChild(me),d.appendChild(ne),W=ne,z=oe},pe=ee=>{l=ee;let oe=e.resolveViewMode?.(ee)??r?.viewMode??"rendered",V=ee.artifactType==="markdown"?ee.file:void 0,ae=ee.status!=="complete";ae||ur(ee.id);let ne=ae?r?.streamingHeight:r?.completeHeight,me=!!r&&typeof ne=="number";if(r?.streamingView==="status"&&ae){ue(ee);return}if(V){let fe=Vi(ee.markdown??""),Te=us(V),Se=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ae&&oe==="rendered"&&Se&&(Te==="html"||Te==="svg")){let ke=ee.id+"\0"+fe;if(u&&y===ke&&u.parentElement===d)return;A(),G(),m(),d.replaceChildren();let qe=n.features?.artifacts?.filePreview,Xe=qe?.iframeSandbox??"allow-scripts";!qe?.dangerouslyAllowSameOrigin&&Xe.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."),Xe=Xe.split(/\s+/).filter(Lt=>Lt&&Lt!=="allow-same-origin").join(" "));let He=Vb(qe?.loading),Le=h("div","persona-artifact-frame"),Je=h("iframe","persona-artifact-iframe");Je.setAttribute("sandbox",Xe),Je.setAttribute("data-artifact-id",ee.id);let ln=null;He.enabled&&He.injectReadySignal?(ln=Gb(),Je.srcdoc=fe+Qb(ln)):Je.srcdoc=fe,Le.appendChild(Je),d.appendChild(Le),He.enabled&&(g=Jb(Le,Je,ln,He,ee.id,n)),u=Le,y=ke;return}if(m(),!ae&&Te==="markdown"&&oe==="rendered"){de(fe);return}Y(fe,{language:V.language,path:V.path},ee,me);return}if(ee.artifactType==="markdown"){if(oe==="source"){m(),Y(ee.markdown??"",void 0,ee,me);return}de(ee.markdown??"");return}m(),A(),G(),d.replaceChildren();let be=ee.component?o.get(ee.component):void 0;if(be){let Te={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Se=be(ee.props??{},Te);if(Se){d.appendChild(Se);return}}catch{}}d.appendChild(qb(ee))};return pe(t),{el:d,update(ee){pe(ee)}}}var og=require("idiomorph"),Zi=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;og.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 rg=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Kl={index:-1,draft:""};function sg(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 ig(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 ag(){return new Map}function lg(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function cg(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function dg(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}function ea(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Ln(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function uo(t,e){return Ln(t)-t.scrollTop<=e}function ta(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 na(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 pg(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function ug(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight);return{targetScrollTop:e,spacerHeight:n}}function gg(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var hs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Yb=["pre","code","a","script","style"],oa=t=>({type:t?.type??hs.type,placeholder:t?.placeholder??hs.placeholder,speed:t?.speed??hs.speed,duration:t?.duration??hs.duration,buffer:t?.buffer??hs.buffer}),Zb=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],mg=new Map;for(let t of Zb)mg.set(t.name,t);var hr=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:mg.get(t)??null,ra=(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},ey=(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},ty=(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},Gl=/\s/,ny=(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},oy=(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(Gl.test(s[l])){let p=l;for(;p<s.length&&Gl.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&&!Gl.test(s[c]);)p.appendChild(ey(o,s[c],e,n.value)),n.value+=1,c+=1;i.appendChild(p),l=c}r.replaceChild(i,t)},ry=(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(ty(o,p,e,n.value)),n.value+=1));r.replaceChild(i,t)},bs=(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??Yb).map(u=>u.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=i.nextNode();for(;p;)ny(p,s)||l.push(p),p=i.nextNode();let c={value:o?.startIndex??0},d=e==="char"?oy:ry;for(let u of l)d(u,n,c);return r.innerHTML},sa=(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},ys=(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},fg=new WeakMap,sy=(t,e)=>{if(!t.styles)return;let n=fg.get(e);if(n||(n=new Set,fg.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)},Ql=new WeakMap,iy=(t,e)=>{if(!t.onAttach)return;let n=Ql.get(e);if(n||(n=new Map,Ql.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},hg=t=>{let e=Ql.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},ia=(t,e)=>{sy(t,e),iy(t,e)};function Xl(t,e=qt){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 vs=0,go=null;function Jl(t=document){if(vs++,vs===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;go={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY: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,vs=Math.max(0,vs-1),vs===0&&go)){let n=t.body,o=t.defaultView??window;n.style.overflow=go.originalOverflow,n.style.position=go.originalPosition,n.style.top=go.originalTop,n.style.width=go.originalWidth,o.scrollTo(0,go.scrollY),go=null}}}var xs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Ot=t=>(t?.launcher?.mountMode??"floating")==="docked",Cs=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",mn=t=>{let e=t?.launcher?.dock;return{side:e?.side??xs.side,width:e?.width??xs.width,animate:e?.animate??xs.animate,reveal:e?.reveal??xs.reveal,maxHeight:e?.maxHeight??xs.maxHeight}};tt();var Sn={"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"};tt();Mt();tt();Mt();var ay="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",aa=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=ay,buttonSize:r,iconSize:s="28px"}=e,i=t?.launcher??{},l=r??i.closeButtonSize??"32px",p=h("div",o),c=i.closeButtonTooltipText??"Close chat",d=i.closeButtonShowTooltip??!0,u=i.closeButtonIconName??"x",y=i.closeButtonIconText??"\xD7",g=!!(i.closeButtonBorderWidth||i.closeButtonBorderColor),m=xe("button",{className:Fn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!i.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"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||Xt.actionIconColor,backgroundColor:i.closeButtonBackgroundColor||void 0,border:g?`${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=se(u,s,"currentColor",1);return C?(C.style.display="block",m.appendChild(C)):m.textContent=y,p.appendChild(m),$t({anchor:m,trigger:p,text:()=>m.getAttribute("aria-label")??c,enabled:d}),{button:m,wrapper:p}},ly="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",la=(t,e={})=>{let{wrapperClassName:n=ly,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??"",u=i.borderWidth??"",y=i.borderColor??"",g=i.borderRadius??"",m=i.paddingX??"",C=i.paddingY??"",D=i.tooltipText??"Clear chat",B=i.showTooltip??!0,E=h("div",n),A=!!(u||y),W=xe("button",{className:Fn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"hover:persona-bg-gray-100",!A&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":D},style:{height:l,width:l,color:c||Xt.actionIconColor,backgroundColor:d||void 0,border:A?`${u||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:m||void 0,paddingRight:m||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),z=se(p,r,"currentColor",1);return z&&(z.style.display="block",W.appendChild(z)),E.appendChild(W),$t({anchor:W,trigger:E,text:()=>W.getAttribute("aria-label")??D,enabled:B}),{button:W,wrapper:E}};var Xt={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))"},Bo=t=>{let{config:e,showClose:n=!0}=t,o=xe("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=xe("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 z=parseFloat(s)||24,G=se(p,z*.6,"currentColor",1);G?c.replaceChildren(G):c.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let z=h("img");z.src=e.launcher.iconUrl,z.alt="",z.className="persona-rounded-xl persona-object-cover",z.style.height=s,z.style.width=s,c.replaceChildren(z)}else c.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let d=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=xe("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Xt.titleColor}}),y=xe("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Xt.subtitleColor}});d.append(u,y),l?o.append(d):o.append(c,d);let g=r.clearChat??{},m=g.enabled??!0,C=g.placement??"inline",D=null,B=null;if(m){let G=la(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});D=G.button,B=G.wrapper,C==="top-right"&&(B.style.right="48px"),C==="inline"&&o.appendChild(B)}let E=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":m&&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:A,wrapper:W}=aa(e,{showClose:n,wrapperClassName:E});return i!=="top-right"&&o.appendChild(W),{header:o,iconHolder:c,headerTitle:u,headerSubtitle:y,closeButton:A,closeButtonWrapper:W,clearChatButton:D,clearChatButtonWrapper:B}},ws=(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))};tt();Mt();var cy=t=>{let e=Bo({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 dy(t,e,n){if(e?.length)for(let o of e){let r=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=se(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=h("div","persona-relative");s.appendChild(r);let i=fr({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-left"});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 py=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=t,i=e?.launcher??{},l=h("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=Gu({label:i.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,c.style.color=Xt.titleColor,d=c.querySelector(".persona-combo-btn-label")??c;else{if(c=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=h("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=Xt.titleColor,d.textContent=i.title??"Chat Assistant",c.appendChild(d),dy(c,r?.trailingActions,r?.onAction??s),r?.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let A=r.onTitleClick;c.addEventListener("click",W=>{W.target.closest("button")||A()}),c.addEventListener("keydown",W=>{(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),A())})}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 u=i.closeButtonSize??"32px",y=h("div",""),g=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=u,g.style.width=u,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=i.closeButtonColor||Xt.actionIconColor;let m=i.closeButtonIconName??"x",C=se(m,"28px","currentColor",1);C?g.appendChild(C):g.textContent="\xD7",o&&g.addEventListener("click",o),y.appendChild(g),l.appendChild(y);let D=h("div");D.style.display="none";let B=h("span");return B.style.display="none",{header:l,iconHolder:D,headerTitle:d,headerSubtitle:B,closeButton:g,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}},bg={default:cy,minimal:py},uy=t=>bg[t]??bg.default,ca=(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=h("div");l.style.display="none";let p=h("span"),c=h("span"),d=h("button");d.style.display="none";let u=h("div");return u.style.display="none",{header:i,iconHolder:l,headerTitle:p,headerSubtitle:c,closeButton:d,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",s=uy(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};tt();tt();Mt();var da=t=>{let e=h("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-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;e.style.maxHeight=`${n*o}px`,e.style.overflowY="auto";let r=()=>{let i=parseFloat(e.style.maxHeight);return Number.isFinite(i)&&i>0?i:n*o},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let i=Math.min(e.scrollHeight,r());e.style.height=`${i}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},pa=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,u=e.size??"40px",y=e.backgroundColor,g=e.textColor,m=h("div","persona-send-button-wrapper"),C=xe("button",{className:Fn("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&&!y&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&y||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}}),D=null,B=null;if(n){let W=parseFloat(u)||24,z=g?.trim()||"currentColor";r?(D=se(r,W,z,2),D?C.appendChild(D):C.textContent=o):C.textContent=o,B=se(s,W,z,2)}else C.textContent=p;C.setAttribute("aria-label",i),m.appendChild(C),$t({anchor:C,trigger:m,text:()=>C.getAttribute("aria-label")??"",enabled:d});let E="send";return{button:C,wrapper:m,setMode:W=>{if(W===E)return;E=W;let z=W==="stop"?l:i;if(C.setAttribute("aria-label",z),n){if(D&&B){let G=W==="stop"?B:D;C.replaceChildren(G)}}else C.textContent=W==="stop"?c:p}}},ua=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,u=e.iconColor??t?.sendButton?.textColor,y=h("div","persona-send-button-wrapper"),g=xe("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:u||"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=se(l,c,u||"currentColor",1.5);C?g.appendChild(C):g.textContent="\u{1F3A4}",y.appendChild(g);let D=e.tooltipText??"Start voice recognition",B=e.showTooltip??!1;return $t({anchor:g,trigger:y,text:()=>g.getAttribute("aria-label")??D,enabled:B}),{button:g,wrapper:y}},ga=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=t?.sendButton?.size??"40px",o=h("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=h("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(e.allowedTypes??$n).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=h("div","persona-send-button-wrapper"),d=xe("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"}}),u=se(s,p,"currentColor",1.5);u?d.appendChild(u):d.textContent="\u{1F4CE}",d.addEventListener("click",g=>{g.preventDefault(),r.click()}),c.appendChild(d);let y=e.buttonTooltipText??"Attach file";return $t({anchor:d,trigger:c,text:()=>d.getAttribute("aria-label")??y}),{button:d,wrapper:c,input:r,previewsContainer:o}},fa=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=h("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=h("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},ma=()=>xe("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ha=t=>{let{config:e}=t,n=xe("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=ma(),r=xe("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:i}=da(e);i();let l=pa(e),p=ua(e),c=ga(e),d=fa(e);c&&(c.previewsContainer.style.gap="8px",r.append(c.previewsContainer,c.input)),r.append(s);let u=xe("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&y.append(c.wrapper),p&&g.append(p.wrapper),g.append(l.wrapper),u.append(y,g),r.append(u),r.addEventListener("click",m=>{m.target!==l.button&&m.target!==l.wrapper&&m.target!==p?.button&&m.target!==p?.wrapper&&m.target!==c?.button&&m.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:u,leftActions:y,rightActions:g,setSendButtonMode:l.setMode}};tt();Mt();var yg=()=>{let t=xe("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=h("span","persona-pill-peek__icon"),n=se("message-square",16,"currentColor",1.5);n&&e.appendChild(n);let o=h("span","persona-pill-peek__text"),r=h("span","persona-pill-peek__caret"),s=se("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},vg=t=>{let{config:e}=t,n=xe("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ma(),r=fa(e);r.style.display="none";let{textarea:s,attachAutoResize:i}=da(e);s.style.maxHeight="100px",i();let l=pa(e),p=ua(e),c=ga(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let d=xe("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=h("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&u.append(c.wrapper);let y=h("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&y.append(p.wrapper),y.append(l.wrapper),d.addEventListener("click",m=>{m.target!==l.button&&m.target!==l.wrapper&&m.target!==p?.button&&m.target!==p?.wrapper&&m.target!==c?.button&&m.target!==c?.wrapper&&s.focus()}),c&&d.append(c.input),d.append(u,s,y),c&&n.append(c.previewsContainer),n.append(o,d,r);let g=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:g,leftActions:u,rightActions:y,setSendButtonMode:l.setMode}};var xg=t=>{let e=t?.launcher?.enabled??!0,n=Ot(t);if(Cs(t)){let d=t?.launcher?.composerBar??{},u=h("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=d.expandedSize??"anchored",u.style.zIndex=String(t?.launcher?.zIndex??qt);let y=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",u.appendChild(y);let g=h("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=d.expandedSize??"anchored",g.style.zIndex=String(t?.launcher?.zIndex??qt),{wrapper:u,panel:y,pillRoot:g}}if(n){let d=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return d.appendChild(u),{wrapper:d,panel:u}}if(!e){let d=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=t?.launcher?.width??"100%";return d.style.width=y,u.style.width="100%",d.appendChild(u),{wrapper:d,panel:u}}let r=t?.launcher??{},s=r.position&&Sn[r.position]?Sn[r.position]:Sn["bottom-right"],i=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(t?.launcher?.zIndex??qt);let l=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=t?.launcher?.width??t?.launcherWidth??zn;return l.style.width=c,l.style.maxWidth=c,i.appendChild(l),{wrapper:i,panel:l}},gy=(t,e)=>{let n=h("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}=aa(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 W=la(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});i=W.button,l=W.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=xe("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=xe("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 d=xe("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=xe("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),y=xe("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},d,u),g=h("div","persona-flex persona-flex-col persona-gap-3"),m=t?.layout?.contentMaxWidth;m&&(g.style.maxWidth=m,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(y.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(y,g);let D=xe("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"}}),B=vg({config:t}),{root:E,textNode:A}=yg();return n.append(p,r,c,D),l&&n.appendChild(l),{container:n,body:c,messagesWrapper:g,composerOverlay:D,suggestions:B.suggestions,textarea:B.textarea,sendButton:B.sendButton,sendButtonWrapper:B.sendButtonWrapper,micButton:B.micButton,micButtonWrapper:B.micButtonWrapper,composerForm:B.composerForm,statusText:B.statusText,introTitle:d,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:l,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:p,footer:B.footer,attachmentButton:B.attachmentButton,attachmentButtonWrapper:B.attachmentButtonWrapper,attachmentInput:B.attachmentInput,attachmentPreviewsContainer:B.attachmentPreviewsContainer,actionsRow:B.actionsRow,leftActions:B.leftActions,rightActions:B.rightActions,setSendButtonMode:B.setSendButtonMode,peekBanner:E,peekTextNode:A}},Cg=(t,e=!0)=>{if(Cs(t))return gy(t,e);let n=xe("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?ca(t,o,{showClose:e}):Bo({config:t,showClose:e}),i=xe("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 l=xe("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=xe("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),c=xe("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Ot(t)?"none":"var(--persona-intro-card-shadow, none)"}},l,p),d=h("div","persona-flex persona-flex-col persona-gap-3"),u=t?.layout?.contentMaxWidth;u&&(d.style.maxWidth=u,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(c.style.display="none",i.classList.remove("persona-gap-6"),i.classList.add("persona-gap-3")),i.append(c,d);let g=ha({config:t}),m=t?.layout?.showFooter!==!1;r?ws(n,s,t):(s.header.style.display="none",ws(n,s,t)),n.append(i);let C=xe("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 m||(g.footer.style.display="none"),n.append(g.footer),n.append(C),{container:n,body:i,messagesWrapper:d,composerOverlay:C,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:l,introSubtitle:p,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:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};tt();Mt();var Yl=(t,e)=>{let n=h("button");n.type="button",n.innerHTML=`
202
+ `)),n=h("span","persona-code-line")),o(r.type,s[i])}return n.childNodes.length>0?e.appendChild(n):e.lastChild||e.appendChild(n),e}function Ku(t,e,n){let o=t.length<=xb?Cb(e,n):null,r=o?Lb(t,o):[{type:"plain",value:t}];return Pb(r)}nt();St();nt();St();function fr(t){let{items:e,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=t,i=h("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(Pi)):(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 g of e){if(g.dividerBefore){let D=document.createElement("hr");i.appendChild(D)}let m=document.createElement("button");if(m.type="button",m.setAttribute("role","menuitem"),m.setAttribute("data-dropdown-item-id",g.id),g.destructive&&m.setAttribute("data-destructive",""),g.icon){let D=se(g.icon,16,"currentColor",1.5);D&&m.appendChild(D)}let C=document.createElement("span");C.textContent=g.label,m.appendChild(C),m.addEventListener("click",D=>{D.stopPropagation(),d(),n(g.id)}),i.appendChild(m)}let l=null;function p(){if(!s)return;let g=o.getBoundingClientRect();i.style.top=`${g.bottom+4}px`,r==="bottom-right"?(i.style.right=`${window.innerWidth-g.right}px`,i.style.left="auto"):(i.style.left=`${g.left}px`,i.style.right="auto")}function c(){p(),i.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=m=>{!i.contains(m.target)&&!o.contains(m.target)&&d()};document.addEventListener("click",g,!0),l=()=>document.removeEventListener("click",g,!0)})}function d(){i.classList.add("persona-hidden"),l?.(),l=null}function u(){i.classList.contains("persona-hidden")?c():d()}function y(){d(),i.remove()}return s&&s.appendChild(i),{element:i,show:c,hide:d,toggle:u,destroy:y}}function Bt(t){let{icon:e,label:n,size:o,strokeWidth:r,className:s,onClick:i,aria:l}=t,p=h("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let c=se(e,o??16,"currentColor",r??2);if(c&&p.appendChild(c),i&&p.addEventListener("click",i),l)for(let[d,u]of Object.entries(l))p.setAttribute(d,u);return p}function Ho(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=h("button",c);if(d.type="button",d.setAttribute("aria-label",n),e){let y=se(e,s??14,"currentColor",2);y&&d.appendChild(y)}let u=h("span");if(u.textContent=n,d.appendChild(u),l&&d.addEventListener("click",l),p)for(let[y,g]of Object.entries(p))d.setAttribute(y,g);return d}function Qi(t){let{items:e,selectedId:n,onSelect:o,className:r}=t,s=h("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 u;d.icon?u=Bt({icon:d.icon,label:d.label,className:d.className,onClick:()=>{i=d.id,p(),o(d.id)}}):(u=h("button","persona-icon-btn"+(d.className?" "+d.className:"")),u.type="button",u.setAttribute("aria-label",d.label),u.title=d.label,u.textContent=d.label,u.addEventListener("click",()=>{i=d.id,p(),o(d.id)})),u.setAttribute("aria-pressed",d.id===i?"true":"false"),l.push({id:d.id,btn:u}),s.appendChild(u)}function c(d){i=d,p()}return{element:s,setSelected:c}}function Gu(t){let{label:e,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:i,className:l,hover:p}=t,c=h("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=h("span","persona-combo-btn-label");d.textContent=e,c.appendChild(d);let u=se(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),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 y=fr({items:o,onSelect:g=>{c.setAttribute("aria-expanded","false"),r(g)},anchor:c,position:s,portal:i});return i||c.appendChild(y.element),c.addEventListener("click",g=>{g.stopPropagation();let m=!y.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",m?"false":"true"),y.toggle()}),c.addEventListener("keydown",g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),c.click())}),{element:c,setLabel:g=>{d.textContent=g,c.setAttribute("aria-label",g)},open:()=>{c.setAttribute("aria-expanded","true"),y.show()},close:()=>{c.setAttribute("aria-expanded","false"),y.hide()},toggle:()=>{let g=!y.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",g?"false":"true"),y.toggle()},destroy:()=>{y.destroy(),c.remove()}}}nt();var Xi="persona-artifact-custom-action-btn";function mr(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 "+Xi+(n?" persona-artifact-doc-copy-btn":"");o=h("button",r)}else{let r="persona-icon-btn "+Xi+(n?" persona-artifact-doc-icon-btn":"");o=h("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=h("span");r.textContent=t.label,o.appendChild(r)}}else t.showLabel||!t.icon?o=Ho({icon:t.icon,label:t.label,className:Xi+(n?" persona-artifact-doc-copy-btn":"")}):o=Bt({icon:t.icon,label:t.label,className:Xi+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function gs(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 Qu(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?kn(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=n?lo(n):l==="component"?"Component":"Document",c=document.createElement("div");c.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",c.tabIndex=0,c.setAttribute("role","button"),c.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&c.setAttribute("data-open-artifact",s);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let u=document.createElement("div");u.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let y=document.createElement("div");y.className="persona-truncate persona-text-sm persona-font-medium",y.style.color="var(--persona-text, #1f2937)",y.textContent=r;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",i==="streaming"){let m=e?.config?.features?.artifacts,C={id:s,artifactType:l==="component"?"component":"markdown",title:o,status:"streaming",...typeof t.markdown=="string"?{markdown:t.markdown}:{},...n?{file:n}:{}},D=gr(C,m,"card");Wo(g,D,m)}else s&&ur(s),g.textContent=p;if(u.append(y,g),c.append(d,u),i==="complete"){let m=e?.config?.features?.artifacts?.cardActions;if(m&&m.length>0){let D={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let B of m)try{if(B.visible===void 0||B.visible(D)){let E=mr(B);E.setAttribute("data-artifact-custom-action",B.id),E.className=`${E.className} persona-flex-shrink-0`,c.append(E)}}catch{}}let C=Ho({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${r}`,C.setAttribute("data-download-artifact",s),c.append(C)}return c}var Ji=(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:()=>Qu(t,e)});if(l)return l}return Qu(t,e)};nt();St();var po=new WeakMap;function jl(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=po.get(r);if(!s)return;let i=o.get(r.getAttribute("data-artifact-inline")??"");i&&s(i,n)})}function eg(t){return po.has(t)}function Ib(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";if(t.artifactType==="component"){let s=t.componentProps,i=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return{id:e,artifactType:"component",title:n,status:o,component:typeof t.component=="string"?t.component:"",props:i}}let r=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:"",...r?{file:r}:{}}}function Xu(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?kn(e.path):t.title&&t.title.trim()?t.title:"Untitled artifact",o=e?lo(e):t.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function Rb(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 Ju=180,Wb=240,Hb=.8,Bb=300,Db=500,Nb="cubic-bezier(0.2, 0, 0, 1)",Yu=240,Ob=.35;function Fb(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:Ju,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let B of i)B.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(Db,Math.max(Bb,Wb+c*Hb))),u=Math.round(d*Ob),y=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,g=y?y.animate([{opacity:0},{opacity:1}],{duration:Yu,delay:u,easing:"ease-out",fill:"backwards"}):null,m=t.animate([{height:`${e}px`},{height:`${p}px`}],{duration:d,easing:Nb});t.style.height=`${p}px`;let C=!1,D=()=>{C||(C=!0,l(),r())};Promise.allSettled([m.finished,g?.finished].filter(Boolean)).then(D),window.setTimeout(D,Math.max(d,u+Yu)+120)},Ju)}function _b(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 fs="--persona-artifact-inline-body-height";function $b(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,u=e?.fadeMask;u===!0?(c=!0,d=!0):u===!1?(c=!1,d=!1):u&&typeof u=="object"?(c=u.top===!0,d=u.bottom===!0):l==="clip"?(c=!1,d=!0):(c=!0,d=!0);let y=e?.transition==="none"?"none":"auto",g=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:l,fadeTop:c,fadeBottom:d,transition:y,completeDisplay:g}}function Zu(t,e){let n=Ib(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:i,showViewToggle:l}=_b(o),p=o?.inlineActions??[],c=$b(o),d=c.completeDisplay==="card",u=null,y=n,g=h("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let m=V=>Ji(Rb(V),e),C=V=>{g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(fs),g.replaceChildren(m(V)),po.set(g,ae=>{g.replaceChildren(m(ae))})};if(d&&n.status==="complete")return C(n),g;let D=Yi(n,{config:e.config,bodyLayout:c,resolveViewMode:()=>u??c.viewMode}),B=h("div","persona-artifact-inline-body");B.appendChild(D.el);let E=V=>{let ae=V.status!=="complete",ne=ae?c.streamingHeight:c.completeHeight,me=typeof ne=="number";me?g.style.setProperty(fs,`${ne}px`):g.style.removeProperty(fs);let be=!!D.el.querySelector(".persona-code-pre"),fe=!!D.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");B.classList.toggle("persona-artifact-content-flush",be),B.classList.toggle("persona-artifact-inline-body--sized",me&&fe),B.classList.toggle("persona-artifact-inline-body--cap",!ae&&!fe&&typeof c.completeHeight=="number")},A=n.status,W=(V,ae)=>{A!=="complete"&&V.status==="complete"?(typeof c.completeHeight=="number"?g.style.setProperty(fs,`${c.completeHeight}px`):g.style.removeProperty(fs),ng(B,ae?.suppressTransition?"none":c.transition,V.id,()=>{D.update(V),E(V)})):D.update(V),E(V),A=V.status};E(n);let z=c.overflow==="clip"&&i&&!!n.id;if(z&&(B.setAttribute("data-expand-artifact-inline",n.id),B.setAttribute("role","button"),B.setAttribute("tabindex","0"),B.classList.add("persona-cursor-pointer"),B.setAttribute("aria-label",`Open ${Xu(n).title} in panel`)),!r)return g.appendChild(B),po.set(g,W),g;let G=h("div","persona-artifact-inline-chrome");G.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let w=h("div","persona-artifact-inline-chrome-lead"),O=h("span","persona-flex persona-items-center persona-flex-shrink-0"),N=se("file-text",16,"currentColor",2);N&&O.appendChild(N);let L=h("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),P=h("span","persona-artifact-inline-type");w.append(O,L,P);let I=h("div","persona-artifact-inline-chrome-actions"),Y=h("span","persona-flex persona-items-center persona-gap-1"),de=()=>u??c.viewMode,ue=l?Qi({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:de(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:V=>{let ae=V==="source"?"source":"rendered";ae!==de()&&(u=ae,D.update(y),E(y))}}):null,pe=s?Bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;pe&&n.id&&pe.setAttribute("data-copy-artifact",n.id);let ee=i?Bt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ee&&n.id&&ee.setAttribute("data-expand-artifact-inline",n.id),I.appendChild(Y),ue&&I.appendChild(ue.element),pe&&I.appendChild(pe),ee&&I.appendChild(ee),G.append(w,I),g.append(G,B);let oe=V=>{let{title:ae,typeLabel:ne}=Xu(V);L.textContent=ae,L.title=ae,z&&B.setAttribute("aria-label",`Open ${ae} in panel`);let me=V.status!=="complete";if(me){P.classList.contains("persona-artifact-inline-status")||(P.className="persona-artifact-inline-status",P.removeAttribute("data-preserve-animation"),P.replaceChildren());let be=gr(V,o,"inline-chrome");Wo(P,be,o)}else ur(V.id),P.className="persona-artifact-inline-type",P.removeAttribute("data-preserve-animation"),P.replaceChildren(),P.textContent=ne;if(pe&&pe.classList.toggle("persona-hidden",me),ue){let be=V.artifactType==="markdown"?V.file:void 0,fe=!1;if(!me&&be&&c.viewMode!=="source"){let Te=us(be);Te==="markdown"?fe=!0:(Te==="html"||Te==="svg")&&(fe=o?.filePreview?.enabled!==!1)}ue.element.classList.toggle("persona-hidden",!fe),ue.setSelected(de())}if(Y.replaceChildren(),!me&&p.length>0){let be=gs(V);if(be)for(let fe of p)try{if(fe.visible===void 0||fe.visible(be)){let Te=mr(fe,{documentChrome:!0});Te.setAttribute("data-artifact-custom-action",fe.id),Te.classList.add("persona-flex-shrink-0"),Y.appendChild(Te)}}catch{}}};return oe(n),po.set(g,(V,ae)=>{if(d&&A!=="complete"&&V.status==="complete"){let ne=g.isConnected?g.getBoundingClientRect().height:0;A="complete";let me=V,be=!1,fe=Te=>{me=Te,be=!0};po.set(g,fe),Fb(g,ne,{swap:()=>{C(me),be=!1,po.set(g,fe)},onSettled:()=>{be?C(me):po.set(g,Te=>{g.replaceChildren(m(Te))})}});return}(V.status!=="complete"||V.id!==y.id)&&(u=null),y=V,W(V,ae),oe(V)}),g}var tg=(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:()=>Zu(t,e)});if(l)return l}return Zu(t,e)};var ql=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)})}},Un=new ql;Un.register("PersonaArtifactCard",Ji,{bubbleChrome:!1});Un.register("PersonaArtifactInline",tg,{bubbleChrome:!1});function ms(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?Vi(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}var Vl=!1;function zb(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function ng(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"||Vl||s){o();return}Vl=!0;let i=zb(n);t.style.setProperty("view-transition-name",i);let l=()=>{Vl=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Ub="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",jb="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function qb(t){let e=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=h("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=t.component?`Component: ${t.component}`:"Component";let o=h("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 Vb(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 Kb=220;function Gb(){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 Qb(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 Xb(t,e,n){let o=h("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=h("div","persona-artifact-frame-loading-indicator");r.appendChild(_u());let s=null;return n.label!==!1&&(s=h("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 Jb(t,e,n,o,r,s){let i=null,l=0,p=!1,c=new Set,d=()=>{c.forEach(A=>clearTimeout(A)),c.clear()},u=(A,W)=>{let z=setTimeout(()=>{c.delete(z),A()},W);c.add(z)},y=()=>{i&&i.parentElement&&i.remove(),i=null},g=()=>{if(i||p)return;let A=Xb(r,s,o);i=A.el,t.appendChild(i),l=Date.now(),o.label!==!1&&u(A.revealLabel,o.labelDelayMs)},m=()=>{i&&(i.classList.add("persona-artifact-frame-loading--out"),u(y,Kb))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",B):e.removeEventListener("load",E)},D=()=>{if(p||(p=!0,C(),d(),!i))return;let A=Math.max(0,o.minVisibleMs-(Date.now()-l));A>0?u(m,A):m()};function B(A){if(n===null)return;let W=A.data;!W||W.persona!=="artifact-preview-ready"||W.token!==n||A.source===e.contentWindow&&D()}function E(){let A=W=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>W()):setTimeout(W,0)};A(()=>A(()=>D()))}return u(g,o.delayMs),u(D,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",B):e.addEventListener("load",E),()=>{p=!0,d(),C(),y()}}function Yi(t,e){let{config:n}=e,o=e.registry??Un,r=e.bodyLayout,s=n.markdown?ai(n.markdown):null,i=li(n.sanitize),l=t,p=!1,c=ee=>{let oe=Nn()!==null;s&&!oe&&!p&&(p=!0,ii(()=>pe(l)));let V=s?s(ee):oo(ee);return s&&oe&&i?i(V):V},d=h("div","persona-artifact-preview-body"),u=null,y=null,g=null,m=()=>{g&&(g(),g=null),u=null,y=null},C=null,D=null,B=null,E=!1,A=()=>{C=null,D=null,B=null,E=!1},W=null,z=null,G=()=>{W=null,z=null},w=40,O=0,N=ee=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ee()):setTimeout(ee,0),L=ee=>ee.scrollHeight-ee.clientHeight-ee.scrollTop<=w,P=ee=>{if(!r)return;let oe=ee.scrollHeight-ee.clientHeight>1,V=ee.scrollHeight-ee.clientHeight-ee.scrollTop;ee.classList.toggle("persona-artifact-fade-top",r.fadeTop&&oe&&ee.scrollTop>1),ee.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&oe&&V>1)},I=ee=>{O||(O=N(()=>{O=0,ee.scrollTop=ee.scrollHeight,P(ee)}))},Y=(ee,oe,V,ae)=>{let ne=!!r,me=V.id+"|"+(ne?"w":"p");if(!C||B!==me||C.parentElement!==d){m(),G(),d.replaceChildren();let Te=h("pre",Ub+" persona-code-pre"),Se=h("code","persona-code");if(Te.appendChild(Se),ne){let Fe=h("div","persona-artifact-source-window");if(Fe.appendChild(Te),d.appendChild(Fe),!(r?.overflow==="clip")&&typeof Fe.addEventListener=="function"){let Ve=()=>Fe.scrollHeight-Fe.clientHeight>1;Fe.addEventListener("scroll",()=>{L(Fe)&&(E=!1),P(Fe)},{passive:!0}),Fe.addEventListener("wheel",Je=>{Ve()&&Je.deltaY<0&&(E=!0)},{passive:!0}),Fe.addEventListener("touchmove",()=>{Ve()&&(E=!0)},{passive:!0})}C=Fe}else d.appendChild(Te),C=Te;D=Se,B=me}let be=ne?C:null;be&&(be.classList.toggle("persona-artifact-source-window--fixed",ae),be.classList.toggle("persona-artifact-source-window--clip",ae&&r?.overflow==="clip"));let fe=be?L(be):!0;if(D.replaceChildren(Ku(ee,oe?.language,oe?.path)),be){let Te=V.status!=="complete";ae&&Te&&r?.followOutput&&!E&&fe?I(be):Te||(E=!1),P(be)}},de=ee=>{m(),A(),G(),d.replaceChildren();let oe=h("div",jb);oe.innerHTML=c(ee),d.appendChild(oe)},ue=ee=>{let oe=ee.id,V=n.features?.artifacts,ae=gr(ee,V,"status-body");if(W&&z===oe&&W.parentElement===d){let be=W.querySelector(".persona-artifact-status-view-text");be&&Wo(be,ae,V);return}m(),A(),d.replaceChildren();let ne=h("div","persona-artifact-status-view"),me=h("div","persona-artifact-status-view-text");Wo(me,ae,V),ne.appendChild(me),d.appendChild(ne),W=ne,z=oe},pe=ee=>{l=ee;let oe=e.resolveViewMode?.(ee)??r?.viewMode??"rendered",V=ee.artifactType==="markdown"?ee.file:void 0,ae=ee.status!=="complete";ae||ur(ee.id);let ne=ae?r?.streamingHeight:r?.completeHeight,me=!!r&&typeof ne=="number";if(r?.streamingView==="status"&&ae){ue(ee);return}if(V){let fe=Vi(ee.markdown??""),Te=us(V),Se=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ae&&oe==="rendered"&&Se&&(Te==="html"||Te==="svg")){let ke=ee.id+"\0"+fe;if(u&&y===ke&&u.parentElement===d)return;A(),G(),m(),d.replaceChildren();let Ve=n.features?.artifacts?.filePreview,Je=Ve?.iframeSandbox??"allow-scripts";!Ve?.dangerouslyAllowSameOrigin&&Je.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."),Je=Je.split(/\s+/).filter(kt=>kt&&kt!=="allow-same-origin").join(" "));let Ne=Vb(Ve?.loading),Pe=h("div","persona-artifact-frame"),Ye=h("iframe","persona-artifact-iframe");Ye.setAttribute("sandbox",Je),Ye.setAttribute("data-artifact-id",ee.id);let ln=null;Ne.enabled&&Ne.injectReadySignal?(ln=Gb(),Ye.srcdoc=fe+Qb(ln)):Ye.srcdoc=fe,Pe.appendChild(Ye),d.appendChild(Pe),Ne.enabled&&(g=Jb(Pe,Ye,ln,Ne,ee.id,n)),u=Pe,y=ke;return}if(m(),!ae&&Te==="markdown"&&oe==="rendered"){de(fe);return}Y(fe,{language:V.language,path:V.path},ee,me);return}if(ee.artifactType==="markdown"){if(oe==="source"){m(),Y(ee.markdown??"",void 0,ee,me);return}de(ee.markdown??"");return}m(),A(),G(),d.replaceChildren();let be=ee.component?o.get(ee.component):void 0;if(be){let Te={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Se=be(ee.props??{},Te);if(Se){d.appendChild(Se);return}}catch{}}d.appendChild(qb(ee))};return pe(t),{el:d,update(ee){pe(ee)}}}var og=require("idiomorph"),Zi=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;og.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 rg=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Kl={index:-1,draft:""};function sg(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 ig(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 ag(){return new Map}function lg(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function cg(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function dg(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}function ea(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Ln(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function uo(t,e){return Ln(t)-t.scrollTop<=e}function ta(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 na(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 pg(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function ug(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight);return{targetScrollTop:e,spacerHeight:n}}function gg(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var hs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Yb=["pre","code","a","script","style"],oa=t=>({type:t?.type??hs.type,placeholder:t?.placeholder??hs.placeholder,speed:t?.speed??hs.speed,duration:t?.duration??hs.duration,buffer:t?.buffer??hs.buffer}),Zb=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],mg=new Map;for(let t of Zb)mg.set(t.name,t);var hr=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:mg.get(t)??null,ra=(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},ey=(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},ty=(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},Gl=/\s/,ny=(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},oy=(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(Gl.test(s[l])){let p=l;for(;p<s.length&&Gl.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&&!Gl.test(s[c]);)p.appendChild(ey(o,s[c],e,n.value)),n.value+=1,c+=1;i.appendChild(p),l=c}r.replaceChild(i,t)},ry=(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(ty(o,p,e,n.value)),n.value+=1));r.replaceChild(i,t)},bs=(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??Yb).map(u=>u.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=i.nextNode();for(;p;)ny(p,s)||l.push(p),p=i.nextNode();let c={value:o?.startIndex??0},d=e==="char"?oy:ry;for(let u of l)d(u,n,c);return r.innerHTML},sa=(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},ys=(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},fg=new WeakMap,sy=(t,e)=>{if(!t.styles)return;let n=fg.get(e);if(n||(n=new Set,fg.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)},Ql=new WeakMap,iy=(t,e)=>{if(!t.onAttach)return;let n=Ql.get(e);if(n||(n=new Map,Ql.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},hg=t=>{let e=Ql.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},ia=(t,e)=>{sy(t,e),iy(t,e)};function Xl(t,e=Vt){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 vs=0,go=null;function Jl(t=document){if(vs++,vs===1){let n=t.body,r=(t.defaultView??window).scrollY||t.documentElement.scrollTop;go={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY: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,vs=Math.max(0,vs-1),vs===0&&go)){let n=t.body,o=t.defaultView??window;n.style.overflow=go.originalOverflow,n.style.position=go.originalPosition,n.style.top=go.originalTop,n.style.width=go.originalWidth,o.scrollTo(0,go.scrollY),go=null}}}var xs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Nt=t=>(t?.launcher?.mountMode??"floating")==="docked",Cs=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",mn=t=>{let e=t?.launcher?.dock;return{side:e?.side??xs.side,width:e?.width??xs.width,animate:e?.animate??xs.animate,reveal:e?.reveal??xs.reveal,maxHeight:e?.maxHeight??xs.maxHeight}};nt();var Sn={"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"};nt();St();nt();St();var ay="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",aa=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=ay,buttonSize:r,iconSize:s="28px"}=e,i=t?.launcher??{},l=r??i.closeButtonSize??"32px",p=h("div",o),c=i.closeButtonTooltipText??"Close chat",d=i.closeButtonShowTooltip??!0,u=i.closeButtonIconName??"x",y=i.closeButtonIconText??"\xD7",g=!!(i.closeButtonBorderWidth||i.closeButtonBorderColor),m=xe("button",{className:Fn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!i.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"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||Xt.actionIconColor,backgroundColor:i.closeButtonBackgroundColor||void 0,border:g?`${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=se(u,s,"currentColor",1);return C?(C.style.display="block",m.appendChild(C)):m.textContent=y,p.appendChild(m),_t({anchor:m,trigger:p,text:()=>m.getAttribute("aria-label")??c,enabled:d}),{button:m,wrapper:p}},ly="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",la=(t,e={})=>{let{wrapperClassName:n=ly,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??"",u=i.borderWidth??"",y=i.borderColor??"",g=i.borderRadius??"",m=i.paddingX??"",C=i.paddingY??"",D=i.tooltipText??"Clear chat",B=i.showTooltip??!0,E=h("div",n),A=!!(u||y),W=xe("button",{className:Fn("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"hover:persona-bg-gray-100",!A&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":D},style:{height:l,width:l,color:c||Xt.actionIconColor,backgroundColor:d||void 0,border:A?`${u||"0px"} solid ${y||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:m||void 0,paddingRight:m||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),z=se(p,r,"currentColor",1);return z&&(z.style.display="block",W.appendChild(z)),E.appendChild(W),_t({anchor:W,trigger:E,text:()=>W.getAttribute("aria-label")??D,enabled:B}),{button:W,wrapper:E}};var Xt={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))"},Bo=t=>{let{config:e,showClose:n=!0}=t,o=xe("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=xe("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 z=parseFloat(s)||24,G=se(p,z*.6,"currentColor",1);G?c.replaceChildren(G):c.textContent=e?.launcher?.agentIconText??"\u{1F4AC}"}else if(e?.launcher?.iconUrl){let z=h("img");z.src=e.launcher.iconUrl,z.alt="",z.className="persona-rounded-xl persona-object-cover",z.style.height=s,z.style.width=s,c.replaceChildren(z)}else c.textContent=e?.launcher?.agentIconText??"\u{1F4AC}";let d=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=xe("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Xt.titleColor}}),y=xe("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Xt.subtitleColor}});d.append(u,y),l?o.append(d):o.append(c,d);let g=r.clearChat??{},m=g.enabled??!0,C=g.placement??"inline",D=null,B=null;if(m){let G=la(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});D=G.button,B=G.wrapper,C==="top-right"&&(B.style.right="48px"),C==="inline"&&o.appendChild(B)}let E=i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":m&&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:A,wrapper:W}=aa(e,{showClose:n,wrapperClassName:E});return i!=="top-right"&&o.appendChild(W),{header:o,iconHolder:c,headerTitle:u,headerSubtitle:y,closeButton:A,closeButtonWrapper:W,clearChatButton:D,clearChatButtonWrapper:B}},ws=(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))};nt();St();var cy=t=>{let e=Bo({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 dy(t,e,n){if(e?.length)for(let o of e){let r=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(r.type="button",r.setAttribute("aria-label",o.ariaLabel??o.label??o.id),o.icon){let s=se(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=h("div","persona-relative");s.appendChild(r);let i=fr({items:o.menuItems,onSelect:l=>n?.(l),anchor:s,position:"bottom-left"});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 py=t=>{let{config:e,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=t,i=e?.launcher??{},l=h("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=Gu({label:i.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,c.style.color=Xt.titleColor,d=c.querySelector(".persona-combo-btn-label")??c;else{if(c=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),d=h("span","persona-text-base persona-font-semibold persona-truncate"),d.style.color=Xt.titleColor,d.textContent=i.title??"Chat Assistant",c.appendChild(d),dy(c,r?.trailingActions,r?.onAction??s),r?.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let A=r.onTitleClick;c.addEventListener("click",W=>{W.target.closest("button")||A()}),c.addEventListener("keydown",W=>{(W.key==="Enter"||W.key===" ")&&(W.preventDefault(),A())})}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 u=i.closeButtonSize??"32px",y=h("div",""),g=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=u,g.style.width=u,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=i.closeButtonColor||Xt.actionIconColor;let m=i.closeButtonIconName??"x",C=se(m,"28px","currentColor",1);C?g.appendChild(C):g.textContent="\xD7",o&&g.addEventListener("click",o),y.appendChild(g),l.appendChild(y);let D=h("div");D.style.display="none";let B=h("span");return B.style.display="none",{header:l,iconHolder:D,headerTitle:d,headerSubtitle:B,closeButton:g,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}},bg={default:cy,minimal:py},uy=t=>bg[t]??bg.default,ca=(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=h("div");l.style.display="none";let p=h("span"),c=h("span"),d=h("button");d.style.display="none";let u=h("div");return u.style.display="none",{header:i,iconHolder:l,headerTitle:p,headerSubtitle:c,closeButton:d,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=e?.layout??"default",s=uy(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};nt();nt();St();var da=t=>{let e=h("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-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;e.style.maxHeight=`${n*o}px`,e.style.overflowY="auto";let r=()=>{let i=parseFloat(e.style.maxHeight);return Number.isFinite(i)&&i>0?i:n*o},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let i=Math.min(e.scrollHeight,r());e.style.height=`${i}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},pa=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,u=e.size??"40px",y=e.backgroundColor,g=e.textColor,m=h("div","persona-send-button-wrapper"),C=xe("button",{className:Fn("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&&!y&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&y||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}}),D=null,B=null;if(n){let W=parseFloat(u)||24,z=g?.trim()||"currentColor";r?(D=se(r,W,z,2),D?C.appendChild(D):C.textContent=o):C.textContent=o,B=se(s,W,z,2)}else C.textContent=p;C.setAttribute("aria-label",i),m.appendChild(C),_t({anchor:C,trigger:m,text:()=>C.getAttribute("aria-label")??"",enabled:d});let E="send";return{button:C,wrapper:m,setMode:W=>{if(W===E)return;E=W;let z=W==="stop"?l:i;if(C.setAttribute("aria-label",z),n){if(D&&B){let G=W==="stop"?B:D;C.replaceChildren(G)}}else C.textContent=W==="stop"?c:p}}},ua=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,u=e.iconColor??t?.sendButton?.textColor,y=h("div","persona-send-button-wrapper"),g=xe("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:u||"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=se(l,c,u||"currentColor",1.5);C?g.appendChild(C):g.textContent="\u{1F3A4}",y.appendChild(g);let D=e.tooltipText??"Start voice recognition",B=e.showTooltip??!1;return _t({anchor:g,trigger:y,text:()=>g.getAttribute("aria-label")??D,enabled:B}),{button:g,wrapper:y}},ga=t=>{let e=t?.attachments??{};if(e.enabled!==!0)return null;let n=t?.sendButton?.size??"40px",o=h("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=h("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(e.allowedTypes??$n).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=h("div","persona-send-button-wrapper"),d=xe("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"}}),u=se(s,p,"currentColor",1.5);u?d.appendChild(u):d.textContent="\u{1F4CE}",d.addEventListener("click",g=>{g.preventDefault(),r.click()}),c.appendChild(d);let y=e.buttonTooltipText??"Attach file";return _t({anchor:d,trigger:c,text:()=>d.getAttribute("aria-label")??y}),{button:d,wrapper:c,input:r,previewsContainer:o}},fa=t=>{let e=t?.statusIndicator??{},n=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",o=h("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=h("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},ma=()=>xe("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ha=t=>{let{config:e}=t,n=xe("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=ma(),r=xe("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:i}=da(e);i();let l=pa(e),p=ua(e),c=ga(e),d=fa(e);c&&(c.previewsContainer.style.gap="8px",r.append(c.previewsContainer,c.input)),r.append(s);let u=xe("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),y=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&y.append(c.wrapper),p&&g.append(p.wrapper),g.append(l.wrapper),u.append(y,g),r.append(u),r.addEventListener("click",m=>{m.target!==l.button&&m.target!==l.wrapper&&m.target!==p?.button&&m.target!==p?.wrapper&&m.target!==c?.button&&m.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:u,leftActions:y,rightActions:g,setSendButtonMode:l.setMode}};nt();St();var yg=()=>{let t=xe("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=h("span","persona-pill-peek__icon"),n=se("message-square",16,"currentColor",1.5);n&&e.appendChild(n);let o=h("span","persona-pill-peek__text"),r=h("span","persona-pill-peek__caret"),s=se("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),t.append(e,o,r),{root:t,textNode:o}},vg=t=>{let{config:e}=t,n=xe("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ma(),r=fa(e);r.style.display="none";let{textarea:s,attachAutoResize:i}=da(e);s.style.maxHeight="100px",i();let l=pa(e),p=ua(e),c=ga(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let d=xe("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=h("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&u.append(c.wrapper);let y=h("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&y.append(p.wrapper),y.append(l.wrapper),d.addEventListener("click",m=>{m.target!==l.button&&m.target!==l.wrapper&&m.target!==p?.button&&m.target!==p?.wrapper&&m.target!==c?.button&&m.target!==c?.wrapper&&s.focus()}),c&&d.append(c.input),d.append(u,s,y),c&&n.append(c.previewsContainer),n.append(o,d,r);let g=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:g,leftActions:u,rightActions:y,setSendButtonMode:l.setMode}};var xg=t=>{let e=t?.launcher?.enabled??!0,n=Nt(t);if(Cs(t)){let d=t?.launcher?.composerBar??{},u=h("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=d.expandedSize??"anchored",u.style.zIndex=String(t?.launcher?.zIndex??Vt);let y=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");y.style.width="100%",u.appendChild(y);let g=h("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=d.expandedSize??"anchored",g.style.zIndex=String(t?.launcher?.zIndex??Vt),{wrapper:u,panel:y,pillRoot:g}}if(n){let d=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return d.appendChild(u),{wrapper:d,panel:u}}if(!e){let d=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),y=t?.launcher?.width??"100%";return d.style.width=y,u.style.width="100%",d.appendChild(u),{wrapper:d,panel:u}}let r=t?.launcher??{},s=r.position&&Sn[r.position]?Sn[r.position]:Sn["bottom-right"],i=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);i.style.zIndex=String(t?.launcher?.zIndex??Vt);let l=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=t?.launcher?.width??t?.launcherWidth??zn;return l.style.width=c,l.style.maxWidth=c,i.appendChild(l),{wrapper:i,panel:l}},gy=(t,e)=>{let n=h("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}=aa(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 W=la(t,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});i=W.button,l=W.wrapper,l.style.position="absolute",l.style.top="8px",l.style.right="32px",l.style.zIndex="10"}let p=xe("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=xe("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 d=xe("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=xe("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),y=xe("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:"var(--persona-intro-card-shadow, none)"}},d,u),g=h("div","persona-flex persona-flex-col persona-gap-3"),m=t?.layout?.contentMaxWidth;m&&(g.style.maxWidth=m,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(y.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(y,g);let D=xe("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"}}),B=vg({config:t}),{root:E,textNode:A}=yg();return n.append(p,r,c,D),l&&n.appendChild(l),{container:n,body:c,messagesWrapper:g,composerOverlay:D,suggestions:B.suggestions,textarea:B.textarea,sendButton:B.sendButton,sendButtonWrapper:B.sendButtonWrapper,micButton:B.micButton,micButtonWrapper:B.micButtonWrapper,composerForm:B.composerForm,statusText:B.statusText,introTitle:d,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:i,clearChatButtonWrapper:l,iconHolder:h("span"),headerTitle:h("span"),headerSubtitle:h("span"),header:p,footer:B.footer,attachmentButton:B.attachmentButton,attachmentButtonWrapper:B.attachmentButtonWrapper,attachmentInput:B.attachmentInput,attachmentPreviewsContainer:B.attachmentPreviewsContainer,actionsRow:B.actionsRow,leftActions:B.leftActions,rightActions:B.rightActions,setSendButtonMode:B.setSendButtonMode,peekBanner:E,peekTextNode:A}},Cg=(t,e=!0)=>{if(Cs(t))return gy(t,e);let n=xe("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?ca(t,o,{showClose:e}):Bo({config:t,showClose:e}),i=xe("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 l=xe("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=xe("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),c=xe("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Nt(t)?"none":"var(--persona-intro-card-shadow, none)"}},l,p),d=h("div","persona-flex persona-flex-col persona-gap-3"),u=t?.layout?.contentMaxWidth;u&&(d.style.maxWidth=u,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(c.style.display="none",i.classList.remove("persona-gap-6"),i.classList.add("persona-gap-3")),i.append(c,d);let g=ha({config:t}),m=t?.layout?.showFooter!==!1;r?ws(n,s,t):(s.header.style.display="none",ws(n,s,t)),n.append(i);let C=xe("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 m||(g.footer.style.display="none"),n.append(g.footer),n.append(C),{container:n,body:i,messagesWrapper:d,composerOverlay:C,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:l,introSubtitle:p,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:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};nt();St();var Yl=(t,e)=>{let n=h("button");n.type="button",n.innerHTML=`
205
205
  <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
206
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
207
207
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -209,14 +209,14 @@ _Details: ${n.message}_`:o}var ns=t=>({isError:!0,content:[{type:"text",text:t}]
209
209
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
210
210
  </span>
211
211
  <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 A=i.title??"Chat Assistant";p.textContent=A,p.setAttribute("title",A)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let A=i.subtitle??"Here to help you get answers fast";c.textContent=A,c.setAttribute("title",A)}let d=n.querySelector(".persona-flex-col");d&&(i.textHidden||l?d.style.display="none":d.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(i.agentIconHidden)u.style.display="none";else{let A=i.agentIconSize??"40px";if(u.style.height=A,u.style.width=A,i.agentIconBackgroundColor?(u.style.backgroundColor=i.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",i.agentIconName){let W=parseFloat(A)||24,z=se(i.agentIconName,W*.6,"var(--persona-text-inverse, #ffffff)",2);z?(u.appendChild(z),u.style.display=""):(u.textContent=i.agentIconText??"\u{1F4AC}",u.style.display="")}else i.iconUrl?u.style.display="none":(u.textContent=i.agentIconText??"\u{1F4AC}",u.style.display="")}let y=n.querySelector("[data-role='launcher-image']");if(y){let A=i.agentIconSize??"40px";y.style.height=A,y.style.width=A,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(y.src=i.iconUrl,y.style.display="block"):y.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let A=i.callToActionIconSize??"32px";g.style.height=A,g.style.width=A,i.callToActionIconBackgroundColor?(g.style.backgroundColor=i.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(g.style.color=i.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let W=0;if(i.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=i.callToActionIconPadding,W=(parseFloat(i.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),i.callToActionIconHidden)g.style.display="none";else if(g.style.display=l?"none":"",g.innerHTML="",i.callToActionIconName){let z=parseFloat(A)||24,G=Math.max(z-W,8),w=se(i.callToActionIconName,G,"currentColor",2);w?g.appendChild(w):g.textContent=i.callToActionIconText??"\u2197"}else g.textContent=i.callToActionIconText??"\u2197"}let m=i.position&&Sn[i.position]?Sn[i.position]:Sn["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",D="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?D:`${C} ${m}`,l||(n.style.zIndex=String(i.zIndex??qt));let B="1px solid 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=i.border??B,n.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.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=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}};var wg=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=xg(t),s=Cg(t,e),i={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,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:y=>(p.element.replaceWith(y.header),p.element=y.header,p.iconHolder=y.iconHolder,p.headerTitle=y.headerTitle,p.headerSubtitle=y.headerSubtitle,p.closeButton=y.closeButton,p.closeButtonWrapper=y.closeButtonWrapper,p.clearChatButton=y.clearChatButton,p.clearChatButtonWrapper=y.clearChatButtonWrapper,y),replaceComposer:y=>{c.footer.replaceWith(y),c.footer=y}}},Zl=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>Yl(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Yl(t,n);return{instance:r,element:r.element}};tt();Mt();var fy=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}},my=(t,e)=>{if(!t)return null;let n=fy(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},hy=(t,e)=>{let n=h("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},by=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},ec=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(":"))},tc=320,Tg=320,yy=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),vy=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),xy=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),Cy=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),wy=t=>{if(!t||t.length===0)return null;let e=xe("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=xe("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=h("span","persona-mention-chip-icon"),s=se(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(xe("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},Ay=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(cs(o.ref,{readonly:!0,render:e}))}return n},Ag="\uE000",Sg="\uE001",Sy=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=y=>`${Ag}${r}:${y}${Sg}`,i=e.map((y,g)=>y.kind==="text"?y.text:s(g)).join(""),l=n(i);if(!e.every((y,g)=>y.kind==="text"||l.includes(s(g)))){t.replaceChildren(Ay(e,o));return}t.innerHTML=l;let c=new RegExp(`${Ag}${r}:(\\d+)${Sg}`),d=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),u=[];for(let y=d.nextNode();y;y=d.nextNode())u.push(y);for(let y of u){let g=y;for(let m=c.exec(g.data);m;m=c.exec(g.data)){let C=e[Number(m[1])],D=g.splitText(m.index);D.data=D.data.slice(m[0].length),C?.kind==="mention"&&D.parentNode?.insertBefore(cs(C.ref,{readonly:!0,render:o}),D),g=D}}},My=(t,e,n)=>{if(t.length===0)return null;try{let o=h("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=h("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=`${tc}px`,c.style.maxHeight=`${Tg}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}),by(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}},Ty=t=>{if(t.length===0)return null;try{let e=h("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!ec(o.audio))return;let r=h("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${tc}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Ey=t=>{if(t.length===0)return null;try{let e=h("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!ec(o.video))return;let r=h("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${tc}px`,r.style.maxHeight=`${Tg}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}},ky=t=>{if(t.length===0)return null;try{let e=h("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!ec(o.data))return;let r=h("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}},As=()=>{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},Ly=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:As};if(e){let r=e(o);if(r!==null)return r}return As()},Py=(t,e)=>{let n=h("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=h("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},Mg=(t,e,n="div")=>{let o=h(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},Iy=(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-primary","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-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),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-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},Ry=(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 m=h("div");return m.style.display="none",m.id=`actions-${t.id}`,m.setAttribute("data-actions-for",t.id),m}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],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],y=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${d} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);y.id=`actions-${t.id}`,y.setAttribute("data-actions-for",t.id);let g=(m,C,D)=>{let B=Dt({icon:m,label:C,size:14,className:"persona-message-action-btn"});return B.setAttribute("data-action",D),B};return o&&y.appendChild(g("copy","Copy message","copy")),i&&y.appendChild(g("volume-2","Read aloud","read-aloud")),r&&y.appendChild(g("thumbs-up","Upvote","upvote")),s&&y.appendChild(g("thumbs-down","Downvote","downvote")),y},nc=(t,e,n,o,r,s)=>{let i=n??{},l=i.layout??"bubble",p=i.avatar,c=i.timestamp,d=p?.show??!1,u=c?.show??!1,y=p?.position??"left",g=c?.position??"below",m=Iy(t.role,l),C=h("div",m.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="var(--persona-primary, 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-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let D=yy(t),B=t.content?.trim()??"",A=D.length>0&&B===Ci,W=oa(s?.widgetConfig?.features?.streamAnimation),z=s?.widgetConfig?.features?.streamAnimation?.plugins,G=t.role==="assistant"&&W.type!=="none"?hr(W.type,z):null,w=t.role==="assistant"&&G?.isAnimating?.(t)===!0,O=t.role==="assistant"&&G!==null&&(!!t.streaming||w);O&&G?.bubbleClass&&C.classList.add(G.bubbleClass);let N=document.createElement("div");N.classList.add("persona-message-content"),t.streaming&&N.classList.add("persona-content-streaming"),O&&G&&(G.containerClass&&N.classList.add(G.containerClass),N.style.setProperty("--persona-stream-step",`${W.speed}ms`),N.style.setProperty("--persona-stream-duration",`${W.duration}ms`));let L=O?ra(t.content??"",W.buffer,G,t,!!t.streaming):t.content??"",P=()=>{let ne=e({text:L,message:t,streaming:!!t.streaming,raw:t.rawContent});return O&&G?.wrap==="char"?bs(ne,"char",t.id,{skipTags:G.skipTags}):O&&G?.wrap==="word"?bs(ne,"word",t.id,{skipTags:G.skipTags}):ne},I=null;if(A?(I=document.createElement("div"),I.innerHTML=P(),I.style.display="none",N.appendChild(I)):t.contentSegments?.length?Sy(N,t.contentSegments,ne=>e({text:ne,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):N.innerHTML=P(),O&&G?.useCaret&&!A&&B){let ne=sa(),me=N.querySelectorAll(".persona-stream-char, .persona-stream-word"),be=me[me.length-1];if(be?.parentNode)be.parentNode.insertBefore(ne,be.nextSibling);else{let fe=N.lastElementChild;fe?fe.appendChild(ne):N.appendChild(ne)}}if(u&&g==="inline"&&t.createdAt){let ne=Mg(t,c,"span");ne.classList.add("persona-timestamp-inline");let me=N.lastElementChild;me?me.appendChild(ne):N.appendChild(ne)}if(D.length>0){let ne=My(D,!A&&!!B,()=>{A&&I&&(I.style.display="")});ne?C.appendChild(ne):A&&I&&(I.style.display="")}let Y=vy(t);if(Y.length>0){let ne=Ty(Y);ne&&C.appendChild(ne)}let de=xy(t);if(de.length>0){let ne=Ey(de);ne&&C.appendChild(ne)}let ue=Cy(t);if(ue.length>0){let ne=ky(ue);ne&&C.appendChild(ne)}let pe=t.contentSegments?.length?null:wy(t.contextMentions);if(pe&&C.appendChild(pe),C.appendChild(N),u&&g==="below"&&t.createdAt){let ne=Mg(t,c);ne.classList.add("persona-mt-1"),C.appendChild(ne)}let ee=t.role==="assistant"?my(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let ne=!!(L&&L.trim()),me=W.placeholder==="skeleton",be=me&&W.buffer==="line"&&ne;if(ne)be&&C.appendChild(ys());else if(me)C.appendChild(ys());else{let fe=Ly("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);fe&&C.appendChild(fe)}}if(ee&&t.stopReason&&!t.streaming&&(B||(N.style.display="none"),C.appendChild(hy(t.stopReason,ee))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1&&o){let ne=Ry(t,o,r);C.appendChild(ne)}if(!d||t.role==="system")return C;let V=h("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),ae=Py(p,t.role);return y==="right"||y==="left"&&t.role==="user"?V.append(C,ae):V.append(ae,C),V};tt();Mt();var br=new Set,Wy=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Hy=(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
- `):""},Eg=(t,e)=>{let n=br.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=se(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")},oc=(t,e)=>{let n=t.reasoning,o=h("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&&br.has(t.id),l=n.status!=="complete",p=Hy(t,r.previewMaxLines??3),c=h("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=h("div","persona-flex persona-flex-col persona-text-left"),u=h("span","persona-text-xs persona-text-persona-primary"),y="Thinking...",g=e?.reasoning??{},m=String(n.startedAt??Date.now()),C=()=>{let de=h("span","");return de.setAttribute("data-tool-elapsed",m),de.textContent=bi(n),de},D=g.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:y,previewText:p,isActive:l,config:e??{},elapsed:bi(n),createElapsedElement:C});typeof D=="string"&&D.trim()?(u.textContent=D,d.appendChild(u)):D instanceof HTMLElement?d.appendChild(D):(u.textContent=y,d.appendChild(u));let B=h("span","persona-text-xs persona-text-persona-primary");B.textContent=vp(n),d.appendChild(B);let E=r.loadingAnimation??"none",A=g.activeTextTemplate,W=g.completeTextTemplate,z=l?A:W,G=D instanceof HTMLElement,w=(de,ue)=>{u.textContent="";let pe=yi(de,""),ee=0;for(let oe of pe){let V=oe.styles.length>0?(()=>{let ae=h("span",oe.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return u.appendChild(ae),ae})():u;if(oe.isDuration&&l)V.appendChild(C());else{let ae=oe.isDuration?bi(n):oe.text;ue?ee=co(V,ae,ee):V.appendChild(document.createTextNode(ae))}}};if(!G&&z)if(B.style.display="none",u.style.display="",l&&E!=="none"){let de=g.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),E==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`),w(z,!1)):(u.classList.add(`persona-tool-loading-${E}`),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`),E==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),w(z,!0))}else w(z,!1);else if(!G&&l&&E!=="none"){u.style.display="";let de=g.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),E==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`);else{u.classList.add(`persona-tool-loading-${E}`),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`),E==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let ue=u.textContent||y;u.textContent="",co(u,ue,0)}n.status==="complete"&&(u.style.display="none")}else G||(n.status==="complete"?u.style.display="none":u.style.display="");let O=null;if(s){O=h("div","persona-flex persona-items-center");let ue=se(i?"chevron-up":"chevron-down",16,"currentColor",2);ue?O.appendChild(ue):O.textContent=i?"Hide":"Show";let pe=h("div","persona-flex persona-items-center persona-ml-auto");pe.append(O),c.append(d,pe)}else c.append(d);let N=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(N.setAttribute("data-persona-collapsed-preview","reasoning"),N.style.display="none",N.style.whiteSpace="pre-wrap",!i&&l&&r.activePreview&&p){let de=e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:n,defaultPreview:p,isActive:l,config:e??{}});Wy(N,de)||(N.textContent=p),N.style.display=""}if(!i&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(c,N),o;let L=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");L.style.display=i?"":"none";let P=n.chunks.join(""),I=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return I.textContent=P||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),L.appendChild(I),(()=>{if(c.setAttribute("aria-expanded",i?"true":"false"),O){O.innerHTML="";let ue=se(i?"chevron-up":"chevron-down",16,"currentColor",2);ue?O.appendChild(ue):O.textContent=i?"Hide":"Show"}L.style.display=i?"":"none",N.style.display=i?"none":N.textContent||N.childNodes.length?"":"none"})(),o.append(c,N,L),o};tt();Mt();var yr=new Set,By=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Dy=(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(`
212
+ `,n.addEventListener("click",e);let o=s=>{let i=s.launcher??{},l=Nt(s),p=n.querySelector("[data-role='launcher-title']");if(p){let A=i.title??"Chat Assistant";p.textContent=A,p.setAttribute("title",A)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let A=i.subtitle??"Here to help you get answers fast";c.textContent=A,c.setAttribute("title",A)}let d=n.querySelector(".persona-flex-col");d&&(i.textHidden||l?d.style.display="none":d.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(i.agentIconHidden)u.style.display="none";else{let A=i.agentIconSize??"40px";if(u.style.height=A,u.style.width=A,i.agentIconBackgroundColor?(u.style.backgroundColor=i.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",i.agentIconName){let W=parseFloat(A)||24,z=se(i.agentIconName,W*.6,"var(--persona-text-inverse, #ffffff)",2);z?(u.appendChild(z),u.style.display=""):(u.textContent=i.agentIconText??"\u{1F4AC}",u.style.display="")}else i.iconUrl?u.style.display="none":(u.textContent=i.agentIconText??"\u{1F4AC}",u.style.display="")}let y=n.querySelector("[data-role='launcher-image']");if(y){let A=i.agentIconSize??"40px";y.style.height=A,y.style.width=A,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(y.src=i.iconUrl,y.style.display="block"):y.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let A=i.callToActionIconSize??"32px";g.style.height=A,g.style.width=A,i.callToActionIconBackgroundColor?(g.style.backgroundColor=i.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(g.style.color=i.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let W=0;if(i.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=i.callToActionIconPadding,W=(parseFloat(i.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),i.callToActionIconHidden)g.style.display="none";else if(g.style.display=l?"none":"",g.innerHTML="",i.callToActionIconName){let z=parseFloat(A)||24,G=Math.max(z-W,8),w=se(i.callToActionIconName,G,"currentColor",2);w?g.appendChild(w):g.textContent=i.callToActionIconText??"\u2197"}else g.textContent=i.callToActionIconText??"\u2197"}let m=i.position&&Sn[i.position]?Sn[i.position]:Sn["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",D="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?D:`${C} ${m}`,l||(n.style.zIndex=String(i.zIndex??Vt));let B="1px solid 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=i.border??B,n.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.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=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}};var wg=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=xg(t),s=Cg(t,e),i={wrapper:n,panel:o,pillRoot:r},l={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,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:y=>(p.element.replaceWith(y.header),p.element=y.header,p.iconHolder=y.iconHolder,p.headerTitle=y.headerTitle,p.headerSubtitle=y.headerSubtitle,p.closeButton=y.closeButton,p.closeButtonWrapper=y.closeButtonWrapper,p.clearChatButton=y.clearChatButton,p.clearChatButtonWrapper=y.clearChatButtonWrapper,y),replaceComposer:y=>{c.footer.replaceWith(y),c.footer=y}}},Zl=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>Yl(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Yl(t,n);return{instance:r,element:r.element}};nt();St();var fy=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}},my=(t,e)=>{if(!t)return null;let n=fy(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},hy=(t,e)=>{let n=h("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},by=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},ec=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(":"))},tc=320,Tg=320,yy=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),vy=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),xy=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),Cy=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),wy=t=>{if(!t||t.length===0)return null;let e=xe("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=xe("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=h("span","persona-mention-chip-icon"),s=se(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(xe("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},Ay=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(cs(o.ref,{readonly:!0,render:e}))}return n},Ag="\uE000",Sg="\uE001",Sy=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=y=>`${Ag}${r}:${y}${Sg}`,i=e.map((y,g)=>y.kind==="text"?y.text:s(g)).join(""),l=n(i);if(!e.every((y,g)=>y.kind==="text"||l.includes(s(g)))){t.replaceChildren(Ay(e,o));return}t.innerHTML=l;let c=new RegExp(`${Ag}${r}:(\\d+)${Sg}`),d=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),u=[];for(let y=d.nextNode();y;y=d.nextNode())u.push(y);for(let y of u){let g=y;for(let m=c.exec(g.data);m;m=c.exec(g.data)){let C=e[Number(m[1])],D=g.splitText(m.index);D.data=D.data.slice(m[0].length),C?.kind==="mention"&&D.parentNode?.insertBefore(cs(C.ref,{readonly:!0,render:o}),D),g=D}}},My=(t,e,n)=>{if(t.length===0)return null;try{let o=h("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=h("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=`${tc}px`,c.style.maxHeight=`${Tg}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}),by(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}},Ty=t=>{if(t.length===0)return null;try{let e=h("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(o=>{if(!ec(o.audio))return;let r=h("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${tc}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Ey=t=>{if(t.length===0)return null;try{let e=h("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(o=>{if(!ec(o.video))return;let r=h("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${tc}px`,r.style.maxHeight=`${Tg}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}},ky=t=>{if(t.length===0)return null;try{let e=h("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(o=>{if(!ec(o.data))return;let r=h("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}},As=()=>{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},Ly=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:As};if(e){let r=e(o);if(r!==null)return r}return As()},Py=(t,e)=>{let n=h("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=h("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},Mg=(t,e,n="div")=>{let o=h(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},Iy=(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-primary","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-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),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-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},Ry=(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 m=h("div");return m.style.display="none",m.id=`actions-${t.id}`,m.setAttribute("data-actions-for",t.id),m}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],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],y=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${d} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);y.id=`actions-${t.id}`,y.setAttribute("data-actions-for",t.id);let g=(m,C,D)=>{let B=Bt({icon:m,label:C,size:14,className:"persona-message-action-btn"});return B.setAttribute("data-action",D),B};return o&&y.appendChild(g("copy","Copy message","copy")),i&&y.appendChild(g("volume-2","Read aloud","read-aloud")),r&&y.appendChild(g("thumbs-up","Upvote","upvote")),s&&y.appendChild(g("thumbs-down","Downvote","downvote")),y},nc=(t,e,n,o,r,s)=>{let i=n??{},l=i.layout??"bubble",p=i.avatar,c=i.timestamp,d=p?.show??!1,u=c?.show??!1,y=p?.position??"left",g=c?.position??"below",m=Iy(t.role,l),C=h("div",m.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="var(--persona-primary, 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-surface))",C.style.color="var(--persona-message-assistant-text, var(--persona-text))");let D=yy(t),B=t.content?.trim()??"",A=D.length>0&&B===Ci,W=oa(s?.widgetConfig?.features?.streamAnimation),z=s?.widgetConfig?.features?.streamAnimation?.plugins,G=t.role==="assistant"&&W.type!=="none"?hr(W.type,z):null,w=t.role==="assistant"&&G?.isAnimating?.(t)===!0,O=t.role==="assistant"&&G!==null&&(!!t.streaming||w);O&&G?.bubbleClass&&C.classList.add(G.bubbleClass);let N=document.createElement("div");N.classList.add("persona-message-content"),t.streaming&&N.classList.add("persona-content-streaming"),O&&G&&(G.containerClass&&N.classList.add(G.containerClass),N.style.setProperty("--persona-stream-step",`${W.speed}ms`),N.style.setProperty("--persona-stream-duration",`${W.duration}ms`));let L=O?ra(t.content??"",W.buffer,G,t,!!t.streaming):t.content??"",P=()=>{let ne=e({text:L,message:t,streaming:!!t.streaming,raw:t.rawContent});return O&&G?.wrap==="char"?bs(ne,"char",t.id,{skipTags:G.skipTags}):O&&G?.wrap==="word"?bs(ne,"word",t.id,{skipTags:G.skipTags}):ne},I=null;if(A?(I=document.createElement("div"),I.innerHTML=P(),I.style.display="none",N.appendChild(I)):t.contentSegments?.length?Sy(N,t.contentSegments,ne=>e({text:ne,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):N.innerHTML=P(),O&&G?.useCaret&&!A&&B){let ne=sa(),me=N.querySelectorAll(".persona-stream-char, .persona-stream-word"),be=me[me.length-1];if(be?.parentNode)be.parentNode.insertBefore(ne,be.nextSibling);else{let fe=N.lastElementChild;fe?fe.appendChild(ne):N.appendChild(ne)}}if(u&&g==="inline"&&t.createdAt){let ne=Mg(t,c,"span");ne.classList.add("persona-timestamp-inline");let me=N.lastElementChild;me?me.appendChild(ne):N.appendChild(ne)}if(D.length>0){let ne=My(D,!A&&!!B,()=>{A&&I&&(I.style.display="")});ne?C.appendChild(ne):A&&I&&(I.style.display="")}let Y=vy(t);if(Y.length>0){let ne=Ty(Y);ne&&C.appendChild(ne)}let de=xy(t);if(de.length>0){let ne=Ey(de);ne&&C.appendChild(ne)}let ue=Cy(t);if(ue.length>0){let ne=ky(ue);ne&&C.appendChild(ne)}let pe=t.contentSegments?.length?null:wy(t.contextMentions);if(pe&&C.appendChild(pe),C.appendChild(N),u&&g==="below"&&t.createdAt){let ne=Mg(t,c);ne.classList.add("persona-mt-1"),C.appendChild(ne)}let ee=t.role==="assistant"?my(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let ne=!!(L&&L.trim()),me=W.placeholder==="skeleton",be=me&&W.buffer==="line"&&ne;if(ne)be&&C.appendChild(ys());else if(me)C.appendChild(ys());else{let fe=Ly("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);fe&&C.appendChild(fe)}}if(ee&&t.stopReason&&!t.streaming&&(B||(N.style.display="none"),C.appendChild(hy(t.stopReason,ee))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1&&o){let ne=Ry(t,o,r);C.appendChild(ne)}if(!d||t.role==="system")return C;let V=h("div",`persona-message-with-avatar persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),ae=Py(p,t.role);return y==="right"||y==="left"&&t.role==="user"?V.append(C,ae):V.append(ae,C),V};nt();St();var br=new Set,Wy=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Hy=(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
+ `):""},Eg=(t,e)=>{let n=br.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=se(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")},oc=(t,e)=>{let n=t.reasoning,o=h("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&&br.has(t.id),l=n.status!=="complete",p=Hy(t,r.previewMaxLines??3),c=h("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=h("div","persona-flex persona-flex-col persona-text-left"),u=h("span","persona-text-xs persona-text-persona-primary"),y="Thinking...",g=e?.reasoning??{},m=String(n.startedAt??Date.now()),C=()=>{let de=h("span","");return de.setAttribute("data-tool-elapsed",m),de.textContent=bi(n),de},D=g.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:y,previewText:p,isActive:l,config:e??{},elapsed:bi(n),createElapsedElement:C});typeof D=="string"&&D.trim()?(u.textContent=D,d.appendChild(u)):D instanceof HTMLElement?d.appendChild(D):(u.textContent=y,d.appendChild(u));let B=h("span","persona-text-xs persona-text-persona-primary");B.textContent=vp(n),d.appendChild(B);let E=r.loadingAnimation??"none",A=g.activeTextTemplate,W=g.completeTextTemplate,z=l?A:W,G=D instanceof HTMLElement,w=(de,ue)=>{u.textContent="";let pe=yi(de,""),ee=0;for(let oe of pe){let V=oe.styles.length>0?(()=>{let ae=h("span",oe.styles.map(ne=>`persona-tool-text-${ne}`).join(" "));return u.appendChild(ae),ae})():u;if(oe.isDuration&&l)V.appendChild(C());else{let ae=oe.isDuration?bi(n):oe.text;ue?ee=co(V,ae,ee):V.appendChild(document.createTextNode(ae))}}};if(!G&&z)if(B.style.display="none",u.style.display="",l&&E!=="none"){let de=g.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),E==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`),w(z,!1)):(u.classList.add(`persona-tool-loading-${E}`),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`),E==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),w(z,!0))}else w(z,!1);else if(!G&&l&&E!=="none"){u.style.display="";let de=g.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),E==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`);else{u.classList.add(`persona-tool-loading-${E}`),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`),E==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let ue=u.textContent||y;u.textContent="",co(u,ue,0)}n.status==="complete"&&(u.style.display="none")}else G||(n.status==="complete"?u.style.display="none":u.style.display="");let O=null;if(s){O=h("div","persona-flex persona-items-center");let ue=se(i?"chevron-up":"chevron-down",16,"currentColor",2);ue?O.appendChild(ue):O.textContent=i?"Hide":"Show";let pe=h("div","persona-flex persona-items-center persona-ml-auto");pe.append(O),c.append(d,pe)}else c.append(d);let N=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(N.setAttribute("data-persona-collapsed-preview","reasoning"),N.style.display="none",N.style.whiteSpace="pre-wrap",!i&&l&&r.activePreview&&p){let de=e?.reasoning?.renderCollapsedPreview?.({message:t,reasoning:n,defaultPreview:p,isActive:l,config:e??{}});Wy(N,de)||(N.textContent=p),N.style.display=""}if(!i&&l&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(c,N),o;let L=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");L.style.display=i?"":"none";let P=n.chunks.join(""),I=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return I.textContent=P||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),L.appendChild(I),(()=>{if(c.setAttribute("aria-expanded",i?"true":"false"),O){O.innerHTML="";let ue=se(i?"chevron-up":"chevron-down",16,"currentColor",2);ue?O.appendChild(ue):O.textContent=i?"Hide":"Show"}L.style.display=i?"":"none",N.style.display=i?"none":N.textContent||N.childNodes.length?"":"none"})(),o.append(c,N,L),o};nt();St();var yr=new Set,By=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Dy=(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
214
  `);let r=ao(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
215
- `):""},rc=(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)"},Ny=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=Dy(t,o?.previewMaxLines??3),i=n?xp(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=fl(n,p.activeTextTemplate,c):!l&&p.completeTextTemplate&&(c=fl(n,p.completeTextTemplate,c)),{summary:c,previewText:s,isActive:l}},kg=(t,e,n)=>{let o=yr.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)",u=se(o?"chevron-up":"chevron-down",16,d,2);u?c.appendChild(u):c.textContent=o?"Hide":"Show"}i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},sc=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=h("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&&yr.has(t.id),{summary:p,previewText:c,isActive:d}=Ny(t,e),u=h("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");u.type="button",i&&(u.setAttribute("aria-expanded",l?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let y=h("div","persona-flex persona-flex-col persona-text-left"),g=h("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let m=String(n.startedAt??Date.now()),C=()=>{let P=h("span","");return P.setAttribute("data-tool-elapsed",m),P.textContent=Xr(n),P},D=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:p,previewText:c,collapsedMode:s.collapsedMode??"tool-call",isActive:d,config:e??{},elapsed:Xr(n),createElapsedElement:C});typeof D=="string"&&D.trim()?(g.textContent=D,y.appendChild(g)):D instanceof HTMLElement?y.appendChild(D):(g.textContent=p,y.appendChild(g));let B=s.loadingAnimation??"none",E=o.activeTextTemplate,A=o.completeTextTemplate,W=d?E:A,z=D instanceof HTMLElement,G=(P,I)=>{g.textContent="";let Y=n.name?.trim()||"tool",de=yi(P,Y),ue=0;for(let pe of de){let ee=pe.styles.length>0?(()=>{let oe=h("span",pe.styles.map(V=>`persona-tool-text-${V}`).join(" "));return g.appendChild(oe),oe})():g;if(pe.isDuration&&d)ee.appendChild(C());else{let oe=pe.isDuration?Xr(n):pe.text;I?ue=co(ee,oe,ue):ee.appendChild(document.createTextNode(oe))}}};if(!z)if(d&&B!=="none"){let P=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),B==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${P}ms`),W&&G(W,!1);else if(g.classList.add(`persona-tool-loading-${B}`),g.style.setProperty("--persona-tool-anim-duration",`${P}ms`),B==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),W)G(W,!0);else{let I=g.textContent||p;g.textContent="",co(g,I,0)}}else W&&G(W,!1);let w=null;if(i){w=h("div","persona-flex persona-items-center");let P=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",I=se(l?"chevron-up":"chevron-down",16,P,2);I?w.appendChild(I):w.textContent=l?"Hide":"Show";let Y=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Y.append(w),u.append(y,Y)}else u.append(y);let O=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(O.setAttribute("data-persona-collapsed-preview","tool"),O.style.display="none",O.style.whiteSpace="pre-wrap",!l&&d&&s.activePreview&&c){let P=o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:c,isActive:d,config:e??{}});By(O,P)||(O.textContent=c),O.style.display=""}if(!l&&d&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!i)return r.append(u,O),r;let N=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(N.style.display=l?"":"none",o.contentBackgroundColor&&(N.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(N.style.color=o.contentTextColor),o.contentPaddingX&&(N.style.paddingLeft=o.contentPaddingX,N.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(N.style.paddingTop=o.contentPaddingY,N.style.paddingBottom=o.contentPaddingY),n.name){let P=h("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,N.appendChild(P)}if(n.args!==void 0){let P=h("div","persona-space-y-1"),I=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(I.style.color=o.labelTextColor),I.textContent="Arguments";let Y=h("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");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",rc(Y,o),Y.textContent=ao(n.args),P.append(I,Y),N.appendChild(P)}if(n.chunks&&n.chunks.length){let P=h("div","persona-space-y-1"),I=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(I.style.color=o.labelTextColor),I.textContent="Activity";let Y=h("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");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",rc(Y,o),Y.textContent=n.chunks.join(""),P.append(I,Y),N.appendChild(P)}if(n.status==="complete"&&n.result!==void 0){let P=h("div","persona-space-y-1"),I=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(I.style.color=o.labelTextColor),I.textContent="Result";let Y=h("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");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",rc(Y,o),Y.textContent=ao(n.result),P.append(I,Y),N.appendChild(P)}if(n.status==="complete"&&typeof n.duration=="number"){let P=h("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(P.style.color=o.contentTextColor),P.textContent=`Duration: ${n.duration}ms`,N.appendChild(P)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),w){w.innerHTML="";let P=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",I=se(l?"chevron-up":"chevron-down",16,P,2);I?w.appendChild(I):w.textContent=l?"Hide":"Show"}N.style.display=l?"":"none",O.style.display=l?"none":O.textContent||O.childNodes.length?"":"none"})(),r.append(u,O,N),r};tt();Mt();var Do=new Map,ba=t=>{let n=(t.startsWith(On)?t.slice(On.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)},Lg=t=>t?.approval!==!1?t?.approval:void 0,Pg=(t,e)=>{let n=Lg(e)?.detailsDisplay??"collapsed";return Do.get(t)??n==="expanded"},Ig=(t,e,n)=>{let o=Lg(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=se(e?"chevron-up":"chevron-down",14,"currentColor",2);i&&s.appendChild(i)}},Rg=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=Pg(t,n);Ig(o,s,n),r.style.display=s?"":"none"};var ya=(t,e)=>{let n=t.approval,o=e?.approval!==!1?e?.approval:void 0,r=n?.status==="pending",s=h("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=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=h("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=se(p,20,c,2);d&&l.appendChild(d);let u=h("div","persona-flex-1 persona-min-w-0"),y=h("div","persona-flex persona-items-center persona-gap-2"),g=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(g.style.color=o.titleColor),g.textContent=o?.title??"Approval Required",y.appendChild(g),!r){let w=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");w.setAttribute("data-approval-status",n.status),n.status==="approved"?(w.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",w.style.color="var(--persona-palette-colors-success-700, #15803d)",w.textContent="Approved"):n.status==="denied"?(w.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",w.style.color="var(--persona-palette-colors-error-700, #b91c1c)",w.textContent="Denied"):n.status==="timeout"&&(w.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",w.style.color="var(--persona-palette-colors-warning-700, #b45309)",w.textContent="Timeout"),y.appendChild(w)}u.appendChild(y);let C=n.toolType==="webmcp"||n.toolName.startsWith(On)?Vr(n.toolName):void 0,D=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),B=!n.toolName,E=D||(B?n.description:`The assistant wants to use \u201C${C??ba(n.toolName)}\u201D.`),A=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(A.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(A.style.color=o.descriptionColor),A.textContent=E,u.appendChild(A),n.reason){let w=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");w.setAttribute("data-approval-reason","true"),o?.reasonColor?w.style.color=o.reasonColor:o?.descriptionColor&&(w.style.color=o.descriptionColor);let O=h("span","persona-font-medium");O.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,w.appendChild(O),w.appendChild(document.createTextNode(n.reason)),u.appendChild(w)}let W=o?.detailsDisplay??"collapsed",z=!!n.description&&!B,G=z||!!n.parameters;if(W!=="hidden"&&G){let w=Pg(t.id,e),O=h("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");O.type="button",O.setAttribute("data-expand-header","true"),O.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(O.style.color=o.descriptionColor);let N=h("span");N.setAttribute("data-approval-details-label","true");let L=h("span","persona-inline-flex persona-items-center");L.setAttribute("data-approval-details-chevron","true"),O.append(N,L),Ig(O,w,e),u.appendChild(O);let P=h("div");if(P.setAttribute("data-approval-details","true"),P.style.display=w?"":"none",z){let I=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(I.style.color=o.descriptionColor),I.textContent=n.description,P.appendChild(I)}if(n.parameters){let I=h("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&&(I.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(I.style.color=o.parameterTextColor),I.style.fontSize="0.75rem",I.style.lineHeight="1rem",I.textContent=ao(n.parameters),P.appendChild(I)}u.appendChild(P)}if(r){let w=h("div","persona-flex persona-gap-2 persona-mt-2");w.setAttribute("data-approval-buttons","true");let O=h("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");O.type="button",O.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",O.style.color=o?.approveButtonTextColor??"#ffffff",O.setAttribute("data-approval-action","approve");let N=se("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);N&&(N.style.marginRight="4px",O.appendChild(N));let L=document.createTextNode(o?.approveLabel??"Approve");O.appendChild(L);let P=h("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 I=se("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);I&&(I.style.marginRight="4px",P.appendChild(I));let Y=document.createTextNode(o?.denyLabel??"Deny");P.appendChild(Y),w.append(O,P),u.appendChild(w)}return i.append(l,u),s.appendChild(i),s};tt();Mt();El();var Oy=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Wg=(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))},No=(t,e)=>{Wg(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)},Fy=t=>t?.approval!==!1?t?.approval:void 0,_y=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return Do.get(t)??n==="expanded"},ic=t=>{let e=h("span","persona-approval-kbd");return e.textContent=t,e},$y=(t,e)=>{let n=h("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(On)?Vr(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??ba(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},zy=t=>{let e=h("div","persona-approval-resolved"),n=se("ban",15,"currentColor",2);n&&e.appendChild(n);let o=h("span","persona-approval-resolved-name");return o.textContent=t.toolName?ba(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},Uy=(t,e,n,o,r,s,i)=>{let l=h("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",u=c||d,y=u&&_y(e.id,o),g=o?.showDetailsLabel??"Show details",m=o?.hideDetailsLabel??"Hide details",C=h("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",y?"true":"false"),C.setAttribute("aria-label",y?m:g)):C.setAttribute("data-static","true");let D=h("span","persona-approval-logo"),B=se("shield-check",16,"currentColor",2);B&&D.appendChild(B),C.appendChild(D);let E=$y(n,o);if(u){let O=h("span","persona-approval-toggle");O.setAttribute("aria-hidden","true");let N=se("chevron-down",14,"currentColor",2);N&&O.appendChild(N),E.append(" "),E.appendChild(O)}C.appendChild(E),l.appendChild(C);let A=h("div","persona-approval-body");if(u){let O=h("div","persona-approval-details");if(O.setAttribute("data-role","params"),O.hidden=!y,c){let N=h("p","persona-approval-desc");o?.descriptionColor&&(N.style.color=o.descriptionColor),N.textContent=n.description,O.appendChild(N)}if(d){let N=h("pre","persona-approval-params");o?.parameterBackgroundColor&&(N.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(N.style.color=o.parameterTextColor),N.textContent=ao(n.parameters),O.appendChild(N)}A.appendChild(O)}if(n.reason){let O=h("p","persona-approval-reason");o?.reasonColor?O.style.color=o.reasonColor:o?.descriptionColor&&(O.style.color=o.descriptionColor);let N=h("span","persona-approval-reason-label");N.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,O.append(N,document.createTextNode(n.reason)),A.appendChild(O)}let W=h("div","persona-approval-actions"),z=null,G=O=>{o?.approveButtonColor&&(O.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(O.style.color=o.approveButtonTextColor)},w=h("button","persona-approval-deny");if(w.type="button",w.setAttribute("data-action","deny"),o?.denyButtonColor&&(w.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(w.style.color=o.denyButtonTextColor),w.append(o?.denyLabel??"Deny"),i){let O=h("div","persona-approval-split"),N=h("button","persona-approval-primary");N.type="button",N.setAttribute("data-action","always"),G(N),N.append(o?.approveLabel??"Always allow",ic("\u23CE"));let L=h("button","persona-approval-caret");L.type="button",L.setAttribute("data-action","toggle-menu"),L.setAttribute("aria-label","More options"),G(L);let P=se("chevron-down",15,"currentColor",2);P&&L.appendChild(P),O.append(N,L),W.append(O,w),w.append(ic("Esc"));let I=h("div","persona-approval-menu"),Y=h("button","persona-approval-menu-item");Y.type="button",Y.append("Allow once",ic("\u2318\u23CE")),I.appendChild(Y),z=Hi({anchor:O,content:I,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,z),Y.addEventListener("click",()=>{No(t,e.id),r()})}else{let O=h("button","persona-approval-primary persona-approval-primary--solo");O.type="button",O.setAttribute("data-action","allow"),G(O),O.append(o?.approveLabel??"Allow"),W.append(O,w)}return A.appendChild(W),l.appendChild(A),l.addEventListener("click",O=>{let N=O.target instanceof Element?O.target.closest("[data-action]"):null;if(!N)return;let L=N.getAttribute("data-action");if(L==="toggle-params"){let P=l.querySelector('[data-role="params"]');if(P){let I=P.hidden;P.hidden=!I,C.setAttribute("aria-expanded",I?"true":"false"),C.setAttribute("aria-label",I?m:g),Do.set(e.id,I)}return}if(L==="toggle-menu"){z?.toggle();return}if(L==="always"){No(t,e.id),r({remember:!0});return}if(L==="allow"){No(t,e.id),r();return}if(L==="deny"){No(t,e.id),s();return}}),l},Hg=()=>{let t=Oy();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=Fy(i);if(l.status!=="pending"){if(No(t,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return zy(l)}Wg(t,o.id);let c=p?.enableAlwaysAllow===!0,d=Uy(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 u=y=>{nu(y)||o.id===t.latestPendingApprovalId&&(y.key!=="Escape"&&y.key!=="Enter"||(y.preventDefault(),y.stopImmediatePropagation(),No(t,o.id),y.key==="Escape"?s():y.metaKey||y.ctrlKey?r():r({remember:!0})))};t.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return d}},teardown:()=>{for(let o of[...t.keyHandlers.keys(),...t.popovers.keys()])No(t,o);t.latestPendingApprovalId=null}}};tt();var Bg=t=>{let e=[],n=null;return{buttons:e,render:(r,s,i,l,p,c)=>{t.innerHTML="",e.length=0;let d=c?.agentPushed===!0;if(d||(n=null),!r||!r.length||!d&&(l??(s?s.getMessages():[])).some(D=>D.role==="user"))return;let u=document.createDocumentFragment(),y=s?s.isStreaming():!1,g=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(r.forEach(m=>{let C=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=m,C.disabled=y,p?.fontFamily&&(C.style.fontFamily=g(p.fontFamily)),p?.fontWeight&&(C.style.fontWeight=p.fontWeight),p?.paddingX&&(C.style.paddingLeft=p.paddingX,C.style.paddingRight=p.paddingX),p?.paddingY&&(C.style.paddingTop=p.paddingY,C.style.paddingBottom=p.paddingY),C.addEventListener("click",()=>{!s||s.isStreaming()||(i.value="",d&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:m},bubbles:!0,composed:!0})),s.sendMessage(m))}),u.appendChild(C),e.push(C)}),t.appendChild(u),d){let m=JSON.stringify(r);m!==n&&(n=m,t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var Ss=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 Ms=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 jy=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),qy=new Set(["step_start","execution_start"]),Vy=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Ky=new Set(["step_complete","agent_turn_complete"]),Gy=new Set(["flow_complete","agent_complete"]),Dg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Og=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),an=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Oo=(t,e)=>{let n=t[e];return Og(n)?n:void 0};function ac(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function va(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function Qy(t,e){return typeof e.type=="string"?e.type:t}function Xy(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 Jy(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 Ng(t){let e=Oo(t,"result"),n=[Oo(t,"tokens"),Oo(t,"totalTokens"),e?Oo(e,"tokens"):void 0,Oo(t,"usage"),e?Oo(e,"usage"):void 0];for(let o of n){if(!o)continue;let r=an(o.output)??an(o.outputTokens)??an(o.completionTokens);if(r!==void 0)return r}return an(t.outputTokens)??an(t.completionTokens)??(e?an(e.outputTokens)??an(e.completionTokens):void 0)}function Yy(t){let e=Oo(t,"result");return an(t.executionTime)??an(t.executionTimeMs)??an(t.execution_time)??an(t.duration)??(e?an(e.executionTime)??an(e.executionTimeMs):void 0)}function Zy(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Ts=class{constructor(e=Zy){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:va(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(!Og(n)){Dg.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Qy(e,n),r=this.now();if(jy.has(o)){this.startRun(r);return}if(qy.has(o)){this.run||this.startRun(r);return}if(Vy.has(o)){if(!Jy(o,n))return;let s=Xy(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+ac(i.visibleCharCount),p=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:va(l,p),outputTokens:l,durationMs:p,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Ky.has(o)){if(!this.run)return;let s=this.run,i=Ng(n);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+ac(s.visibleCharCount),c=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:va(p,c),outputTokens:p,durationMs:c,source:l?"usage":"estimate"};return}if(Gy.has(o)){if(!this.run)return;let s=this.run,i=Ng(n),l=i??s.exactOutputTokens+ac(s.visibleCharCount),p=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",c=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:va(l,c),outputTokens:l,durationMs:c,source:p},this.run=null;return}if(Dg.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:Yy(n)??o-e.startedAt}};tt();Mt();function vr(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}var ev={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)"}},tv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},nv=["flowName","stepName","reasoningText","text","name","tool","toolName"],ov=100;function rv(t,e){let n={...ev,...e};if(n[t])return n[t];for(let o of Object.keys(n))if(o.endsWith("_")&&t.startsWith(o))return n[o];return tv}function sv(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function iv(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 av(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 lv(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 cv(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 dv(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function pv(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 uv(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=h("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=h("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 lc(t,e,n,o,r,s,i,l){let p=r.has(t.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");vr(c,o.classNames?.eventRow);let d=i.find(y=>y.renderEventStreamRow);if(d?.renderEventStreamRow&&l){let y=d.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(t.id)});if(y)return c.appendChild(y),c}return c.appendChild(u()),c;function u(){let y=h("div",""),g=h("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");g.setAttribute("data-event-id",t.id);let m=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=se(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&m.appendChild(C);let D=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),B=o.timestampFormat??"relative";D.textContent=B==="relative"?sv(t.timestamp,n):iv(t.timestamp);let E=null;o.showSequenceNumbers!==!1&&(E=h("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 A=rv(t.type,o.badgeColors),W=h("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");W.style.backgroundColor=A.bg,W.style.color=A.text,W.style.borderColor=A.text+"50",W.textContent=t.type;let z=o.descriptionFields??nv,G=av(t.payload,z),w=null;G&&(w=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=G);let O=h("div","persona-flex-1 persona-min-w-0"),N=h("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"),L=se("clipboard","12px","currentColor",1.5);return L&&N.appendChild(L),N.addEventListener("click",async P=>{P.stopPropagation(),await lv(cv(t)),N.innerHTML="";let I=se("check","12px","currentColor",1.5);I&&N.appendChild(I),setTimeout(()=>{N.innerHTML="";let Y=se("clipboard","12px","currentColor",1.5);Y&&N.appendChild(Y)},1500)}),g.appendChild(m),g.appendChild(D),E&&g.appendChild(E),g.appendChild(W),w&&g.appendChild(w),g.appendChild(O),g.appendChild(N),y.appendChild(g),p&&y.appendChild(uv(t,i,l)),y}}function Fg(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??"",u=r?.features?.eventStream??{},y=s.find(m=>m.renderEventStreamView);if(y?.renderEventStreamView&&r){let m=y.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>g().element,onClose:o});if(m)return{element:m,update:()=>{},destroy:()=>{}}}return g();function g(){let m=u.classNames,C=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");vr(C,m?.panel);let D=[],B="",E="",A=null,W=[],z={},G=0,w=ea(),O=0,N=0,L=!1,P=null,I=!1,Y=0,de=new Set,ue=new Map,pe="",ee="",oe=null,V,ae,ne,me,be=null,fe=null,Te=null;function Se(){let $=h("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),K=h("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(vr(K,m?.headerBar),i){fe=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),fe.style.cursor="help",be=h("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"),be.textContent="-- tok/s",Te=h("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 Ye=fe,fo=Te,mo=()=>{if(!fo.textContent)return;let Is=Ye.getBoundingClientRect(),Yt=$.getBoundingClientRect();fo.style.left=`${Is.left-Yt.left}px`,fo.style.top=`${Is.bottom-Yt.top+4}px`,fo.style.display="block"},wa=()=>{fo.style.display="none"};fe.addEventListener("mouseenter",mo),fe.addEventListener("mouseleave",wa),fe.appendChild(be)}let ce=h("div","persona-flex-1");V=h("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 Ve=h("option","");Ve.value="",Ve.textContent="All events (0)",V.appendChild(Ve),ae=h("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"),ae.type="button",ae.title="Copy All";let it=se("clipboard-copy","12px","currentColor",1.5);it&&ae.appendChild(it);let X=h("span","persona-event-copy-all persona-text-xs");X.textContent="Copy All",ae.appendChild(X),fe&&K.appendChild(fe),K.appendChild(ce),K.appendChild(V),K.appendChild(ae);let ze=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");vr(ze,m?.searchBar);let Ee=se("search","14px","var(--persona-muted, #9ca3af)",1.5),We=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Ee&&We.appendChild(Ee),ne=h("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"),vr(ne,m?.searchInput),ne.type="text",ne.placeholder="Search event payloads...",me=h("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 Re=se("x","12px","currentColor",2);return Re&&me.appendChild(Re),ze.appendChild(We),ze.appendChild(ne),ze.appendChild(me),$.appendChild(K),$.appendChild(ze),Te&&$.appendChild(Te),$}let Fe,ke=s.find($=>$.renderEventStreamToolbar);ke?.renderEventStreamToolbar&&r?Fe=ke.renderEventStreamToolbar({config:r,defaultRenderer:()=>Se(),eventCount:e.getSize(),filteredCount:0,onFilterChange:K=>{B=K,Ie(),we()},onSearchChange:K=>{E=K,Ie(),we()}})??Se():Fe=Se();let qe=h("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");qe.style.display="none";function Xe(){if(!i||!be||!fe)return;let $=i(),K=dv($);be.textContent=K;let ce=pv($);Te&&(Te.textContent=ce,ce||(Te.style.display="none")),fe.setAttribute("aria-label",ce?`Throughput: ${K}, ${ce}`:`Throughput: ${K}`)}let He=h("div","persona-flex-1 persona-min-h-0 persona-relative"),Le=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Le.style.height="100%";let Je=h("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");vr(Je,m?.scrollIndicator),Je.style.display="none",Je.setAttribute("data-persona-scroll-to-bottom-has-label",d?"true":"false");let ln=se(c,"14px","currentColor",2);ln&&Je.appendChild(ln);let Lt=h("span","");Lt.textContent=d,Je.appendChild(Lt);let xt=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");xt.style.display="none",He.appendChild(Le),He.appendChild(xt),He.appendChild(Je),C.setAttribute("tabindex","0"),C.appendChild(Fe),C.appendChild(qe),C.appendChild(He);function Be(){let $=e.getAll(),K={};for(let ze of $)K[ze.type]=(K[ze.type]||0)+1;let ce=Object.keys(K).sort(),Ve=ce.length!==W.length||!ce.every((ze,Ee)=>ze===W[Ee]),Pe=!Ve&&ce.some(ze=>K[ze]!==z[ze]),it=$.length!==Object.values(z).reduce((ze,Ee)=>ze+Ee,0);if(!Ve&&!Pe&&!it||(W=ce,z=K,!V))return;let X=V.value;if(V.options[0].textContent=`All events (${$.length})`,Ve){for(;V.options.length>1;)V.remove(1);for(let ze of ce){let Ee=h("option","");Ee.value=ze,Ee.textContent=`${ze} (${K[ze]||0})`,V.appendChild(Ee)}X&&ce.includes(X)?V.value=X:X&&(V.value="",B="")}else for(let ze=1;ze<V.options.length;ze++){let Ee=V.options[ze];Ee.textContent=`${Ee.value} (${K[Ee.value]||0})`}}function Ce(){let $=e.getAll();if(B&&($=$.filter(K=>K.type===B)),E){let K=E.toLowerCase();$=$.filter(ce=>ce.type.toLowerCase().includes(K)||ce.payload.toLowerCase().includes(K))}return $}function Ge(){return B!==""||E!==""}function Ie(){G=0,O=0,w.resume(),Je.style.display="none"}function ye($){de.has($)?de.delete($):de.add($),oe=$;let K=Le.scrollTop,ce=w.isFollowing();I=!0,w.pause(),we(),Le.scrollTop=K,ce&&w.resume(),I=!1}function ge(){return uo(Le,50)}function we(){N=Date.now(),L=!1,Xe(),Be();let $=e.getEvictedCount();$>0?(qe.textContent=`${$.toLocaleString()} older events truncated`,qe.style.display=""):qe.style.display="none",D=Ce();let K=D.length,ce=e.getSize()>0;K===0&&ce&&Ge()?(xt.textContent=E?`No events matching '${E}'`:"No events matching filter",xt.style.display="",Le.style.display="none"):(xt.style.display="none",Le.style.display=""),ae&&(ae.title=Ge()?`Copy Filtered (${K})`:"Copy All"),p&&!w.isFollowing()&&K>G&&(O+=K-G,Lt.textContent=d?`${d}${O>0?` (${O})`:""}`:"",Je.style.display=""),G=K;let Ve=e.getAll(),Pe=Ve.length>0?Ve[0].timestamp:0,it=new Set(D.map(Ee=>Ee.id));for(let Ee of de)it.has(Ee)||de.delete(Ee);let X=B!==pe||E!==ee,ze=ue.size===0&&D.length>0;if(X||ze||D.length===0){Le.innerHTML="",ue.clear();let Ee=document.createDocumentFragment();for(let We=0;We<D.length;We++){let Re=lc(D[We],We,Pe,u,de,ye,s,r);ue.set(D[We].id,Re),Ee.appendChild(Re)}Le.appendChild(Ee),pe=B,ee=E,oe=null}else{if(oe!==null){let We=ue.get(oe);if(We&&We.parentNode===Le){let Re=D.findIndex(Ye=>Ye.id===oe);if(Re>=0){let Ye=lc(D[Re],Re,Pe,u,de,ye,s,r);Le.insertBefore(Ye,We),We.remove(),ue.set(oe,Ye)}}oe=null}let Ee=new Set(D.map(We=>We.id));for(let[We,Re]of ue)Ee.has(We)||(Re.remove(),ue.delete(We));for(let We=0;We<D.length;We++){let Re=D[We];if(!ue.has(Re.id)){let Ye=lc(Re,We,Pe,u,de,ye,s,r);ue.set(Re.id,Ye),Le.appendChild(Ye)}}}w.isFollowing()&&(Le.scrollTop=Le.scrollHeight)}function Ct(){if(Date.now()-N>=ov){P!==null&&(cancelAnimationFrame(P),P=null),we();return}L||(L=!0,P=requestAnimationFrame(()=>{P=null,we()}))}let Ae=($,K)=>{if(!ae)return;ae.innerHTML="";let ce=se($,"12px","currentColor",1.5);ce&&ae.appendChild(ce);let Ve=h("span","persona-text-xs");Ve.textContent="Copy All",ae.appendChild(Ve),setTimeout(()=>{ae.innerHTML="";let Pe=se("clipboard-copy","12px","currentColor",1.5);Pe&&ae.appendChild(Pe);let it=h("span","persona-text-xs");it.textContent="Copy All",ae.appendChild(it),ae.disabled=!1},K)},he=async()=>{if(ae){ae.disabled=!0;try{let $;Ge()?$=D:n?($=await n(),$.length===0&&($=e.getAll())):$=e.getAll();let K=$.map(ce=>{try{return JSON.parse(ce.payload)}catch{return ce.payload}});await navigator.clipboard.writeText(JSON.stringify(K,null,2)),Ae("check",1500)}catch{Ae("x",1500)}}},hn=()=>{V&&(B=V.value,Ie(),we())},te=()=>{!ne||!me||(me.style.display=ne.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{E=ne.value,Ie(),we()},150))},k=()=>{!ne||!me||(ne.value="",E="",me.style.display="none",A&&clearTimeout(A),Ie(),we())},j=()=>{if(I)return;let $=Le.scrollTop,{action:K,nextLastScrollTop:ce}=ta({following:w.isFollowing(),currentScrollTop:$,lastScrollTop:Y,nearBottom:ge(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Y=ce,K==="resume"?(w.resume(),O=0,Je.style.display="none"):K==="pause"&&(w.pause(),p&&(Lt.textContent=d,Je.style.display=""))},v=$=>{let K=na({following:w.isFollowing(),deltaY:$.deltaY,nearBottom:ge(),resumeWhenNearBottom:!0});K==="pause"?(w.pause(),p&&(Lt.textContent=d,Je.style.display="")):K==="resume"&&(w.resume(),O=0,Je.style.display="none")},T=()=>{p&&(Le.scrollTop=Le.scrollHeight,w.resume(),O=0,Je.style.display="none")},R=$=>{let K=$.target;if(!K||K.closest("button"))return;let ce=K.closest("[data-event-id]");if(!ce)return;let Ve=ce.getAttribute("data-event-id");Ve&&ye(Ve)},_=$=>{if(($.metaKey||$.ctrlKey)&&$.key==="f"){$.preventDefault(),ne?.focus(),ne?.select();return}$.key==="Escape"&&(ne&&document.activeElement===ne?(k(),ne.blur(),C.focus()):o&&o())};ae&&ae.addEventListener("click",he),V&&V.addEventListener("change",hn),ne&&ne.addEventListener("input",te),me&&me.addEventListener("click",k),Le.addEventListener("scroll",j),Le.addEventListener("wheel",v,{passive:!0}),Le.addEventListener("click",R),Je.addEventListener("click",T),C.addEventListener("keydown",_);function Q(){A&&clearTimeout(A),P!==null&&(cancelAnimationFrame(P),P=null),L=!1,ue.clear(),ae&&ae.removeEventListener("click",he),V&&V.removeEventListener("change",hn),ne&&ne.removeEventListener("input",te),me&&me.removeEventListener("click",k),Le.removeEventListener("scroll",j),Le.removeEventListener("wheel",v),Le.removeEventListener("click",R),Je.removeEventListener("click",T),C.removeEventListener("keydown",_)}return{element:C,update:Ct,destroy:Q}}}tt();Mt();function _g(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=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let y=u;return s.findIndex(g=>g===y||g.contains(y))},c=u=>{let y=p(u.target);if(y<0)return;let g=y;if(u.key===r)g=Math.min(y+1,s.length-1);else if(u.key===o)g=Math.max(y-1,0);else if(u.key==="Home")g=0;else if(u.key==="End")g=s.length-1;else return;u.preventDefault(),g!==y&&e.onSelect(g)},d=u=>{let y=p(u.target);y>=0&&l(s[y])};return t.addEventListener("keydown",c),t.addEventListener("focusin",d),{beforeRender(){i=typeof document<"u"&&t.contains(document.activeElement)},render(u,y){if(s=u,u.forEach((g,m)=>{g.setAttribute("role","tab");let C=m===y;g.setAttribute("aria-selected",C?"true":"false"),g.tabIndex=C||y<0&&m===0?0:-1}),i){let g=(y>=0?u[y]:void 0)??u[0];g&&typeof g.focus=="function"&&(l(g),g.focus())}},destroy(){t.removeEventListener("keydown",c),t.removeEventListener("focusin",d)}}}function $g(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=te=>({start:te===!1?!1:typeof te=="object"&&te?te.start!==!1:!0,end:te===!1?!1:typeof te=="object"&&te?te.end!==!1:!0}),{start:d,end:u}=c(n?.tabFade),y=typeof document<"u"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{y?.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),I?.hide()};y&&y.addEventListener("click",()=>{g(),e.onDismiss?.()});let m=h("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");m.setAttribute("data-persona-theme-zone","artifact-pane"),r&&m.classList.add("persona-artifact-pane-document");let C=h("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 D=h("span","persona-text-xs persona-font-medium persona-truncate");D.textContent=s;let B=Dt({icon:"x",label:i});B.addEventListener("click",()=>{g(),e.onDismiss?.()});let E="rendered",A=Qi({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:te=>{E=te==="source"?"source":"rendered",Ae()}}),W=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),z=n?.documentToolbarShowCopyLabel===!0,G=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,O=!!(G&&w&&w.length>0),N=null,L,P=null,I=null;if(r&&(z||G)&&!O){if(L=z?Ho({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),G){let te=se("chevron-down",14,"currentColor",2);te&&L.appendChild(te)}}else r&&O?(N=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),L=z?Ho({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P=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"}}),N.append(L,P)):r?L=Dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(L=Dt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&L.classList.add("persona-hidden"));let Y=r?Dt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Dt({icon:"refresh-cw",label:"Refresh"}),de=r?Dt({icon:"x",label:i,className:"persona-artifact-doc-icon-btn"}):Dt({icon:"x",label:i}),ue=Dt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&ue.classList.add("persona-hidden");let pe=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ee=t.features?.artifacts?.toolbarActions??[],oe=()=>{let te=He.find(T=>T.id===Le)??He[He.length-1],k=te?.id??null,j=te?.artifactType==="markdown"?te.markdown??"":"",v=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:j,jsonPayload:v,id:k}},V=async()=>{let te=He.find(k=>k.id===Le)??He[He.length-1];try{await navigator.clipboard.writeText(ms(te))}catch{}};if(L.addEventListener("click",async()=>{let te=n?.onDocumentToolbarCopyMenuSelect;if(te&&O){let{markdown:k,jsonPayload:j,id:v}=oe();try{await te({actionId:"primary",artifactId:v,markdown:k,jsonPayload:j})}catch{}return}await V()}),P&&w?.length){let te=()=>m.closest("[data-persona-root]")??document.body,k=()=>{I=fr({items:w.map(j=>({id:j.id,label:j.label})),onSelect:async j=>{let{markdown:v,jsonPayload:T,id:R}=oe(),_=n?.onDocumentToolbarCopyMenuSelect;try{_?await _({actionId:j,artifactId:R,markdown:v,jsonPayload:T}):j==="markdown"||j==="md"?await navigator.clipboard.writeText(v):j==="json"||j==="source"?await navigator.clipboard.writeText(T):await navigator.clipboard.writeText(v||T)}catch{}},anchor:N??P,position:"bottom-right",portal:te()})};m.isConnected?k():requestAnimationFrame(k),P.addEventListener("click",j=>{j.stopPropagation(),I?.toggle()})}Y.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}Ae()}),de.addEventListener("click",()=>{g(),e.onDismiss?.()});let ae=h("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(),N?W.append(N,Y,de):W.append(L,Y,de),W.insertBefore(pe,de),W.insertBefore(ue,de),C.append(A.element,ae,W);else{let te=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");te.append(L,pe,ue,B),C.appendChild(D),C.appendChild(te)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let ne=h("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,be=h("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),fe=_g(ne,{onSelect:te=>e.onSelect(He[te].id)}),Te=te=>{let k=te.scrollWidth-te.clientWidth,j=k>1,v=Math.abs(te.scrollLeft);te.classList.toggle("persona-artifact-tab-fade-start",d&&j&&v>1),te.classList.toggle("persona-artifact-tab-fade-end",u&&j&&v<k-1)},Se=0,Fe=()=>{if(Se)return;let te=()=>{Se=0,Te(ne)};Se=typeof requestAnimationFrame=="function"?requestAnimationFrame(te):setTimeout(te,0)};ne.addEventListener("scroll",()=>Fe(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Te(ne)).observe(ne);let ke=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),qe=()=>{ke.scrollLeft=0},Xe=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(qe):setTimeout(qe,0)};if(l){for(let te of[ne,be])te.style.paddingLeft=l,te.style.paddingRight=l;ke.style.padding=l}m.appendChild(C),m.appendChild(ne),m.appendChild(be),m.appendChild(ke);let He=[],Le=null,Je=!1,ln=!1,Lt=!0,xt=!1,Be=null,Ce="",Ge=null,Ie=!1,ye=te=>te.artifactType==="markdown"&&!!te.file||r?E:"rendered",ge=te=>{r||(te&&!Ie?(C.insertBefore(A.element,D),Ie=!0):!te&&Ie&&(A.element.remove(),Ie=!1))},we=()=>Le&&He.find(te=>te.id===Le)||He[He.length-1],Ct=()=>{let te=gs(we());if(!te){pe.replaceChildren();return}let k=ee.filter(j=>j.visible===void 0||j.visible(te)).map(j=>mr(j,{documentChrome:r,onClick:()=>{let v=gs(we());if(v)try{Promise.resolve(j.onClick(v)).catch(()=>{})}catch{}}}));pe.replaceChildren(...k)},Ae=()=>{Ct();let te=r&&He.length<=1,k=!!me;if(ne.classList.toggle("persona-hidden",te||k),be.classList.toggle("persona-hidden",te||!k),k&&me){let T=He.map(R=>R.id).join("|")+" "+(Le??"");if(T!==Ce){Ce=T;let R=me({records:He,selectedId:Le,onSelect:e.onSelect});be.firstElementChild!==R&&be.replaceChildren(R)}}else{fe.beforeRender(),ne.replaceChildren();let T=[],R=-1;for(let[_,Q]of He.entries()){let $=h("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");$.type="button";let K=Q.artifactType==="markdown"?Q.file:void 0,ce=K?kn(K.path):Q.title||Q.id.slice(0,8),Ve=K?.path||Q.title||ce;$.textContent=ce,$.title=Ve,$.setAttribute("aria-label",Ve),Q.id===Le&&($.classList.add("persona-bg-persona-container","persona-border-persona-border"),R=_),$.addEventListener("click",()=>e.onSelect(Q.id)),ne.appendChild($),T.push($)}if(fe.render(T,R),R>=0&&Le!==Be){Be=Le;let _=T[R];typeof _.scrollIntoView=="function"&&_.scrollIntoView({block:"nearest",inline:"nearest"})}Te(ne)}let j=Le&&He.find(T=>T.id===Le)||He[He.length-1];if(!j){ke.replaceChildren(),Ge=null,ge(!1);return}let v=j.artifactType==="markdown"?j.file:void 0;if(ge(!!v),r){let T=v?lo(v):j.artifactType==="markdown"?"MD":j.component??"Component",R=(j.title||"Document").trim(),_=v?kn(v.path):R.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ae.textContent=`${_} \xB7 ${T}`}else D.textContent=v?kn(v.path):s;Ge?(Ge.el.parentElement!==ke&&ke.replaceChildren(Ge.el),Ge.update(j)):(Ge=Yi(j,{config:t,resolveViewMode:ye}),ke.replaceChildren(Ge.el)),ke.classList.toggle("persona-artifact-content-flush",!!ke.querySelector(".persona-code-pre"))},he=()=>{let te=He.length>0;if(m.classList.toggle("persona-hidden",!te),y){let v=((typeof m.closest=="function"?m.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;te&&v&&Je?(y.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(y.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}},hn=()=>{xt=!1,Ae(),he()};return{element:m,backdrop:y,update(te){let k=te.selectedId??te.artifacts[te.artifacts.length-1]?.id??null,j=k!==Le;He=te.artifacts,Le=k,He.length>0&&(Je=!0),xt=!0,Lt&&hn(),j&&qe()},setMobileOpen(te){Je=te,!te&&y?(y.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):he()},setExpanded(te){te!==ln&&(ln=te,Xe());let k=se(te?"minimize":"maximize",16,"currentColor",2);k&&ue.replaceChildren(k);let j=te?"Collapse artifacts panel":"Expand artifacts panel";ue.setAttribute("aria-label",j),ue.title=j},setExpandToggleVisible(te){ue.classList.toggle("persona-hidden",!te)},setCopyButtonVisible(te){r||L.classList.toggle("persona-hidden",!te)},setCustomActions(te){ee=te,Ct()},setTabFade(te){let k=c(te);k.start===d&&k.end===u||(d=k.start,u=k.end,Te(ne))},setRenderTabBar(te){te!==me&&(me=te,Ce="",Ae())},setVisible(te){te!==Lt&&(Lt=te,te&&xt&&hn())}}}function Jt(t){return t?.features?.artifacts?.enabled===!0}function zg(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"),!Jt(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 gv(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 Ug=["panel","seamless","detached"];function cc(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&Ug.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function dc(t){return!t||!Jt(t)?!1:cc(t)==="detached"}function Es(t,e){if(!Jt(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-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),gv(t),zg(t,e);return}let n=e.features?.artifacts?.layout,o=cc(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?.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"),zg(t,e)}function ks(t,e){for(let l of Ug)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"),!Jt(e))return;let n=e.features?.artifacts?.layout,o=cc(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 jg(t,e){return!e||!Jt(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function fv(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 mv(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 hv(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function bv(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function pc(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 qg(t,e,n,o,r,s){let i=fv(r,200),l=bv(e,n,o,200);l=Math.max(i,l);let p=mv(s);return p!==null&&(l=Math.min(l,p)),hv(t,i,l)}tt();var Vg={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"}},uc=(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=Vg[i]??Vg.init;s.classList.add("persona-form-card","persona-space-y-4");let p=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=l.title,p.appendChild(c),l.description){let m=h("p","persona-text-sm persona-text-persona-muted");m.textContent=l.description,p.appendChild(m)}let d=document.createElement("form");d.className="persona-form-grid persona-space-y-3",l.fields.forEach(m=>{let C=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${e.id}-${i}-${m.name}`;let D=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");D.textContent=m.label,C.appendChild(D);let B=m.type??"text",E;B==="textarea"?(E=document.createElement("textarea"),E.rows=3):(E=document.createElement("input"),E.type=B),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}-${i}-${m.name}`,E.name=m.name,E.placeholder=m.placeholder??"",m.required&&(E.required=!0),C.appendChild(E),d.appendChild(C)});let u=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),y=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=h("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");g.type="submit",g.textContent=l.submitLabel??"Submit",u.appendChild(y),u.appendChild(g),d.appendChild(u),s.replaceChildren(p,d),d.addEventListener("submit",async m=>{m.preventDefault();let C=n.formEndpoint??"/form",D=new FormData(d),B={};D.forEach((E,A)=>{B[A]=E}),B.type=i,g.disabled=!0,y.textContent="Submitting\u2026";try{let E=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let A=await E.json();y.textContent=A.message??"Thanks! We'll be in touch soon.",A.success&&A.nextPrompt&&await o.sendMessage(String(A.nextPrompt))}catch(E){y.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var gc=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()}},fc=new gc;var Kg=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),yv=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.streamAnimation.plugins"]),Gg=(t,e,n)=>{if(!Kg(t)||!Kg(e)||yv.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]=Gg(t[r],e[r],s)}return o};function Qg(t,e){let n=Gg(t,e,"");return zi(n)}var Xg=()=>{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 vv=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},xv=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},hc=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=vv(t),n=xv(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}},mc=t=>typeof t=="string"?t:t==null?"":String(t),Ls={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:mc(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=mc(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:mc(n.text)}}},Jg=t=>Array.isArray(t)?t.map(e=>String(e)):[],bc=t=>{let e=new Set(Jg(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(Jg(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)},u=c(l,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:d});if(!u)continue;if(u.handled){let y=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:y,resubmit:u.resubmit}}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:n}};var Cv=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}},wv=t=>t.map(e=>({...e,streaming:!1})),Av=t=>t.map(e=>({...e,status:"complete"})),Yg=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?Cv(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?wv(n.messages):void 0,artifacts:n.artifacts?Av(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 yc=require("partial-json");function Zg(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=Un.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 ef(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 vc(t){let e=ef(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 tf(t){let e=ef(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 Sv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function nf(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=Sv}=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 u=null,y=document.createElement("div");y.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let m=document.createElement("h3");m.className="persona-feedback-title",m.textContent=o,g.appendChild(m);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,g.appendChild(C),y.appendChild(g);let D=document.createElement("div");D.className="persona-feedback-rating persona-feedback-rating-csat",D.setAttribute("role","radiogroup"),D.setAttribute("aria-label","Satisfaction rating from 1 to 5");let B=[];for(let G=1;G<=5;G++){let w=document.createElement("button");w.type="button",w.className="persona-feedback-rating-btn persona-feedback-star-btn",w.setAttribute("role","radio"),w.setAttribute("aria-checked","false"),w.setAttribute("aria-label",`${G} star${G>1?"s":""}: ${c[G-1]}`),w.title=c[G-1],w.dataset.rating=String(G),w.innerHTML=`
215
+ `):""},rc=(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)"},Ny=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=Dy(t,o?.previewMaxLines??3),i=n?xp(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=fl(n,p.activeTextTemplate,c):!l&&p.completeTextTemplate&&(c=fl(n,p.completeTextTemplate,c)),{summary:c,previewText:s,isActive:l}},kg=(t,e,n)=>{let o=yr.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)",u=se(o?"chevron-up":"chevron-down",16,d,2);u?c.appendChild(u):c.textContent=o?"Hide":"Show"}i.style.display=o?"":"none",l&&(l.style.display=o?"none":l.textContent||l.childNodes.length?"":"none")},sc=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=h("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&&yr.has(t.id),{summary:p,previewText:c,isActive:d}=Ny(t,e),u=h("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");u.type="button",i&&(u.setAttribute("aria-expanded",l?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(u.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(u.style.paddingLeft=o.headerPaddingX,u.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(u.style.paddingTop=o.headerPaddingY,u.style.paddingBottom=o.headerPaddingY);let y=h("div","persona-flex persona-flex-col persona-text-left"),g=h("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let m=String(n.startedAt??Date.now()),C=()=>{let P=h("span","");return P.setAttribute("data-tool-elapsed",m),P.textContent=Xr(n),P},D=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:p,previewText:c,collapsedMode:s.collapsedMode??"tool-call",isActive:d,config:e??{},elapsed:Xr(n),createElapsedElement:C});typeof D=="string"&&D.trim()?(g.textContent=D,y.appendChild(g)):D instanceof HTMLElement?y.appendChild(D):(g.textContent=p,y.appendChild(g));let B=s.loadingAnimation??"none",E=o.activeTextTemplate,A=o.completeTextTemplate,W=d?E:A,z=D instanceof HTMLElement,G=(P,I)=>{g.textContent="";let Y=n.name?.trim()||"tool",de=yi(P,Y),ue=0;for(let pe of de){let ee=pe.styles.length>0?(()=>{let oe=h("span",pe.styles.map(V=>`persona-tool-text-${V}`).join(" "));return g.appendChild(oe),oe})():g;if(pe.isDuration&&d)ee.appendChild(C());else{let oe=pe.isDuration?Xr(n):pe.text;I?ue=co(ee,oe,ue):ee.appendChild(document.createTextNode(oe))}}};if(!z)if(d&&B!=="none"){let P=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),B==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${P}ms`),W&&G(W,!1);else if(g.classList.add(`persona-tool-loading-${B}`),g.style.setProperty("--persona-tool-anim-duration",`${P}ms`),B==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),W)G(W,!0);else{let I=g.textContent||p;g.textContent="",co(g,I,0)}}else W&&G(W,!1);let w=null;if(i){w=h("div","persona-flex persona-items-center");let P=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",I=se(l?"chevron-up":"chevron-down",16,P,2);I?w.appendChild(I):w.textContent=l?"Hide":"Show";let Y=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");Y.append(w),u.append(y,Y)}else u.append(y);let O=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(O.setAttribute("data-persona-collapsed-preview","tool"),O.style.display="none",O.style.whiteSpace="pre-wrap",!l&&d&&s.activePreview&&c){let P=o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:c,isActive:d,config:e??{}});By(O,P)||(O.textContent=c),O.style.display=""}if(!l&&d&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!i)return r.append(u,O),r;let N=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(N.style.display=l?"":"none",o.contentBackgroundColor&&(N.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(N.style.color=o.contentTextColor),o.contentPaddingX&&(N.style.paddingLeft=o.contentPaddingX,N.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(N.style.paddingTop=o.contentPaddingY,N.style.paddingBottom=o.contentPaddingY),n.name){let P=h("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,N.appendChild(P)}if(n.args!==void 0){let P=h("div","persona-space-y-1"),I=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(I.style.color=o.labelTextColor),I.textContent="Arguments";let Y=h("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");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",rc(Y,o),Y.textContent=ao(n.args),P.append(I,Y),N.appendChild(P)}if(n.chunks&&n.chunks.length){let P=h("div","persona-space-y-1"),I=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(I.style.color=o.labelTextColor),I.textContent="Activity";let Y=h("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");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",rc(Y,o),Y.textContent=n.chunks.join(""),P.append(I,Y),N.appendChild(P)}if(n.status==="complete"&&n.result!==void 0){let P=h("div","persona-space-y-1"),I=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(I.style.color=o.labelTextColor),I.textContent="Result";let Y=h("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");Y.style.fontSize="0.75rem",Y.style.lineHeight="1rem",rc(Y,o),Y.textContent=ao(n.result),P.append(I,Y),N.appendChild(P)}if(n.status==="complete"&&typeof n.duration=="number"){let P=h("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(P.style.color=o.contentTextColor),P.textContent=`Duration: ${n.duration}ms`,N.appendChild(P)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),w){w.innerHTML="";let P=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",I=se(l?"chevron-up":"chevron-down",16,P,2);I?w.appendChild(I):w.textContent=l?"Hide":"Show"}N.style.display=l?"":"none",O.style.display=l?"none":O.textContent||O.childNodes.length?"":"none"})(),r.append(u,O,N),r};nt();St();var Do=new Map,ba=t=>{let n=(t.startsWith(On)?t.slice(On.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)},Lg=t=>t?.approval!==!1?t?.approval:void 0,Pg=(t,e)=>{let n=Lg(e)?.detailsDisplay??"collapsed";return Do.get(t)??n==="expanded"},Ig=(t,e,n)=>{let o=Lg(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=se(e?"chevron-up":"chevron-down",14,"currentColor",2);i&&s.appendChild(i)}},Rg=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=Pg(t,n);Ig(o,s,n),r.style.display=s?"":"none"};var ya=(t,e)=>{let n=t.approval,o=e?.approval!==!1?e?.approval:void 0,r=n?.status==="pending",s=h("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=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),l=h("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=se(p,20,c,2);d&&l.appendChild(d);let u=h("div","persona-flex-1 persona-min-w-0"),y=h("div","persona-flex persona-items-center persona-gap-2"),g=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(g.style.color=o.titleColor),g.textContent=o?.title??"Approval Required",y.appendChild(g),!r){let w=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");w.setAttribute("data-approval-status",n.status),n.status==="approved"?(w.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",w.style.color="var(--persona-palette-colors-success-700, #15803d)",w.textContent="Approved"):n.status==="denied"?(w.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",w.style.color="var(--persona-palette-colors-error-700, #b91c1c)",w.textContent="Denied"):n.status==="timeout"&&(w.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",w.style.color="var(--persona-palette-colors-warning-700, #b45309)",w.textContent="Timeout"),y.appendChild(w)}u.appendChild(y);let C=n.toolType==="webmcp"||n.toolName.startsWith(On)?Vr(n.toolName):void 0,D=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),B=!n.toolName,E=D||(B?n.description:`The assistant wants to use \u201C${C??ba(n.toolName)}\u201D.`),A=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(A.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(A.style.color=o.descriptionColor),A.textContent=E,u.appendChild(A),n.reason){let w=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");w.setAttribute("data-approval-reason","true"),o?.reasonColor?w.style.color=o.reasonColor:o?.descriptionColor&&(w.style.color=o.descriptionColor);let O=h("span","persona-font-medium");O.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,w.appendChild(O),w.appendChild(document.createTextNode(n.reason)),u.appendChild(w)}let W=o?.detailsDisplay??"collapsed",z=!!n.description&&!B,G=z||!!n.parameters;if(W!=="hidden"&&G){let w=Pg(t.id,e),O=h("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");O.type="button",O.setAttribute("data-expand-header","true"),O.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(O.style.color=o.descriptionColor);let N=h("span");N.setAttribute("data-approval-details-label","true");let L=h("span","persona-inline-flex persona-items-center");L.setAttribute("data-approval-details-chevron","true"),O.append(N,L),Ig(O,w,e),u.appendChild(O);let P=h("div");if(P.setAttribute("data-approval-details","true"),P.style.display=w?"":"none",z){let I=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(I.style.color=o.descriptionColor),I.textContent=n.description,P.appendChild(I)}if(n.parameters){let I=h("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&&(I.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(I.style.color=o.parameterTextColor),I.style.fontSize="0.75rem",I.style.lineHeight="1rem",I.textContent=ao(n.parameters),P.appendChild(I)}u.appendChild(P)}if(r){let w=h("div","persona-flex persona-gap-2 persona-mt-2");w.setAttribute("data-approval-buttons","true");let O=h("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");O.type="button",O.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",O.style.color=o?.approveButtonTextColor??"#ffffff",O.setAttribute("data-approval-action","approve");let N=se("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);N&&(N.style.marginRight="4px",O.appendChild(N));let L=document.createTextNode(o?.approveLabel??"Approve");O.appendChild(L);let P=h("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 I=se("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);I&&(I.style.marginRight="4px",P.appendChild(I));let Y=document.createTextNode(o?.denyLabel??"Deny");P.appendChild(Y),w.append(O,P),u.appendChild(w)}return i.append(l,u),s.appendChild(i),s};nt();St();El();var Oy=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Wg=(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))},No=(t,e)=>{Wg(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)},Fy=t=>t?.approval!==!1?t?.approval:void 0,_y=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return Do.get(t)??n==="expanded"},ic=t=>{let e=h("span","persona-approval-kbd");return e.textContent=t,e},$y=(t,e)=>{let n=h("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(On)?Vr(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??ba(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},zy=t=>{let e=h("div","persona-approval-resolved"),n=se("ban",15,"currentColor",2);n&&e.appendChild(n);let o=h("span","persona-approval-resolved-name");return o.textContent=t.toolName?ba(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},Uy=(t,e,n,o,r,s,i)=>{let l=h("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",u=c||d,y=u&&_y(e.id,o),g=o?.showDetailsLabel??"Show details",m=o?.hideDetailsLabel??"Hide details",C=h("button","persona-approval-head");C.type="button",u?(C.setAttribute("data-action","toggle-params"),C.setAttribute("aria-expanded",y?"true":"false"),C.setAttribute("aria-label",y?m:g)):C.setAttribute("data-static","true");let D=h("span","persona-approval-logo"),B=se("shield-check",16,"currentColor",2);B&&D.appendChild(B),C.appendChild(D);let E=$y(n,o);if(u){let O=h("span","persona-approval-toggle");O.setAttribute("aria-hidden","true");let N=se("chevron-down",14,"currentColor",2);N&&O.appendChild(N),E.append(" "),E.appendChild(O)}C.appendChild(E),l.appendChild(C);let A=h("div","persona-approval-body");if(u){let O=h("div","persona-approval-details");if(O.setAttribute("data-role","params"),O.hidden=!y,c){let N=h("p","persona-approval-desc");o?.descriptionColor&&(N.style.color=o.descriptionColor),N.textContent=n.description,O.appendChild(N)}if(d){let N=h("pre","persona-approval-params");o?.parameterBackgroundColor&&(N.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(N.style.color=o.parameterTextColor),N.textContent=ao(n.parameters),O.appendChild(N)}A.appendChild(O)}if(n.reason){let O=h("p","persona-approval-reason");o?.reasonColor?O.style.color=o.reasonColor:o?.descriptionColor&&(O.style.color=o.descriptionColor);let N=h("span","persona-approval-reason-label");N.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,O.append(N,document.createTextNode(n.reason)),A.appendChild(O)}let W=h("div","persona-approval-actions"),z=null,G=O=>{o?.approveButtonColor&&(O.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(O.style.color=o.approveButtonTextColor)},w=h("button","persona-approval-deny");if(w.type="button",w.setAttribute("data-action","deny"),o?.denyButtonColor&&(w.style.background=o.denyButtonColor),o?.denyButtonTextColor&&(w.style.color=o.denyButtonTextColor),w.append(o?.denyLabel??"Deny"),i){let O=h("div","persona-approval-split"),N=h("button","persona-approval-primary");N.type="button",N.setAttribute("data-action","always"),G(N),N.append(o?.approveLabel??"Always allow",ic("\u23CE"));let L=h("button","persona-approval-caret");L.type="button",L.setAttribute("data-action","toggle-menu"),L.setAttribute("aria-label","More options"),G(L);let P=se("chevron-down",15,"currentColor",2);P&&L.appendChild(P),O.append(N,L),W.append(O,w),w.append(ic("Esc"));let I=h("div","persona-approval-menu"),Y=h("button","persona-approval-menu-item");Y.type="button",Y.append("Allow once",ic("\u2318\u23CE")),I.appendChild(Y),z=Hi({anchor:O,content:I,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,z),Y.addEventListener("click",()=>{No(t,e.id),r()})}else{let O=h("button","persona-approval-primary persona-approval-primary--solo");O.type="button",O.setAttribute("data-action","allow"),G(O),O.append(o?.approveLabel??"Allow"),W.append(O,w)}return A.appendChild(W),l.appendChild(A),l.addEventListener("click",O=>{let N=O.target instanceof Element?O.target.closest("[data-action]"):null;if(!N)return;let L=N.getAttribute("data-action");if(L==="toggle-params"){let P=l.querySelector('[data-role="params"]');if(P){let I=P.hidden;P.hidden=!I,C.setAttribute("aria-expanded",I?"true":"false"),C.setAttribute("aria-label",I?m:g),Do.set(e.id,I)}return}if(L==="toggle-menu"){z?.toggle();return}if(L==="always"){No(t,e.id),r({remember:!0});return}if(L==="allow"){No(t,e.id),r();return}if(L==="deny"){No(t,e.id),s();return}}),l},Hg=()=>{let t=Oy();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=Fy(i);if(l.status!=="pending"){if(No(t,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return zy(l)}Wg(t,o.id);let c=p?.enableAlwaysAllow===!0,d=Uy(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 u=y=>{nu(y)||o.id===t.latestPendingApprovalId&&(y.key!=="Escape"&&y.key!=="Enter"||(y.preventDefault(),y.stopImmediatePropagation(),No(t,o.id),y.key==="Escape"?s():y.metaKey||y.ctrlKey?r():r({remember:!0})))};t.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return d}},teardown:()=>{for(let o of[...t.keyHandlers.keys(),...t.popovers.keys()])No(t,o);t.latestPendingApprovalId=null}}};nt();var Bg=t=>{let e=[],n=null;return{buttons:e,render:(r,s,i,l,p,c)=>{t.innerHTML="",e.length=0;let d=c?.agentPushed===!0;if(d||(n=null),!r||!r.length||!d&&(l??(s?s.getMessages():[])).some(D=>D.role==="user"))return;let u=document.createDocumentFragment(),y=s?s.isStreaming():!1,g=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(r.forEach(m=>{let C=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=m,C.disabled=y,p?.fontFamily&&(C.style.fontFamily=g(p.fontFamily)),p?.fontWeight&&(C.style.fontWeight=p.fontWeight),p?.paddingX&&(C.style.paddingLeft=p.paddingX,C.style.paddingRight=p.paddingX),p?.paddingY&&(C.style.paddingTop=p.paddingY,C.style.paddingBottom=p.paddingY),C.addEventListener("click",()=>{!s||s.isStreaming()||(i.value="",d&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:m},bubbles:!0,composed:!0})),s.sendMessage(m))}),u.appendChild(C),e.push(C)}),t.appendChild(u),d){let m=JSON.stringify(r);m!==n&&(n=m,t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var Ss=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 Ms=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 jy=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),qy=new Set(["step_start","execution_start"]),Vy=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Ky=new Set(["step_complete","agent_turn_complete"]),Gy=new Set(["flow_complete","agent_complete"]),Dg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Og=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),an=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Oo=(t,e)=>{let n=t[e];return Og(n)?n:void 0};function ac(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function va(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function Qy(t,e){return typeof e.type=="string"?e.type:t}function Xy(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 Jy(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 Ng(t){let e=Oo(t,"result"),n=[Oo(t,"tokens"),Oo(t,"totalTokens"),e?Oo(e,"tokens"):void 0,Oo(t,"usage"),e?Oo(e,"usage"):void 0];for(let o of n){if(!o)continue;let r=an(o.output)??an(o.outputTokens)??an(o.completionTokens);if(r!==void 0)return r}return an(t.outputTokens)??an(t.completionTokens)??(e?an(e.outputTokens)??an(e.completionTokens):void 0)}function Yy(t){let e=Oo(t,"result");return an(t.executionTime)??an(t.executionTimeMs)??an(t.execution_time)??an(t.duration)??(e?an(e.executionTime)??an(e.executionTimeMs):void 0)}function Zy(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Ts=class{constructor(e=Zy){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:va(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(!Og(n)){Dg.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Qy(e,n),r=this.now();if(jy.has(o)){this.startRun(r);return}if(qy.has(o)){this.run||this.startRun(r);return}if(Vy.has(o)){if(!Jy(o,n))return;let s=Xy(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+ac(i.visibleCharCount),p=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:va(l,p),outputTokens:l,durationMs:p,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Ky.has(o)){if(!this.run)return;let s=this.run,i=Ng(n);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+ac(s.visibleCharCount),c=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:va(p,c),outputTokens:p,durationMs:c,source:l?"usage":"estimate"};return}if(Gy.has(o)){if(!this.run)return;let s=this.run,i=Ng(n),l=i??s.exactOutputTokens+ac(s.visibleCharCount),p=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",c=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:va(l,c),outputTokens:l,durationMs:c,source:p},this.run=null;return}if(Dg.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:Yy(n)??o-e.startedAt}};nt();St();function vr(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}var ev={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)"}},tv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},nv=["flowName","stepName","reasoningText","text","name","tool","toolName"],ov=100;function rv(t,e){let n={...ev,...e};if(n[t])return n[t];for(let o of Object.keys(n))if(o.endsWith("_")&&t.startsWith(o))return n[o];return tv}function sv(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function iv(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 av(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 lv(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 cv(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 dv(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function pv(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 uv(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=h("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=h("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 lc(t,e,n,o,r,s,i,l){let p=r.has(t.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");vr(c,o.classNames?.eventRow);let d=i.find(y=>y.renderEventStreamRow);if(d?.renderEventStreamRow&&l){let y=d.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(t.id)});if(y)return c.appendChild(y),c}return c.appendChild(u()),c;function u(){let y=h("div",""),g=h("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");g.setAttribute("data-event-id",t.id);let m=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=se(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&m.appendChild(C);let D=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),B=o.timestampFormat??"relative";D.textContent=B==="relative"?sv(t.timestamp,n):iv(t.timestamp);let E=null;o.showSequenceNumbers!==!1&&(E=h("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 A=rv(t.type,o.badgeColors),W=h("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");W.style.backgroundColor=A.bg,W.style.color=A.text,W.style.borderColor=A.text+"50",W.textContent=t.type;let z=o.descriptionFields??nv,G=av(t.payload,z),w=null;G&&(w=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=G);let O=h("div","persona-flex-1 persona-min-w-0"),N=h("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"),L=se("clipboard","12px","currentColor",1.5);return L&&N.appendChild(L),N.addEventListener("click",async P=>{P.stopPropagation(),await lv(cv(t)),N.innerHTML="";let I=se("check","12px","currentColor",1.5);I&&N.appendChild(I),setTimeout(()=>{N.innerHTML="";let Y=se("clipboard","12px","currentColor",1.5);Y&&N.appendChild(Y)},1500)}),g.appendChild(m),g.appendChild(D),E&&g.appendChild(E),g.appendChild(W),w&&g.appendChild(w),g.appendChild(O),g.appendChild(N),y.appendChild(g),p&&y.appendChild(uv(t,i,l)),y}}function Fg(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??"",u=r?.features?.eventStream??{},y=s.find(m=>m.renderEventStreamView);if(y?.renderEventStreamView&&r){let m=y.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>g().element,onClose:o});if(m)return{element:m,update:()=>{},destroy:()=>{}}}return g();function g(){let m=u.classNames,C=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");vr(C,m?.panel);let D=[],B="",E="",A=null,W=[],z={},G=0,w=ea(),O=0,N=0,L=!1,P=null,I=!1,Y=0,de=new Set,ue=new Map,pe="",ee="",oe=null,V,ae,ne,me,be=null,fe=null,Te=null;function Se(){let $=h("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),K=h("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(vr(K,m?.headerBar),i){fe=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),fe.style.cursor="help",be=h("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"),be.textContent="-- tok/s",Te=h("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 Ze=fe,fo=Te,mo=()=>{if(!fo.textContent)return;let Is=Ze.getBoundingClientRect(),Yt=$.getBoundingClientRect();fo.style.left=`${Is.left-Yt.left}px`,fo.style.top=`${Is.bottom-Yt.top+4}px`,fo.style.display="block"},wa=()=>{fo.style.display="none"};fe.addEventListener("mouseenter",mo),fe.addEventListener("mouseleave",wa),fe.appendChild(be)}let ce=h("div","persona-flex-1");V=h("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 Ke=h("option","");Ke.value="",Ke.textContent="All events (0)",V.appendChild(Ke),ae=h("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"),ae.type="button",ae.title="Copy All";let it=se("clipboard-copy","12px","currentColor",1.5);it&&ae.appendChild(it);let X=h("span","persona-event-copy-all persona-text-xs");X.textContent="Copy All",ae.appendChild(X),fe&&K.appendChild(fe),K.appendChild(ce),K.appendChild(V),K.appendChild(ae);let Ue=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");vr(Ue,m?.searchBar);let Ee=se("search","14px","var(--persona-muted, #9ca3af)",1.5),De=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Ee&&De.appendChild(Ee),ne=h("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"),vr(ne,m?.searchInput),ne.type="text",ne.placeholder="Search event payloads...",me=h("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 We=se("x","12px","currentColor",2);return We&&me.appendChild(We),Ue.appendChild(De),Ue.appendChild(ne),Ue.appendChild(me),$.appendChild(K),$.appendChild(Ue),Te&&$.appendChild(Te),$}let Fe,ke=s.find($=>$.renderEventStreamToolbar);ke?.renderEventStreamToolbar&&r?Fe=ke.renderEventStreamToolbar({config:r,defaultRenderer:()=>Se(),eventCount:e.getSize(),filteredCount:0,onFilterChange:K=>{B=K,Re(),we()},onSearchChange:K=>{E=K,Re(),we()}})??Se():Fe=Se();let Ve=h("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");Ve.style.display="none";function Je(){if(!i||!be||!fe)return;let $=i(),K=dv($);be.textContent=K;let ce=pv($);Te&&(Te.textContent=ce,ce||(Te.style.display="none")),fe.setAttribute("aria-label",ce?`Throughput: ${K}, ${ce}`:`Throughput: ${K}`)}let Ne=h("div","persona-flex-1 persona-min-h-0 persona-relative"),Pe=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Pe.style.height="100%";let Ye=h("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");vr(Ye,m?.scrollIndicator),Ye.style.display="none",Ye.setAttribute("data-persona-scroll-to-bottom-has-label",d?"true":"false");let ln=se(c,"14px","currentColor",2);ln&&Ye.appendChild(ln);let kt=h("span","");kt.textContent=d,Ye.appendChild(kt);let vt=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");vt.style.display="none",Ne.appendChild(Pe),Ne.appendChild(vt),Ne.appendChild(Ye),C.setAttribute("tabindex","0"),C.appendChild(Fe),C.appendChild(Ve),C.appendChild(Ne);function Oe(){let $=e.getAll(),K={};for(let Ue of $)K[Ue.type]=(K[Ue.type]||0)+1;let ce=Object.keys(K).sort(),Ke=ce.length!==W.length||!ce.every((Ue,Ee)=>Ue===W[Ee]),Ie=!Ke&&ce.some(Ue=>K[Ue]!==z[Ue]),it=$.length!==Object.values(z).reduce((Ue,Ee)=>Ue+Ee,0);if(!Ke&&!Ie&&!it||(W=ce,z=K,!V))return;let X=V.value;if(V.options[0].textContent=`All events (${$.length})`,Ke){for(;V.options.length>1;)V.remove(1);for(let Ue of ce){let Ee=h("option","");Ee.value=Ue,Ee.textContent=`${Ue} (${K[Ue]||0})`,V.appendChild(Ee)}X&&ce.includes(X)?V.value=X:X&&(V.value="",B="")}else for(let Ue=1;Ue<V.options.length;Ue++){let Ee=V.options[Ue];Ee.textContent=`${Ee.value} (${K[Ee.value]||0})`}}function Ce(){let $=e.getAll();if(B&&($=$.filter(K=>K.type===B)),E){let K=E.toLowerCase();$=$.filter(ce=>ce.type.toLowerCase().includes(K)||ce.payload.toLowerCase().includes(K))}return $}function Qe(){return B!==""||E!==""}function Re(){G=0,O=0,w.resume(),Ye.style.display="none"}function ye($){de.has($)?de.delete($):de.add($),oe=$;let K=Pe.scrollTop,ce=w.isFollowing();I=!0,w.pause(),we(),Pe.scrollTop=K,ce&&w.resume(),I=!1}function ge(){return uo(Pe,50)}function we(){N=Date.now(),L=!1,Je(),Oe();let $=e.getEvictedCount();$>0?(Ve.textContent=`${$.toLocaleString()} older events truncated`,Ve.style.display=""):Ve.style.display="none",D=Ce();let K=D.length,ce=e.getSize()>0;K===0&&ce&&Qe()?(vt.textContent=E?`No events matching '${E}'`:"No events matching filter",vt.style.display="",Pe.style.display="none"):(vt.style.display="none",Pe.style.display=""),ae&&(ae.title=Qe()?`Copy Filtered (${K})`:"Copy All"),p&&!w.isFollowing()&&K>G&&(O+=K-G,kt.textContent=d?`${d}${O>0?` (${O})`:""}`:"",Ye.style.display=""),G=K;let Ke=e.getAll(),Ie=Ke.length>0?Ke[0].timestamp:0,it=new Set(D.map(Ee=>Ee.id));for(let Ee of de)it.has(Ee)||de.delete(Ee);let X=B!==pe||E!==ee,Ue=ue.size===0&&D.length>0;if(X||Ue||D.length===0){Pe.innerHTML="",ue.clear();let Ee=document.createDocumentFragment();for(let De=0;De<D.length;De++){let We=lc(D[De],De,Ie,u,de,ye,s,r);ue.set(D[De].id,We),Ee.appendChild(We)}Pe.appendChild(Ee),pe=B,ee=E,oe=null}else{if(oe!==null){let De=ue.get(oe);if(De&&De.parentNode===Pe){let We=D.findIndex(Ze=>Ze.id===oe);if(We>=0){let Ze=lc(D[We],We,Ie,u,de,ye,s,r);Pe.insertBefore(Ze,De),De.remove(),ue.set(oe,Ze)}}oe=null}let Ee=new Set(D.map(De=>De.id));for(let[De,We]of ue)Ee.has(De)||(We.remove(),ue.delete(De));for(let De=0;De<D.length;De++){let We=D[De];if(!ue.has(We.id)){let Ze=lc(We,De,Ie,u,de,ye,s,r);ue.set(We.id,Ze),Pe.appendChild(Ze)}}}w.isFollowing()&&(Pe.scrollTop=Pe.scrollHeight)}function xt(){if(Date.now()-N>=ov){P!==null&&(cancelAnimationFrame(P),P=null),we();return}L||(L=!0,P=requestAnimationFrame(()=>{P=null,we()}))}let Ae=($,K)=>{if(!ae)return;ae.innerHTML="";let ce=se($,"12px","currentColor",1.5);ce&&ae.appendChild(ce);let Ke=h("span","persona-text-xs");Ke.textContent="Copy All",ae.appendChild(Ke),setTimeout(()=>{ae.innerHTML="";let Ie=se("clipboard-copy","12px","currentColor",1.5);Ie&&ae.appendChild(Ie);let it=h("span","persona-text-xs");it.textContent="Copy All",ae.appendChild(it),ae.disabled=!1},K)},he=async()=>{if(ae){ae.disabled=!0;try{let $;Qe()?$=D:n?($=await n(),$.length===0&&($=e.getAll())):$=e.getAll();let K=$.map(ce=>{try{return JSON.parse(ce.payload)}catch{return ce.payload}});await navigator.clipboard.writeText(JSON.stringify(K,null,2)),Ae("check",1500)}catch{Ae("x",1500)}}},hn=()=>{V&&(B=V.value,Re(),we())},te=()=>{!ne||!me||(me.style.display=ne.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{E=ne.value,Re(),we()},150))},k=()=>{!ne||!me||(ne.value="",E="",me.style.display="none",A&&clearTimeout(A),Re(),we())},j=()=>{if(I)return;let $=Pe.scrollTop,{action:K,nextLastScrollTop:ce}=ta({following:w.isFollowing(),currentScrollTop:$,lastScrollTop:Y,nearBottom:ge(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Y=ce,K==="resume"?(w.resume(),O=0,Ye.style.display="none"):K==="pause"&&(w.pause(),p&&(kt.textContent=d,Ye.style.display=""))},v=$=>{let K=na({following:w.isFollowing(),deltaY:$.deltaY,nearBottom:ge(),resumeWhenNearBottom:!0});K==="pause"?(w.pause(),p&&(kt.textContent=d,Ye.style.display="")):K==="resume"&&(w.resume(),O=0,Ye.style.display="none")},T=()=>{p&&(Pe.scrollTop=Pe.scrollHeight,w.resume(),O=0,Ye.style.display="none")},R=$=>{let K=$.target;if(!K||K.closest("button"))return;let ce=K.closest("[data-event-id]");if(!ce)return;let Ke=ce.getAttribute("data-event-id");Ke&&ye(Ke)},_=$=>{if(($.metaKey||$.ctrlKey)&&$.key==="f"){$.preventDefault(),ne?.focus(),ne?.select();return}$.key==="Escape"&&(ne&&document.activeElement===ne?(k(),ne.blur(),C.focus()):o&&o())};ae&&ae.addEventListener("click",he),V&&V.addEventListener("change",hn),ne&&ne.addEventListener("input",te),me&&me.addEventListener("click",k),Pe.addEventListener("scroll",j),Pe.addEventListener("wheel",v,{passive:!0}),Pe.addEventListener("click",R),Ye.addEventListener("click",T),C.addEventListener("keydown",_);function Q(){A&&clearTimeout(A),P!==null&&(cancelAnimationFrame(P),P=null),L=!1,ue.clear(),ae&&ae.removeEventListener("click",he),V&&V.removeEventListener("change",hn),ne&&ne.removeEventListener("input",te),me&&me.removeEventListener("click",k),Pe.removeEventListener("scroll",j),Pe.removeEventListener("wheel",v),Pe.removeEventListener("click",R),Ye.removeEventListener("click",T),C.removeEventListener("keydown",_)}return{element:C,update:xt,destroy:Q}}}nt();St();function _g(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=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let y=u;return s.findIndex(g=>g===y||g.contains(y))},c=u=>{let y=p(u.target);if(y<0)return;let g=y;if(u.key===r)g=Math.min(y+1,s.length-1);else if(u.key===o)g=Math.max(y-1,0);else if(u.key==="Home")g=0;else if(u.key==="End")g=s.length-1;else return;u.preventDefault(),g!==y&&e.onSelect(g)},d=u=>{let y=p(u.target);y>=0&&l(s[y])};return t.addEventListener("keydown",c),t.addEventListener("focusin",d),{beforeRender(){i=typeof document<"u"&&t.contains(document.activeElement)},render(u,y){if(s=u,u.forEach((g,m)=>{g.setAttribute("role","tab");let C=m===y;g.setAttribute("aria-selected",C?"true":"false"),g.tabIndex=C||y<0&&m===0?0:-1}),i){let g=(y>=0?u[y]:void 0)??u[0];g&&typeof g.focus=="function"&&(l(g),g.focus())}},destroy(){t.removeEventListener("keydown",c),t.removeEventListener("focusin",d)}}}function $g(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=te=>({start:te===!1?!1:typeof te=="object"&&te?te.start!==!1:!0,end:te===!1?!1:typeof te=="object"&&te?te.end!==!1:!0}),{start:d,end:u}=c(n?.tabFade),y=typeof document<"u"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{y?.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),I?.hide()};y&&y.addEventListener("click",()=>{g(),e.onDismiss?.()});let m=h("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");m.setAttribute("data-persona-theme-zone","artifact-pane"),r&&m.classList.add("persona-artifact-pane-document");let C=h("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 D=h("span","persona-text-xs persona-font-medium persona-truncate");D.textContent=s;let B=Bt({icon:"x",label:i});B.addEventListener("click",()=>{g(),e.onDismiss?.()});let E="rendered",A=Qi({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:te=>{E=te==="source"?"source":"rendered",Ae()}}),W=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),z=n?.documentToolbarShowCopyLabel===!0,G=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,O=!!(G&&w&&w.length>0),N=null,L,P=null,I=null;if(r&&(z||G)&&!O){if(L=z?Ho({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),G){let te=se("chevron-down",14,"currentColor",2);te&&L.appendChild(te)}}else r&&O?(N=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),L=z?Ho({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P=Bt({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"}}),N.append(L,P)):r?L=Bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(L=Bt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&L.classList.add("persona-hidden"));let Y=r?Bt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Bt({icon:"refresh-cw",label:"Refresh"}),de=r?Bt({icon:"x",label:i,className:"persona-artifact-doc-icon-btn"}):Bt({icon:"x",label:i}),ue=Bt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&ue.classList.add("persona-hidden");let pe=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ee=t.features?.artifacts?.toolbarActions??[],oe=()=>{let te=Ne.find(T=>T.id===Pe)??Ne[Ne.length-1],k=te?.id??null,j=te?.artifactType==="markdown"?te.markdown??"":"",v=te?JSON.stringify({component:te.component,props:te.props},null,2):"";return{markdown:j,jsonPayload:v,id:k}},V=async()=>{let te=Ne.find(k=>k.id===Pe)??Ne[Ne.length-1];try{await navigator.clipboard.writeText(ms(te))}catch{}};if(L.addEventListener("click",async()=>{let te=n?.onDocumentToolbarCopyMenuSelect;if(te&&O){let{markdown:k,jsonPayload:j,id:v}=oe();try{await te({actionId:"primary",artifactId:v,markdown:k,jsonPayload:j})}catch{}return}await V()}),P&&w?.length){let te=()=>m.closest("[data-persona-root]")??document.body,k=()=>{I=fr({items:w.map(j=>({id:j.id,label:j.label})),onSelect:async j=>{let{markdown:v,jsonPayload:T,id:R}=oe(),_=n?.onDocumentToolbarCopyMenuSelect;try{_?await _({actionId:j,artifactId:R,markdown:v,jsonPayload:T}):j==="markdown"||j==="md"?await navigator.clipboard.writeText(v):j==="json"||j==="source"?await navigator.clipboard.writeText(T):await navigator.clipboard.writeText(v||T)}catch{}},anchor:N??P,position:"bottom-right",portal:te()})};m.isConnected?k():requestAnimationFrame(k),P.addEventListener("click",j=>{j.stopPropagation(),I?.toggle()})}Y.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}Ae()}),de.addEventListener("click",()=>{g(),e.onDismiss?.()});let ae=h("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(),N?W.append(N,Y,de):W.append(L,Y,de),W.insertBefore(pe,de),W.insertBefore(ue,de),C.append(A.element,ae,W);else{let te=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");te.append(L,pe,ue,B),C.appendChild(D),C.appendChild(te)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let ne=h("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,be=h("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),fe=_g(ne,{onSelect:te=>e.onSelect(Ne[te].id)}),Te=te=>{let k=te.scrollWidth-te.clientWidth,j=k>1,v=Math.abs(te.scrollLeft);te.classList.toggle("persona-artifact-tab-fade-start",d&&j&&v>1),te.classList.toggle("persona-artifact-tab-fade-end",u&&j&&v<k-1)},Se=0,Fe=()=>{if(Se)return;let te=()=>{Se=0,Te(ne)};Se=typeof requestAnimationFrame=="function"?requestAnimationFrame(te):setTimeout(te,0)};ne.addEventListener("scroll",()=>Fe(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Te(ne)).observe(ne);let ke=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Ve=()=>{ke.scrollLeft=0},Je=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Ve):setTimeout(Ve,0)};if(l){for(let te of[ne,be])te.style.paddingLeft=l,te.style.paddingRight=l;ke.style.padding=l}m.appendChild(C),m.appendChild(ne),m.appendChild(be),m.appendChild(ke);let Ne=[],Pe=null,Ye=!1,ln=!1,kt=!0,vt=!1,Oe=null,Ce="",Qe=null,Re=!1,ye=te=>te.artifactType==="markdown"&&!!te.file||r?E:"rendered",ge=te=>{r||(te&&!Re?(C.insertBefore(A.element,D),Re=!0):!te&&Re&&(A.element.remove(),Re=!1))},we=()=>Pe&&Ne.find(te=>te.id===Pe)||Ne[Ne.length-1],xt=()=>{let te=gs(we());if(!te){pe.replaceChildren();return}let k=ee.filter(j=>j.visible===void 0||j.visible(te)).map(j=>mr(j,{documentChrome:r,onClick:()=>{let v=gs(we());if(v)try{Promise.resolve(j.onClick(v)).catch(()=>{})}catch{}}}));pe.replaceChildren(...k)},Ae=()=>{xt();let te=r&&Ne.length<=1,k=!!me;if(ne.classList.toggle("persona-hidden",te||k),be.classList.toggle("persona-hidden",te||!k),k&&me){let T=Ne.map(R=>R.id).join("|")+" "+(Pe??"");if(T!==Ce){Ce=T;let R=me({records:Ne,selectedId:Pe,onSelect:e.onSelect});be.firstElementChild!==R&&be.replaceChildren(R)}}else{fe.beforeRender(),ne.replaceChildren();let T=[],R=-1;for(let[_,Q]of Ne.entries()){let $=h("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");$.type="button";let K=Q.artifactType==="markdown"?Q.file:void 0,ce=K?kn(K.path):Q.title||Q.id.slice(0,8),Ke=K?.path||Q.title||ce;$.textContent=ce,$.title=Ke,$.setAttribute("aria-label",Ke),Q.id===Pe&&($.classList.add("persona-bg-persona-container","persona-border-persona-border"),R=_),$.addEventListener("click",()=>e.onSelect(Q.id)),ne.appendChild($),T.push($)}if(fe.render(T,R),R>=0&&Pe!==Oe){Oe=Pe;let _=T[R];typeof _.scrollIntoView=="function"&&_.scrollIntoView({block:"nearest",inline:"nearest"})}Te(ne)}let j=Pe&&Ne.find(T=>T.id===Pe)||Ne[Ne.length-1];if(!j){ke.replaceChildren(),Qe=null,ge(!1);return}let v=j.artifactType==="markdown"?j.file:void 0;if(ge(!!v),r){let T=v?lo(v):j.artifactType==="markdown"?"MD":j.component??"Component",R=(j.title||"Document").trim(),_=v?kn(v.path):R.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ae.textContent=`${_} \xB7 ${T}`}else D.textContent=v?kn(v.path):s;Qe?(Qe.el.parentElement!==ke&&ke.replaceChildren(Qe.el),Qe.update(j)):(Qe=Yi(j,{config:t,resolveViewMode:ye}),ke.replaceChildren(Qe.el)),ke.classList.toggle("persona-artifact-content-flush",!!ke.querySelector(".persona-code-pre"))},he=()=>{let te=Ne.length>0;if(m.classList.toggle("persona-hidden",!te),y){let v=((typeof m.closest=="function"?m.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;te&&v&&Ye?(y.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(y.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}},hn=()=>{vt=!1,Ae(),he()};return{element:m,backdrop:y,update(te){let k=te.selectedId??te.artifacts[te.artifacts.length-1]?.id??null,j=k!==Pe;Ne=te.artifacts,Pe=k,Ne.length>0&&(Ye=!0),vt=!0,kt&&hn(),j&&Ve()},setMobileOpen(te){Ye=te,!te&&y?(y.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):he()},setExpanded(te){te!==ln&&(ln=te,Je());let k=se(te?"minimize":"maximize",16,"currentColor",2);k&&ue.replaceChildren(k);let j=te?"Collapse artifacts panel":"Expand artifacts panel";ue.setAttribute("aria-label",j),ue.title=j},setExpandToggleVisible(te){ue.classList.toggle("persona-hidden",!te)},setCopyButtonVisible(te){r||L.classList.toggle("persona-hidden",!te)},setCustomActions(te){ee=te,xt()},setTabFade(te){let k=c(te);k.start===d&&k.end===u||(d=k.start,u=k.end,Te(ne))},setRenderTabBar(te){te!==me&&(me=te,Ce="",Ae())},setVisible(te){te!==kt&&(kt=te,te&&vt&&hn())}}}function Jt(t){return t?.features?.artifacts?.enabled===!0}function zg(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"),!Jt(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 gv(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 Ug=["panel","seamless","detached"];function cc(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&Ug.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function dc(t){return!t||!Jt(t)?!1:cc(t)==="detached"}function Es(t,e){if(!Jt(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-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),gv(t),zg(t,e);return}let n=e.features?.artifacts?.layout,o=cc(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?.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"),zg(t,e)}function ks(t,e){for(let l of Ug)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"),!Jt(e))return;let n=e.features?.artifacts?.layout,o=cc(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 jg(t,e){return!e||!Jt(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function fv(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 mv(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 hv(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function bv(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function pc(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 qg(t,e,n,o,r,s){let i=fv(r,200),l=bv(e,n,o,200);l=Math.max(i,l);let p=mv(s);return p!==null&&(l=Math.min(l,p)),hv(t,i,l)}nt();var Vg={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"}},uc=(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=Vg[i]??Vg.init;s.classList.add("persona-form-card","persona-space-y-4");let p=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=l.title,p.appendChild(c),l.description){let m=h("p","persona-text-sm persona-text-persona-muted");m.textContent=l.description,p.appendChild(m)}let d=document.createElement("form");d.className="persona-form-grid persona-space-y-3",l.fields.forEach(m=>{let C=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${e.id}-${i}-${m.name}`;let D=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");D.textContent=m.label,C.appendChild(D);let B=m.type??"text",E;B==="textarea"?(E=document.createElement("textarea"),E.rows=3):(E=document.createElement("input"),E.type=B),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}-${i}-${m.name}`,E.name=m.name,E.placeholder=m.placeholder??"",m.required&&(E.required=!0),C.appendChild(E),d.appendChild(C)});let u=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),y=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=h("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");g.type="submit",g.textContent=l.submitLabel??"Submit",u.appendChild(y),u.appendChild(g),d.appendChild(u),s.replaceChildren(p,d),d.addEventListener("submit",async m=>{m.preventDefault();let C=n.formEndpoint??"/form",D=new FormData(d),B={};D.forEach((E,A)=>{B[A]=E}),B.type=i,g.disabled=!0,y.textContent="Submitting\u2026";try{let E=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(B)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let A=await E.json();y.textContent=A.message??"Thanks! We'll be in touch soon.",A.success&&A.nextPrompt&&await o.sendMessage(String(A.nextPrompt))}catch(E){y.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var gc=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()}},fc=new gc;var Kg=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),yv=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.streamAnimation.plugins"]),Gg=(t,e,n)=>{if(!Kg(t)||!Kg(e)||yv.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]=Gg(t[r],e[r],s)}return o};function Qg(t,e){let n=Gg(t,e,"");return zi(n)}var Xg=()=>{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 vv=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},xv=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},hc=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=vv(t),n=xv(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}},mc=t=>typeof t=="string"?t:t==null?"":String(t),Ls={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:mc(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=mc(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:mc(n.text)}}},Jg=t=>Array.isArray(t)?t.map(e=>String(e)):[],bc=t=>{let e=new Set(Jg(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(Jg(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)},u=c(l,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:d});if(!u)continue;if(u.handled){let y=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:y,resubmit:u.resubmit}}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:n}};var Cv=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}},wv=t=>t.map(e=>({...e,streaming:!1})),Av=t=>t.map(e=>({...e,status:"complete"})),Yg=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?Cv(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?wv(n.messages):void 0,artifacts:n.artifacts?Av(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 yc=require("partial-json");function Zg(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=Un.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 ef(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 vc(t){let e=ef(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 tf(t){let e=ef(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 Sv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function nf(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=Sv}=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 u=null,y=document.createElement("div");y.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let m=document.createElement("h3");m.className="persona-feedback-title",m.textContent=o,g.appendChild(m);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,g.appendChild(C),y.appendChild(g);let D=document.createElement("div");D.className="persona-feedback-rating persona-feedback-rating-csat",D.setAttribute("role","radiogroup"),D.setAttribute("aria-label","Satisfaction rating from 1 to 5");let B=[];for(let G=1;G<=5;G++){let w=document.createElement("button");w.type="button",w.className="persona-feedback-rating-btn persona-feedback-star-btn",w.setAttribute("role","radio"),w.setAttribute("aria-checked","false"),w.setAttribute("aria-label",`${G} star${G>1?"s":""}: ${c[G-1]}`),w.title=c[G-1],w.dataset.rating=String(G),w.innerHTML=`
216
216
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
217
217
  <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
218
  </svg>
219
- `,w.addEventListener("click",()=>{u=G,B.forEach((O,N)=>{let L=N<G;O.classList.toggle("selected",L),O.setAttribute("aria-checked",N===G-1?"true":"false")})}),B.push(w),D.appendChild(w)}y.appendChild(D);let E=null;if(p){let G=document.createElement("div");G.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"),G.appendChild(E),y.appendChild(G)}let A=document.createElement("div");A.className="persona-feedback-actions";let W=document.createElement("button");W.type="button",W.className="persona-feedback-btn persona-feedback-btn-skip",W.textContent=l,W.addEventListener("click",()=>{n?.(),d.remove()});let z=document.createElement("button");return z.type="button",z.className="persona-feedback-btn persona-feedback-btn-submit",z.textContent=i,z.addEventListener("click",async()=>{if(u===null){D.classList.add("persona-feedback-shake"),setTimeout(()=>D.classList.remove("persona-feedback-shake"),500);return}z.disabled=!0,z.textContent="Submitting...";try{let G=E?.value.trim()||void 0;await e(u,G),d.remove()}catch(G){z.disabled=!1,z.textContent=i,console.error("[CSAT Feedback] Failed to submit:",G)}}),A.appendChild(W),A.appendChild(z),y.appendChild(A),d.appendChild(y),d}function of(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,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let y=null,g=document.createElement("div");g.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,m.appendChild(C);let D=document.createElement("p");D.className="persona-feedback-subtitle",D.textContent=r,m.appendChild(D),g.appendChild(m);let B=document.createElement("div");B.className="persona-feedback-rating persona-feedback-rating-nps",B.setAttribute("role","radiogroup"),B.setAttribute("aria-label","Likelihood rating from 0 to 10");let E=document.createElement("div");E.className="persona-feedback-labels";let A=document.createElement("span");A.className="persona-feedback-label-low",A.textContent=c;let W=document.createElement("span");W.className="persona-feedback-label-high",W.textContent=d,E.appendChild(A),E.appendChild(W);let z=document.createElement("div");z.className="persona-feedback-numbers";let G=[];for(let P=0;P<=10;P++){let I=document.createElement("button");I.type="button",I.className="persona-feedback-rating-btn persona-feedback-number-btn",I.setAttribute("role","radio"),I.setAttribute("aria-checked","false"),I.setAttribute("aria-label",`Rating ${P} out of 10`),I.textContent=String(P),I.dataset.rating=String(P),P<=6?I.classList.add("persona-feedback-detractor"):P<=8?I.classList.add("persona-feedback-passive"):I.classList.add("persona-feedback-promoter"),I.addEventListener("click",()=>{y=P,G.forEach((Y,de)=>{Y.classList.toggle("selected",de===P),Y.setAttribute("aria-checked",de===P?"true":"false")})}),G.push(I),z.appendChild(I)}B.appendChild(E),B.appendChild(z),g.appendChild(B);let w=null;if(p){let P=document.createElement("div");P.className="persona-feedback-comment-container",w=document.createElement("textarea"),w.className="persona-feedback-comment",w.placeholder=s,w.rows=3,w.setAttribute("aria-label","Additional comments"),P.appendChild(w),g.appendChild(P)}let O=document.createElement("div");O.className="persona-feedback-actions";let N=document.createElement("button");N.type="button",N.className="persona-feedback-btn persona-feedback-btn-skip",N.textContent=l,N.addEventListener("click",()=>{n?.(),u.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=i,L.addEventListener("click",async()=>{if(y===null){z.classList.add("persona-feedback-shake"),setTimeout(()=>z.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let P=w?.value.trim()||void 0;await e(y,P),u.remove()}catch(P){L.disabled=!1,L.textContent=i,console.error("[NPS Feedback] Failed to submit:",P)}}),O.appendChild(N),O.appendChild(L),g.appendChild(O),u.appendChild(g),u}var xr="persona-chat-history",Mv=30*1e3,Tv=641,Ev={"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 kv(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=Ev[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 xa(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 Lv(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 Pv(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var xc=t=>!t||typeof t!="object"?{}:{...t},rf=t=>t.map(e=>({...e,streaming:!1})),sf=(t,e,n)=>{let o=t?.markdown?ai(t.markdown):null,r=li(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=Nn()!==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?qd(i):i,u=o(d);c=r&&p?r(u):u}else c=oo(i);return c}};function af(t){let e=h("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=se(n,o,r,s);if(i&&e.appendChild(i),t?.label){let l=h("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var Iv=(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},Rv=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:Iv(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),lf=(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=zi(e),r=fc.getForInstance(o.plugins),{plugin:s,teardown:i}=Hg();o.components&&Un.registerAll(o.components);let l=Xg(),c=o.persistState===!1?null:o.storageAdapter??Yg(),d={},u=null,y=!1,g=a=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(a);if(f&&typeof f=="object"&&"state"in f){let{state:b,open:x}=f;return x&&(y=!0),b}return f}catch(f){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return a};if(c?.load)try{let a=c.load();if(a&&typeof a.then=="function")u=a.then(f=>g(f??{messages:[],metadata:{}}));else{let b=g(a??{messages:[],metadata:{}});b.metadata&&(d=xc(b.metadata)),b.messages?.length&&(o={...o,initialMessages:b.messages}),b.artifacts?.length&&(o={...o,initialArtifacts:b.artifacts,initialSelectedArtifactId:b.selectedArtifactId??null})}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=g({messages:[],metadata:{}});a.messages?.length&&(o={...o,initialMessages:a.messages})}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}let m=()=>d,C=a=>{d=a({...d})??{},Oa()},D=o.actionParsers&&o.actionParsers.length?o.actionParsers:[hc],B=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Ls.message,Ls.messageAndClick],E=bc({parsers:D,handlers:B,getSessionMetadata:m,updateSessionMetadata:C,emit:l.emit,documentRef:typeof document<"u"?document:null});E.syncFromMetadata();let A=o.launcher?.enabled??!0,W=o.launcher?.autoExpand??!1,z=o.autoFocusInput??!1,G=W,w=A,O=o.layout?.header?.layout,N=!1,L=()=>Cs(o),P=()=>A||L(),I=L()?!1:A?W:!0,Y=!1,de=null,ue=()=>{Y=!0,de&&clearTimeout(de),de=setTimeout(()=>{Y&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Y=!1)},1e4)},pe=sf(o,E,ue),ee=o.features?.showReasoning??!0,oe=o.features?.showToolCalls??!0,V=o.features?.showEventStreamToggle??!1,ae=o.features?.scrollToBottom??{},ne=o.features?.scrollBehavior??{},be=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,fe=V?new Ms(be):null,Te=o.features?.eventStream?.maxEvents??2e3,Se=V?new Ss(Te,fe):null,Fe=V?new Ts:null,ke=null,qe=!1,Xe=null,He=0;fe?.open().then(()=>Se?.restore()).catch(a=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",a)});let Le={onCopy:a=>{l.emit("message:copy",a),q?.isClientTokenMode()&&q.submitMessageFeedback(a.id,"copy").catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",f)}),o.messageActions?.onCopy?.(a)},onFeedback:a=>{l.emit("message:feedback",a),q?.isClientTokenMode()&&q.submitMessageFeedback(a.messageId,a.type).catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",f)}),o.messageActions?.onFeedback?.(a)}},Je=o.statusIndicator??{},ln=a=>a==="idle"?Je.idleText??Bt.idle:a==="connecting"?Je.connectingText??Bt.connecting:a==="connected"?Je.connectedText??Bt.connected:a==="error"?Je.errorText??Bt.error:a==="paused"?Je.pausedText??Bt.paused:a==="resuming"?Je.resumingText??Bt.resuming:Bt[a];function Lt(a,f,b,x){if(x==="idle"&&b.idleLink){a.textContent="";let S=document.createElement("a");S.href=b.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=f,S.style.color="inherit",S.style.textDecoration="none",a.appendChild(S)}else a.textContent=f}let xt=wg({config:o,showClose:P()}),{wrapper:Be,panel:Ce,pillRoot:Ge}=xt.shell,Ie=xt.panelElements,{container:ye,body:ge,messagesWrapper:we,suggestions:Ct,textarea:Ae,sendButton:he,sendButtonWrapper:hn,composerForm:te,statusText:k,introTitle:j,introSubtitle:v,closeButton:T,iconHolder:R,headerTitle:_,headerSubtitle:Q,header:$,footer:K,actionsRow:ce,rightActions:Ve}=Ie,Pe=Ie.leftActions,it=Ie.setSendButtonMode,X=Ie.micButton,ze=Ie.micButtonWrapper,Ee=Ie.attachmentButton,We=Ie.attachmentButtonWrapper,Re=Ie.attachmentInput,Ye=Ie.attachmentPreviewsContainer;ye.classList.add("persona-relative"),ge.classList.add("persona-relative");let fo=12,mo=()=>ae.label??"",wa=()=>ae.iconName??"arrow-down",Is=()=>ae.enabled!==!1,Yt=()=>ne.mode??"anchor-top",jn=()=>Yt()==="follow"||Yt()==="anchor-top"&&Pr,Ec=()=>ne.anchorTopOffset??16,Cf=()=>ne.restorePosition??"bottom",kc=()=>ne.pauseOnInteraction===!0,Lc=()=>ne.showActivityWhilePinned!==!1,Pc=()=>ne.announce===!0,It=h("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 wr=h("span","persona-flex persona-items-center"),Aa=h("span",""),ho=h("span","");ho.setAttribute("data-persona-scroll-to-bottom-count",""),ho.style.display="none",It.append(wr,Aa,ho),ye.appendChild(It);let qn=h("div","persona-stream-anchor-spacer");qn.setAttribute("aria-hidden","true"),qn.setAttribute("data-persona-anchor-spacer",""),qn.style.flexShrink="0",qn.style.pointerEvents="none",qn.style.height="0px",ge.appendChild(qn);let bo=h("div","persona-sr-only");bo.setAttribute("aria-live","polite"),bo.setAttribute("aria-atomic","true"),bo.setAttribute("role","status"),bo.setAttribute("data-persona-live-region",""),Object.assign(bo.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"}),ye.appendChild(bo);let Ar=null,Rs=null,Ic=a=>{!Pc()||!a||(Rs=a,Ar===null&&(Ar=setTimeout(()=>{Ar=null,Rs&&Pc()&&(bo.textContent=Rs),Rs=null},400)))},Fo=()=>{let f=K.style.display==="none"?0:K.offsetHeight;It.style.bottom=`${f+fo}px`};Fo();let Rc=()=>{let a=!!mo();It.setAttribute("aria-label",mo()||"Jump to latest"),It.title=mo(),It.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),wr.innerHTML="";let f=se(wa(),"14px","currentColor",2);f?(wr.appendChild(f),wr.style.display=""):wr.style.display="none",Aa.textContent=mo(),Aa.style.display=a?"":"none"};Rc();let Tt=null,tn=null,Wc=null,Hc=r.find(a=>a.renderHeader);if(Hc?.renderHeader){let a=Hc.renderHeader({config:o,defaultRenderer:()=>{let f=Bo({config:o,showClose:P()});return ws(ye,f,o),f.header},onClose:()=>ut(!1,"user")});if(a){let f=ye.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(a),$=a,xt.header.element=a)}}let Sa=()=>{if(!Se)return;if(qe=!0,!ke&&Se&&(ke=Fg({buffer:Se,getFullHistory:()=>Se.getAllFromStore(),onClose:()=>Sr(),config:o,plugins:r,getThroughput:()=>Fe?.getMetric()??{status:"idle"}})),ke&&(ge.style.display="none",K.parentNode?.insertBefore(ke.element,K),ke.update()),ot){ot.style.boxShadow=`inset 0 0 0 1.5px ${Xt.actionIconColor}`;let f=o.features?.eventStream?.classNames?.toggleButtonActive;f&&f.split(/\s+/).forEach(b=>b&&ot.classList.add(b))}let a=()=>{if(!qe)return;let f=Date.now();f-He>=200&&(ke?.update(),He=f),Xe=requestAnimationFrame(a)};He=0,Xe=requestAnimationFrame(a),on(),l.emit("eventStream:opened",{timestamp:Date.now()})},Sr=()=>{if(qe){if(qe=!1,ke&&ke.element.remove(),ge.style.display="",ot){ot.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(f=>f&&ot.classList.remove(f))}Xe!==null&&(cancelAnimationFrame(Xe),Xe=null),on(),l.emit("eventStream:closed",{timestamp:Date.now()})}},ot=null;if(V){let a=o.features?.eventStream?.classNames,f="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:"");ot=h("button",f),ot.style.width="28px",ot.style.height="28px",ot.style.color=Xt.actionIconColor,ot.type="button",ot.setAttribute("aria-label","Event Stream"),ot.title="Event Stream";let b=se("activity","18px","currentColor",1.5);b&&ot.appendChild(b);let x=Ie.clearChatButtonWrapper,S=Ie.closeButtonWrapper,H=x||S;H&&H.parentNode===$?$.insertBefore(ot,H):$.appendChild(ot),ot.addEventListener("click",()=>{qe?Sr():Sa()})}let wf=a=>{let f=o.attachments;if(!f?.enabled)return;let b=a.querySelector("[data-persona-composer-attachment-previews]")??a.querySelector(".persona-attachment-previews");if(!b){b=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.setAttribute("data-persona-composer-attachment-previews",""),b.style.display="none";let S=a.querySelector("[data-persona-composer-form]");S?.parentNode?S.parentNode.insertBefore(b,S):a.insertBefore(b,a.firstChild)}if(!(a.querySelector("[data-persona-composer-attachment-input]")??a.querySelector('input[type="file"]'))){let S=h("input");S.type="file",S.setAttribute("data-persona-composer-attachment-input",""),S.accept=(f.allowedTypes??$n).join(","),S.multiple=(f.maxFiles??4)>1,S.style.display="none",S.setAttribute("aria-label",f.buttonTooltipText??"Attach files"),a.appendChild(S)}},Bc=r.find(a=>a.renderComposer);if(Bc?.renderComposer){let a=o.composer,f=Bc.renderComposer({config:o,defaultRenderer:()=>ha({config:o}).footer,onSubmit:b=>{if(!q||q.isStreaming())return;let x=b.trim(),S=Tt?.hasAttachments()??!1;if(!x&&!S)return;dd();let H;S&&(H=[],H.push(...Tt.getContentParts()),x&&H.push(ir(x))),q.sendMessage(x,{contentParts:H}),S&&Tt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Re?.click()},models:a?.models,selectedModelId:a?.selectedModelId,onModelChange:b=>{o.composer={...o.composer,selectedModelId:b},o.agent&&(o.agent={...o.agent,model:b})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Wc?.()}:void 0});f&&(xt.replaceComposer(f),K=xt.composer.footer)}let Af=a=>{let f=(...ve)=>{for(let ie of ve){let Me=a.querySelector(ie);if(Me)return Me}return null},b=a.querySelector("[data-persona-composer-form]"),x=a.querySelector("[data-persona-composer-input]"),S=a.querySelector("[data-persona-composer-submit]"),H=a.querySelector("[data-persona-composer-mic]"),Z=a.querySelector("[data-persona-composer-status]");b&&(te=b),x&&(Ae=x),S&&(he=S),H&&(X=H,ze=H.parentElement),Z&&(k=Z);let U=f("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(Ct=U);let J=f("[data-persona-composer-attachment-button]",".persona-attachment-button");J&&(Ee=J,We=J.parentElement),Re=f("[data-persona-composer-attachment-input]",'input[type="file"]'),Ye=f("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let le=f("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");le&&(ce=le),Pe=f(".persona-widget-composer__left-actions")};wf(K),Af(K);let Vn=o.layout?.contentMaxWidth??(L()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Vn&&(we.style.maxWidth=Vn,we.style.marginLeft="auto",we.style.marginRight="auto",we.style.width="100%"),Vn&&te&&!L()&&(te.style.maxWidth=Vn,te.style.marginLeft="auto",te.style.marginRight="auto"),Vn&&Ct&&!L()&&(Ct.style.maxWidth=Vn,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),Vn&&Ye&&!L()&&(Ye.style.maxWidth=Vn,Ye.style.marginLeft="auto",Ye.style.marginRight="auto"),o.attachments?.enabled&&Re&&Ye){Tt=os.fromConfig(o.attachments),Tt.setPreviewsContainer(Ye),Re.addEventListener("change",b=>{let x=b.target;Tt?.handleFileSelect(x.files),x.value=""});let a=o.attachments.dropOverlay,f=af(a);ye.appendChild(f)}let Sf=()=>tn?.prefetch();if(o.contextMentions?.enabled&&Ae&&(tn=Lu({config:o,textarea:Ae,anchor:te??Ae,getMessages:()=>q.getMessages(),liveRegionHost:ye}),tn)){let a=Ae;a.parentElement?.insertBefore(tn.contextRow,a);let f=tn.affordanceButtons;for(let b=f.length-1;b>=0;b--){let x=f[b];Pe?Pe.insertBefore(x,Pe.firstChild):te?.appendChild(x)}}(()=>{let a=o.layout?.slots??{},f=x=>{switch(x){case"body-top":return ye.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return we;case"footer-top":return Ct;case"composer":return te;case"footer-bottom":return k;default:return null}},b=(x,S)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")$.insertBefore(S,$.firstChild);else if(x==="header-right")$.appendChild(S);else{let H=$.querySelector(".persona-flex-col");H?H.parentNode?.insertBefore(S,H.nextSibling):$.appendChild(S)}break;case"body-top":{let H=ge.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.replaceWith(S):ge.insertBefore(S,ge.firstChild);break}case"body-bottom":ge.appendChild(S);break;case"footer-top":Ct.replaceWith(S);break;case"footer-bottom":k.replaceWith(S);break;default:break}};for(let[x,S]of Object.entries(a))if(S)try{let H=S({config:o,defaultContent:()=>f(x)});H&&b(x,H)}catch(H){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,H)}})();let Dc=a=>{let b=a.target.closest('button[data-expand-header="true"]');if(!b)return;let x=b.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let S=x.getAttribute("data-message-id");if(!S)return;let H=b.getAttribute("data-bubble-type");if(H==="reasoning")br.has(S)?br.delete(S):br.add(S),Eg(S,x);else if(H==="tool")yr.has(S)?yr.delete(S):yr.add(S),kg(S,x,o);else if(H==="approval"){let U=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",J=Do.get(S)??U;Do.set(S,!J),Rg(S,x,o)}Co.delete(S)};we.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Dc(a))}),we.addEventListener("keydown",a=>{let f=a.target;(a.key==="Enter"||a.key===" ")&&f.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Dc(a))}),we.addEventListener("copy",a=>{let{clipboardData:f}=a;if(!f)return;let b=we.getRootNode(),x=typeof b.getSelection=="function"?b.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let S=x.toString(),H=rg(S);!H||H===S||(f.setData("text/plain",H),a.preventDefault())});let Ma=new Map,Nc=null,Oc="idle",Mf={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Tf=(a,f)=>{let{icon:b,label:x}=Mf[f];a.setAttribute("aria-label",x),a.title=x,a.setAttribute("aria-pressed",f==="idle"?"false":"true"),a.classList.toggle("persona-message-action-active",f!=="idle"),a.classList.toggle("persona-message-action-loading",f==="loading");let S=se(b,14,"currentColor",2);S&&(a.innerHTML="",a.appendChild(S))},Fc=()=>{we.querySelectorAll('[data-action="read-aloud"]').forEach(f=>{let x=f.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Tf(f,x&&x===Nc?Oc:"idle")})};we.addEventListener("click",a=>{let b=a.target.closest(".persona-message-action-btn[data-action]");if(!b)return;a.preventDefault(),a.stopPropagation();let x=b.closest("[data-actions-for]");if(!x)return;let S=x.getAttribute("data-actions-for");if(!S)return;let H=b.getAttribute("data-action");if(H==="copy"){let U=q.getMessages().find(J=>J.id===S);if(U&&Le.onCopy){let J=U.content||"";navigator.clipboard.writeText(J).then(()=>{b.classList.add("persona-message-action-success");let le=se("check",14,"currentColor",2);le&&(b.innerHTML="",b.appendChild(le)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let ve=se("copy",14,"currentColor",2);ve&&(b.innerHTML="",b.appendChild(ve))},2e3)}).catch(le=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",le)}),Le.onCopy(U)}}else if(H==="read-aloud")q.toggleReadAloud(S);else if(H==="upvote"||H==="downvote"){let U=(Ma.get(S)??null)===H,J=H==="upvote"?"thumbs-up":"thumbs-down";if(U){Ma.delete(S),b.classList.remove("persona-message-action-active");let le=se(J,14,"currentColor",2);le&&(b.innerHTML="",b.appendChild(le))}else{let le=H==="upvote"?"downvote":"upvote",ve=x.querySelector(`[data-action="${le}"]`);if(ve){ve.classList.remove("persona-message-action-active");let rt=se(le==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);rt&&(ve.innerHTML="",ve.appendChild(rt))}Ma.set(S,H),b.classList.add("persona-message-action-active");let ie=se(J,14,"currentColor",2);ie&&(ie.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(ie)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let je=q.getMessages().find(gt=>gt.id===S);je&&Le.onFeedback&&Le.onFeedback({type:H,messageId:je.id,message:je})}}}),we.addEventListener("click",a=>{let b=a.target.closest("button[data-approval-action]");if(!b)return;a.preventDefault(),a.stopPropagation();let x=b.closest(".persona-approval-bubble");if(!x)return;let S=x.getAttribute("data-message-id");if(!S)return;let H=b.getAttribute("data-approval-action");if(!H)return;let Z=H==="approve"?"approved":"denied",J=q.getMessages().find(ve=>ve.id===S);if(!J?.approval)return;let le=x.querySelector("[data-approval-buttons]");le&&le.querySelectorAll("button").forEach(ie=>{ie.disabled=!0,ie.style.opacity="0.5",ie.style.cursor="not-allowed"}),J.approval.toolType==="webmcp"?q.resolveWebMcpApproval(S,Z):q.resolveApproval(J.approval,Z)});let Ze=null,Mr=null,Tr=()=>{},Er="none",Ws=null,bn={artifacts:[],selectedId:null},Pn=!1,yn=!1,kr=!1,_o=!1,_c=()=>_o||bn.artifacts.some(a=>Lo(o.features?.artifacts,a.artifactType)==="panel"),Hs=()=>bn.artifacts.length>0&&!Pn&&_c(),dt={current:null},Ta=(a,f)=>{let b=q.getArtifactById(f),x=b?.markdown,S=b?.title||"artifact",H=b?.file,Z=b?.artifactType??"markdown";if(!x){let le=a.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(le){let ie=q.getMessages().find(Me=>Me.id===le);if(ie?.rawContent)try{let Me=JSON.parse(ie.rawContent);x=Me?.props?.markdown,S=Me?.props?.title||S,Me?.props?.file&&typeof Me.props.file=="object"&&(H=Me.props.file),!b&&typeof Me?.props?.artifactType=="string"&&(Z=Me.props.artifactType)}catch{}}}return{markdown:x,title:S,file:H,artifactType:Z}};we.addEventListener("click",a=>{let b=a.target.closest("[data-download-artifact]");if(!b)return;a.preventDefault(),a.stopPropagation();let x=b.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:H,title:Z,file:U}=Ta(b,x);if(!H)return;let{filename:J,mime:le,content:ve}=Fu({title:Z,markdown:H,file:U}),ie=new Blob([ve],{type:le}),Me=URL.createObjectURL(ie),je=document.createElement("a");je.href=Me,je.download=J,je.click(),URL.revokeObjectURL(Me)}),we.addEventListener("click",a=>{let b=a.target.closest("[data-artifact-custom-action]");if(!b)return;a.preventDefault(),a.stopPropagation();let x=b.getAttribute("data-artifact-custom-action");if(!x)return;let S=b.closest("[data-artifact-inline]"),H=S?null:b.closest("[data-open-artifact]"),Z=S?S.getAttribute("data-artifact-inline"):H?.getAttribute("data-open-artifact")??null,J=(S?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(gt=>gt.id===x);if(!J)return;let{markdown:le,title:ve,file:ie,artifactType:Me}=Ta(b,Z??""),je={artifactId:Z,title:ve,artifactType:Me,markdown:le,file:ie};try{Promise.resolve(J.onClick(je)).catch(()=>{})}catch{}}),we.addEventListener("click",a=>{let b=a.target.closest("[data-copy-artifact]");if(!b)return;a.preventDefault(),a.stopPropagation();let x=b.getAttribute("data-copy-artifact");if(!x)return;let S=q.getArtifactById(x),H="";if(S)H=ms(S);else{let{markdown:Z,file:U,artifactType:J}=Ta(b,x);J==="markdown"&&(H=ms({id:x,artifactType:"markdown",status:"complete",markdown:Z??"",...U?{file:U}:{}}))}H&&navigator.clipboard.writeText(H).then(()=>{let Z=se("check",16,"currentColor",2);Z&&(b.replaceChildren(Z),setTimeout(()=>{let U=se("copy",16,"currentColor",2);U&&b.replaceChildren(U)},1500))}).catch(()=>{})}),we.addEventListener("click",a=>{let b=a.target.closest("[data-expand-artifact-inline]");if(!b)return;a.preventDefault(),a.stopPropagation();let x=b.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(Pn=!1,_o=!0,yn=!0,kr=!0,q.selectArtifact(x),In())}),we.addEventListener("click",a=>{let f=a.target;if(f.closest("[data-download-artifact]")||f.closest("[data-artifact-custom-action]"))return;let b=f.closest("[data-open-artifact]");if(!b)return;let x=b.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(a.preventDefault(),a.stopPropagation(),Pn=!1,_o=!0,q.selectArtifact(x),In())}),we.addEventListener("keydown",a=>{if(a.key!=="Enter"&&a.key!==" ")return;let f=a.target;!f.hasAttribute("data-open-artifact")&&!f.hasAttribute("data-expand-artifact-inline")||(a.preventDefault(),f.click())});let $o=Ie.composerOverlay,zo=(a,f,b)=>{let x=f.trim();if(!x||!dt.current)return;let S=a.getAttribute("data-tool-call-id")??"",H=b.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:x,answers:b.structured,values:b.values??(b.source==="multi"?x.split(", "):[x]),isFreeText:H,source:b.source},bubbles:!0,composed:!0})),or($o,S);let Z=dt.current.getMessages().find(U=>U.toolCall?.id===S);Z?.agentMetadata?.awaitingLocalTool?dt.current.resolveAskUserQuestion(Z,b.structured??x):dt.current.sendMessage(x)},yo=a=>{let f=dt.current;if(!f)return;let b=a.getAttribute("data-tool-call-id")??"",x=f.getMessages().find(S=>S.toolCall?.id===b);x&&f.persistAskUserQuestionProgress(x,{answers:ui(a,x),currentIndex:fn(a)})},$c=a=>Object.entries(a).map(([f,b])=>`${f}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),Ea=a=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let f=fn(a),b=nr(a);if(f>=b-1)return;let x=dt.current?.getMessages().find(S=>S.toolCall?.id===a.getAttribute("data-tool-call-id"));x&&(fi(a,x,o,f+1),yo(a))};$o.addEventListener("click",a=>{let b=a.target.closest("[data-ask-user-action]");if(!b)return;let x=b.closest("[data-persona-ask-sheet-for]");if(!x)return;let S=b.getAttribute("data-ask-user-action");if(a.preventDefault(),a.stopPropagation(),S==="dismiss"){let H=x.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:H},bubbles:!0,composed:!0})),or($o,H);let Z=dt.current?.getMessages().find(U=>U.toolCall?.id===H);Z?.agentMetadata?.awaitingLocalTool&&(dt.current?.markAskUserQuestionResolved(Z),dt.current?.resolveAskUserQuestion(Z,"(dismissed)"));return}if(S==="pick"){let H=b.getAttribute("data-option-label");if(!H)return;let Z=x.getAttribute("data-multi-select")==="true",U=so(x);if(U&&Z){let J=Io(x)[fn(x)],le=new Set(Array.isArray(J)?J:[]);le.has(H)?le.delete(H):le.add(H),io(x,Array.from(le)),yo(x);return}if(U){io(x,H),yo(x),Ea(x);return}if(Z){let J=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",J?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!J);let le=x.querySelector('[data-ask-user-action="submit-multi"]');le&&(le.disabled=pl(x).length===0);return}zo(x,H,{source:"pick",values:[H]});return}if(S==="submit-multi"){let H=pl(x);if(H.length===0)return;zo(x,H.join(", "),{source:"multi",values:H});return}if(S==="open-free-text"){let H=x.querySelector('[data-ask-free-text-row="true"]');H&&(H.classList.remove("persona-hidden"),H.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(S==="focus-free-text"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(S==="submit-free-text"){let Z=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!Z.trim())return;if(so(x)){io(x,Z.trim()),yo(x),Ea(x);return}zo(x,Z,{source:"free-text"});return}if(S==="next"||S==="back"){if(!dt.current)return;let H=x.getAttribute("data-tool-call-id")??"",Z=dt.current.getMessages().find(ie=>ie.toolCall?.id===H);if(!Z)return;let J=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(J){let ie=Io(x)[fn(x)];(typeof ie!="string"||ie!==J)&&io(x,J)}let le=S==="next"?1:-1,ve=fn(x)+le;fi(x,Z,o,ve),yo(x);return}if(S==="submit-all"){if(!dt.current)return;let H=x.getAttribute("data-tool-call-id")??"",Z=dt.current.getMessages().find(ie=>ie.toolCall?.id===H);if(!Z)return;let J=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";J&&io(x,J);let le=ui(x,Z);dt.current.persistAskUserQuestionProgress(Z,{answers:le,currentIndex:fn(x)});let ve=$c(le);zo(x,ve||"(submitted)",{source:"submit-all",structured:le});return}if(S==="skip"){if(!dt.current)return;let H=x.getAttribute("data-tool-call-id")??"",Z=dt.current.getMessages().find(Me=>Me.toolCall?.id===H);if(!Z)return;let U=so(x),J=fn(x),le=nr(x),ve=J>=le-1;if(!U){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:H},bubbles:!0,composed:!0})),or($o,H),Z.agentMetadata?.awaitingLocalTool&&(dt.current.markAskUserQuestionResolved(Z),dt.current.resolveAskUserQuestion(Z,"(dismissed)"));return}io(x,"");let ie=x.querySelector('[data-ask-free-text-input="true"]');if(ie&&(ie.value=""),ve){let Me=ui(x,Z),je=$c(Me);zo(x,je||"(skipped)",{source:"submit-all",structured:Me});return}fi(x,Z,o,J+1),yo(x);return}}),$o.addEventListener("keydown",a=>{if(a.key!=="Enter")return;let b=a.target;if(!b.matches?.('[data-ask-free-text-input="true"]'))return;let x=b.closest("[data-persona-ask-sheet-for]");if(!x)return;a.preventDefault();let S=b.value;if(S.trim()){if(so(x)){io(x,S.trim()),yo(x),Ea(x);return}zo(x,S,{source:"free-text"})}});let zc=a=>{if(!/^[1-9]$/.test(a.key)||a.metaKey||a.ctrlKey||a.altKey)return;let f=a.target;if(f?.tagName==="INPUT"||f?.tagName==="TEXTAREA"||f?.isContentEditable)return;let b=$o.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let x=Number(a.key),H=b.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];H&&(a.preventDefault(),H.click())};document.addEventListener("keydown",zc);let Kn=null,wt=null,Lr=null,Bs=null,ka=()=>{},Uc=!1,Ds="",Ns="";function La(){Bs?.(),Bs=null}let jc=()=>{if(!Kn||!wt)return;let a=t.classList.contains("persona-artifact-welded-split"),f=t.ownerDocument.defaultView??window,b=f.innerWidth<=640;if(!a||t.classList.contains("persona-artifact-narrow-host")||b){wt.style.removeProperty("position"),wt.style.removeProperty("left"),wt.style.removeProperty("top"),wt.style.removeProperty("bottom"),wt.style.removeProperty("width"),wt.style.removeProperty("z-index");return}let x=Kn.firstElementChild;if(!x||x===wt)return;let S=10;wt.style.position="absolute",wt.style.top="0",wt.style.bottom="0",wt.style.width=`${S}px`,wt.style.zIndex="5";let H=pc(Kn,f),Z=x.offsetWidth+H/2-S/2;wt.style.left=`${Math.max(0,Z)}px`},Os=()=>{},Ef=()=>{let a=t.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640;return!f||a.innerWidth>b?!1:A||Ot(o)},Fs=()=>!Jt(o)||!Hs()||t.classList.contains("persona-artifact-narrow-host")||Ef()||(t.ownerDocument.defaultView??window).innerWidth<Tv?"none":dc(o)?"detached":"welded",In=()=>{if(!Ze||!Jt(o))return;Es(t,o),ks(t,o),Os();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,f=Ce.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",f>0&&f<=a);let b=Hs();Ze.setVisible(b),Ze.update(bn),Pn?(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),Ze.backdrop?.classList.add("persona-hidden"),yn=!1,kr=!1):bn.artifacts.length>0&&_c()?(Ze.element.classList.remove("persona-hidden"),Ze.setMobileOpen(!0)):(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),Ze.backdrop?.classList.add("persona-hidden"),yn=!1,kr=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ze.setExpandToggleVisible(x),Ze.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ze.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ze.setTabFade(o.features?.artifacts?.layout?.tabFade),Ze.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!kr&&(yn=!1),yn!==Uc){let H=Ze.element;yn?(Ds=H.style.width,Ns=H.style.maxWidth,H.style.removeProperty("width"),H.style.removeProperty("max-width")):(Ds&&(H.style.width=Ds),Ns&&(H.style.maxWidth=Ns),Ds="",Ns=""),Uc=yn}t.classList.toggle("persona-artifact-expanded",yn),Ze.setExpanded(yn);let S=Fs();S!==Er&&(Er=S,Tr()),ka()};if(Jt(o)){Ce.style.position="relative";let a=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");a.appendChild(ye),Ze=$g(o,{onSelect:b=>dt.current?.selectArtifact(b),onDismiss:()=>{Pn=!0,In()},onToggleExpand:()=>{let b=!yn,x=bn.selectedId??bn.artifacts[bn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:b})!==!0&&(yn=b,b||(kr=!1),In())}}),Ze.element.classList.add("persona-hidden"),Kn=f,f.appendChild(a),f.appendChild(Ze.element),Ze.backdrop&&Ce.appendChild(Ze.backdrop),Ce.appendChild(f),ka=()=>{if(!Kn||!Ze)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Lr?.(),Lr=null,La(),wt&&(wt.remove(),wt=null),Ze.element.style.removeProperty("width"),Ze.element.style.removeProperty("maxWidth");return}if(!wt){let x=h("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 S=t.ownerDocument,H=S.defaultView??window,Z=U=>{if(!Ze||U.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||H.innerWidth<=640)return;U.preventDefault(),La();let J=U.clientX,le=Ze.element.getBoundingClientRect().width,ve=o.features?.artifacts?.layout,ie=je=>{let gt=Kn.getBoundingClientRect().width,rt=t.classList.contains("persona-artifact-welded-split"),rn=pc(Kn,H),Et=rt?0:x.getBoundingClientRect().width||6,Wt=le-(je.clientX-J),F=qg(Wt,gt,rn,Et,ve?.resizableMinWidth,ve?.resizableMaxWidth);Ze.element.style.width=`${F}px`,Ze.element.style.maxWidth="none",jc()},Me=()=>{S.removeEventListener("pointermove",ie),S.removeEventListener("pointerup",Me),S.removeEventListener("pointercancel",Me),Bs=null;try{x.releasePointerCapture(U.pointerId)}catch{}};Bs=Me,S.addEventListener("pointermove",ie),S.addEventListener("pointerup",Me),S.addEventListener("pointercancel",Me);try{x.setPointerCapture(U.pointerId)}catch{}};x.addEventListener("pointerdown",Z),wt=x,Kn.insertBefore(x,Ze.element),Lr=()=>{x.removeEventListener("pointerdown",Z)}}if(wt){let x=Hs();wt.classList.toggle("persona-hidden",!x),jc()}},Os=()=>{if(!A||!Ze||(o.launcher?.sidebarMode??!1)||Ot(o)&&mn(o).reveal==="emerge")return;let x=t.ownerDocument.defaultView??window,S=o.launcher?.mobileFullscreen??!0,H=o.launcher?.mobileBreakpoint??640;if(S&&x.innerWidth<=H||!jg(o,A))return;let Z=o.launcher?.width??o.launcherWidth??zn,U=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Hs()?(Ce.style.width=U,Ce.style.maxWidth=U):(Ce.style.width=Z,Ce.style.maxWidth=Z)},typeof ResizeObserver<"u"&&(Mr=new ResizeObserver(()=>{In()}),Mr.observe(Ce))}else Ce.appendChild(ye);L()&&Ge&&(Ie.peekBanner&&Ge.appendChild(Ie.peekBanner),Ge.appendChild(K)),t.appendChild(Be),Ge&&t.appendChild(Ge);let _s=()=>{if(L()){Ce.style.width="100%",Ce.style.maxWidth="100%";let Pt=o.launcher?.composerBar??{},en=Be.dataset.state==="expanded",ei=Pt.expandedSize??"anchored";if(!(en&&ei!=="fullscreen")){ye.style.background="",ye.style.border="",ye.style.borderRadius="",ye.style.overflow="",ye.style.boxShadow="";return}let jr=o.theme?.components?.panel,ti=pr(o),Xo=(Bn,ko)=>Bn==null||Bn===""?ko:Qt(ti,Bn)??Bn,ni="1px solid var(--persona-border)",el="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Eo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ye.style.background="var(--persona-surface, #ffffff)",ye.style.border=Xo(jr?.border,ni),ye.style.borderRadius=Xo(jr?.borderRadius,Eo),ye.style.boxShadow=Xo(jr?.shadow,el),ye.style.overflow="hidden";return}let a=Ot(o),f=o.launcher?.sidebarMode??!1,b=a||f||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,S=o.launcher?.detachedPanel===!0,H=o.theme?.components?.panel,Z=pr(o),U=(Pt,en)=>Pt==null||Pt===""?en:Qt(Z,Pt)??Pt,J=t.ownerDocument.defaultView??window,le=o.launcher?.mobileFullscreen??!0,ve=o.launcher?.mobileBreakpoint??640,ie=J.innerWidth<=ve,Me=le&&ie&&A,je=a&&le&&ie,gt=o.launcher?.position??"bottom-left",rt=gt==="bottom-left"||gt==="top-left",rn=o.launcher?.zIndex??qt,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)))",F="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",De=S&&!Me&&!je;De?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let Ne=De?Et:f||Me?"none":Et,$e=De?Wt:Me?"none":f?rt?"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&&!Me&&!De&&($e="none",Ne="none");let kt=De?F:f||Me?"0":F,ft=U(H?.border,Ne),Kt=U(H?.shadow,$e),mt=U(H?.borderRadius,kt),Zt=Fs(),Ht=Zt==="detached",Oe=Zt==="welded";t.classList.toggle("persona-artifact-detached-split",Ht),t.classList.toggle("persona-artifact-welded-split",Oe);let nt="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)))))",at=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Jt(o)&&dc(o)&&x&&!a;t.classList.toggle("persona-artifact-chat-flush",at);let pt=Ht||at?"none":Kt,ht=Ht?Et:Oe?"none":ft,et=Ht?F:mt;at&&(ht="none",et="0");let _e=H?.borderRadius!=null&&H.borderRadius!=="",vt=at&&!_e?"0":mt,zt=ge.scrollTop;t.style.cssText="",Be.style.cssText="",Ce.style.cssText="",ye.style.cssText="",ge.style.cssText="",K.style.cssText="",qe&&(ge.style.display="none"),(b||x)&&(t.style.minWidth="0");let gn=()=>{if(zt<=0)return;(ge.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ge.scrollTop===zt)return;let en=ge.scrollHeight-ge.clientHeight;en<=0||(ge.scrollTop=Math.min(zt,en))})};if(Me){Be.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"),Be.style.cssText=`
219
+ `,w.addEventListener("click",()=>{u=G,B.forEach((O,N)=>{let L=N<G;O.classList.toggle("selected",L),O.setAttribute("aria-checked",N===G-1?"true":"false")})}),B.push(w),D.appendChild(w)}y.appendChild(D);let E=null;if(p){let G=document.createElement("div");G.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"),G.appendChild(E),y.appendChild(G)}let A=document.createElement("div");A.className="persona-feedback-actions";let W=document.createElement("button");W.type="button",W.className="persona-feedback-btn persona-feedback-btn-skip",W.textContent=l,W.addEventListener("click",()=>{n?.(),d.remove()});let z=document.createElement("button");return z.type="button",z.className="persona-feedback-btn persona-feedback-btn-submit",z.textContent=i,z.addEventListener("click",async()=>{if(u===null){D.classList.add("persona-feedback-shake"),setTimeout(()=>D.classList.remove("persona-feedback-shake"),500);return}z.disabled=!0,z.textContent="Submitting...";try{let G=E?.value.trim()||void 0;await e(u,G),d.remove()}catch(G){z.disabled=!1,z.textContent=i,console.error("[CSAT Feedback] Failed to submit:",G)}}),A.appendChild(W),A.appendChild(z),y.appendChild(A),d.appendChild(y),d}function of(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,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let y=null,g=document.createElement("div");g.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,m.appendChild(C);let D=document.createElement("p");D.className="persona-feedback-subtitle",D.textContent=r,m.appendChild(D),g.appendChild(m);let B=document.createElement("div");B.className="persona-feedback-rating persona-feedback-rating-nps",B.setAttribute("role","radiogroup"),B.setAttribute("aria-label","Likelihood rating from 0 to 10");let E=document.createElement("div");E.className="persona-feedback-labels";let A=document.createElement("span");A.className="persona-feedback-label-low",A.textContent=c;let W=document.createElement("span");W.className="persona-feedback-label-high",W.textContent=d,E.appendChild(A),E.appendChild(W);let z=document.createElement("div");z.className="persona-feedback-numbers";let G=[];for(let P=0;P<=10;P++){let I=document.createElement("button");I.type="button",I.className="persona-feedback-rating-btn persona-feedback-number-btn",I.setAttribute("role","radio"),I.setAttribute("aria-checked","false"),I.setAttribute("aria-label",`Rating ${P} out of 10`),I.textContent=String(P),I.dataset.rating=String(P),P<=6?I.classList.add("persona-feedback-detractor"):P<=8?I.classList.add("persona-feedback-passive"):I.classList.add("persona-feedback-promoter"),I.addEventListener("click",()=>{y=P,G.forEach((Y,de)=>{Y.classList.toggle("selected",de===P),Y.setAttribute("aria-checked",de===P?"true":"false")})}),G.push(I),z.appendChild(I)}B.appendChild(E),B.appendChild(z),g.appendChild(B);let w=null;if(p){let P=document.createElement("div");P.className="persona-feedback-comment-container",w=document.createElement("textarea"),w.className="persona-feedback-comment",w.placeholder=s,w.rows=3,w.setAttribute("aria-label","Additional comments"),P.appendChild(w),g.appendChild(P)}let O=document.createElement("div");O.className="persona-feedback-actions";let N=document.createElement("button");N.type="button",N.className="persona-feedback-btn persona-feedback-btn-skip",N.textContent=l,N.addEventListener("click",()=>{n?.(),u.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=i,L.addEventListener("click",async()=>{if(y===null){z.classList.add("persona-feedback-shake"),setTimeout(()=>z.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let P=w?.value.trim()||void 0;await e(y,P),u.remove()}catch(P){L.disabled=!1,L.textContent=i,console.error("[NPS Feedback] Failed to submit:",P)}}),O.appendChild(N),O.appendChild(L),g.appendChild(O),u.appendChild(g),u}var xr="persona-chat-history",Mv=30*1e3,Tv=641,Ev={"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 kv(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=Ev[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 xa(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 Lv(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 Pv(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var xc=t=>!t||typeof t!="object"?{}:{...t},rf=t=>t.map(e=>({...e,streaming:!1})),sf=(t,e,n)=>{let o=t?.markdown?ai(t.markdown):null,r=li(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=Nn()!==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?qd(i):i,u=o(d);c=r&&p?r(u):u}else c=oo(i);return c}};function af(t){let e=h("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=se(n,o,r,s);if(i&&e.appendChild(i),t?.label){let l=h("span","persona-drop-overlay-label");l.textContent=t.label,e.appendChild(l)}return e}var Iv=(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},Rv=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:Iv(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),lf=(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=zi(e),r=fc.getForInstance(o.plugins),{plugin:s,teardown:i}=Hg();o.components&&Un.registerAll(o.components);let l=Xg(),c=o.persistState===!1?null:o.storageAdapter??Yg(),d={},u=null,y=!1,g=a=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(a);if(f&&typeof f=="object"&&"state"in f){let{state:b,open:x}=f;return x&&(y=!0),b}return f}catch(f){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return a};if(c?.load)try{let a=c.load();if(a&&typeof a.then=="function")u=a.then(f=>g(f??{messages:[],metadata:{}}));else{let b=g(a??{messages:[],metadata:{}});b.metadata&&(d=xc(b.metadata)),b.messages?.length&&(o={...o,initialMessages:b.messages}),b.artifacts?.length&&(o={...o,initialArtifacts:b.artifacts,initialSelectedArtifactId:b.selectedArtifactId??null})}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=g({messages:[],metadata:{}});a.messages?.length&&(o={...o,initialMessages:a.messages})}catch(a){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",a)}let m=()=>d,C=a=>{d=a({...d})??{},Oa()},D=o.actionParsers&&o.actionParsers.length?o.actionParsers:[hc],B=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Ls.message,Ls.messageAndClick],E=bc({parsers:D,handlers:B,getSessionMetadata:m,updateSessionMetadata:C,emit:l.emit,documentRef:typeof document<"u"?document:null});E.syncFromMetadata();let A=o.launcher?.enabled??!0,W=o.launcher?.autoExpand??!1,z=o.autoFocusInput??!1,G=W,w=A,O=o.layout?.header?.layout,N=!1,L=()=>Cs(o),P=()=>A||L(),I=L()?!1:A?W:!0,Y=!1,de=null,ue=()=>{Y=!0,de&&clearTimeout(de),de=setTimeout(()=>{Y&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Y=!1)},1e4)},pe=sf(o,E,ue),ee=o.features?.showReasoning??!0,oe=o.features?.showToolCalls??!0,V=o.features?.showEventStreamToggle??!1,ae=o.features?.scrollToBottom??{},ne=o.features?.scrollBehavior??{},be=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,fe=V?new Ms(be):null,Te=o.features?.eventStream?.maxEvents??2e3,Se=V?new Ss(Te,fe):null,Fe=V?new Ts:null,ke=null,Ve=!1,Je=null,Ne=0;fe?.open().then(()=>Se?.restore()).catch(a=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",a)});let Pe={onCopy:a=>{l.emit("message:copy",a),q?.isClientTokenMode()&&q.submitMessageFeedback(a.id,"copy").catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",f)}),o.messageActions?.onCopy?.(a)},onFeedback:a=>{l.emit("message:feedback",a),q?.isClientTokenMode()&&q.submitMessageFeedback(a.messageId,a.type).catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",f)}),o.messageActions?.onFeedback?.(a)}},Ye=o.statusIndicator??{},ln=a=>a==="idle"?Ye.idleText??Ht.idle:a==="connecting"?Ye.connectingText??Ht.connecting:a==="connected"?Ye.connectedText??Ht.connected:a==="error"?Ye.errorText??Ht.error:a==="paused"?Ye.pausedText??Ht.paused:a==="resuming"?Ye.resumingText??Ht.resuming:Ht[a];function kt(a,f,b,x){if(x==="idle"&&b.idleLink){a.textContent="";let S=document.createElement("a");S.href=b.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=f,S.style.color="inherit",S.style.textDecoration="none",a.appendChild(S)}else a.textContent=f}let vt=wg({config:o,showClose:P()}),{wrapper:Oe,panel:Ce,pillRoot:Qe}=vt.shell,Re=vt.panelElements,{container:ye,body:ge,messagesWrapper:we,suggestions:xt,textarea:Ae,sendButton:he,sendButtonWrapper:hn,composerForm:te,statusText:k,introTitle:j,introSubtitle:v,closeButton:T,iconHolder:R,headerTitle:_,headerSubtitle:Q,header:$,footer:K,actionsRow:ce,rightActions:Ke}=Re,Ie=Re.leftActions,it=Re.setSendButtonMode,X=Re.micButton,Ue=Re.micButtonWrapper,Ee=Re.attachmentButton,De=Re.attachmentButtonWrapper,We=Re.attachmentInput,Ze=Re.attachmentPreviewsContainer;ye.classList.add("persona-relative"),ge.classList.add("persona-relative");let fo=12,mo=()=>ae.label??"",wa=()=>ae.iconName??"arrow-down",Is=()=>ae.enabled!==!1,Yt=()=>ne.mode??"anchor-top",jn=()=>Yt()==="follow"||Yt()==="anchor-top"&&Pr,Ec=()=>ne.anchorTopOffset??16,Cf=()=>ne.restorePosition??"bottom",kc=()=>ne.pauseOnInteraction===!0,Lc=()=>ne.showActivityWhilePinned!==!1,Pc=()=>ne.announce===!0,Pt=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Pt.type="button",Pt.style.display="none",Pt.setAttribute("data-persona-scroll-to-bottom","true");let wr=h("span","persona-flex persona-items-center"),Aa=h("span",""),ho=h("span","");ho.setAttribute("data-persona-scroll-to-bottom-count",""),ho.style.display="none",Pt.append(wr,Aa,ho),ye.appendChild(Pt);let qn=h("div","persona-stream-anchor-spacer");qn.setAttribute("aria-hidden","true"),qn.setAttribute("data-persona-anchor-spacer",""),qn.style.flexShrink="0",qn.style.pointerEvents="none",qn.style.height="0px",ge.appendChild(qn);let bo=h("div","persona-sr-only");bo.setAttribute("aria-live","polite"),bo.setAttribute("aria-atomic","true"),bo.setAttribute("role","status"),bo.setAttribute("data-persona-live-region",""),Object.assign(bo.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"}),ye.appendChild(bo);let Ar=null,Rs=null,Ic=a=>{!Pc()||!a||(Rs=a,Ar===null&&(Ar=setTimeout(()=>{Ar=null,Rs&&Pc()&&(bo.textContent=Rs),Rs=null},400)))},Fo=()=>{let f=K.style.display==="none"?0:K.offsetHeight;Pt.style.bottom=`${f+fo}px`};Fo();let Rc=()=>{let a=!!mo();Pt.setAttribute("aria-label",mo()||"Jump to latest"),Pt.title=mo(),Pt.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),wr.innerHTML="";let f=se(wa(),"14px","currentColor",2);f?(wr.appendChild(f),wr.style.display=""):wr.style.display="none",Aa.textContent=mo(),Aa.style.display=a?"":"none"};Rc();let Mt=null,tn=null,Wc=null,Hc=r.find(a=>a.renderHeader);if(Hc?.renderHeader){let a=Hc.renderHeader({config:o,defaultRenderer:()=>{let f=Bo({config:o,showClose:P()});return ws(ye,f,o),f.header},onClose:()=>pt(!1,"user")});if(a){let f=ye.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(a),$=a,vt.header.element=a)}}let Sa=()=>{if(!Se)return;if(Ve=!0,!ke&&Se&&(ke=Fg({buffer:Se,getFullHistory:()=>Se.getAllFromStore(),onClose:()=>Sr(),config:o,plugins:r,getThroughput:()=>Fe?.getMetric()??{status:"idle"}})),ke&&(ge.style.display="none",K.parentNode?.insertBefore(ke.element,K),ke.update()),ot){ot.style.boxShadow=`inset 0 0 0 1.5px ${Xt.actionIconColor}`;let f=o.features?.eventStream?.classNames?.toggleButtonActive;f&&f.split(/\s+/).forEach(b=>b&&ot.classList.add(b))}let a=()=>{if(!Ve)return;let f=Date.now();f-Ne>=200&&(ke?.update(),Ne=f),Je=requestAnimationFrame(a)};Ne=0,Je=requestAnimationFrame(a),on(),l.emit("eventStream:opened",{timestamp:Date.now()})},Sr=()=>{if(Ve){if(Ve=!1,ke&&ke.element.remove(),ge.style.display="",ot){ot.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(f=>f&&ot.classList.remove(f))}Je!==null&&(cancelAnimationFrame(Je),Je=null),on(),l.emit("eventStream:closed",{timestamp:Date.now()})}},ot=null;if(V){let a=o.features?.eventStream?.classNames,f="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:"");ot=h("button",f),ot.style.width="28px",ot.style.height="28px",ot.style.color=Xt.actionIconColor,ot.type="button",ot.setAttribute("aria-label","Event Stream"),ot.title="Event Stream";let b=se("activity","18px","currentColor",1.5);b&&ot.appendChild(b);let x=Re.clearChatButtonWrapper,S=Re.closeButtonWrapper,H=x||S;H&&H.parentNode===$?$.insertBefore(ot,H):$.appendChild(ot),ot.addEventListener("click",()=>{Ve?Sr():Sa()})}let wf=a=>{let f=o.attachments;if(!f?.enabled)return;let b=a.querySelector("[data-persona-composer-attachment-previews]")??a.querySelector(".persona-attachment-previews");if(!b){b=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),b.setAttribute("data-persona-composer-attachment-previews",""),b.style.display="none";let S=a.querySelector("[data-persona-composer-form]");S?.parentNode?S.parentNode.insertBefore(b,S):a.insertBefore(b,a.firstChild)}if(!(a.querySelector("[data-persona-composer-attachment-input]")??a.querySelector('input[type="file"]'))){let S=h("input");S.type="file",S.setAttribute("data-persona-composer-attachment-input",""),S.accept=(f.allowedTypes??$n).join(","),S.multiple=(f.maxFiles??4)>1,S.style.display="none",S.setAttribute("aria-label",f.buttonTooltipText??"Attach files"),a.appendChild(S)}},Bc=r.find(a=>a.renderComposer);if(Bc?.renderComposer){let a=o.composer,f=Bc.renderComposer({config:o,defaultRenderer:()=>ha({config:o}).footer,onSubmit:b=>{if(!q||q.isStreaming())return;let x=b.trim(),S=Mt?.hasAttachments()??!1;if(!x&&!S)return;dd();let H;S&&(H=[],H.push(...Mt.getContentParts()),x&&H.push(ir(x))),q.sendMessage(x,{contentParts:H}),S&&Mt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{We?.click()},models:a?.models,selectedModelId:a?.selectedModelId,onModelChange:b=>{o.composer={...o.composer,selectedModelId:b},o.agent&&(o.agent={...o.agent,model:b})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Wc?.()}:void 0});f&&(vt.replaceComposer(f),K=vt.composer.footer)}let Af=a=>{let f=(...ve)=>{for(let ie of ve){let Me=a.querySelector(ie);if(Me)return Me}return null},b=a.querySelector("[data-persona-composer-form]"),x=a.querySelector("[data-persona-composer-input]"),S=a.querySelector("[data-persona-composer-submit]"),H=a.querySelector("[data-persona-composer-mic]"),Z=a.querySelector("[data-persona-composer-status]");b&&(te=b),x&&(Ae=x),S&&(he=S),H&&(X=H,Ue=H.parentElement),Z&&(k=Z);let U=f("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(xt=U);let J=f("[data-persona-composer-attachment-button]",".persona-attachment-button");J&&(Ee=J,De=J.parentElement),We=f("[data-persona-composer-attachment-input]",'input[type="file"]'),Ze=f("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let le=f("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");le&&(ce=le),Ie=f(".persona-widget-composer__left-actions")};wf(K),Af(K);let Vn=o.layout?.contentMaxWidth??(L()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Vn&&(we.style.maxWidth=Vn,we.style.marginLeft="auto",we.style.marginRight="auto",we.style.width="100%"),Vn&&te&&!L()&&(te.style.maxWidth=Vn,te.style.marginLeft="auto",te.style.marginRight="auto"),Vn&&xt&&!L()&&(xt.style.maxWidth=Vn,xt.style.marginLeft="auto",xt.style.marginRight="auto"),Vn&&Ze&&!L()&&(Ze.style.maxWidth=Vn,Ze.style.marginLeft="auto",Ze.style.marginRight="auto"),o.attachments?.enabled&&We&&Ze){Mt=os.fromConfig(o.attachments),Mt.setPreviewsContainer(Ze),We.addEventListener("change",b=>{let x=b.target;Mt?.handleFileSelect(x.files),x.value=""});let a=o.attachments.dropOverlay,f=af(a);ye.appendChild(f)}let Sf=()=>tn?.prefetch();if(o.contextMentions?.enabled&&Ae&&(tn=Lu({config:o,textarea:Ae,anchor:te??Ae,getMessages:()=>q.getMessages(),liveRegionHost:ye}),tn)){let a=Ae;a.parentElement?.insertBefore(tn.contextRow,a);let f=tn.affordanceButtons;for(let b=f.length-1;b>=0;b--){let x=f[b];Ie?Ie.insertBefore(x,Ie.firstChild):te?.appendChild(x)}}(()=>{let a=o.layout?.slots??{},f=x=>{switch(x){case"body-top":return ye.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return we;case"footer-top":return xt;case"composer":return te;case"footer-bottom":return k;default:return null}},b=(x,S)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")$.insertBefore(S,$.firstChild);else if(x==="header-right")$.appendChild(S);else{let H=$.querySelector(".persona-flex-col");H?H.parentNode?.insertBefore(S,H.nextSibling):$.appendChild(S)}break;case"body-top":{let H=ge.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");H?H.replaceWith(S):ge.insertBefore(S,ge.firstChild);break}case"body-bottom":ge.appendChild(S);break;case"footer-top":xt.replaceWith(S);break;case"footer-bottom":k.replaceWith(S);break;default:break}};for(let[x,S]of Object.entries(a))if(S)try{let H=S({config:o,defaultContent:()=>f(x)});H&&b(x,H)}catch(H){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,H)}})();let Dc=a=>{let b=a.target.closest('button[data-expand-header="true"]');if(!b)return;let x=b.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let S=x.getAttribute("data-message-id");if(!S)return;let H=b.getAttribute("data-bubble-type");if(H==="reasoning")br.has(S)?br.delete(S):br.add(S),Eg(S,x);else if(H==="tool")yr.has(S)?yr.delete(S):yr.add(S),kg(S,x,o);else if(H==="approval"){let U=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",J=Do.get(S)??U;Do.set(S,!J),Rg(S,x,o)}Co.delete(S)};we.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Dc(a))}),we.addEventListener("keydown",a=>{let f=a.target;(a.key==="Enter"||a.key===" ")&&f.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Dc(a))}),we.addEventListener("copy",a=>{let{clipboardData:f}=a;if(!f)return;let b=we.getRootNode(),x=typeof b.getSelection=="function"?b.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let S=x.toString(),H=rg(S);!H||H===S||(f.setData("text/plain",H),a.preventDefault())});let Ma=new Map,Nc=null,Oc="idle",Mf={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Tf=(a,f)=>{let{icon:b,label:x}=Mf[f];a.setAttribute("aria-label",x),a.title=x,a.setAttribute("aria-pressed",f==="idle"?"false":"true"),a.classList.toggle("persona-message-action-active",f!=="idle"),a.classList.toggle("persona-message-action-loading",f==="loading");let S=se(b,14,"currentColor",2);S&&(a.innerHTML="",a.appendChild(S))},Fc=()=>{we.querySelectorAll('[data-action="read-aloud"]').forEach(f=>{let x=f.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;Tf(f,x&&x===Nc?Oc:"idle")})};we.addEventListener("click",a=>{let b=a.target.closest(".persona-message-action-btn[data-action]");if(!b)return;a.preventDefault(),a.stopPropagation();let x=b.closest("[data-actions-for]");if(!x)return;let S=x.getAttribute("data-actions-for");if(!S)return;let H=b.getAttribute("data-action");if(H==="copy"){let U=q.getMessages().find(J=>J.id===S);if(U&&Pe.onCopy){let J=U.content||"";navigator.clipboard.writeText(J).then(()=>{b.classList.add("persona-message-action-success");let le=se("check",14,"currentColor",2);le&&(b.innerHTML="",b.appendChild(le)),setTimeout(()=>{b.classList.remove("persona-message-action-success");let ve=se("copy",14,"currentColor",2);ve&&(b.innerHTML="",b.appendChild(ve))},2e3)}).catch(le=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",le)}),Pe.onCopy(U)}}else if(H==="read-aloud")q.toggleReadAloud(S);else if(H==="upvote"||H==="downvote"){let U=(Ma.get(S)??null)===H,J=H==="upvote"?"thumbs-up":"thumbs-down";if(U){Ma.delete(S),b.classList.remove("persona-message-action-active");let le=se(J,14,"currentColor",2);le&&(b.innerHTML="",b.appendChild(le))}else{let le=H==="upvote"?"downvote":"upvote",ve=x.querySelector(`[data-action="${le}"]`);if(ve){ve.classList.remove("persona-message-action-active");let rt=se(le==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);rt&&(ve.innerHTML="",ve.appendChild(rt))}Ma.set(S,H),b.classList.add("persona-message-action-active");let ie=se(J,14,"currentColor",2);ie&&(ie.setAttribute("fill","currentColor"),b.innerHTML="",b.appendChild(ie)),b.classList.remove("persona-message-action-pop"),b.offsetWidth,b.classList.add("persona-message-action-pop");let qe=q.getMessages().find(ut=>ut.id===S);qe&&Pe.onFeedback&&Pe.onFeedback({type:H,messageId:qe.id,message:qe})}}}),we.addEventListener("click",a=>{let b=a.target.closest("button[data-approval-action]");if(!b)return;a.preventDefault(),a.stopPropagation();let x=b.closest(".persona-approval-bubble");if(!x)return;let S=x.getAttribute("data-message-id");if(!S)return;let H=b.getAttribute("data-approval-action");if(!H)return;let Z=H==="approve"?"approved":"denied",J=q.getMessages().find(ve=>ve.id===S);if(!J?.approval)return;let le=x.querySelector("[data-approval-buttons]");le&&le.querySelectorAll("button").forEach(ie=>{ie.disabled=!0,ie.style.opacity="0.5",ie.style.cursor="not-allowed"}),J.approval.toolType==="webmcp"?q.resolveWebMcpApproval(S,Z):q.resolveApproval(J.approval,Z)});let et=null,Mr=null,Tr=()=>{},Er="none",Ws=null,bn={artifacts:[],selectedId:null},Pn=!1,yn=!1,kr=!1,_o=!1,_c=()=>_o||bn.artifacts.some(a=>Lo(o.features?.artifacts,a.artifactType)==="panel"),Hs=()=>bn.artifacts.length>0&&!Pn&&_c(),ct={current:null},Ta=(a,f)=>{let b=q.getArtifactById(f),x=b?.markdown,S=b?.title||"artifact",H=b?.file,Z=b?.artifactType??"markdown";if(!x){let le=a.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(le){let ie=q.getMessages().find(Me=>Me.id===le);if(ie?.rawContent)try{let Me=JSON.parse(ie.rawContent);x=Me?.props?.markdown,S=Me?.props?.title||S,Me?.props?.file&&typeof Me.props.file=="object"&&(H=Me.props.file),!b&&typeof Me?.props?.artifactType=="string"&&(Z=Me.props.artifactType)}catch{}}}return{markdown:x,title:S,file:H,artifactType:Z}};we.addEventListener("click",a=>{let b=a.target.closest("[data-download-artifact]");if(!b)return;a.preventDefault(),a.stopPropagation();let x=b.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:H,title:Z,file:U}=Ta(b,x);if(!H)return;let{filename:J,mime:le,content:ve}=Fu({title:Z,markdown:H,file:U}),ie=new Blob([ve],{type:le}),Me=URL.createObjectURL(ie),qe=document.createElement("a");qe.href=Me,qe.download=J,qe.click(),URL.revokeObjectURL(Me)}),we.addEventListener("click",a=>{let b=a.target.closest("[data-artifact-custom-action]");if(!b)return;a.preventDefault(),a.stopPropagation();let x=b.getAttribute("data-artifact-custom-action");if(!x)return;let S=b.closest("[data-artifact-inline]"),H=S?null:b.closest("[data-open-artifact]"),Z=S?S.getAttribute("data-artifact-inline"):H?.getAttribute("data-open-artifact")??null,J=(S?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ut=>ut.id===x);if(!J)return;let{markdown:le,title:ve,file:ie,artifactType:Me}=Ta(b,Z??""),qe={artifactId:Z,title:ve,artifactType:Me,markdown:le,file:ie};try{Promise.resolve(J.onClick(qe)).catch(()=>{})}catch{}}),we.addEventListener("click",a=>{let b=a.target.closest("[data-copy-artifact]");if(!b)return;a.preventDefault(),a.stopPropagation();let x=b.getAttribute("data-copy-artifact");if(!x)return;let S=q.getArtifactById(x),H="";if(S)H=ms(S);else{let{markdown:Z,file:U,artifactType:J}=Ta(b,x);J==="markdown"&&(H=ms({id:x,artifactType:"markdown",status:"complete",markdown:Z??"",...U?{file:U}:{}}))}H&&navigator.clipboard.writeText(H).then(()=>{let Z=se("check",16,"currentColor",2);Z&&(b.replaceChildren(Z),setTimeout(()=>{let U=se("copy",16,"currentColor",2);U&&b.replaceChildren(U)},1500))}).catch(()=>{})}),we.addEventListener("click",a=>{let b=a.target.closest("[data-expand-artifact-inline]");if(!b)return;a.preventDefault(),a.stopPropagation();let x=b.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(Pn=!1,_o=!0,yn=!0,kr=!0,q.selectArtifact(x),In())}),we.addEventListener("click",a=>{let f=a.target;if(f.closest("[data-download-artifact]")||f.closest("[data-artifact-custom-action]"))return;let b=f.closest("[data-open-artifact]");if(!b)return;let x=b.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(a.preventDefault(),a.stopPropagation(),Pn=!1,_o=!0,q.selectArtifact(x),In())}),we.addEventListener("keydown",a=>{if(a.key!=="Enter"&&a.key!==" ")return;let f=a.target;!f.hasAttribute("data-open-artifact")&&!f.hasAttribute("data-expand-artifact-inline")||(a.preventDefault(),f.click())});let $o=Re.composerOverlay,zo=(a,f,b)=>{let x=f.trim();if(!x||!ct.current)return;let S=a.getAttribute("data-tool-call-id")??"",H=b.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:x,answers:b.structured,values:b.values??(b.source==="multi"?x.split(", "):[x]),isFreeText:H,source:b.source},bubbles:!0,composed:!0})),or($o,S);let Z=ct.current.getMessages().find(U=>U.toolCall?.id===S);Z?.agentMetadata?.awaitingLocalTool?ct.current.resolveAskUserQuestion(Z,b.structured??x):ct.current.sendMessage(x)},yo=a=>{let f=ct.current;if(!f)return;let b=a.getAttribute("data-tool-call-id")??"",x=f.getMessages().find(S=>S.toolCall?.id===b);x&&f.persistAskUserQuestionProgress(x,{answers:ui(a,x),currentIndex:fn(a)})},$c=a=>Object.entries(a).map(([f,b])=>`${f}: ${Array.isArray(b)?b.join(", "):b}`).join(" | "),Ea=a=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let f=fn(a),b=nr(a);if(f>=b-1)return;let x=ct.current?.getMessages().find(S=>S.toolCall?.id===a.getAttribute("data-tool-call-id"));x&&(fi(a,x,o,f+1),yo(a))};$o.addEventListener("click",a=>{let b=a.target.closest("[data-ask-user-action]");if(!b)return;let x=b.closest("[data-persona-ask-sheet-for]");if(!x)return;let S=b.getAttribute("data-ask-user-action");if(a.preventDefault(),a.stopPropagation(),S==="dismiss"){let H=x.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:H},bubbles:!0,composed:!0})),or($o,H);let Z=ct.current?.getMessages().find(U=>U.toolCall?.id===H);Z?.agentMetadata?.awaitingLocalTool&&(ct.current?.markAskUserQuestionResolved(Z),ct.current?.resolveAskUserQuestion(Z,"(dismissed)"));return}if(S==="pick"){let H=b.getAttribute("data-option-label");if(!H)return;let Z=x.getAttribute("data-multi-select")==="true",U=so(x);if(U&&Z){let J=Io(x)[fn(x)],le=new Set(Array.isArray(J)?J:[]);le.has(H)?le.delete(H):le.add(H),io(x,Array.from(le)),yo(x);return}if(U){io(x,H),yo(x),Ea(x);return}if(Z){let J=b.getAttribute("aria-pressed")==="true";b.setAttribute("aria-pressed",J?"false":"true"),b.classList.toggle("persona-ask-pill-selected",!J);let le=x.querySelector('[data-ask-user-action="submit-multi"]');le&&(le.disabled=pl(x).length===0);return}zo(x,H,{source:"pick",values:[H]});return}if(S==="submit-multi"){let H=pl(x);if(H.length===0)return;zo(x,H.join(", "),{source:"multi",values:H});return}if(S==="open-free-text"){let H=x.querySelector('[data-ask-free-text-row="true"]');H&&(H.classList.remove("persona-hidden"),H.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(S==="focus-free-text"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(S==="submit-free-text"){let Z=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!Z.trim())return;if(so(x)){io(x,Z.trim()),yo(x),Ea(x);return}zo(x,Z,{source:"free-text"});return}if(S==="next"||S==="back"){if(!ct.current)return;let H=x.getAttribute("data-tool-call-id")??"",Z=ct.current.getMessages().find(ie=>ie.toolCall?.id===H);if(!Z)return;let J=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(J){let ie=Io(x)[fn(x)];(typeof ie!="string"||ie!==J)&&io(x,J)}let le=S==="next"?1:-1,ve=fn(x)+le;fi(x,Z,o,ve),yo(x);return}if(S==="submit-all"){if(!ct.current)return;let H=x.getAttribute("data-tool-call-id")??"",Z=ct.current.getMessages().find(ie=>ie.toolCall?.id===H);if(!Z)return;let J=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";J&&io(x,J);let le=ui(x,Z);ct.current.persistAskUserQuestionProgress(Z,{answers:le,currentIndex:fn(x)});let ve=$c(le);zo(x,ve||"(submitted)",{source:"submit-all",structured:le});return}if(S==="skip"){if(!ct.current)return;let H=x.getAttribute("data-tool-call-id")??"",Z=ct.current.getMessages().find(Me=>Me.toolCall?.id===H);if(!Z)return;let U=so(x),J=fn(x),le=nr(x),ve=J>=le-1;if(!U){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:H},bubbles:!0,composed:!0})),or($o,H),Z.agentMetadata?.awaitingLocalTool&&(ct.current.markAskUserQuestionResolved(Z),ct.current.resolveAskUserQuestion(Z,"(dismissed)"));return}io(x,"");let ie=x.querySelector('[data-ask-free-text-input="true"]');if(ie&&(ie.value=""),ve){let Me=ui(x,Z),qe=$c(Me);zo(x,qe||"(skipped)",{source:"submit-all",structured:Me});return}fi(x,Z,o,J+1),yo(x);return}}),$o.addEventListener("keydown",a=>{if(a.key!=="Enter")return;let b=a.target;if(!b.matches?.('[data-ask-free-text-input="true"]'))return;let x=b.closest("[data-persona-ask-sheet-for]");if(!x)return;a.preventDefault();let S=b.value;if(S.trim()){if(so(x)){io(x,S.trim()),yo(x),Ea(x);return}zo(x,S,{source:"free-text"})}});let zc=a=>{if(!/^[1-9]$/.test(a.key)||a.metaKey||a.ctrlKey||a.altKey)return;let f=a.target;if(f?.tagName==="INPUT"||f?.tagName==="TEXTAREA"||f?.isContentEditable)return;let b=$o.querySelector("[data-persona-ask-sheet-for]");if(!b||b.getAttribute("data-ask-layout")!=="rows"||b.getAttribute("data-multi-select")==="true")return;let x=Number(a.key),H=b.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];H&&(a.preventDefault(),H.click())};document.addEventListener("keydown",zc);let Kn=null,Ct=null,Lr=null,Bs=null,ka=()=>{},Uc=!1,Ds="",Ns="";function La(){Bs?.(),Bs=null}let jc=()=>{if(!Kn||!Ct)return;let a=t.classList.contains("persona-artifact-welded-split"),f=t.ownerDocument.defaultView??window,b=f.innerWidth<=640;if(!a||t.classList.contains("persona-artifact-narrow-host")||b){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=Kn.firstElementChild;if(!x||x===Ct)return;let S=10;Ct.style.position="absolute",Ct.style.top="0",Ct.style.bottom="0",Ct.style.width=`${S}px`,Ct.style.zIndex="5";let H=pc(Kn,f),Z=x.offsetWidth+H/2-S/2;Ct.style.left=`${Math.max(0,Z)}px`},Os=()=>{},Ef=()=>{let a=t.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,b=o.launcher?.mobileBreakpoint??640;return!f||a.innerWidth>b?!1:A||Nt(o)},Fs=()=>!Jt(o)||!Hs()||t.classList.contains("persona-artifact-narrow-host")||Ef()||(t.ownerDocument.defaultView??window).innerWidth<Tv?"none":dc(o)?"detached":"welded",In=()=>{if(!et||!Jt(o))return;Es(t,o),ks(t,o),Os();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,f=Ce.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",f>0&&f<=a);let b=Hs();et.setVisible(b),et.update(bn),Pn?(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),et.backdrop?.classList.add("persona-hidden"),yn=!1,kr=!1):bn.artifacts.length>0&&_c()?(et.element.classList.remove("persona-hidden"),et.setMobileOpen(!0)):(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),et.backdrop?.classList.add("persona-hidden"),yn=!1,kr=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(et.setExpandToggleVisible(x),et.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),et.setCustomActions(o.features?.artifacts?.toolbarActions??[]),et.setTabFade(o.features?.artifacts?.layout?.tabFade),et.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!kr&&(yn=!1),yn!==Uc){let H=et.element;yn?(Ds=H.style.width,Ns=H.style.maxWidth,H.style.removeProperty("width"),H.style.removeProperty("max-width")):(Ds&&(H.style.width=Ds),Ns&&(H.style.maxWidth=Ns),Ds="",Ns=""),Uc=yn}t.classList.toggle("persona-artifact-expanded",yn),et.setExpanded(yn);let S=Fs();S!==Er&&(Er=S,Tr()),ka()};if(Jt(o)){Ce.style.position="relative";let a=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");a.appendChild(ye),et=$g(o,{onSelect:b=>ct.current?.selectArtifact(b),onDismiss:()=>{Pn=!0,In()},onToggleExpand:()=>{let b=!yn,x=bn.selectedId??bn.artifacts[bn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:b})!==!0&&(yn=b,b||(kr=!1),In())}}),et.element.classList.add("persona-hidden"),Kn=f,f.appendChild(a),f.appendChild(et.element),et.backdrop&&Ce.appendChild(et.backdrop),Ce.appendChild(f),ka=()=>{if(!Kn||!et)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Lr?.(),Lr=null,La(),Ct&&(Ct.remove(),Ct=null),et.element.style.removeProperty("width"),et.element.style.removeProperty("maxWidth");return}if(!Ct){let x=h("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 S=t.ownerDocument,H=S.defaultView??window,Z=U=>{if(!et||U.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||H.innerWidth<=640)return;U.preventDefault(),La();let J=U.clientX,le=et.element.getBoundingClientRect().width,ve=o.features?.artifacts?.layout,ie=qe=>{let ut=Kn.getBoundingClientRect().width,rt=t.classList.contains("persona-artifact-welded-split"),rn=pc(Kn,H),Tt=rt?0:x.getBoundingClientRect().width||6,Rt=le-(qe.clientX-J),F=qg(Rt,ut,rn,Tt,ve?.resizableMinWidth,ve?.resizableMaxWidth);et.element.style.width=`${F}px`,et.element.style.maxWidth="none",jc()},Me=()=>{S.removeEventListener("pointermove",ie),S.removeEventListener("pointerup",Me),S.removeEventListener("pointercancel",Me),Bs=null;try{x.releasePointerCapture(U.pointerId)}catch{}};Bs=Me,S.addEventListener("pointermove",ie),S.addEventListener("pointerup",Me),S.addEventListener("pointercancel",Me);try{x.setPointerCapture(U.pointerId)}catch{}};x.addEventListener("pointerdown",Z),Ct=x,Kn.insertBefore(x,et.element),Lr=()=>{x.removeEventListener("pointerdown",Z)}}if(Ct){let x=Hs();Ct.classList.toggle("persona-hidden",!x),jc()}},Os=()=>{if(!A||!et||(o.launcher?.sidebarMode??!1)||Nt(o)&&mn(o).reveal==="emerge")return;let x=t.ownerDocument.defaultView??window,S=o.launcher?.mobileFullscreen??!0,H=o.launcher?.mobileBreakpoint??640;if(S&&x.innerWidth<=H||!jg(o,A))return;let Z=o.launcher?.width??o.launcherWidth??zn,U=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";Hs()?(Ce.style.width=U,Ce.style.maxWidth=U):(Ce.style.width=Z,Ce.style.maxWidth=Z)},typeof ResizeObserver<"u"&&(Mr=new ResizeObserver(()=>{In()}),Mr.observe(Ce))}else Ce.appendChild(ye);L()&&Qe&&(Re.peekBanner&&Qe.appendChild(Re.peekBanner),Qe.appendChild(K)),t.appendChild(Oe),Qe&&t.appendChild(Qe);let _s=()=>{if(L()){Ce.style.width="100%",Ce.style.maxWidth="100%";let Lt=o.launcher?.composerBar??{},en=Oe.dataset.state==="expanded",ei=Lt.expandedSize??"anchored";if(!(en&&ei!=="fullscreen")){ye.style.background="",ye.style.border="",ye.style.borderRadius="",ye.style.overflow="",ye.style.boxShadow="";return}let jr=o.theme?.components?.panel,ti=pr(o),Xo=(Bn,ko)=>Bn==null||Bn===""?ko:Qt(ti,Bn)??Bn,ni="1px solid var(--persona-border)",el="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Eo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ye.style.background="var(--persona-surface, #ffffff)",ye.style.border=Xo(jr?.border,ni),ye.style.borderRadius=Xo(jr?.borderRadius,Eo),ye.style.boxShadow=Xo(jr?.shadow,el),ye.style.overflow="hidden";return}let a=Nt(o),f=o.launcher?.sidebarMode??!1,b=a||f||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,S=o.launcher?.detachedPanel===!0,H=o.theme?.components?.panel,Z=pr(o),U=(Lt,en)=>Lt==null||Lt===""?en:Qt(Z,Lt)??Lt,J=t.ownerDocument.defaultView??window,le=o.launcher?.mobileFullscreen??!0,ve=o.launcher?.mobileBreakpoint??640,ie=J.innerWidth<=ve,Me=le&&ie&&A,qe=a&&le&&ie,ut=o.launcher?.position??"bottom-left",rt=ut==="bottom-left"||ut==="top-left",rn=o.launcher?.zIndex??Vt,Tt="var(--persona-panel-border, 1px solid var(--persona-border))",Rt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",F="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",He=S&&!Me&&!qe;He?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let $e=He?Tt:f||Me?"none":Tt,Le=He?Rt:Me?"none":f?rt?"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":Rt;a&&!Me&&!He&&(Le="none",$e="none");let Et=He?F:f||Me?"0":F,gt=U(H?.border,$e),Gt=U(H?.shadow,Le),ft=U(H?.borderRadius,Et),Zt=Fs(),Wt=Zt==="detached",Be=Zt==="welded";t.classList.toggle("persona-artifact-detached-split",Wt),t.classList.toggle("persona-artifact-welded-split",Be);let ze="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)))))",At=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Jt(o)&&dc(o)&&x&&!a;t.classList.toggle("persona-artifact-chat-flush",At);let dt=Wt||At?"none":Gt,mt=Wt?Tt:Be?"none":gt,tt=Wt?F:ft;At&&(mt="none",tt="0");let _e=H?.borderRadius!=null&&H.borderRadius!=="",yt=At&&!_e?"0":ft,Ut=ge.scrollTop;t.style.cssText="",Oe.style.cssText="",Ce.style.cssText="",ye.style.cssText="",ge.style.cssText="",K.style.cssText="",Ve&&(ge.style.display="none"),(b||x)&&(t.style.minWidth="0");let gn=()=>{if(Ut<=0)return;(ge.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ge.scrollTop===Ut)return;let en=ge.scrollHeight-ge.clientHeight;en<=0||(ge.scrollTop=Math.min(Ut,en))})};if(Me){Oe.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"),Oe.style.cssText=`
220
220
  position: fixed !important;
221
221
  inset: 0 !important;
222
222
  width: 100% !important;
@@ -252,11 +252,11 @@ _Details: ${n.message}_`:o}var ns=t=>({isError:!0,content:[{type:"text",text:t}]
252
252
  overflow: hidden !important;
253
253
  border-radius: 0 !important;
254
254
  border: none !important;
255
- `,ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.overflowY="auto",K.style.flexShrink="0",N=!0,gn();return}let Zs=o?.launcher?.width??o?.launcherWidth??zn;if(!f&&!a)x&&b?(Ce.style.width="100%",Ce.style.maxWidth="100%"):(Ce.style.width=Zs,Ce.style.maxWidth=Zs);else if(a)if(mn(o).reveal==="emerge"&&!S){let en=mn(o).width;Ce.style.width=en,Ce.style.maxWidth=en}else Ce.style.width="100%",Ce.style.maxWidth="100%";if(Os(),Ce.style.boxShadow=pt,Ce.style.borderRadius=vt,Ht?Ce.style.border="none":Oe&&(Ce.style.border=ft),ye.style.border=ht,ye.style.borderRadius=et,ye.style.boxShadow=Ht&&!at?nt:"",at&&(ye.style.background="transparent",ge.style.background="transparent",K.style.background="transparent",K.style.borderTop="none"),Oe){let Pt=o.features?.artifacts?.layout;Ws=Pt?.unifiedSplitOuterRadius?.trim()||Pt?.paneBorderRadius?.trim()||mt}else Ws=null;if(a&&!Me&&!De&&!Ht&&!Oe&&H?.border===void 0&&(ye.style.border="none",mn(o).side==="right"?ye.style.borderLeft="1px solid var(--persona-border)":ye.style.borderRight="1px solid var(--persona-border)"),a&&!Me&&Oe&&H?.border===void 0&&(mn(o).side==="right"?Ce.style.borderLeft="1px solid var(--persona-border)":Ce.style.borderRight="1px solid var(--persona-border)"),b&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",x&&(t.style.width="100%"),Be.style.display="flex",Be.style.flexDirection="column",Be.style.flex="1 1 0%",Be.style.minHeight="0",Be.style.maxHeight="100%",Be.style.height="100%",x&&(Be.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.height="100%",Ht||(Ce.style.overflow="hidden"),ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1 1 0%",ye.style.minHeight="0",ye.style.maxHeight="100%",ye.style.overflow="hidden",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.overflowY="auto",K.style.flexShrink="0"),x&&(De||Ht||at)&&!a&&(at||(Be.style.padding="var(--persona-panel-inset)"),Be.style.background="var(--persona-panel-canvas-bg)"),Be.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"),!f&&!x&&!a&&(Sn[gt]??Sn["bottom-right"]).split(" ").forEach(en=>Be.classList.add(en)),f){let Pt=o.launcher?.sidebarWidth??"420px";S?Be.style.cssText=`
255
+ `,ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.overflowY="auto",K.style.flexShrink="0",N=!0,gn();return}let Zs=o?.launcher?.width??o?.launcherWidth??zn;if(!f&&!a)x&&b?(Ce.style.width="100%",Ce.style.maxWidth="100%"):(Ce.style.width=Zs,Ce.style.maxWidth=Zs);else if(a)if(mn(o).reveal==="emerge"&&!S){let en=mn(o).width;Ce.style.width=en,Ce.style.maxWidth=en}else Ce.style.width="100%",Ce.style.maxWidth="100%";if(Os(),Ce.style.boxShadow=dt,Ce.style.borderRadius=yt,Wt?Ce.style.border="none":Be&&(Ce.style.border=gt),ye.style.border=mt,ye.style.borderRadius=tt,ye.style.boxShadow=Wt&&!At?ze:"",At&&(ye.style.background="transparent",ge.style.background="transparent",K.style.background="transparent",K.style.borderTop="none"),Be){let Lt=o.features?.artifacts?.layout;Ws=Lt?.unifiedSplitOuterRadius?.trim()||Lt?.paneBorderRadius?.trim()||ft}else Ws=null;if(a&&!Me&&!He&&!Wt&&!Be&&H?.border===void 0&&(ye.style.border="none",mn(o).side==="right"?ye.style.borderLeft="1px solid var(--persona-border)":ye.style.borderRight="1px solid var(--persona-border)"),a&&!Me&&Be&&H?.border===void 0&&(mn(o).side==="right"?Ce.style.borderLeft="1px solid var(--persona-border)":Ce.style.borderRight="1px solid var(--persona-border)"),b&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",x&&(t.style.width="100%"),Oe.style.display="flex",Oe.style.flexDirection="column",Oe.style.flex="1 1 0%",Oe.style.minHeight="0",Oe.style.maxHeight="100%",Oe.style.height="100%",x&&(Oe.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.height="100%",Wt||(Ce.style.overflow="hidden"),ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1 1 0%",ye.style.minHeight="0",ye.style.maxHeight="100%",ye.style.overflow="hidden",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.overflowY="auto",K.style.flexShrink="0"),x&&(He||Wt||At)&&!a&&(At||(Oe.style.padding="var(--persona-panel-inset)"),Oe.style.background="var(--persona-panel-canvas-bg)"),Oe.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"),!f&&!x&&!a&&(Sn[ut]??Sn["bottom-right"]).split(" ").forEach(en=>Oe.classList.add(en)),f){let Lt=o.launcher?.sidebarWidth??"420px";S?Oe.style.cssText=`
256
256
  position: fixed !important;
257
257
  top: var(--persona-panel-inset) !important;
258
258
  bottom: var(--persona-panel-inset) !important;
259
- width: ${Pt} !important;
259
+ width: ${Lt} !important;
260
260
  height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
261
261
  max-height: calc(100vh - (2 * var(--persona-panel-inset))) !important;
262
262
  margin: 0 !important;
@@ -265,11 +265,11 @@ _Details: ${n.message}_`:o}var ns=t=>({isError:!0,content:[{type:"text",text:t}]
265
265
  flex-direction: column !important;
266
266
  z-index: ${rn} !important;
267
267
  ${rt?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
268
- `:Be.style.cssText=`
268
+ `:Oe.style.cssText=`
269
269
  position: fixed !important;
270
270
  top: 0 !important;
271
271
  bottom: 0 !important;
272
- width: ${Pt} !important;
272
+ width: ${Lt} !important;
273
273
  height: 100vh !important;
274
274
  max-height: 100vh !important;
275
275
  margin: 0 !important;
@@ -289,9 +289,9 @@ _Details: ${n.message}_`:o}var ns=t=>({isError:!0,content:[{type:"text",text:t}]
289
289
  min-height: 0 !important;
290
290
  margin: 0 !important;
291
291
  padding: 0 !important;
292
- box-shadow: ${pt} !important;
293
- border-radius: ${vt} !important;
294
- ${Ht?"border: none !important;":Oe?`border: ${ft} !important;`:""}
292
+ box-shadow: ${dt} !important;
293
+ border-radius: ${yt} !important;
294
+ ${Wt?"border: none !important;":Be?`border: ${gt} !important;`:""}
295
295
  `,Ce.style.setProperty("width","100%","important"),Ce.style.setProperty("max-width","100%","important"),ye.style.cssText=`
296
296
  display: flex !important;
297
297
  flex-direction: column !important;
@@ -301,16 +301,16 @@ _Details: ${n.message}_`:o}var ns=t=>({isError:!0,content:[{type:"text",text:t}]
301
301
  min-height: 0 !important;
302
302
  max-height: 100% !important;
303
303
  overflow: hidden !important;
304
- border-radius: ${et} !important;
305
- border: ${ht} !important;
306
- ${Ht&&!at?`box-shadow: ${nt} !important;`:""}
307
- ${at?"background: transparent !important;":""}
304
+ border-radius: ${tt} !important;
305
+ border: ${mt} !important;
306
+ ${Wt&&!At?`box-shadow: ${ze} !important;`:""}
307
+ ${At?"background: transparent !important;":""}
308
308
  `,K.style.cssText=`
309
309
  flex-shrink: 0 !important;
310
310
  border-top: none !important;
311
311
  padding: 8px 16px 12px 16px !important;
312
- ${at?"background: transparent !important;":""}
313
- `}if(!x&&!a){let Pt="max-height: -moz-available !important; max-height: stretch !important;",en=f?"":"padding-top: 1.25em !important;",ei=f?"":`z-index: ${o.launcher?.zIndex??qt} !important;`;Be.style.cssText+=Pt+en+ei}gn()};_s(),ps(t,o),Es(t,o),ks(t,o),Tr=()=>{_s(),ps(t,o),Es(t,o),ks(t,o),Ws?t.style.setProperty("--persona-artifact-welded-outer-radius",Ws):t.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ue=[];Ue.push(()=>{document.removeEventListener("keydown",zc)}),Ue.push(()=>{Ar!==null&&clearTimeout(Ar)});let Mn=null,Tn=null;Ue.push(()=>{Mn?.(),Mn=null,Tn?.(),Tn=null}),Mr&&Ue.push(()=>{Mr?.disconnect(),Mr=null}),Ue.push(()=>{Lr?.(),Lr=null,La(),wt&&(wt.remove(),wt=null),Ze?.element.style.removeProperty("width"),Ze?.element.style.removeProperty("maxWidth")}),V&&Ue.push(()=>{Xe!==null&&(cancelAnimationFrame(Xe),Xe=null),ke?.destroy(),ke=null,Se?.destroy(),Se=null,fe=null});let vo=null,qc=()=>{vo&&(vo(),vo=null),o.colorScheme==="auto"&&(vo=qi(()=>{ps(t,o)}))};qc(),Ue.push(()=>{vo&&(vo(),vo=null)}),Ue.push(i);let $s=o.features?.streamAnimation;if($s?.type&&$s.type!=="none"){let a=hr($s.type,$s.plugins);a&&(ia(a,t),Ue.push(()=>hg(t)))}let zs=Bg(Ct),xo=null,q,Pa=a=>{if(!q)return;let f=a??q.getMessages(),b=o.features?.suggestReplies?.enabled!==!1?hp(f):null;b?zs.render(b,q,Ae,f,o.suggestionChipsConfig,{agentPushed:!0}):f.some(x=>x.role==="user")?zs.render([],q,Ae,f):zs.render(o.suggestionChips,q,Ae,f,o.suggestionChipsConfig)},vn=!1,Co=ag(),Uo=new Map,wo=new Map,Gn=new Map,Ia=0,kf=Nn()!==null,nn=ea(),cn=0,Qn=null,dn=!1,Us=!1,Xn=0,xn=null,Ao=null,Ra=!1,js=!1,Wa=null,Pr=!0,Ha=!1,Ba=null,Lf=4,qs=24,Pf=80,Da=new Map,Qe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Vc=o.voiceRecognition?.autoResume??!1,Rn=a=>{l.emit("voice:state",{active:Qe.active,source:a,timestamp:Date.now()})},Cn=()=>{C(a=>({...a,voiceState:{active:Qe.active,timestamp:Date.now(),manuallyDeactivated:Qe.manuallyDeactivated}}))},If=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=xc(d.voiceState),f=!!a.active,b=Number(a.timestamp??0);Qe.manuallyDeactivated=!!a.manuallyDeactivated,f&&Date.now()-b<Mv&&setTimeout(()=>{Qe.active||(Qe.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?q.toggleVoice().then(()=>{Qe.active=q.isVoiceActive(),Rn("restore"),q.isVoiceActive()&&Go()}):Qs("restore"))},1e3)},Rf=()=>q?rf(q.getMessages()).filter(a=>!a.__skipPersist):[],Vs=null,Kc=(a,f)=>{typeof console<"u"&&console.error(a,f)},Na=(a,f)=>{let b=()=>{try{let Z=a();return!Z||typeof Z.then!="function"?null:Promise.resolve(Z).catch(U=>{Kc(f,U)})}catch(Z){return Kc(f,Z),null}},x=Vs,S=x?x.then(()=>b()??void 0):b();if(!S)return;let H=S.finally(()=>{Vs===H&&(Vs=null)});Vs=H};function Oa(a){if(!c?.save)return;let b={messages:a?rf(a):q?Rf():[],metadata:d,artifacts:bn.artifacts,selectedArtifactId:bn.selectedId};Na(()=>c.save(b),"[AgentWidget] Failed to persist state:")}let jo=null,Gc=()=>Be.querySelector("#persona-scroll-container")||ge,Ir=()=>{jo!==null&&(cancelAnimationFrame(jo),jo=null),dn=!1},Qc=()=>{Qn!==null&&(cancelAnimationFrame(Qn),Qn=null),Us=!1,Ir()},Wf=()=>vn&&_a()&&(Yt()!=="anchor-top"||Lc()),Fa=()=>{let a=mo()||"Jump to latest",f=Wf();It.toggleAttribute("data-persona-scroll-to-bottom-streaming",f),Xn>0?(ho.textContent=String(Xn),ho.style.display="",It.setAttribute("aria-label",`${a} (${Xn} new)`)):(ho.textContent="",ho.style.display="none",It.setAttribute("aria-label",f?`${a} (response streaming below)`:a))},Xc=()=>{Xn!==0&&(Xn=0,Fa())},_a=()=>jn()?!nn.isFollowing():!uo(ge,qs),on=()=>{if(!Is()||qe){It.parentNode&&It.remove(),It.style.display="none";return}It.parentNode!==ye&&ye.appendChild(It),Fo();let f=Ln(ge)>0&&_a();f?Fa():Xc(),It.style.display=f?"":"none"},Rr=()=>{nn.pause()&&(Qc(),on())},Jn=()=>{nn.resume(),Xc(),on()},Yn=(a=!1)=>{jn()&&nn.isFollowing()&&(!a&&!vn||(Qn!==null&&(cancelAnimationFrame(Qn),Qn=null),Us=!0,Qn=requestAnimationFrame(()=>{Qn=null,Us=!1,nn.isFollowing()&&Hf(Gc(),a?220:140)})))},Jc=(a,f,b,x=()=>!0)=>{let S=a.scrollTop,H=f(),Z=H-S;if(Ir(),Math.abs(Z)<1){dn=!0,a.scrollTop=H,cn=a.scrollTop,dn=!1;return}let U=performance.now();dn=!0;let J=ve=>1-Math.pow(1-ve,3),le=ve=>{if(!x()){Ir();return}let ie=f();ie!==H&&(H=ie,Z=H-S);let Me=ve-U,je=Math.min(Me/b,1),gt=J(je),rt=S+Z*gt;a.scrollTop=rt,cn=a.scrollTop,je<1?jo=requestAnimationFrame(le):(a.scrollTop=H,cn=a.scrollTop,jo=null,dn=!1)};jo=requestAnimationFrame(le)},Hf=(a,f=500)=>{let b=Ln(a)-a.scrollTop;if(Math.abs(b)<1){cn=a.scrollTop;return}if(Math.abs(b)>=Pf){Ir(),dn=!0,a.scrollTop=Ln(a),cn=a.scrollTop,dn=!1;return}Jc(a,()=>Ln(a),f,()=>nn.isFollowing())},Yc=()=>{let a=Gc();dn=!0,a.scrollTop=Ln(a),cn=a.scrollTop,dn=!1,on()},Zc=a=>{let f=0,b=a;for(;b&&b!==ge;)f+=b.offsetTop,b=b.offsetParent;return f},ed=()=>{if(Cf()!=="last-user-turn")return!1;let a=q?.getMessages()??[];if(a.length<2)return!1;let f=[...a].reverse().find(H=>H.role==="user");if(!f)return!1;let b=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(f.id):f.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=ge.querySelector(`[data-message-id="${b}"]`);if(!x)return!1;let S=Math.min(Math.max(0,Zc(x)-Ec()),Ln(ge));return dn=!0,ge.scrollTop=S,cn=ge.scrollTop,dn=!1,Yt()==="follow"&&!uo(ge,qs)&&nn.pause(),on(),!0},td=a=>{qn.style.height=`${Math.max(0,Math.round(a))}px`,xn&&(xn.spacerHeight=Math.max(0,a))},Wr=()=>{Ao!==null&&(cancelAnimationFrame(Ao),Ao=null),Ir(),xn=null,qn.style.height="0px"},Bf=a=>{Ao!==null&&cancelAnimationFrame(Ao),Ao=requestAnimationFrame(()=>{Ao=null;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=ge.querySelector(`[data-message-id="${f}"]`);if(!b)return;let x=Zc(b),S=xn?.spacerHeight??0,H=ge.scrollHeight-S,{targetScrollTop:Z,spacerHeight:U}=ug({anchorOffsetTop:x,topOffset:Ec(),viewportHeight:ge.clientHeight,contentHeight:H});xn={initialSpacerHeight:U,contentHeightAtAnchor:H,spacerHeight:U},td(U),Jc(ge,()=>Z,220)})},Df=()=>{if(jn()){if(!nn.isFollowing()||uo(ge,1))return;Yn(!vn);return}if(xn&&xn.initialSpacerHeight>0){let a=ge.scrollHeight-xn.spacerHeight,f=gg({initialSpacerHeight:xn.initialSpacerHeight,contentHeightAtAnchor:xn.contentHeightAtAnchor,currentContentHeight:a});f!==xn.spacerHeight&&td(f)}on()},Nf=a=>{let f=Yt();f==="follow"?(Jn(),Yn(!0)):f==="anchor-top"&&(Pr=!1,Ha=!0,Bf(a))},Of=()=>{if(Yt()==="anchor-top"){if(Ha){Pr=!1;return}Pr=!0,Wr(),Jn(),Yn(!0)}},Ff=a=>{let f=new Map;a.forEach(b=>{let x=Da.get(b.id);f.set(b.id,{streaming:b.streaming,role:b.role}),!x&&b.role==="assistant"&&(l.emit("assistant:message",b),!js&&(Yt()!=="anchor-top"||Lc())&&_a()&&(Xn+=1,Fa(),on(),Ic(Xn===1?"1 new message below.":`${Xn} new messages below.`))),b.role==="assistant"&&x?.streaming&&b.streaming===!1&&l.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(x?b.approval.status!=="pending"&&l.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):l.emit("approval:requested",{approval:b.approval,message:b}))}),Da.clear(),f.forEach((b,x)=>{Da.set(x,b)})},Ks=(a,f)=>{let b=f==="user"?"user":"assistant",x=o.layout?.messages?.[b],S=x?.width??"content",H=x?.maxWidth??(S==="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-${f}`,`persona-message-width-${S}`),a.classList.toggle("persona-justify-end",f==="user"),a.setAttribute("data-message-role",f),a.setAttribute("data-message-width",S),a.style.setProperty("--persona-message-row-max-width",H)},So=(a,f)=>{let b=document.createElement("div");return b.className="persona-flex",b.id=`wrapper-${a}`,b.setAttribute("data-wrapper-id",a),Ks(b,f),b},_f=(a,f,b)=>{let x=document.createElement("div"),H=(()=>{let F=r.find(De=>De.renderLoadingIndicator);if(F?.renderLoadingIndicator)return F.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),Z=(F,De)=>De==null?!1:typeof De=="string"?(F.textContent=De,!0):(F.appendChild(De),!0),U=new Set,J=new Map,le=new Set,ve=r.some(F=>F.renderAskUserQuestion),ie=[],Me=[],je=o.enableComponentStreaming!==!1,gt=o.approval!==!1,rt=[];if(f.forEach(F=>{U.add(F.id),J.set(F.id,F.role);let De=ve&&Po(F),Ne=gt&&F.variant==="approval"&&!!F.approval,$e=!De&&F.role==="assistant"&&!F.variant&&je&&vc(F);!Ne&&Gn.has(F.id)&&(a.querySelector(`#wrapper-${F.id}`)?.removeAttribute("data-preserve-runtime"),Gn.delete(F.id)),!$e&&wo.has(F.id)&&(a.querySelector(`#wrapper-${F.id}`)?.removeAttribute("data-preserve-runtime"),wo.delete(F.id));let kt=Po(F)?`:${F.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${F.agentMetadata?.askUserQuestionAnswers?Object.keys(F.agentMetadata.askUserQuestionAnswers).length:0}`:"",ft=ig(F,Ia)+kt,Kt=De||Ne||$e?null:lg(Co,F.id,ft);if(Kt){x.appendChild(Kt.cloneNode(!0)),Po(F)&&F.toolCall?.id&&F.agentMetadata?.awaitingLocalTool===!0&&!F.agentMetadata?.askUserQuestionAnswered&&(le.add(F.toolCall.id),gi(F,o,Ie.composerOverlay));return}let mt=null,Zt=r.find(nt=>!!(F.variant==="reasoning"&&nt.renderReasoning||F.variant==="tool"&&nt.renderToolCall||!F.variant&&nt.renderMessage)),Ht=o.layout?.messages;if(Po(F)&&F.agentMetadata?.askUserQuestionAnswered===!0){Uo.delete(F.id),a.querySelector(`#wrapper-${F.id}`)?.removeAttribute("data-preserve-runtime");return}if(gl(F)&&o.features?.suggestReplies?.enabled!==!1)return;if(Po(F)&&o.features?.askUserQuestion?.enabled!==!1){let nt=r.find(St=>typeof St.renderAskUserQuestion=="function");if(nt&&dt.current){let St=Uo.get(F.id),Gt=St!==ft,at=null;if(Gt){let{payload:et,complete:_e}=tr(F),vt=F.id,zt=()=>dt.current?.getMessages().find(gn=>gn.id===vt);at=nt.renderAskUserQuestion({message:F,payload:et,complete:_e,resolve:gn=>{let Ur=zt();Ur&&dt.current?.resolveAskUserQuestion(Ur,gn)},dismiss:()=>{let gn=zt();gn?.agentMetadata?.awaitingLocalTool&&(dt.current?.markAskUserQuestionResolved(gn),dt.current?.resolveAskUserQuestion(gn,"(dismissed)"))},config:o})}let pt=St!=null;if(Gt&&at===null&&!pt){F.agentMetadata?.awaitingLocalTool===!0&&!F.agentMetadata?.askUserQuestionAnswered&&(le.add(F.toolCall.id),gi(F,o,Ie.composerOverlay));return}let ht=So(F.id,F.role);ht.setAttribute("data-ask-plugin-stub","true"),ht.setAttribute("data-preserve-runtime","true"),x.appendChild(ht),ie.push({messageId:F.id,fingerprint:ft,bubble:at});return}else{F.agentMetadata?.awaitingLocalTool===!0&&!F.agentMetadata?.askUserQuestionAnswered&&(le.add(F.toolCall.id),gi(F,o,Ie.composerOverlay));return}}else if(Ne){let nt=r.find(pt=>typeof pt.renderApproval=="function")??s,Gt=Gn.get(F.id)!==ft,at=null;if(Gt&&nt?.renderApproval){let pt=F.id,ht=(et,_e)=>{let vt=dt.current?.getMessages().find(zt=>zt.id===pt);vt?.approval&&(vt.approval.toolType==="webmcp"?dt.current?.resolveWebMcpApproval(vt.id,et):dt.current?.resolveApproval(vt.approval,et,_e))};at=nt.renderApproval({message:F,defaultRenderer:()=>ya(F,o),config:o,approve:et=>ht("approved",et),deny:et=>ht("denied",et)})}if(Gt&&at===null)a.querySelector(`#wrapper-${F.id}`)?.removeAttribute("data-preserve-runtime"),Gn.delete(F.id),mt=ya(F,o);else{let pt=So(F.id,F.role);pt.setAttribute("data-approval-plugin-stub","true"),pt.setAttribute("data-preserve-runtime","true"),x.appendChild(pt),rt.push({messageId:F.id,fingerprint:ft,bubble:at});return}}else if(Zt)if(F.variant==="reasoning"&&F.reasoning&&Zt.renderReasoning){if(!ee)return;mt=Zt.renderReasoning({message:F,defaultRenderer:()=>oc(F,o),config:o})}else if(F.variant==="tool"&&F.toolCall&&Zt.renderToolCall){if(!oe)return;mt=Zt.renderToolCall({message:F,defaultRenderer:()=>sc(F,o),config:o})}else Zt.renderMessage&&(mt=Zt.renderMessage({message:F,defaultRenderer:()=>{let nt=nc(F,b,Ht,o.messageActions,Le,{loadingIndicatorRenderer:H,widgetConfig:o});return F.role!=="user"&&uc(nt,F,o,q),nt},config:o}));if(!mt&&$e){let nt=tf(F);if(nt){let St=wo.get(F.id),Gt=St!==ft,at=o.wrapComponentDirectiveInBubble!==!1&&Un.getOptions(nt.component)?.bubbleChrome!==!1,pt=null;if(Gt){let ht=Zg(nt,{config:o,message:F,transform:b});if(ht&&nt.component==="PersonaArtifactInline"){let et=ht.hasAttribute("data-artifact-inline")?ht:ht.querySelector("[data-artifact-inline]"),_e=et?.getAttribute("data-artifact-inline")??"",vt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(_e):_e,zt=_e?a.querySelector(`#wrapper-${F.id}`)?.querySelector(`[data-artifact-inline="${vt}"]`)??null:null;et&&zt&&zt!==et&&eg(zt)&&(et===ht?ht=zt:et.replaceWith(zt))}if(ht)if(at){let et=document.createElement("div");if(et.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),et.id=`bubble-${F.id}`,et.setAttribute("data-message-id",F.id),F.content&&F.content.trim()){let _e=document.createElement("div");_e.className="persona-mb-3 persona-text-sm persona-leading-relaxed",_e.innerHTML=b({text:F.content,message:F,streaming:!!F.streaming,raw:F.rawContent}),et.appendChild(_e)}et.appendChild(ht),pt=et}else{let et=document.createElement("div");if(et.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",et.id=`bubble-${F.id}`,et.setAttribute("data-message-id",F.id),et.setAttribute("data-persona-component-directive","true"),F.content&&F.content.trim()){let _e=document.createElement("div");_e.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",_e.innerHTML=b({text:F.content,message:F,streaming:!!F.streaming,raw:F.rawContent}),et.appendChild(_e)}et.appendChild(ht),pt=et}}if(pt||St!=null){let ht=So(F.id,F.role);ht.setAttribute("data-component-directive-stub","true"),ht.setAttribute("data-preserve-runtime","true"),x.appendChild(ht),Me.push({messageId:F.id,fingerprint:ft,bubble:pt});return}}}if(!mt)if(F.variant==="reasoning"&&F.reasoning){if(!ee)return;mt=oc(F,o)}else if(F.variant==="tool"&&F.toolCall){if(!oe)return;mt=sc(F,o)}else if(F.variant==="approval"&&F.approval){if(o.approval===!1)return;mt=ya(F,o)}else{let nt=o.layout?.messages;nt?.renderUserMessage&&F.role==="user"?mt=nt.renderUserMessage({message:F,config:o,streaming:!!F.streaming}):nt?.renderAssistantMessage&&F.role==="assistant"?mt=nt.renderAssistantMessage({message:F,config:o,streaming:!!F.streaming}):mt=nc(F,b,nt,o.messageActions,Le,{loadingIndicatorRenderer:H,widgetConfig:o}),F.role!=="user"&&mt&&uc(mt,F,o,q)}let Oe=So(F.id,F.role);Oe.appendChild(mt),cg(Co,F.id,ft,Oe),x.appendChild(Oe)}),Ie.composerOverlay&&Ie.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let Ne=De.getAttribute("data-persona-ask-sheet-for");Ne&&!le.has(Ne)&&or(Ie.composerOverlay,Ne)}),o.features?.toolCallDisplay?.grouped){let F=[],De=[];f.forEach(Ne=>{if(Ne.variant==="tool"&&Ne.toolCall&&oe){De.push(Ne);return}Ne.variant==="reasoning"&&!ee||(De.length>1&&F.push(De),De=[])}),De.length>1&&F.push(De),F.forEach((Ne,$e)=>{let kt=Ne.map(St=>Array.from(x.children).find(Gt=>Gt instanceof HTMLElement&&Gt.getAttribute("data-wrapper-id")===St.id)).filter(St=>!!St);if(kt.length<2)return;let ft=So(`tool-group-${$e}-${Ne[0].id}`,"assistant");ft.setAttribute("data-persona-tool-group-row","true");let Kt=document.createElement("div");Kt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Kt.setAttribute("data-persona-tool-group","true");let mt=document.createElement("div");mt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Zt=`Called ${Ne.length} tools`,Ht=o.toolCall?.renderGroupedSummary?.({messages:Ne,toolCalls:Ne.map(St=>St.toolCall).filter(St=>!!St),defaultSummary:Zt,config:o});Z(mt,Ht)||(mt.textContent=Zt);let Oe=document.createElement("div");Oe.className="persona-tool-group-stack persona-flex persona-flex-col";let nt=o.features?.toolCallDisplay?.groupedMode==="summary";Kt.appendChild(mt),nt||Kt.appendChild(Oe),ft.appendChild(Kt),kt[0].before(ft),kt.forEach((St,Gt)=>{if(nt){St.remove();return}St.style.setProperty("--persona-message-row-max-width","100%");let at=document.createElement("div");at.className="persona-tool-group-item persona-relative",at.setAttribute("data-persona-tool-group-item","true"),Gt<kt.length-1&&at.setAttribute("data-persona-tool-group-connector","true"),at.appendChild(St),Oe.appendChild(at)})})}dg(Co,U);let rn=f.some(F=>F.role==="assistant"&&F.streaming),Et=f[f.length-1],Wt=Et?.role==="assistant"&&!Et.streaming&&Et.variant!=="approval";if(vn&&f.some(F=>F.role==="user")&&!rn&&!Wt){let F={config:o,streaming:!0,location:"standalone",defaultRenderer:As},De=r.find($e=>$e.renderLoadingIndicator),Ne=null;if(De?.renderLoadingIndicator&&(Ne=De.renderLoadingIndicator(F)),Ne===null&&o.loadingIndicator?.render&&(Ne=o.loadingIndicator.render(F)),Ne===null&&(Ne=As()),Ne){let $e=document.createElement("div"),kt=o.loadingIndicator?.showBubble!==!1;$e.className=kt?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),$e.setAttribute("data-typing-indicator","true"),$e.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",$e.appendChild(Ne);let ft=So("typing-indicator","assistant");ft.appendChild($e),x.appendChild(ft)}}if(!vn&&f.length>0){let F=f[f.length-1],De={config:o,lastMessage:F,messageCount:f.length},Ne=r.find(kt=>kt.renderIdleIndicator),$e=null;if(Ne?.renderIdleIndicator&&($e=Ne.renderIdleIndicator(De)),$e===null&&o.loadingIndicator?.renderIdle&&($e=o.loadingIndicator.renderIdle(De)),$e){let kt=document.createElement("div"),ft=o.loadingIndicator?.showBubble!==!1;kt.className=ft?["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(" "),kt.setAttribute("data-idle-indicator","true"),kt.appendChild($e);let Kt=So("idle-indicator","assistant");Kt.appendChild(kt),x.appendChild(Kt)}}if(Qd(x),Zi(a,x),ol(a),ie.length>0)for(let{messageId:F,fingerprint:De,bubble:Ne}of ie){let $e=a.querySelector(`#wrapper-${F}`);$e&&(Ks($e,J.get(F)??"assistant"),Ne!==null&&($e.replaceChildren(Ne),$e.setAttribute("data-bubble-fp",De),Uo.set(F,De)))}if(Uo.size>0)for(let F of Uo.keys())U.has(F)||Uo.delete(F);if(Me.length>0)for(let{messageId:F,fingerprint:De,bubble:Ne}of Me){let $e=a.querySelector(`#wrapper-${F}`);$e&&(Ks($e,J.get(F)??"assistant"),Ne!==null&&($e.replaceChildren(Ne),$e.setAttribute("data-bubble-fp",De),wo.set(F,De)))}if(wo.size>0)for(let F of wo.keys())U.has(F)||wo.delete(F);if(rt.length>0)for(let{messageId:F,fingerprint:De,bubble:Ne}of rt){let $e=a.querySelector(`#wrapper-${F}`);$e&&(Ks($e,J.get(F)??"assistant"),Ne!==null&&($e.replaceChildren(Ne),$e.setAttribute("data-bubble-fp",De),Gn.set(F,De)))}if(Gn.size>0)for(let F of Gn.keys())U.has(F)||Gn.delete(F)},Hr=(a,f,b)=>{_f(a,f,b),Fc()},Br=null,$f=()=>{if(Br)return;let a=b=>{let x=b.composedPath();x.includes(Be)||Ge&&x.includes(Ge)||ut(!1,"user")};Br=a,(t.ownerDocument??document).addEventListener("pointerdown",a,!0)},nd=()=>{if(!Br)return;(t.ownerDocument??document).removeEventListener("pointerdown",Br,!0),Br=null};Ue.push(()=>nd());let Dr=null,zf=()=>{if(Dr)return;let a=b=>{b.key==="Escape"&&(b.isComposing||ut(!1,"user"))};Dr=a,(t.ownerDocument??document).addEventListener("keydown",a,!0)},od=()=>{if(!Dr)return;(t.ownerDocument??document).removeEventListener("keydown",Dr,!0),Dr=null};Ue.push(()=>od());let Nr=!1,rd=new Set,Uf=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},qo=()=>{if(!L())return;let a=Ie.peekBanner,f=Ie.peekTextNode;if(!a||!f)return;if(I){a.classList.remove("persona-pill-peek--visible");return}let b=q?.getMessages()??[],x;for(let Et=b.length-1;Et>=0;Et--){let Wt=b[Et];if(Wt.role==="assistant"&&Wt.content){x=Wt;break}}if(!x){a.classList.remove("persona-pill-peek--visible");return}let S=x.content,H=!!x.streaming,Z=Uf(),U=oa(Z),J=U.type!=="none"?hr(U.type,Z?.plugins):null,le=J?.isAnimating?.(x)===!0,ve=J!==null&&(H||le);ve&&J&&!rd.has(J.name)&&(ia(J,t),rd.add(J.name));let ie=ve&&J?.containerClass?J.containerClass:null,Me=f.dataset.personaPeekStreamClass??null;Me&&Me!==ie&&(f.classList.remove(Me),delete f.dataset.personaPeekStreamClass),ie&&Me!==ie&&(f.classList.add(ie),f.dataset.personaPeekStreamClass=ie),ve?(f.style.setProperty("--persona-stream-step",`${U.speed}ms`),f.style.setProperty("--persona-stream-duration",`${U.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let je=ve?ra(S,U.buffer,J,x,H):S;if(ve&&U.placeholder==="skeleton"&&H&&(!je||!je.trim())){let Et=document.createElement("div"),Wt=ys();Wt.classList.add("persona-pill-peek__skeleton"),Et.appendChild(Wt),Zi(f,Et)}else{let Et=Math.max(0,je.length-100),Wt=je.length>100?je.slice(-100):je,F=oo(Wt);if(!ve||!J){let De=je.length>100?`\u2026${Wt}`:Wt;f.textContent!==De&&(f.textContent=De)}else{let De=F;(J.wrap==="char"||J.wrap==="word")&&(De=bs(F,J.wrap,`peek-${x.id}`,{skipTags:J.skipTags,startIndex:Et}));let Ne=document.createElement("div");if(Ne.innerHTML=De,J.useCaret&&Wt.length>0){let $e=sa(),kt=Ne.querySelectorAll(".persona-stream-char, .persona-stream-word"),ft=kt[kt.length-1];ft?.parentNode?ft.parentNode.insertBefore($e,ft.nextSibling):Ne.appendChild($e)}Zi(f,Ne),J.onAfterRender?.({container:f,bubble:a,messageId:x.id,message:x,speed:U.speed,duration:U.duration})}}let rn=vn||Nr;a.classList.toggle("persona-pill-peek--visible",rn)};if(L()){let a=Ie.peekBanner;if(a){let x=S=>{S.preventDefault(),S.stopPropagation(),ut(!0,"user")};a.addEventListener("pointerdown",x),Ue.push(()=>{a.removeEventListener("pointerdown",x)})}let f=()=>{Nr||(Nr=!0,qo())},b=()=>{Nr&&(Nr=!1,qo())};Ce.addEventListener("pointerenter",f),Ce.addEventListener("pointerleave",b),Ue.push(()=>{Ce.removeEventListener("pointerenter",f),Ce.removeEventListener("pointerleave",b)}),Ge&&(Ge.addEventListener("pointerenter",f),Ge.addEventListener("pointerleave",b),Ue.push(()=>{Ge.removeEventListener("pointerenter",f),Ge.removeEventListener("pointerleave",b)}))}let jf=a=>{let f=o.launcher?.composerBar??{},b=f.expandedSize??"anchored",x=f.bottomOffset??"16px",S=f.collapsedMaxWidth,H=f.expandedMaxWidth??"880px",Z=f.expandedTopOffset??"5vh",U=f.modalMaxWidth??"880px",J=f.modalMaxHeight??"min(90vh, 800px)",le="calc(100vw - 32px)",ve="var(--persona-pill-area-height, 80px)",ie=Be.style;if(ie.left="",ie.right="",ie.top="",ie.bottom="",ie.transform="",ie.width="",ie.maxWidth="",ie.height="",ie.maxHeight="",Ge){let Me=Ge.style;Me.bottom=x,Me.width=S??""}if(a&&b!=="fullscreen"){if(b==="modal"){ie.top="50%",ie.left="50%",ie.transform="translate(-50%, -50%)",ie.bottom="auto",ie.right="auto",ie.width=U,ie.maxWidth=le,ie.maxHeight=J,ie.height=J;return}ie.left="50%",ie.transform="translateX(-50%)",ie.bottom=`calc(${x} + ${ve})`,ie.top=Z,ie.width=H,ie.maxWidth=le}},Or=()=>{if(!P())return;if(L()){let le=(o.launcher?.composerBar??{}).expandedSize??"anchored",ve=I?"expanded":"collapsed";Be.dataset.state=ve,Be.dataset.expandedSize=le,Ge&&(Ge.dataset.state=ve,Ge.dataset.expandedSize=le),Be.style.removeProperty("display"),Be.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),jf(I),ye.style.display=I?"flex":"none",_s(),I?($f(),zf()):(nd(),od()),qo();return}let a=Ot(o),f=t.ownerDocument.defaultView??window,b=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,S=f.innerWidth<=b,H=x&&S&&A,Z=mn(o).reveal;I?(Be.style.removeProperty("display"),Be.style.display=a?"flex":"",Be.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-95","persona-opacity-0"),Ce.classList.add("persona-scale-100","persona-opacity-100"),Ft?Ft.element.style.display="none":Vt&&(Vt.style.display="none")):(a?a&&(Z==="overlay"||Z==="push")&&!H?(Be.style.removeProperty("display"),Be.style.display="flex",Be.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Be.style.setProperty("display","none","important"),Be.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Be.style.display="",Be.classList.add("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-100","persona-opacity-100"),Ce.classList.add("persona-scale-95","persona-opacity-0")),Ft?Ft.element.style.display=a?"none":"":Vt&&(Vt.style.display=a?"none":""))},ut=(a,f="user")=>{if(!P()||I===a)return;let b=I;I=a,Or();let x=(()=>{let H=o.launcher?.sidebarMode??!1,Z=t.ownerDocument.defaultView??window,U=o.launcher?.mobileFullscreen??!0,J=o.launcher?.mobileBreakpoint??640,le=Z.innerWidth<=J,ve=Ot(o)&&U&&le,ie=L()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return H||U&&le&&A||ve||ie})();if(I&&x){if(!Mn){let H=t.getRootNode(),Z=H instanceof ShadowRoot?H.host:t.closest(".persona-host");Z&&(Mn=Xl(Z,o.launcher?.zIndex??qt))}Tn||(Tn=Jl(t.ownerDocument))}else I||(Mn?.(),Mn=null,Tn?.(),Tn=null);I&&($r(),ed()||(Yt()==="follow"?Yn(!0):Yc()));let S={open:I,source:f,timestamp:Date.now()};I&&!b?l.emit("widget:opened",S):!I&&b&&l.emit("widget:closed",S),l.emit("widget:state",{open:I,launcherEnabled:A,voiceActive:Qe.active,streaming:q.isStreaming()})},$a=a=>{it(a?"stop":"send"),X&&(X.disabled=a),zs.buttons.forEach(f=>{f.disabled=a}),K.dataset.personaComposerStreaming=a?"true":"false",K.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=a)})},za=()=>{Qe.active||Ae&&Ae.focus()};l.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>za(),200)});let sd=()=>{j.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",v.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",Ae.placeholder=o.copy?.inputPlaceholder??"How can I help...";let a=ge.querySelector("[data-persona-intro-card]");if(a){let b=o.copy?.showWelcomeCard!==!1;a.style.display=b?"":"none",b?(ge.classList.remove("persona-gap-3"),ge.classList.add("persona-gap-6")):(ge.classList.remove("persona-gap-6"),ge.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!q?.isStreaming()&&(he.textContent=o.copy?.sendButtonLabel??"Send"),Ae.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Ae.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let a=d.sessionId;return typeof a=="string"?a:null},setStoredSessionId:a=>{C(f=>({...f,sessionId:a}))}});let Mo=null,qf=()=>{Mo==null&&(Mo=setInterval(()=>{let a=we.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(Mo),Mo=null;return}let f=Date.now();a.forEach(b=>{let x=Number(b.getAttribute("data-tool-elapsed"));x&&(b.textContent=hi(f-x))})},100))},Ua=(a,f)=>{if(Object.is(a,f))return!0;if(a===null||f===null||typeof a!="object"||typeof f!="object")return!1;if(Array.isArray(a)||Array.isArray(f))return!Array.isArray(a)||!Array.isArray(f)||a.length!==f.length?!1:a.every((Z,U)=>Ua(Z,f[U]));let b=a,x=f,S=Object.keys(b),H=Object.keys(x);return S.length===H.length&&S.every(Z=>Object.prototype.hasOwnProperty.call(x,Z)&&Ua(b[Z],x[Z]))},id=a=>{let{content:f,rawContent:b,llmContent:x,...S}=a;return S},ja=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!vc(a),Vf=(a,f,b)=>{if(a.length!==f.length)return!1;let x=a[b.index],S=f[b.index];return!x||!S||x.id!==b.id||S.id!==b.id?!1:(!Object.is(x.content,S.content)||!Object.is(x.rawContent,S.rawContent)||!Object.is(x.llmContent,S.llmContent))&&ja(x)&&ja(S)&&Ua(id(x),id(S))},ad=null,Vo=null,To=null,Wn=null,Gs=a=>{ad=a;let f,b;Vo=null;for(let S=a.length-1;S>=0;S-=1){let H=a[S];if(!f&&H.role==="user"&&(f=H),!b&&H.role==="assistant"&&(b=H),!Vo&&ja(H)&&(Vo={index:S,id:H.id}),f&&b&&Vo)break}Hr(we,a,pe),jl(we,bn.artifacts,{suppressTransition:vn}),qf(),Pa(a),Yn(!vn),Ff(a),a.length===0&&(Wr(),Pr=!0,Ha=!1),!Ra||js?(Ra=!0,Wa=f?.id??null,Ba=b?.id??null):f&&f.id!==Wa?(Wa=f.id,Nf(f.id)):b&&b.id!==Ba&&Of(),b&&(Ba=b.id);let x=Qe.lastUserMessageId;f&&f.id!==x&&(Qe.lastUserMessageId=f.id,l.emit("user:message",f)),Qe.lastUserMessageWasVoice=!!f?.viaVoice,Oa(a),qo()},qa=()=>{Wn!==null&&(cancelAnimationFrame(Wn),Wn=null);let a=To;To=null,a&&Gs(a)},ld=()=>{Wn!==null&&cancelAnimationFrame(Wn),Wn=null,To=null},Kf=a=>{let f=To??ad;if(vn&&f&&Vo&&Vf(f,a,Vo)){To=a,Wn===null&&(Wn=requestAnimationFrame(()=>{Wn=null;let b=To;To=null,b&&Gs(b)}));return}if(a.length===0){ld(),Gs(a);return}qa(),Gs(a)};q=new Ti(o,{onMessagesChanged(a){Kf(a)},onStatusChanged(a){let f=o.statusIndicator??{};Lt(k,(x=>x==="idle"?f.idleText??Bt.idle:x==="connecting"?f.connectingText??Bt.connecting:x==="connected"?f.connectedText??Bt.connected:x==="error"?f.errorText??Bt.error:x==="paused"?f.pausedText??Bt.paused:x==="resuming"?f.resumingText??Bt.resuming:Bt[x])(a),f,a)},onStreamingChanged(a){a||(q?.getMessages().length===0?ld():qa()),vn=a,$a(a),q&&Hr(we,q.getMessages(),pe),a||Yn(!0),on(),Ic(a?"Responding\u2026":"Response complete."),qo()},onVoiceStatusChanged(a){if(l.emit("voice:status",{status:a,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(a){case"listening":Hn(),Go();break;case"processing":Hn(),rm();break;case"speaking":Hn(),sm();break;default:a==="idle"&&q.isBargeInActive()?(Hn(),Go(),X?.setAttribute("aria-label","End voice session")):(Qe.active=!1,Hn(),Rn("system"),Cn());break}},onArtifactsState(a){bn=a,a.artifacts.length===0&&(_o=!1),jl(we,a.artifacts,{suppressTransition:vn}),In(),Oa()},onReconnect(a){let{executionId:f,lastEventId:b}=a.handle;a.phase==="paused"?l.emit("stream:paused",{executionId:f,after:b}):a.phase==="resuming"?l.emit("stream:resuming",{executionId:f,after:b,attempt:a.attempt??1}):l.emit("stream:resumed",{executionId:f,after:b})}}),dt.current=q,Ue.push(()=>q.cancel());let Va=null;if(q.onReadAloudChange((a,f)=>{Nc=a,Oc=f,Fc();let b=a??Va;a&&(Va=a);let x=b?q.getMessages().find(S=>S.id===b)??null:null;l.emit("message:read-aloud",{messageId:b,message:x,state:f,timestamp:Date.now()}),f==="idle"&&(Va=null)}),Ra=!0,o.voiceRecognition?.provider?.type==="runtype")try{q.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}o.clientToken&&q.initClientSession().catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)}),(Se||o.onSSEEvent)&&q.setSSEEventCallback((a,f)=>{o.onSSEEvent?.(a,f),Fe?.processEvent(a,f),Se?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(f)})});let cd=()=>{o.resume&&typeof o.reconnectStream=="function"&&q.resumeFromHandle(o.resume)};u?u.then(a=>{if(a){if(a.metadata&&(d=xc(a.metadata),E.syncFromMetadata()),a.messages?.length){js=!0;try{q.hydrateMessages(a.messages)}finally{js=!1}}a.artifacts?.length&&q.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>cd()):cd();let dd=()=>{!L()||I||!(o.launcher?.composerBar?.expandOnSubmit??!0)||ut(!0,"auto")},Gf=(a,f)=>a?f?{refs:[...a.refs,...f.refs],finalize:async()=>{let[b,x]=await Promise.allSettled([a.finalize(),f.finalize()]),S=[];return b.status==="fulfilled"?S.push(b.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",b.reason),x.status==="fulfilled"?S.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),Rv(S)}}:a:f,Qf=()=>{let f=Ae.getInlineMessageFields?.();return f&&f.contentSegments.some(x=>x.kind==="mention")?f.contentSegments:void 0},Fr=!1,Xf=async a=>{let f=Ae.value.trim(),b=Tt?.hasAttachments()??!1,x=f?await(tn?.takeInlineCommand(f)??Promise.resolve(null)):null;if(x?.kind==="action"){Ae.value="",Ae.style.height="auto",_r(),tn?.clear();return}let S=tn?.collectForSubmit()??null,H=x?.kind==="server"?x.mentions:null,Z=Gf(S,H),U=x?.kind==="prompt"?x.sendText:f,J=!!S&&S.refs.length>0;if(!U&&!b&&!J&&!H)return;dd();let le;b&&(le=[],le.push(...Tt.getContentParts()),U&&le.push(ir(U)));let ve=x?.kind==="prompt"?void 0:Qf();Ae.value="",Ae.style.height="auto",_r(),q.sendMessage(U,{contentParts:le,mentions:Z??void 0,contentSegments:ve,viaVoice:a?.viaVoice}),b&&Tt.clearAttachments(),S&&tn?.clear()},Ka=async a=>{if(!Fr){Fr=!0;try{await Xf(a)}finally{Fr=!1}}},pd=a=>{if(a.preventDefault(),q.isStreaming()){q.cancel(),Fe?.reset(),ke?.update();return}Fr||Ka()},Jf=()=>o.features?.composerHistory!==!1,Ga={...Kl},Qa=!1,_r=()=>{Ga={...Kl}},Yf=()=>q.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),Zf=a=>{if(!Ae)return;Qa=!0,Ae.value=a,Ae.dispatchEvent(new Event("input",{bubbles:!0})),Qa=!1;let f=Ae.value.length;Ae.setSelectionRange(f,f)},em=a=>{Qa||(a.isComposing||tn?.handleInput(a.inputType??void 0),_r())},tm=a=>{if(Ae&&!(!a.isComposing&&tn?.handleKeydown(a))){if(Jf()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let f=Ae.selectionStart===0&&Ae.selectionEnd===0,b=sg({direction:a.key==="ArrowUp"?"up":"down",history:Yf(),currentValue:Ae.value,atStart:f,state:Ga});if(Ga=b.state,b.handled){a.preventDefault(),b.value!==void 0&&Zf(b.value);return}}if(a.key==="Enter"&&!a.shiftKey){if(q.isStreaming()){a.preventDefault();return}if(Fr){a.preventDefault();return}_r(),a.preventDefault(),he.click()}}},ud=a=>{a.key!=="Escape"||a.isComposing||q.isStreaming()&&a.composedPath().includes(ye)&&(q.cancel(),Fe?.reset(),ke?.update(),_r(),a.preventDefault(),a.stopImmediatePropagation())},nm=async a=>{if(o.attachments?.enabled!==!0||!Tt)return;let f=kv(a.clipboardData);f.length!==0&&(a.preventDefault(),await Tt.handleFiles(f))},pn=null,En=!1,Ko=null,At=null,gd=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Qs=(a="user")=>{if(En||q.isStreaming())return;let f=gd();if(!f)return;pn=new f;let x=(o.voiceRecognition??{}).pauseDuration??2e3;pn.continuous=!0,pn.interimResults=!0,pn.lang="en-US";let S=Ae.value;pn.onresult=H=>{let Z="",U="";for(let le=0;le<H.results.length;le++){let ve=H.results[le],ie=ve[0].transcript;ve.isFinal?Z+=ie+" ":U=ie}let J=S+Z+U;Ae.value=J,Ko&&clearTimeout(Ko),(Z||U)&&(Ko=window.setTimeout(()=>{Ae.value.trim()&&pn&&En&&(Zn(),Ka({viaVoice:!0}))},x))},pn.onerror=H=>{H.error!=="no-speech"&&Zn()},pn.onend=()=>{if(En){let H=Ae.value.trim();H&&H!==S.trim()&&Ka({viaVoice:!0}),Zn()}};try{if(pn.start(),En=!0,Qe.active=!0,a!=="system"&&(Qe.manuallyDeactivated=!1),Rn(a),Cn(),X){let H=o.voiceRecognition??{};At={backgroundColor:X.style.backgroundColor,color:X.style.color,borderColor:X.style.borderColor,iconName:H.iconName??"mic",iconSize:parseFloat(H.iconSize??o.sendButton?.size??"40")||24};let Z=H.recordingBackgroundColor,U=H.recordingIconColor,J=H.recordingBorderColor;if(X.classList.add("persona-voice-recording"),X.style.backgroundColor=Z??"var(--persona-voice-recording-bg, #ef4444)",X.style.color=U??"var(--persona-voice-recording-indicator, #ffffff)",U){let le=X.querySelector("svg");le&&le.setAttribute("stroke",U)}J&&(X.style.borderColor=J),X.setAttribute("aria-label","Stop voice recognition")}}catch{Zn("system")}},Zn=(a="user")=>{if(En){if(En=!1,Ko&&(clearTimeout(Ko),Ko=null),pn){try{pn.stop()}catch{}pn=null}if(Qe.active=!1,Rn(a),Cn(),X){if(X.classList.remove("persona-voice-recording"),At){X.style.backgroundColor=At.backgroundColor,X.style.color=At.color,X.style.borderColor=At.borderColor;let f=X.querySelector("svg");f&&f.setAttribute("stroke",At.color||"currentColor"),At=null}X.setAttribute("aria-label","Start voice recognition")}}},om=(a,f)=>{let b=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=a?.provider?.type==="runtype",S=a?.provider?.type==="custom";if(!(b||x||S))return null;let Z=h("div","persona-send-button-wrapper"),U=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");U.type="button";let J=a?.tooltipText??"Start voice recognition";U.setAttribute("aria-label",J);let le=a?.iconName??"mic",ve=f?.size??"40px",ie=a?.iconSize??ve,Me=parseFloat(ie)||24,je=a?.backgroundColor??f?.backgroundColor,gt=a?.iconColor??f?.textColor;U.style.width=ie,U.style.height=ie,U.style.minWidth=ie,U.style.minHeight=ie,U.style.fontSize="18px",U.style.lineHeight="1",gt?U.style.color=gt:U.style.color="var(--persona-text, #111827)";let rn=se(le,Me,gt||"currentColor",1.5);rn?U.appendChild(rn):U.textContent="\u{1F3A4}",je?U.style.backgroundColor=je:U.style.backgroundColor="",a?.borderWidth&&(U.style.borderWidth=a.borderWidth,U.style.borderStyle="solid"),a?.borderColor&&(U.style.borderColor=a.borderColor),a?.paddingX&&(U.style.paddingLeft=a.paddingX,U.style.paddingRight=a.paddingX),a?.paddingY&&(U.style.paddingTop=a.paddingY,U.style.paddingBottom=a.paddingY),Z.appendChild(U);let Et=a?.showTooltip??!1;return $t({anchor:U,trigger:Z,text:()=>U.getAttribute("aria-label")??J,enabled:Et}),{micButton:U,micButtonWrapper:Z}},Xa=()=>{if(!X||At)return;let a=o.voiceRecognition??{};At={backgroundColor:X.style.backgroundColor,color:X.style.color,borderColor:X.style.borderColor,iconName:a.iconName??"mic",iconSize:parseFloat(a.iconSize??o.sendButton?.size??"40")||24}},Ja=(a,f)=>{if(!X)return;let b=X.querySelector("svg");b&&b.remove();let x=At?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),S=se(a,x,f,1.5);S&&X.appendChild(S)},Xs=()=>{X&&X.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Go=()=>{if(!X)return;Xa();let a=o.voiceRecognition??{},f=a.recordingBackgroundColor,b=a.recordingIconColor,x=a.recordingBorderColor;if(Xs(),X.classList.add("persona-voice-recording"),X.style.backgroundColor=f??"var(--persona-voice-recording-bg, #ef4444)",X.style.color=b??"var(--persona-voice-recording-indicator, #ffffff)",b){let S=X.querySelector("svg");S&&S.setAttribute("stroke",b)}x&&(X.style.borderColor=x),X.setAttribute("aria-label","Stop voice recognition")},rm=()=>{if(!X)return;Xa();let a=o.voiceRecognition??{},f=q.getVoiceInterruptionMode(),b=a.processingIconName??"loader",x=a.processingIconColor??At?.color??"",S=a.processingBackgroundColor??At?.backgroundColor??"",H=a.processingBorderColor??At?.borderColor??"";Xs(),X.classList.add("persona-voice-processing"),X.style.backgroundColor=S,X.style.borderColor=H;let Z=x||"currentColor";X.style.color=Z,Ja(b,Z),X.setAttribute("aria-label","Processing voice input"),f==="none"&&(X.style.cursor="default")},sm=()=>{if(!X)return;Xa();let a=o.voiceRecognition??{},f=q.getVoiceInterruptionMode(),b=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",x=a.speakingIconName??b,S=a.speakingIconColor??(f==="barge-in"?a.recordingIconColor??At?.color??"":At?.color??""),H=a.speakingBackgroundColor??(f==="barge-in"?a.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":At?.backgroundColor??""),Z=a.speakingBorderColor??(f==="barge-in"?a.recordingBorderColor??"":At?.borderColor??"");Xs(),X.classList.add("persona-voice-speaking"),X.style.backgroundColor=H,X.style.borderColor=Z;let U=S||"currentColor";X.style.color=U,Ja(x,U);let J=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";X.setAttribute("aria-label",J),f==="none"&&(X.style.cursor="default"),f==="barge-in"&&X.classList.add("persona-voice-recording")},Hn=()=>{X&&(Xs(),At&&(X.style.backgroundColor=At.backgroundColor??"",X.style.color=At.color??"",X.style.borderColor=At.borderColor??"",Ja(At.iconName,At.color||"currentColor"),At=null),X.style.cursor="",X.setAttribute("aria-label","Start voice recognition"))},Js=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let a=q.getVoiceStatus(),f=q.getVoiceInterruptionMode();if(f==="none"&&(a==="processing"||a==="speaking"))return;if(f==="cancel"&&(a==="processing"||a==="speaking")){q.stopVoicePlayback();return}if(q.isBargeInActive()){q.stopVoicePlayback(),q.deactivateBargeIn().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,Cn(),Rn("user"),Hn()});return}q.toggleVoice().then(()=>{Qe.active=q.isVoiceActive(),Qe.manuallyDeactivated=!q.isVoiceActive(),Cn(),Rn("user"),q.isVoiceActive()?Go():Hn()});return}if(En){let a=Ae.value.trim();Qe.manuallyDeactivated=!0,Cn(),Zn("user"),a&&(Ae.value="",Ae.style.height="auto",q.sendMessage(a))}else Qe.manuallyDeactivated=!1,Cn(),Qs("user")};Wc=Js,X&&(X.addEventListener("click",Js),Ue.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),Hn()):Zn("system"),X&&X.removeEventListener("click",Js)}));let im=l.on("assistant:complete",()=>{Vc&&(Qe.active||Qe.manuallyDeactivated||Vc==="assistant"&&!Qe.lastUserMessageWasVoice||setTimeout(()=>{!Qe.active&&!Qe.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?q.toggleVoice().then(()=>{Qe.active=q.isVoiceActive(),Rn("auto"),q.isVoiceActive()&&Go()}):Qs("auto"))},600))});Ue.push(im);let am=l.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});Ue.push(am);let fd=()=>{ut(!I,"user")},Ft=null,Vt=null;if(A&&!L()){let{instance:a,element:f}=Zl({config:o,plugins:r,onToggle:fd});Ft=a,a||(Vt=f)}Ft?t.appendChild(Ft.element):Vt&&t.appendChild(Vt),Or(),Pa(),sd(),$a(q.isStreaming()),ed()||(Yt()==="follow"?Yn(!0):Yc()),If(),z&&(!A||L()?setTimeout(()=>za(),0):I&&setTimeout(()=>za(),200));let $r=()=>{if(L()){Fo(),Or();return}let a=Ot(o),f=o.launcher?.sidebarMode??!1,b=a||f||(o.launcher?.fullHeight??!1),x=t.ownerDocument.defaultView??window,S=o.launcher?.mobileFullscreen??!0,H=o.launcher?.mobileBreakpoint??640,Z=x.innerWidth<=H,U=S&&Z&&A;try{if(U){Tr(),Er=Fs();return}let J=!1;N&&(N=!1,Tr(),J=!0);let le=Fs();if(!J&&le!==Er&&(Tr(),J=!0),Er=le,J&&ka(),!A&&!a){Ce.style.height="",Ce.style.width="";return}if(!f&&!a){let ie=o?.launcher?.width??o?.launcherWidth??zn;Ce.style.width=ie,Ce.style.maxWidth=ie}if(Os(),!b){let ve=x.innerHeight,ie=64,Me=o.launcher?.heightOffset??0,je=Math.max(200,ve-ie),gt=Math.min(640,je),rt=Math.max(200,gt-Me);Ce.style.height=`${rt}px`}}finally{if(Fo(),Or(),I&&A){let le=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ve=o.launcher?.sidebarMode??!1,ie=o.launcher?.mobileFullscreen??!0,Me=Ot(o)&&ie&&le,je=ve||ie&&le&&A||Me;if(je&&!Tn){let gt=t.getRootNode(),rt=gt instanceof ShadowRoot?gt.host:t.closest(".persona-host");rt&&!Mn&&(Mn=Xl(rt,o.launcher?.zIndex??qt)),Tn=Jl(t.ownerDocument)}else je||(Mn?.(),Mn=null,Tn?.(),Tn=null)}}};$r();let md=t.ownerDocument.defaultView??window;if(md.addEventListener("resize",$r),Ue.push(()=>md.removeEventListener("resize",$r)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{Fo()});a.observe(K),Ue.push(()=>a.disconnect())}cn=ge.scrollTop;let hd=Ln(ge),lm=()=>{let a=ge.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??ge.ownerDocument.getSelection()},Ya=()=>pg(lm(),ge),bd=()=>{let a=ge.scrollTop,f=Ln(ge),b=f<hd;if(hd=f,!jn()){cn=a,on();return}let{action:x,nextLastScrollTop:S}=ta({following:nn.isFollowing(),currentScrollTop:a,lastScrollTop:cn,nearBottom:uo(ge,qs),userScrollThreshold:Lf,isAutoScrolling:dn||Us||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(cn=S,x==="resume"){Ya()||Jn();return}x==="pause"&&Rr()};if(ge.addEventListener("scroll",bd,{passive:!0}),Ue.push(()=>ge.removeEventListener("scroll",bd)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{Df(),ol(we)});a.observe(we),a.observe(ge),Ue.push(()=>a.disconnect())}let yd=()=>{jn()&&nn.isFollowing()&&Ya()&&Rr()},vd=ge.ownerDocument;vd.addEventListener("selectionchange",yd),Ue.push(()=>{vd.removeEventListener("selectionchange",yd)});let cm=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),xd=a=>{kc()&&jn()&&nn.isFollowing()&&cm.has(a.key)&&Rr()},Cd=a=>{if(!kc()||!jn()||!nn.isFollowing())return;let f=a.target;f&&f.closest("a, button, [tabindex], input, textarea, select")&&Rr()};ge.addEventListener("keydown",xd),ge.addEventListener("focusin",Cd),Ue.push(()=>{ge.removeEventListener("keydown",xd),ge.removeEventListener("focusin",Cd)});let wd=a=>{if(!jn())return;let f=na({following:nn.isFollowing(),deltaY:a.deltaY,nearBottom:uo(ge,qs),resumeWhenNearBottom:!0});f==="pause"?Rr():f==="resume"&&!Ya()&&Jn()};ge.addEventListener("wheel",wd,{passive:!0}),Ue.push(()=>ge.removeEventListener("wheel",wd)),It.addEventListener("click",()=>{Wr(),ge.scrollTop=ge.scrollHeight,cn=ge.scrollTop,Jn(),Yn(!0),on()}),Ue.push(()=>It.remove()),Ue.push(()=>{Qc(),Wr()});let Ad=()=>{T&&(xo&&(T.removeEventListener("click",xo),xo=null),P()?(T.style.display="",xo=()=>{ut(!1,"user")},T.addEventListener("click",xo)):T.style.display="none")};Ad(),(()=>{let{clearChatButton:a}=Ie;a&&a.addEventListener("click",()=>{q.clearMessages(),Co.clear(),Jn(),or(Ie.composerOverlay);try{localStorage.removeItem(xr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xr}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==xr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(f),c?.clear&&Na(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),d={},E.syncFromMetadata(),Se?.clear(),Fe?.reset(),ke?.update()})})(),te&&te.addEventListener("submit",pd);let Sd=[["keydown",tm],["input",em],["paste",nm],["focus",Sf]],Md=a=>{if(a)for(let[f,b]of Sd)a.addEventListener(f,b)},Td=a=>{if(a)for(let[f,b]of Sd)a.removeEventListener(f,b)};Md(Ae),tn?.onComposerSwap((a,f)=>{Td(f),Ae=a,Md(a)});let Ed=t.ownerDocument??document;Ed.addEventListener("keydown",ud,!0);let kd="persona-attachment-drop-active",zr=0,Za=()=>{zr=0,ye.classList.remove(kd)},Qo=()=>o.attachments?.enabled===!0&&Tt!==null,Ld=a=>{!xa(a.dataTransfer)||!Qo()||(zr++,zr===1&&ye.classList.add(kd))},Pd=a=>{!xa(a.dataTransfer)||!Qo()||(zr--,zr<=0&&Za())},Id=a=>{!xa(a.dataTransfer)||!Qo()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},Rd=a=>{if(!xa(a.dataTransfer)||!Qo())return;a.preventDefault(),a.stopPropagation(),Za();let f=Array.from(a.dataTransfer.files??[]);f.length!==0&&Tt.handleFiles(f)},eo=!0;ye.addEventListener("dragenter",Ld,eo),ye.addEventListener("dragleave",Pd,eo),t.addEventListener("dragover",Id,eo),t.addEventListener("drop",Rd,eo);let Ys=t.ownerDocument,Wd=a=>{Qo()&&a.preventDefault()},Hd=a=>{Qo()&&a.preventDefault()};Ys.addEventListener("dragover",Wd),Ys.addEventListener("drop",Hd),Ue.push(()=>{te&&te.removeEventListener("submit",pd),Td(Ae),Ed.removeEventListener("keydown",ud,!0),tn?.destroy()}),Ue.push(()=>{ye.removeEventListener("dragenter",Ld,eo),ye.removeEventListener("dragleave",Pd,eo),t.removeEventListener("dragover",Id,eo),t.removeEventListener("drop",Rd,eo),Ys.removeEventListener("dragover",Wd),Ys.removeEventListener("drop",Hd),Za()}),Ue.push(()=>{q.cancel()}),Ft?Ue.push(()=>{Ft?.destroy()}):Vt&&Ue.push(()=>{Vt?.remove()});let Rt={update(a){let f=o.toolCall,b=o.messageActions,x=o.layout?.messages,S=o.colorScheme,H=o.loadingIndicator,Z=o.iterationDisplay,U=o.features?.showReasoning,J=o.features?.showToolCalls,le=o.features?.toolCallDisplay,ve=o.features?.reasoningDisplay,ie=o.features?.streamAnimation?.type;o=Qg(o,a),_s(),ps(t,o),Es(t,o),ks(t,o),In(),o.colorScheme!==S&&qc();let Me=fc.getForInstance(o.plugins);r.length=0,r.push(...Me),A=o.launcher?.enabled??!0,W=o.launcher?.autoExpand??!1,ee=o.features?.showReasoning??!0,oe=o.features?.showToolCalls??!0,ae=o.features?.scrollToBottom??{};let je=Yt();ne=o.features?.scrollBehavior??{},je!==Yt()&&(Wr(),Jn()),Rc(),on();let gt=V;if(V=o.features?.showEventStreamToggle??!1,V&&!gt){if(Se||(fe=new Ms(be),Se=new Ss(Te,fe),Fe=Fe??new Ts,fe.open().then(()=>Se?.restore()).catch(()=>{}),q.setSSEEventCallback((re,Ke)=>{o.onSSEEvent?.(re,Ke),Fe?.processEvent(re,Ke),Se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:re,timestamp:Date.now(),payload:JSON.stringify(Ke)})})),!ot&&$){let re=o.features?.eventStream?.classNames,Ke="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"+(re?.toggleButton?" "+re.toggleButton:"");ot=h("button",Ke),ot.style.width="28px",ot.style.height="28px",ot.style.color=Xt.actionIconColor,ot.type="button",ot.setAttribute("aria-label","Event Stream"),ot.title="Event Stream";let bt=se("activity","18px","currentColor",1.5);bt&&ot.appendChild(bt);let st=Ie.clearChatButtonWrapper,lt=Ie.closeButtonWrapper,Ut=st||lt;Ut&&Ut.parentNode===$?$.insertBefore(ot,Ut):$.appendChild(ot),ot.addEventListener("click",()=>{qe?Sr():Sa()})}}else!V&&gt&&(Sr(),ot&&(ot.remove(),ot=null),Se?.clear(),fe?.destroy(),Se=null,fe=null,Fe?.reset(),Fe=null);if(o.launcher?.enabled===!1&&Ft&&(Ft.destroy(),Ft=null),o.launcher?.enabled===!1&&Vt&&(Vt.remove(),Vt=null),o.launcher?.enabled!==!1&&!Ft&&!Vt){let{instance:re,element:Ke}=Zl({config:o,plugins:r,onToggle:fd});Ft=re,re||(Vt=Ke),t.appendChild(Ke)}Ft&&Ft.update(o),_&&o.launcher?.title!==void 0&&(_.textContent=o.launcher.title),Q&&o.launcher?.subtitle!==void 0&&(Q.textContent=o.launcher.subtitle);let rt=o.layout?.header;if(rt?.layout!==O&&$){let re=rt?ca(o,rt,{showClose:P(),onClose:()=>ut(!1,"user")}):Bo({config:o,showClose:P(),onClose:()=>ut(!1,"user")});xt.replaceHeader(re),$=xt.header.element,R=xt.header.iconHolder,_=xt.header.headerTitle,Q=xt.header.headerSubtitle,T=xt.header.closeButton,O=rt?.layout}else if(rt){if(R&&(R.style.display=rt.showIcon===!1?"none":""),_&&(_.style.display=rt.showTitle===!1?"none":""),Q&&(Q.style.display=rt.showSubtitle===!1?"none":""),T){let re=P()&&rt.showCloseButton!==!1;T.style.display=re?"":"none"}if(Ie.clearChatButtonWrapper){let re=rt.showClearChat;if(re!==void 0){Ie.clearChatButtonWrapper.style.display=re?"":"none";let{closeButtonWrapper:Ke}=Ie;Ke&&!Ke.classList.contains("persona-absolute")&&(re?Ke.classList.remove("persona-ml-auto"):Ke.classList.add("persona-ml-auto"))}}}let Et=o.layout?.showHeader!==!1;$&&($.style.display=Et?"":"none");let Wt=o.layout?.showFooter!==!1;K&&(K.style.display=Wt?"":"none"),Fo(),on(),A!==w?A?ut(W,"auto"):(I=!0,Or()):W!==G&&ut(W,"auto"),G=W,w=A,$r(),Ad();let Ne=JSON.stringify(o.toolCall)!==JSON.stringify(f),$e=JSON.stringify(o.messageActions)!==JSON.stringify(b),kt=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),ft=o.loadingIndicator?.render!==H?.render||o.loadingIndicator?.renderIdle!==H?.renderIdle||o.loadingIndicator?.showBubble!==H?.showBubble,Kt=o.iterationDisplay!==Z,mt=(o.features?.showReasoning??!0)!==(U??!0)||(o.features?.showToolCalls??!0)!==(J??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(le)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ve);(Ne||$e||kt||ft||Kt||mt)&&q&&(Ia++,Hr(we,q.getMessages(),pe));let Ht=o.features?.streamAnimation?.type;if(Ht!==ie&&Ht&&Ht!=="none"){let re=hr(Ht,o.features?.streamAnimation?.plugins);re&&ia(re,t)}let Oe=o.launcher??{},nt=Oe.headerIconHidden??!1,St=o.layout?.header?.showIcon,Gt=nt||St===!1,at=Oe.headerIconName,pt=Oe.headerIconSize??"48px";if(R){let re=ye.querySelector(".persona-border-b-persona-divider"),Ke=re?.querySelector(".persona-flex-col");if(Gt)R.style.display="none",re&&Ke&&!re.contains(Ke)&&re.insertBefore(Ke,re.firstChild);else{if(R.style.display="",R.style.height=pt,R.style.width=pt,re&&Ke&&(re.contains(R)?R.nextSibling!==Ke&&(R.remove(),re.insertBefore(R,Ke)):re.insertBefore(R,Ke)),at){let st=parseFloat(pt)||24,lt=se(at,st*.6,"currentColor",1);lt?R.replaceChildren(lt):R.textContent=Oe.agentIconText??"\u{1F4AC}"}else if(Oe.iconUrl){let st=R.querySelector("img");if(st)st.src=Oe.iconUrl,st.style.height=pt,st.style.width=pt;else{let lt=document.createElement("img");lt.src=Oe.iconUrl,lt.alt="",lt.className="persona-rounded-xl persona-object-cover",lt.style.height=pt,lt.style.width=pt,R.replaceChildren(lt)}}else{let st=R.querySelector("svg"),lt=R.querySelector("img");(st||lt)&&R.replaceChildren(),R.textContent=Oe.agentIconText??"\u{1F4AC}"}let bt=R.querySelector("img");bt&&(bt.style.height=pt,bt.style.width=pt)}}let ht=o.layout?.header?.showTitle,et=o.layout?.header?.showSubtitle;if(_&&(_.style.display=ht===!1?"none":""),Q&&(Q.style.display=et===!1?"none":""),T){let re=P()&&o.layout?.header?.showCloseButton!==!1;T.style.display=re?"":"none";let Ke=Oe.closeButtonSize??"32px",bt=Oe.closeButtonPlacement??"inline";T.style.height=Ke,T.style.width=Ke;let{closeButtonWrapper:st}=Ie,lt=bt==="top-right",Ut=st?.classList.contains("persona-absolute");if(st&&lt!==Ut)if(st.remove(),lt)st.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ye.style.position="relative",ye.appendChild(st);else{let no=Oe.clearChat?.placement??"inline",qr=Oe.clearChat?.enabled??!0;st.className=qr&&no==="inline"?"":"persona-ml-auto";let Bd=ye.querySelector(".persona-border-b-persona-divider");Bd&&Bd.appendChild(st)}if(T.style.color=Oe.closeButtonColor||Xt.actionIconColor,Oe.closeButtonBackgroundColor?(T.style.backgroundColor=Oe.closeButtonBackgroundColor,T.classList.remove("hover:persona-bg-gray-100")):(T.style.backgroundColor="",T.classList.add("hover:persona-bg-gray-100")),Oe.closeButtonBorderWidth||Oe.closeButtonBorderColor){let no=Oe.closeButtonBorderWidth||"0px",qr=Oe.closeButtonBorderColor||"transparent";T.style.border=`${no} solid ${qr}`,T.classList.remove("persona-border-none")}else T.style.border="",T.classList.add("persona-border-none");Oe.closeButtonBorderRadius?(T.style.borderRadius=Oe.closeButtonBorderRadius,T.classList.remove("persona-rounded-full")):(T.style.borderRadius="",T.classList.add("persona-rounded-full")),Oe.closeButtonPaddingX?(T.style.paddingLeft=Oe.closeButtonPaddingX,T.style.paddingRight=Oe.closeButtonPaddingX):(T.style.paddingLeft="",T.style.paddingRight=""),Oe.closeButtonPaddingY?(T.style.paddingTop=Oe.closeButtonPaddingY,T.style.paddingBottom=Oe.closeButtonPaddingY):(T.style.paddingTop="",T.style.paddingBottom="");let sn=Oe.closeButtonIconName??"x",wn=Oe.closeButtonIconText??"\xD7";T.innerHTML="";let _t=se(sn,"28px","currentColor",1);_t?(_t.style.display="block",T.appendChild(_t)):T.textContent=wn;let jt=Oe.closeButtonTooltipText??"Close chat",Dn=Oe.closeButtonShowTooltip??!0;T.setAttribute("aria-label",jt),st&&$t({anchor:T,trigger:st,text:()=>T?.getAttribute("aria-label")??jt,enabled:Dn})}let{clearChatButton:_e,clearChatButtonWrapper:vt}=Ie;if(_e){let re=Oe.clearChat??{},Ke=re.enabled??!0,bt=o.layout?.header?.showClearChat,st=bt!==void 0?bt:Ke,lt=re.placement??"inline";if(vt){vt.style.display=st?"":"none";let{closeButtonWrapper:Ut}=Ie;!L()&&Ut&&!Ut.classList.contains("persona-absolute")&&(st?Ut.classList.remove("persona-ml-auto"):Ut.classList.add("persona-ml-auto"));let sn=lt==="top-right",wn=vt.classList.contains("persona-absolute");if(!L()&&sn!==wn&&st){if(vt.remove(),sn)vt.className="persona-absolute persona-top-4 persona-z-50",vt.style.right="48px",ye.style.position="relative",ye.appendChild(vt);else{vt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",vt.style.right="";let jt=ye.querySelector(".persona-border-b-persona-divider"),Dn=Ie.closeButtonWrapper;jt&&Dn&&Dn.parentElement===jt?jt.insertBefore(vt,Dn):jt&&jt.appendChild(vt)}let _t=Ie.closeButtonWrapper;_t&&!_t.classList.contains("persona-absolute")&&(sn?_t.classList.add("persona-ml-auto"):_t.classList.remove("persona-ml-auto"))}}if(st){if(!L()){let no=re.size??"32px";_e.style.height=no,_e.style.width=no}let Ut=re.iconName??"refresh-cw",sn=re.iconColor??"";_e.style.color=sn||Xt.actionIconColor,_e.innerHTML="";let wn=L()?"14px":"20px",_t=se(Ut,wn,"currentColor",1);if(_t&&(_t.style.display="block",_e.appendChild(_t)),re.backgroundColor?(_e.style.backgroundColor=re.backgroundColor,_e.classList.remove("hover:persona-bg-gray-100")):(_e.style.backgroundColor="",_e.classList.add("hover:persona-bg-gray-100")),re.borderWidth||re.borderColor){let no=re.borderWidth||"0px",qr=re.borderColor||"transparent";_e.style.border=`${no} solid ${qr}`,_e.classList.remove("persona-border-none")}else _e.style.border="",_e.classList.add("persona-border-none");re.borderRadius?(_e.style.borderRadius=re.borderRadius,_e.classList.remove("persona-rounded-full")):(_e.style.borderRadius="",_e.classList.add("persona-rounded-full")),re.paddingX?(_e.style.paddingLeft=re.paddingX,_e.style.paddingRight=re.paddingX):(_e.style.paddingLeft="",_e.style.paddingRight=""),re.paddingY?(_e.style.paddingTop=re.paddingY,_e.style.paddingBottom=re.paddingY):(_e.style.paddingTop="",_e.style.paddingBottom="");let jt=re.tooltipText??"Clear chat",Dn=re.showTooltip??!0;_e.setAttribute("aria-label",jt),vt&&$t({anchor:_e,trigger:vt,text:()=>_e?.getAttribute("aria-label")??jt,enabled:Dn})}}let zt=o.actionParsers&&o.actionParsers.length?o.actionParsers:[hc],gn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Ls.message,Ls.messageAndClick];E=bc({parsers:zt,handlers:gn,getSessionMetadata:m,updateSessionMetadata:C,emit:l.emit,documentRef:typeof document<"u"?document:null}),pe=sf(o,E,ue),q.updateConfig(o),Hr(we,q.getMessages(),pe),Pa(),sd(),$a(q.isStreaming());let Ur=o.voiceRecognition?.enabled===!0,Zs=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Pt=o.voiceRecognition?.provider?.type==="runtype";if(Ur&&(Zs||Pt))if(!X||!ze){let re=om(o.voiceRecognition,o.sendButton);re&&(X=re.micButton,ze=re.micButtonWrapper,Ve.insertBefore(ze,hn),X.addEventListener("click",Js),X.disabled=q.isStreaming())}else{let re=o.voiceRecognition??{},Ke=o.sendButton??{},bt=re.iconName??"mic",st=Ke.size??"40px",lt=re.iconSize??st,Ut=parseFloat(lt)||24;X.style.width=lt,X.style.height=lt,X.style.minWidth=lt,X.style.minHeight=lt;let sn=re.iconColor??Ke.textColor;X.innerHTML="";let wn=se(bt,Ut,sn||"currentColor",1.5);wn?X.appendChild(wn):X.textContent="\u{1F3A4}";let _t=re.backgroundColor??Ke.backgroundColor;_t?X.style.backgroundColor=_t:X.style.backgroundColor="",sn?X.style.color=sn:X.style.color="var(--persona-text, #111827)",re.borderWidth?(X.style.borderWidth=re.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),re.borderColor?X.style.borderColor=re.borderColor:X.style.borderColor="",re.paddingX?(X.style.paddingLeft=re.paddingX,X.style.paddingRight=re.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),re.paddingY?(X.style.paddingTop=re.paddingY,X.style.paddingBottom=re.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let jt=re.tooltipText??"Start voice recognition",Dn=re.showTooltip??!1;X.setAttribute("aria-label",jt),ze&&$t({anchor:X,trigger:ze,text:()=>X?.getAttribute("aria-label")??jt,enabled:Dn}),ze.style.display="",X.disabled=q.isStreaming()}else X&&ze&&(ze.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?q.isVoiceActive()&&q.toggleVoice():En&&Zn());if(o.attachments?.enabled===!0){if(!We||!Ee){let re=o.attachments??{},bt=(o.sendButton??{}).size??"40px";Ye||(Ye=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ye.style.display="none",te.insertBefore(Ye,Ae)),Re||(Re=document.createElement("input"),Re.type="file",Re.accept=(re.allowedTypes??$n).join(","),Re.multiple=(re.maxFiles??4)>1,Re.style.display="none",Re.setAttribute("aria-label","Attach files"),te.insertBefore(Re,Ae)),We=h("div","persona-send-button-wrapper"),Ee=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ee.type="button",Ee.setAttribute("aria-label",re.buttonTooltipText??"Attach file");let st=re.buttonIconName??"paperclip",lt=bt,Ut=parseFloat(lt)||40,sn=Math.round(Ut*.6);Ee.style.width=lt,Ee.style.height=lt,Ee.style.minWidth=lt,Ee.style.minHeight=lt,Ee.style.fontSize="18px",Ee.style.lineHeight="1";let wn=se(st,sn,"currentColor",1.5);wn?Ee.appendChild(wn):Ee.textContent="\u{1F4CE}",Ee.addEventListener("click",jt=>{jt.preventDefault(),Re?.click()}),We.appendChild(Ee);let _t=re.buttonTooltipText??"Attach file";$t({anchor:Ee,trigger:We,text:()=>Ee?.getAttribute("aria-label")??_t}),Pe?Pe.append(We):te.appendChild(We),!Tt&&Re&&Ye&&(Tt=os.fromConfig(re),Tt.setPreviewsContainer(Ye),Re.addEventListener("change",async()=>{Tt&&Re?.files&&(await Tt.handleFileSelect(Re.files),Re.value="")}))}else{We.style.display="";let re=o.attachments??{};Re&&(Re.accept=(re.allowedTypes??$n).join(","),Re.multiple=(re.maxFiles??4)>1),Tt&&Tt.updateConfig({allowedTypes:re.allowedTypes,maxFileSize:re.maxFileSize,maxFiles:re.maxFiles})}if(ye.querySelector(".persona-attachment-drop-overlay")?.remove(),ye.appendChild(af(o.attachments?.dropOverlay)),Ee){let re=o.attachments??{},Ke=re.buttonTooltipText??"Attach file";Ee.setAttribute("aria-label",Ke),Ee.textContent="";let bt=parseFloat(o.sendButton?.size??"40px")||40,st=se(re.buttonIconName??"paperclip",Math.round(bt*.6),"currentColor",1.5);st?Ee.appendChild(st):Ee.textContent="\u{1F4CE}",We&&$t({anchor:Ee,trigger:We,text:()=>Ee?.getAttribute("aria-label")??Ke})}}else We&&(We.style.display="none"),Tt&&Tt.clearAttachments(),ye.querySelector(".persona-attachment-drop-overlay")?.remove();let Nt=o.sendButton??{},jr=Nt.useIcon??!1,ti=Nt.iconText??"\u2191",Xo=Nt.iconName,ni=Nt.tooltipText??"Send message",el=Nt.showTooltip??!1,Eo=Nt.size??"40px",Bn=Nt.backgroundColor,ko=Nt.textColor;if(jr){if(he.style.width=Eo,he.style.height=Eo,he.style.minWidth=Eo,he.style.minHeight=Eo,he.style.fontSize="18px",he.style.lineHeight="1",ko?he.style.color=ko:he.style.color="var(--persona-button-primary-fg, #ffffff)",!q.isStreaming())if(he.innerHTML="",Xo){let re=parseFloat(Eo)||24,Ke=ko?.trim()||"currentColor",bt=se(Xo,re,Ke,2);bt?he.appendChild(bt):he.textContent=ti}else he.textContent=ti;he.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Bn?(he.style.backgroundColor=Bn,he.classList.remove("persona-bg-persona-primary")):(he.style.backgroundColor="",he.classList.add("persona-bg-persona-primary"))}else he.textContent=o.copy?.sendButtonLabel??"Send",he.style.width="",he.style.height="",he.style.minWidth="",he.style.minHeight="",he.style.fontSize="",he.style.lineHeight="",he.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",Bn?(he.style.backgroundColor=Bn,he.classList.remove("persona-bg-persona-accent")):he.classList.add("persona-bg-persona-accent"),ko?he.style.color=ko:he.classList.add("persona-text-white");Nt.borderWidth?(he.style.borderWidth=Nt.borderWidth,he.style.borderStyle="solid"):(he.style.borderWidth="",he.style.borderStyle=""),Nt.borderColor?he.style.borderColor=Nt.borderColor:he.style.borderColor="",Nt.paddingX?(he.style.paddingLeft=Nt.paddingX,he.style.paddingRight=Nt.paddingX):(he.style.paddingLeft="",he.style.paddingRight=""),Nt.paddingY?(he.style.paddingTop=Nt.paddingY,he.style.paddingBottom=Nt.paddingY):(he.style.paddingTop="",he.style.paddingBottom=""),q.isStreaming()||he.setAttribute("aria-label",ni),hn&&$t({anchor:he,trigger:hn,text:()=>he.getAttribute("aria-label")??ni,enabled:el});let oi=o.layout?.contentMaxWidth??(L()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);oi?(we.style.maxWidth=oi,we.style.marginLeft="auto",we.style.marginRight="auto",we.style.width="100%",te&&(te.style.maxWidth=oi,te.style.marginLeft="auto",te.style.marginRight="auto"),Ct&&(Ct.style.maxWidth=oi,Ct.style.marginLeft="auto",Ct.style.marginRight="auto")):(we.style.maxWidth="",we.style.marginLeft="",we.style.marginRight="",we.style.width="",te&&(te.style.maxWidth="",te.style.marginLeft="",te.style.marginRight=""),Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""));let to=o.statusIndicator??{},dm=to.visible??!0;if(k.style.display=dm?"":"none",q){let re=q.getStatus();Lt(k,(bt=>bt==="idle"?to.idleText??Bt.idle:bt==="connecting"?to.connectingText??Bt.connecting:bt==="connected"?to.connectedText??Bt.connected:bt==="error"?to.errorText??Bt.error:Bt[bt])(re),to,re)}k.classList.remove("persona-text-left","persona-text-center","persona-text-right");let pm=to.align==="left"?"persona-text-left":to.align==="center"?"persona-text-center":"persona-text-right";k.classList.add(pm)},open(){P()&&ut(!0,"api")},close(){P()&&ut(!1,"api")},toggle(){P()&&ut(!I,"api")},reconnect(){q.reconnectNow()},clearChat(){Pn=!1,q.clearMessages(),Co.clear(),Jn();try{localStorage.removeItem(xr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xr}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==xr)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 a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),c?.clear&&Na(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),d={},E.syncFromMetadata(),Se?.clear(),Fe?.reset(),ke?.update()},setMessage(a){return!Ae||q.isStreaming()?!1:(!I&&P()&&ut(!0,"system"),Ae.value=a,Ae.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(q.isStreaming())return!1;let f=a?.trim()||Ae.value.trim();return f?(!I&&P()&&ut(!0,"system"),Ae.value="",Ae.style.height="auto",q.sendMessage(f),!0):!1},startVoiceRecognition(){return q.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(q.isVoiceActive()||(!I&&P()&&ut(!0,"system"),Qe.manuallyDeactivated=!1,Cn(),q.toggleVoice().then(()=>{Qe.active=q.isVoiceActive(),Rn("user"),q.isVoiceActive()&&Go()})),!0):En?!0:gd()?(!I&&P()&&ut(!0,"system"),Qe.manuallyDeactivated=!1,Cn(),Qs("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?q.isVoiceActive()?(q.toggleVoice().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,Cn(),Rn("user"),Hn()}),!0):!1:En?(Qe.manuallyDeactivated=!0,Cn(),Zn("user"),!0):!1},injectMessage(a){return!I&&P()&&ut(!0,"system"),q.injectMessage(a)},injectAssistantMessage(a){!I&&P()&&ut(!0,"system");let f=q.injectAssistantMessage(a);return Y&&(Y=!1,de&&(clearTimeout(de),de=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),f},injectUserMessage(a){return!I&&P()&&ut(!0,"system"),q.injectUserMessage(a)},injectSystemMessage(a){return!I&&P()&&ut(!0,"system"),q.injectSystemMessage(a)},injectMessageBatch(a){return!I&&P()&&ut(!0,"system"),q.injectMessageBatch(a)},injectComponentDirective(a){return!I&&P()&&ut(!0,"system"),q.injectComponentDirective(a)},injectTestMessage(a){!I&&P()&&ut(!0,"system"),q.injectTestEvent(a)},async connectStream(a,f){return q.connectStream(a,f)},__pushEventStreamEvent(a){Se&&(Fe?.processEvent(a.type,a.payload),Se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a.type,timestamp:Date.now(),payload:JSON.stringify(a.payload)}))},showEventStream(){!V||!Se||Sa()},hideEventStream(){qe&&Sr()},isEventStreamVisible(){return qe},showArtifacts(){Jt(o)&&(Pn=!1,_o=!0,In(),Ze?.setMobileOpen(!0))},hideArtifacts(){Jt(o)&&(Pn=!0,In())},upsertArtifact(a){return Jt(o)?(Lo(o.features?.artifacts,a.artifactType)==="panel"&&(Pn=!1,_o=!0),q.upsertArtifact(a)):null},selectArtifact(a){Jt(o)&&q.selectArtifact(a)},clearArtifacts(){Jt(o)&&q.clearArtifacts()},getArtifacts(){return q?.getArtifacts()??[]},getSelectedArtifactId(){return q?.getSelectedArtifactId()??null},focusInput(){return A&&!I&&!L()||!Ae?!1:(Ae.focus(),!0)},async resolveApproval(a,f,b){let S=q.getMessages().find(H=>H.variant==="approval"&&H.approval?.id===a);if(!S?.approval)throw new Error(`Approval not found: ${a}`);if(S.approval.toolType==="webmcp"){q.resolveWebMcpApproval(S.id,f);return}return q.resolveApproval(S.approval,f,b)},getMessages(){return q.getMessages()},getStatus(){return q.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(a){C(a)},on(a,f){return l.on(a,f)},off(a,f){l.off(a,f)},isOpen(){return P()&&I},isVoiceActive(){return Qe.active},toggleReadAloud(a){q.toggleReadAloud(a)},stopReadAloud(){q.stopSpeaking()},getReadAloudState(a){return q.getReadAloudState(a)},onReadAloudChange(a){return q.onReadAloudChange(a)},getState(){return{open:P()&&I,launcherEnabled:A,voiceActive:Qe.active,streaming:q.isStreaming()}},showCSATFeedback(a){!I&&P()&&ut(!0,"system");let f=we.querySelector(".persona-feedback-container");f&&f.remove();let b=nf({onSubmit:async(x,S)=>{q.isClientTokenMode()&&await q.submitCSATFeedback(x,S),a?.onSubmit?.(x,S)},onDismiss:a?.onDismiss,...a});we.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!I&&P()&&ut(!0,"system");let f=we.querySelector(".persona-feedback-container");f&&f.remove();let b=of({onSubmit:async(x,S)=>{q.isClientTokenMode()&&await q.submitNPSFeedback(x,S),a?.onSubmit?.(x,S)},onDismiss:a?.onDismiss,...a});we.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,f){return q.submitCSATFeedback(a,f)},async submitNPSFeedback(a,f){return q.submitNPSFeedback(a,f)},destroy(){qa(),Mo!=null&&(clearInterval(Mo),Mo=null),Ue.forEach(a=>a()),Be.remove(),Ge?.remove(),Ft?.destroy(),Vt?.remove(),xo&&T.removeEventListener("click",xo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,f={controller:Rt,getMessages:Rt.getMessages,getStatus:Rt.getStatus,getMetadata:Rt.getPersistentMetadata,updateMetadata:Rt.updatePersistentMetadata,clearHistory:()=>Rt.clearChat(),setVoiceActive:b=>b?Rt.startVoiceRecognition():Rt.stopVoiceRecognition()};window.AgentWidgetBrowser=f,Ue.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=a)})}if(typeof window<"u"){let a=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),f=U=>{let J=U.detail;(!J?.instanceId||J.instanceId===a)&&Rt.focusInput()};if(window.addEventListener("persona:focusInput",f),Ue.push(()=>{window.removeEventListener("persona:focusInput",f)}),V){let U=le=>{let ve=le.detail;(!ve?.instanceId||ve.instanceId===a)&&Rt.showEventStream()},J=le=>{let ve=le.detail;(!ve?.instanceId||ve.instanceId===a)&&Rt.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",J),Ue.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",J)})}let b=U=>{let J=U.detail;(!J?.instanceId||J.instanceId===a)&&Rt.showArtifacts()},x=U=>{let J=U.detail;(!J?.instanceId||J.instanceId===a)&&Rt.hideArtifacts()},S=U=>{let J=U.detail;J?.instanceId&&J.instanceId!==a||J?.artifact&&Rt.upsertArtifact(J.artifact)},H=U=>{let J=U.detail;J?.instanceId&&J.instanceId!==a||typeof J?.id=="string"&&Rt.selectArtifact(J.id)},Z=U=>{let J=U.detail;(!J?.instanceId||J.instanceId===a)&&Rt.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",H),window.addEventListener("persona:clearArtifacts",Z),Ue.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",H),window.removeEventListener("persona:clearArtifacts",Z)})}let un=Lv(o.persistState);if(un&&P()){let a=Pv(un.storage),f=`${un.keyPrefix}widget-open`,b=`${un.keyPrefix}widget-voice`,x=`${un.keyPrefix}widget-voice-mode`;if(a){let S=un.persist?.openState&&a.getItem(f)==="true",H=un.persist?.voiceState&&a.getItem(b)==="true",Z=un.persist?.voiceState&&a.getItem(x)==="true";if(S&&setTimeout(()=>{Rt.open(),setTimeout(()=>{if(H||Z)Rt.startVoiceRecognition();else if(un.persist?.focusInput){let U=t.querySelector("textarea");U&&U.focus()}},100)},0),un.persist?.openState&&(l.on("widget:opened",()=>{a.setItem(f,"true")}),l.on("widget:closed",()=>{a.setItem(f,"false")})),un.persist?.voiceState&&(l.on("voice:state",U=>{a.setItem(b,U.active?"true":"false")}),l.on("user:message",U=>{a.setItem(x,U.viaVoice?"true":"false")})),un.clearOnChatClear){let U=()=>{a.removeItem(f),a.removeItem(b),a.removeItem(x)},J=()=>U();window.addEventListener("persona:clear-chat",J),Ue.push(()=>{window.removeEventListener("persona:clear-chat",J)})}}}if(y&&P()&&setTimeout(()=>{Rt.open()},0),qo(),!kf){let a=ii(()=>{q&&(Ia++,Co.clear(),Hr(we,q.getMessages(),pe))});Ue.push(a)}return Rt};var cf=(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},Wv=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},Hv=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},Bv=(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.")},df=(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"},Sc=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=""},pf=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Sc(t)},Cc=t=>{t.style.transition=""},wc=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=""},Ac=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Ca=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},Dv=(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))},Nv=(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)},Ov=t=>{let e=pr(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:Qt(e,r)??r;return{inset:o(n?.inset,Ui),canvasBackground:o(n?.canvasBackground,ji)}},uf=(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},Fv=(t,e,n,o,r,s,i,l)=>{let p=mn(s),c=p.reveal==="push",d=l!=null,u=l?.inset??"",y=l?.canvasBackground??"";Dv(t,e,n,o,c),Nv(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 g=t.ownerDocument.defaultView,m=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,D=g!=null?g.innerWidth<=C:!1;if(m&&D&&i){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),wc(e),Cc(o),pf(o),Ac(n),Ca(r,o),uf(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??qt),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"),pf(o),Wv(o,p.maxHeight),uf(o,d&&i,u,y),p.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",wc(e),Cc(o),Ac(n),Ca(r,o);let E=p.animate?"transform 180ms ease":"none",A=p.side==="right"?"translateX(100%)":"translateX(-100%)",W=i?"translateX(0)":A;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=E,o.style.transform=W,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",Cc(o),Sc(o),Ca(r,o);let E=cf(p.width,t.clientWidth),A=Math.max(0,t.clientWidth),W=p.animate?"margin-left 180ms ease":"none",z=p.side==="right"?i?-E:0:i?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=`${A+E}px`,e.style.transition=W,e.style.marginLeft=`${z}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${A}px`,n.style.maxWidth=`${A}px`,n.style.minWidth=`${A}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="",wc(e),Sc(o),Ac(n),Ca(r,o);let E=p.reveal==="emerge";E?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let A=i?p.width:"0px",W=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${d?", padding 180ms ease":""}`:"none",z=!i;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${A}`,o.style.width=A,o.style.maxWidth=A,o.style.minWidth=A,o.style.minHeight="0",Hv(o,p.maxHeight),o.style.overflow=E||z?"hidden":"visible",o.style.transition=W,E){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let G=d?`calc(${cf(p.width,t.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=G,r.style.minWidth=G,r.style.maxWidth=G,r.style.boxSizing="border-box"}}},_v=(t,e)=>{let n=t.ownerDocument.createElement("div");return df(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){df(n,o)},destroy(){n.remove()}}},$v=(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"),u=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 y=null,g=()=>{y?.disconnect(),y=null},m=null,C=()=>{m=e?.launcher?.detachedPanel===!0?Ov(e):null};C();let D=()=>{Fv(i,l,p,c,d,e,u,m)},B=null,E=()=>{B?.(),B=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(B=qi(()=>{C(),D()}))},A=()=>{g(),mn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{D()}),y.observe(i)))},W=!1,z=()=>{D(),A(),u&&!W&&i.dataset.personaDockMobileFullscreen!=="true"&&(W=!0,Bv(i,mn(e)))},G=i.ownerDocument.defaultView,w=()=>{z()};return G?.addEventListener("resize",w),mn(e).reveal==="push"?(l.appendChild(p),l.appendChild(c),i.appendChild(l)):(i.appendChild(p),i.appendChild(c)),z(),E(),{mode:"docked",host:d,shell:i,syncWidgetState(O){let N=O.launcherEnabled?O.open:!0;u!==N&&(u=N,z())},updateConfig(O){e=O,(e?.launcher?.enabled??!0)===!1&&(u=!0),C(),z(),E()},destroy(){G?.removeEventListener("resize",w),B?.(),B=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),i.remove()}}},gf=(t,e)=>Ot(e)?$v(t,e):_v(t,e);var Ps={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ff=.15,mf=1.5,Mc="persona-preview-shell-theme",zv={load:()=>null,save:()=>{},clear:()=>{}},Uv=["How do I get started?","Pricing & plans","Talk to support"];function Tc(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function jv(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 hf(t){let e=jv(t);return`* { box-sizing: border-box; }
312
+ ${At?"background: transparent !important;":""}
313
+ `}if(!x&&!a){let Lt="max-height: -moz-available !important; max-height: stretch !important;",en=f?"":"padding-top: 1.25em !important;",ei=f?"":`z-index: ${o.launcher?.zIndex??Vt} !important;`;Oe.style.cssText+=Lt+en+ei}gn()};_s(),ps(t,o),Es(t,o),ks(t,o),Tr=()=>{_s(),ps(t,o),Es(t,o),ks(t,o),Ws?t.style.setProperty("--persona-artifact-welded-outer-radius",Ws):t.style.removeProperty("--persona-artifact-welded-outer-radius")};let je=[];je.push(()=>{document.removeEventListener("keydown",zc)}),je.push(()=>{Ar!==null&&clearTimeout(Ar)});let Mn=null,Tn=null;je.push(()=>{Mn?.(),Mn=null,Tn?.(),Tn=null}),Mr&&je.push(()=>{Mr?.disconnect(),Mr=null}),je.push(()=>{Lr?.(),Lr=null,La(),Ct&&(Ct.remove(),Ct=null),et?.element.style.removeProperty("width"),et?.element.style.removeProperty("maxWidth")}),V&&je.push(()=>{Je!==null&&(cancelAnimationFrame(Je),Je=null),ke?.destroy(),ke=null,Se?.destroy(),Se=null,fe=null});let vo=null,qc=()=>{vo&&(vo(),vo=null),o.colorScheme==="auto"&&(vo=qi(()=>{ps(t,o)}))};qc(),je.push(()=>{vo&&(vo(),vo=null)}),je.push(i);let $s=o.features?.streamAnimation;if($s?.type&&$s.type!=="none"){let a=hr($s.type,$s.plugins);a&&(ia(a,t),je.push(()=>hg(t)))}let zs=Bg(xt),xo=null,q,Pa=a=>{if(!q)return;let f=a??q.getMessages(),b=o.features?.suggestReplies?.enabled!==!1?hp(f):null;b?zs.render(b,q,Ae,f,o.suggestionChipsConfig,{agentPushed:!0}):f.some(x=>x.role==="user")?zs.render([],q,Ae,f):zs.render(o.suggestionChips,q,Ae,f,o.suggestionChipsConfig)},vn=!1,Co=ag(),Uo=new Map,wo=new Map,Gn=new Map,Ia=0,kf=Nn()!==null,nn=ea(),cn=0,Qn=null,dn=!1,Us=!1,Xn=0,xn=null,Ao=null,Ra=!1,js=!1,Wa=null,Pr=!0,Ha=!1,Ba=null,Lf=4,qs=24,Pf=80,Da=new Map,Xe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Vc=o.voiceRecognition?.autoResume??!1,Rn=a=>{l.emit("voice:state",{active:Xe.active,source:a,timestamp:Date.now()})},Cn=()=>{C(a=>({...a,voiceState:{active:Xe.active,timestamp:Date.now(),manuallyDeactivated:Xe.manuallyDeactivated}}))},If=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=xc(d.voiceState),f=!!a.active,b=Number(a.timestamp??0);Xe.manuallyDeactivated=!!a.manuallyDeactivated,f&&Date.now()-b<Mv&&setTimeout(()=>{Xe.active||(Xe.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?q.toggleVoice().then(()=>{Xe.active=q.isVoiceActive(),Rn("restore"),q.isVoiceActive()&&Go()}):Qs("restore"))},1e3)},Rf=()=>q?rf(q.getMessages()).filter(a=>!a.__skipPersist):[],Vs=null,Kc=(a,f)=>{typeof console<"u"&&console.error(a,f)},Na=(a,f)=>{let b=()=>{try{let Z=a();return!Z||typeof Z.then!="function"?null:Promise.resolve(Z).catch(U=>{Kc(f,U)})}catch(Z){return Kc(f,Z),null}},x=Vs,S=x?x.then(()=>b()??void 0):b();if(!S)return;let H=S.finally(()=>{Vs===H&&(Vs=null)});Vs=H};function Oa(a){if(!c?.save)return;let b={messages:a?rf(a):q?Rf():[],metadata:d,artifacts:bn.artifacts,selectedArtifactId:bn.selectedId};Na(()=>c.save(b),"[AgentWidget] Failed to persist state:")}let jo=null,Gc=()=>Oe.querySelector("#persona-scroll-container")||ge,Ir=()=>{jo!==null&&(cancelAnimationFrame(jo),jo=null),dn=!1},Qc=()=>{Qn!==null&&(cancelAnimationFrame(Qn),Qn=null),Us=!1,Ir()},Wf=()=>vn&&_a()&&(Yt()!=="anchor-top"||Lc()),Fa=()=>{let a=mo()||"Jump to latest",f=Wf();Pt.toggleAttribute("data-persona-scroll-to-bottom-streaming",f),Xn>0?(ho.textContent=String(Xn),ho.style.display="",Pt.setAttribute("aria-label",`${a} (${Xn} new)`)):(ho.textContent="",ho.style.display="none",Pt.setAttribute("aria-label",f?`${a} (response streaming below)`:a))},Xc=()=>{Xn!==0&&(Xn=0,Fa())},_a=()=>jn()?!nn.isFollowing():!uo(ge,qs),on=()=>{if(!Is()||Ve){Pt.parentNode&&Pt.remove(),Pt.style.display="none";return}Pt.parentNode!==ye&&ye.appendChild(Pt),Fo();let f=Ln(ge)>0&&_a();f?Fa():Xc(),Pt.style.display=f?"":"none"},Rr=()=>{nn.pause()&&(Qc(),on())},Jn=()=>{nn.resume(),Xc(),on()},Yn=(a=!1)=>{jn()&&nn.isFollowing()&&(!a&&!vn||(Qn!==null&&(cancelAnimationFrame(Qn),Qn=null),Us=!0,Qn=requestAnimationFrame(()=>{Qn=null,Us=!1,nn.isFollowing()&&Hf(Gc(),a?220:140)})))},Jc=(a,f,b,x=()=>!0)=>{let S=a.scrollTop,H=f(),Z=H-S;if(Ir(),Math.abs(Z)<1){dn=!0,a.scrollTop=H,cn=a.scrollTop,dn=!1;return}let U=performance.now();dn=!0;let J=ve=>1-Math.pow(1-ve,3),le=ve=>{if(!x()){Ir();return}let ie=f();ie!==H&&(H=ie,Z=H-S);let Me=ve-U,qe=Math.min(Me/b,1),ut=J(qe),rt=S+Z*ut;a.scrollTop=rt,cn=a.scrollTop,qe<1?jo=requestAnimationFrame(le):(a.scrollTop=H,cn=a.scrollTop,jo=null,dn=!1)};jo=requestAnimationFrame(le)},Hf=(a,f=500)=>{let b=Ln(a)-a.scrollTop;if(Math.abs(b)<1){cn=a.scrollTop;return}if(Math.abs(b)>=Pf){Ir(),dn=!0,a.scrollTop=Ln(a),cn=a.scrollTop,dn=!1;return}Jc(a,()=>Ln(a),f,()=>nn.isFollowing())},Yc=()=>{let a=Gc();dn=!0,a.scrollTop=Ln(a),cn=a.scrollTop,dn=!1,on()},Zc=a=>{let f=0,b=a;for(;b&&b!==ge;)f+=b.offsetTop,b=b.offsetParent;return f},ed=()=>{if(Cf()!=="last-user-turn")return!1;let a=q?.getMessages()??[];if(a.length<2)return!1;let f=[...a].reverse().find(H=>H.role==="user");if(!f)return!1;let b=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(f.id):f.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=ge.querySelector(`[data-message-id="${b}"]`);if(!x)return!1;let S=Math.min(Math.max(0,Zc(x)-Ec()),Ln(ge));return dn=!0,ge.scrollTop=S,cn=ge.scrollTop,dn=!1,Yt()==="follow"&&!uo(ge,qs)&&nn.pause(),on(),!0},td=a=>{qn.style.height=`${Math.max(0,Math.round(a))}px`,xn&&(xn.spacerHeight=Math.max(0,a))},Wr=()=>{Ao!==null&&(cancelAnimationFrame(Ao),Ao=null),Ir(),xn=null,qn.style.height="0px"},Bf=a=>{Ao!==null&&cancelAnimationFrame(Ao),Ao=requestAnimationFrame(()=>{Ao=null;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=ge.querySelector(`[data-message-id="${f}"]`);if(!b)return;let x=Zc(b),S=xn?.spacerHeight??0,H=ge.scrollHeight-S,{targetScrollTop:Z,spacerHeight:U}=ug({anchorOffsetTop:x,topOffset:Ec(),viewportHeight:ge.clientHeight,contentHeight:H});xn={initialSpacerHeight:U,contentHeightAtAnchor:H,spacerHeight:U},td(U),Jc(ge,()=>Z,220)})},Df=()=>{if(jn()){if(!nn.isFollowing()||uo(ge,1))return;Yn(!vn);return}if(xn&&xn.initialSpacerHeight>0){let a=ge.scrollHeight-xn.spacerHeight,f=gg({initialSpacerHeight:xn.initialSpacerHeight,contentHeightAtAnchor:xn.contentHeightAtAnchor,currentContentHeight:a});f!==xn.spacerHeight&&td(f)}on()},Nf=a=>{let f=Yt();f==="follow"?(Jn(),Yn(!0)):f==="anchor-top"&&(Pr=!1,Ha=!0,Bf(a))},Of=()=>{if(Yt()==="anchor-top"){if(Ha){Pr=!1;return}Pr=!0,Wr(),Jn(),Yn(!0)}},Ff=a=>{let f=new Map;a.forEach(b=>{let x=Da.get(b.id);f.set(b.id,{streaming:b.streaming,role:b.role}),!x&&b.role==="assistant"&&(l.emit("assistant:message",b),!js&&(Yt()!=="anchor-top"||Lc())&&_a()&&(Xn+=1,Fa(),on(),Ic(Xn===1?"1 new message below.":`${Xn} new messages below.`))),b.role==="assistant"&&x?.streaming&&b.streaming===!1&&l.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(x?b.approval.status!=="pending"&&l.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):l.emit("approval:requested",{approval:b.approval,message:b}))}),Da.clear(),f.forEach((b,x)=>{Da.set(x,b)})},Ks=(a,f)=>{let b=f==="user"?"user":"assistant",x=o.layout?.messages?.[b],S=x?.width??"content",H=x?.maxWidth??(S==="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-${f}`,`persona-message-width-${S}`),a.classList.toggle("persona-justify-end",f==="user"),a.setAttribute("data-message-role",f),a.setAttribute("data-message-width",S),a.style.setProperty("--persona-message-row-max-width",H)},So=(a,f)=>{let b=document.createElement("div");return b.className="persona-flex",b.id=`wrapper-${a}`,b.setAttribute("data-wrapper-id",a),Ks(b,f),b},_f=(a,f,b)=>{let x=document.createElement("div"),H=(()=>{let F=r.find(He=>He.renderLoadingIndicator);if(F?.renderLoadingIndicator)return F.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),Z=(F,He)=>He==null?!1:typeof He=="string"?(F.textContent=He,!0):(F.appendChild(He),!0),U=new Set,J=new Map,le=new Set,ve=r.some(F=>F.renderAskUserQuestion),ie=[],Me=[],qe=o.enableComponentStreaming!==!1,ut=o.approval!==!1,rt=[];if(f.forEach(F=>{U.add(F.id),J.set(F.id,F.role);let He=ve&&Po(F),$e=ut&&F.variant==="approval"&&!!F.approval,Le=!He&&F.role==="assistant"&&!F.variant&&qe&&vc(F);!$e&&Gn.has(F.id)&&(a.querySelector(`#wrapper-${F.id}`)?.removeAttribute("data-preserve-runtime"),Gn.delete(F.id)),!Le&&wo.has(F.id)&&(a.querySelector(`#wrapper-${F.id}`)?.removeAttribute("data-preserve-runtime"),wo.delete(F.id));let Et=Po(F)?`:${F.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${F.agentMetadata?.askUserQuestionAnswers?Object.keys(F.agentMetadata.askUserQuestionAnswers).length:0}`:"",gt=ig(F,Ia)+Et,Gt=He||$e||Le?null:lg(Co,F.id,gt);if(Gt){x.appendChild(Gt.cloneNode(!0)),Po(F)&&F.toolCall?.id&&F.agentMetadata?.awaitingLocalTool===!0&&!F.agentMetadata?.askUserQuestionAnswered&&(le.add(F.toolCall.id),gi(F,o,Re.composerOverlay));return}let ft=null,Zt=r.find(ze=>!!(F.variant==="reasoning"&&ze.renderReasoning||F.variant==="tool"&&ze.renderToolCall||!F.variant&&ze.renderMessage)),Wt=o.layout?.messages;if(Po(F)&&F.agentMetadata?.askUserQuestionAnswered===!0){Uo.delete(F.id),a.querySelector(`#wrapper-${F.id}`)?.removeAttribute("data-preserve-runtime");return}if(gl(F)&&o.features?.suggestReplies?.enabled!==!1)return;if(Po(F)&&o.features?.askUserQuestion?.enabled!==!1){let ze=r.find($t=>typeof $t.renderAskUserQuestion=="function");if(ze&&ct.current){let $t=Uo.get(F.id),zt=$t!==gt,At=null;if(zt){let{payload:tt,complete:_e}=tr(F),yt=F.id,Ut=()=>ct.current?.getMessages().find(gn=>gn.id===yt);At=ze.renderAskUserQuestion({message:F,payload:tt,complete:_e,resolve:gn=>{let Ur=Ut();Ur&&ct.current?.resolveAskUserQuestion(Ur,gn)},dismiss:()=>{let gn=Ut();gn?.agentMetadata?.awaitingLocalTool&&(ct.current?.markAskUserQuestionResolved(gn),ct.current?.resolveAskUserQuestion(gn,"(dismissed)"))},config:o})}let dt=$t!=null;if(zt&&At===null&&!dt){F.agentMetadata?.awaitingLocalTool===!0&&!F.agentMetadata?.askUserQuestionAnswered&&(le.add(F.toolCall.id),gi(F,o,Re.composerOverlay));return}let mt=So(F.id,F.role);mt.setAttribute("data-ask-plugin-stub","true"),mt.setAttribute("data-preserve-runtime","true"),x.appendChild(mt),ie.push({messageId:F.id,fingerprint:gt,bubble:At});return}else{F.agentMetadata?.awaitingLocalTool===!0&&!F.agentMetadata?.askUserQuestionAnswered&&(le.add(F.toolCall.id),gi(F,o,Re.composerOverlay));return}}else if($e){let ze=r.find(dt=>typeof dt.renderApproval=="function")??s,zt=Gn.get(F.id)!==gt,At=null;if(zt&&ze?.renderApproval){let dt=F.id,mt=(tt,_e)=>{let yt=ct.current?.getMessages().find(Ut=>Ut.id===dt);yt?.approval&&(yt.approval.toolType==="webmcp"?ct.current?.resolveWebMcpApproval(yt.id,tt):ct.current?.resolveApproval(yt.approval,tt,_e))};At=ze.renderApproval({message:F,defaultRenderer:()=>ya(F,o),config:o,approve:tt=>mt("approved",tt),deny:tt=>mt("denied",tt)})}if(zt&&At===null)a.querySelector(`#wrapper-${F.id}`)?.removeAttribute("data-preserve-runtime"),Gn.delete(F.id),ft=ya(F,o);else{let dt=So(F.id,F.role);dt.setAttribute("data-approval-plugin-stub","true"),dt.setAttribute("data-preserve-runtime","true"),x.appendChild(dt),rt.push({messageId:F.id,fingerprint:gt,bubble:At});return}}else if(Zt)if(F.variant==="reasoning"&&F.reasoning&&Zt.renderReasoning){if(!ee)return;ft=Zt.renderReasoning({message:F,defaultRenderer:()=>oc(F,o),config:o})}else if(F.variant==="tool"&&F.toolCall&&Zt.renderToolCall){if(!oe)return;ft=Zt.renderToolCall({message:F,defaultRenderer:()=>sc(F,o),config:o})}else Zt.renderMessage&&(ft=Zt.renderMessage({message:F,defaultRenderer:()=>{let ze=nc(F,b,Wt,o.messageActions,Pe,{loadingIndicatorRenderer:H,widgetConfig:o});return F.role!=="user"&&uc(ze,F,o,q),ze},config:o}));if(!ft&&Le){let ze=tf(F);if(ze){let $t=wo.get(F.id),zt=$t!==gt,At=o.wrapComponentDirectiveInBubble!==!1&&Un.getOptions(ze.component)?.bubbleChrome!==!1,dt=null;if(zt){let mt=Zg(ze,{config:o,message:F,transform:b});if(mt&&ze.component==="PersonaArtifactInline"){let tt=mt.hasAttribute("data-artifact-inline")?mt:mt.querySelector("[data-artifact-inline]"),_e=tt?.getAttribute("data-artifact-inline")??"",yt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(_e):_e,Ut=_e?a.querySelector(`#wrapper-${F.id}`)?.querySelector(`[data-artifact-inline="${yt}"]`)??null:null;tt&&Ut&&Ut!==tt&&eg(Ut)&&(tt===mt?mt=Ut:tt.replaceWith(Ut))}if(mt)if(At){let tt=document.createElement("div");if(tt.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),tt.id=`bubble-${F.id}`,tt.setAttribute("data-message-id",F.id),F.content&&F.content.trim()){let _e=document.createElement("div");_e.className="persona-mb-3 persona-text-sm persona-leading-relaxed",_e.innerHTML=b({text:F.content,message:F,streaming:!!F.streaming,raw:F.rawContent}),tt.appendChild(_e)}tt.appendChild(mt),dt=tt}else{let tt=document.createElement("div");if(tt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",tt.id=`bubble-${F.id}`,tt.setAttribute("data-message-id",F.id),tt.setAttribute("data-persona-component-directive","true"),F.content&&F.content.trim()){let _e=document.createElement("div");_e.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",_e.innerHTML=b({text:F.content,message:F,streaming:!!F.streaming,raw:F.rawContent}),tt.appendChild(_e)}tt.appendChild(mt),dt=tt}}if(dt||$t!=null){let mt=So(F.id,F.role);mt.setAttribute("data-component-directive-stub","true"),mt.setAttribute("data-preserve-runtime","true"),x.appendChild(mt),Me.push({messageId:F.id,fingerprint:gt,bubble:dt});return}}}if(!ft)if(F.variant==="reasoning"&&F.reasoning){if(!ee)return;ft=oc(F,o)}else if(F.variant==="tool"&&F.toolCall){if(!oe)return;ft=sc(F,o)}else if(F.variant==="approval"&&F.approval){if(o.approval===!1)return;ft=ya(F,o)}else{let ze=o.layout?.messages;ze?.renderUserMessage&&F.role==="user"?ft=ze.renderUserMessage({message:F,config:o,streaming:!!F.streaming}):ze?.renderAssistantMessage&&F.role==="assistant"?ft=ze.renderAssistantMessage({message:F,config:o,streaming:!!F.streaming}):ft=nc(F,b,ze,o.messageActions,Pe,{loadingIndicatorRenderer:H,widgetConfig:o}),F.role!=="user"&&ft&&uc(ft,F,o,q)}let Be=So(F.id,F.role);Be.appendChild(ft),cg(Co,F.id,gt,Be),x.appendChild(Be)}),Re.composerOverlay&&Re.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(He=>{let $e=He.getAttribute("data-persona-ask-sheet-for");$e&&!le.has($e)&&or(Re.composerOverlay,$e)}),o.features?.toolCallDisplay?.grouped){let F=[],He=[],$e=o.features.toolCallDisplay.groupedMode==="summary";f.forEach(Le=>{if(Le.variant==="tool"&&Le.toolCall&&oe){He.push(Le);return}Le.variant==="reasoning"&&!ee||((He.length>1||$e&&He.length>0)&&F.push(He),He=[])}),(He.length>1||$e&&He.length>0)&&F.push(He),F.forEach(Le=>{let Et=Le.map(ze=>Array.from(x.children).find($t=>$t instanceof HTMLElement&&$t.getAttribute("data-wrapper-id")===ze.id)).filter(ze=>!!ze);if(Et.length<($e?1:2))return;let gt=So(`tool-group-${Le[0].id}`,"assistant");gt.setAttribute("data-persona-tool-group-row","true");let Gt=document.createElement("div");Gt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Gt.setAttribute("data-persona-tool-group","true");let ft=document.createElement("div");ft.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",ft.id=`tool-group-summary-${Le[0].id}`;let Zt=`Called ${Le.length} ${Le.length===1?"tool":"tools"}`,Wt=o.toolCall?.renderGroupedSummary?.({messages:Le,toolCalls:Le.map(ze=>ze.toolCall).filter(ze=>!!ze),defaultSummary:Zt,config:o});Z(ft,Wt)||(ft.textContent=Zt);let Be=document.createElement("div");Be.className="persona-tool-group-stack persona-flex persona-flex-col",Be.id=`tool-group-stack-${Le[0].id}`,Be.setAttribute("data-persona-tool-group-stack","true"),Gt.appendChild(ft),$e||Gt.appendChild(Be),gt.appendChild(Gt),Et[0].before(gt),Et.forEach((ze,$t)=>{if($e){ze.remove();return}ze.style.setProperty("--persona-message-row-max-width","100%");let zt=document.createElement("div");zt.className="persona-tool-group-item persona-relative",zt.setAttribute("data-persona-tool-group-item","true"),$t<Et.length-1&&zt.setAttribute("data-persona-tool-group-connector","true"),zt.appendChild(ze),Be.appendChild(zt)})})}dg(Co,U);let rn=f.some(F=>F.role==="assistant"&&F.streaming),Tt=f[f.length-1],Rt=Tt?.role==="assistant"&&!Tt.streaming&&Tt.variant!=="approval";if(vn&&f.some(F=>F.role==="user")&&!rn&&!Rt){let F={config:o,streaming:!0,location:"standalone",defaultRenderer:As},He=r.find(Le=>Le.renderLoadingIndicator),$e=null;if(He?.renderLoadingIndicator&&($e=He.renderLoadingIndicator(F)),$e===null&&o.loadingIndicator?.render&&($e=o.loadingIndicator.render(F)),$e===null&&($e=As()),$e){let Le=document.createElement("div"),Et=o.loadingIndicator?.showBubble!==!1;Le.className=Et?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Le.setAttribute("data-typing-indicator","true"),Le.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Le.appendChild($e);let gt=So("typing-indicator","assistant");gt.appendChild(Le),x.appendChild(gt)}}if(!vn&&f.length>0){let F=f[f.length-1],He={config:o,lastMessage:F,messageCount:f.length},$e=r.find(Et=>Et.renderIdleIndicator),Le=null;if($e?.renderIdleIndicator&&(Le=$e.renderIdleIndicator(He)),Le===null&&o.loadingIndicator?.renderIdle&&(Le=o.loadingIndicator.renderIdle(He)),Le){let Et=document.createElement("div"),gt=o.loadingIndicator?.showBubble!==!1;Et.className=gt?["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(" "),Et.setAttribute("data-idle-indicator","true"),Et.appendChild(Le);let Gt=So("idle-indicator","assistant");Gt.appendChild(Et),x.appendChild(Gt)}}if(Qd(x),Zi(a,x),ol(a),ie.length>0)for(let{messageId:F,fingerprint:He,bubble:$e}of ie){let Le=a.querySelector(`#wrapper-${F}`);Le&&(Ks(Le,J.get(F)??"assistant"),$e!==null&&(Le.replaceChildren($e),Le.setAttribute("data-bubble-fp",He),Uo.set(F,He)))}if(Uo.size>0)for(let F of Uo.keys())U.has(F)||Uo.delete(F);if(Me.length>0)for(let{messageId:F,fingerprint:He,bubble:$e}of Me){let Le=a.querySelector(`#wrapper-${F}`);Le&&(Ks(Le,J.get(F)??"assistant"),$e!==null&&(Le.replaceChildren($e),Le.setAttribute("data-bubble-fp",He),wo.set(F,He)))}if(wo.size>0)for(let F of wo.keys())U.has(F)||wo.delete(F);if(rt.length>0)for(let{messageId:F,fingerprint:He,bubble:$e}of rt){let Le=a.querySelector(`#wrapper-${F}`);Le&&(Ks(Le,J.get(F)??"assistant"),$e!==null&&(Le.replaceChildren($e),Le.setAttribute("data-bubble-fp",He),Gn.set(F,He)))}if(Gn.size>0)for(let F of Gn.keys())U.has(F)||Gn.delete(F)},Hr=(a,f,b)=>{_f(a,f,b),Fc()},Br=null,$f=()=>{if(Br)return;let a=b=>{let x=b.composedPath();x.includes(Oe)||Qe&&x.includes(Qe)||pt(!1,"user")};Br=a,(t.ownerDocument??document).addEventListener("pointerdown",a,!0)},nd=()=>{if(!Br)return;(t.ownerDocument??document).removeEventListener("pointerdown",Br,!0),Br=null};je.push(()=>nd());let Dr=null,zf=()=>{if(Dr)return;let a=b=>{b.key==="Escape"&&(b.isComposing||pt(!1,"user"))};Dr=a,(t.ownerDocument??document).addEventListener("keydown",a,!0)},od=()=>{if(!Dr)return;(t.ownerDocument??document).removeEventListener("keydown",Dr,!0),Dr=null};je.push(()=>od());let Nr=!1,rd=new Set,Uf=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},qo=()=>{if(!L())return;let a=Re.peekBanner,f=Re.peekTextNode;if(!a||!f)return;if(I){a.classList.remove("persona-pill-peek--visible");return}let b=q?.getMessages()??[],x;for(let Tt=b.length-1;Tt>=0;Tt--){let Rt=b[Tt];if(Rt.role==="assistant"&&Rt.content){x=Rt;break}}if(!x){a.classList.remove("persona-pill-peek--visible");return}let S=x.content,H=!!x.streaming,Z=Uf(),U=oa(Z),J=U.type!=="none"?hr(U.type,Z?.plugins):null,le=J?.isAnimating?.(x)===!0,ve=J!==null&&(H||le);ve&&J&&!rd.has(J.name)&&(ia(J,t),rd.add(J.name));let ie=ve&&J?.containerClass?J.containerClass:null,Me=f.dataset.personaPeekStreamClass??null;Me&&Me!==ie&&(f.classList.remove(Me),delete f.dataset.personaPeekStreamClass),ie&&Me!==ie&&(f.classList.add(ie),f.dataset.personaPeekStreamClass=ie),ve?(f.style.setProperty("--persona-stream-step",`${U.speed}ms`),f.style.setProperty("--persona-stream-duration",`${U.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let qe=ve?ra(S,U.buffer,J,x,H):S;if(ve&&U.placeholder==="skeleton"&&H&&(!qe||!qe.trim())){let Tt=document.createElement("div"),Rt=ys();Rt.classList.add("persona-pill-peek__skeleton"),Tt.appendChild(Rt),Zi(f,Tt)}else{let Tt=Math.max(0,qe.length-100),Rt=qe.length>100?qe.slice(-100):qe,F=oo(Rt);if(!ve||!J){let He=qe.length>100?`\u2026${Rt}`:Rt;f.textContent!==He&&(f.textContent=He)}else{let He=F;(J.wrap==="char"||J.wrap==="word")&&(He=bs(F,J.wrap,`peek-${x.id}`,{skipTags:J.skipTags,startIndex:Tt}));let $e=document.createElement("div");if($e.innerHTML=He,J.useCaret&&Rt.length>0){let Le=sa(),Et=$e.querySelectorAll(".persona-stream-char, .persona-stream-word"),gt=Et[Et.length-1];gt?.parentNode?gt.parentNode.insertBefore(Le,gt.nextSibling):$e.appendChild(Le)}Zi(f,$e),J.onAfterRender?.({container:f,bubble:a,messageId:x.id,message:x,speed:U.speed,duration:U.duration})}}let rn=vn||Nr;a.classList.toggle("persona-pill-peek--visible",rn)};if(L()){let a=Re.peekBanner;if(a){let x=S=>{S.preventDefault(),S.stopPropagation(),pt(!0,"user")};a.addEventListener("pointerdown",x),je.push(()=>{a.removeEventListener("pointerdown",x)})}let f=()=>{Nr||(Nr=!0,qo())},b=()=>{Nr&&(Nr=!1,qo())};Ce.addEventListener("pointerenter",f),Ce.addEventListener("pointerleave",b),je.push(()=>{Ce.removeEventListener("pointerenter",f),Ce.removeEventListener("pointerleave",b)}),Qe&&(Qe.addEventListener("pointerenter",f),Qe.addEventListener("pointerleave",b),je.push(()=>{Qe.removeEventListener("pointerenter",f),Qe.removeEventListener("pointerleave",b)}))}let jf=a=>{let f=o.launcher?.composerBar??{},b=f.expandedSize??"anchored",x=f.bottomOffset??"16px",S=f.collapsedMaxWidth,H=f.expandedMaxWidth??"880px",Z=f.expandedTopOffset??"5vh",U=f.modalMaxWidth??"880px",J=f.modalMaxHeight??"min(90vh, 800px)",le="calc(100vw - 32px)",ve="var(--persona-pill-area-height, 80px)",ie=Oe.style;if(ie.left="",ie.right="",ie.top="",ie.bottom="",ie.transform="",ie.width="",ie.maxWidth="",ie.height="",ie.maxHeight="",Qe){let Me=Qe.style;Me.bottom=x,Me.width=S??""}if(a&&b!=="fullscreen"){if(b==="modal"){ie.top="50%",ie.left="50%",ie.transform="translate(-50%, -50%)",ie.bottom="auto",ie.right="auto",ie.width=U,ie.maxWidth=le,ie.maxHeight=J,ie.height=J;return}ie.left="50%",ie.transform="translateX(-50%)",ie.bottom=`calc(${x} + ${ve})`,ie.top=Z,ie.width=H,ie.maxWidth=le}},Or=()=>{if(!P())return;if(L()){let le=(o.launcher?.composerBar??{}).expandedSize??"anchored",ve=I?"expanded":"collapsed";Oe.dataset.state=ve,Oe.dataset.expandedSize=le,Qe&&(Qe.dataset.state=ve,Qe.dataset.expandedSize=le),Oe.style.removeProperty("display"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),jf(I),ye.style.display=I?"flex":"none",_s(),I?($f(),zf()):(nd(),od()),qo();return}let a=Nt(o),f=t.ownerDocument.defaultView??window,b=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,S=f.innerWidth<=b,H=x&&S&&A,Z=mn(o).reveal;I?(Oe.style.removeProperty("display"),Oe.style.display=a?"flex":"",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-95","persona-opacity-0"),Ce.classList.add("persona-scale-100","persona-opacity-100"),Ot?Ot.element.style.display="none":Kt&&(Kt.style.display="none")):(a?a&&(Z==="overlay"||Z==="push")&&!H?(Oe.style.removeProperty("display"),Oe.style.display="flex",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Oe.style.setProperty("display","none","important"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Oe.style.display="",Oe.classList.add("persona-pointer-events-none","persona-opacity-0"),Ce.classList.remove("persona-scale-100","persona-opacity-100"),Ce.classList.add("persona-scale-95","persona-opacity-0")),Ot?Ot.element.style.display=a?"none":"":Kt&&(Kt.style.display=a?"none":""))},pt=(a,f="user")=>{if(!P()||I===a)return;let b=I;I=a,Or();let x=(()=>{let H=o.launcher?.sidebarMode??!1,Z=t.ownerDocument.defaultView??window,U=o.launcher?.mobileFullscreen??!0,J=o.launcher?.mobileBreakpoint??640,le=Z.innerWidth<=J,ve=Nt(o)&&U&&le,ie=L()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return H||U&&le&&A||ve||ie})();if(I&&x){if(!Mn){let H=t.getRootNode(),Z=H instanceof ShadowRoot?H.host:t.closest(".persona-host");Z&&(Mn=Xl(Z,o.launcher?.zIndex??Vt))}Tn||(Tn=Jl(t.ownerDocument))}else I||(Mn?.(),Mn=null,Tn?.(),Tn=null);I&&($r(),ed()||(Yt()==="follow"?Yn(!0):Yc()));let S={open:I,source:f,timestamp:Date.now()};I&&!b?l.emit("widget:opened",S):!I&&b&&l.emit("widget:closed",S),l.emit("widget:state",{open:I,launcherEnabled:A,voiceActive:Xe.active,streaming:q.isStreaming()})},$a=a=>{it(a?"stop":"send"),X&&(X.disabled=a),zs.buttons.forEach(f=>{f.disabled=a}),K.dataset.personaComposerStreaming=a?"true":"false",K.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=a)})},za=()=>{Xe.active||Ae&&Ae.focus()};l.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>za(),200)});let sd=()=>{j.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",v.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",Ae.placeholder=o.copy?.inputPlaceholder??"How can I help...";let a=ge.querySelector("[data-persona-intro-card]");if(a){let b=o.copy?.showWelcomeCard!==!1;a.style.display=b?"":"none",b?(ge.classList.remove("persona-gap-3"),ge.classList.add("persona-gap-6")):(ge.classList.remove("persona-gap-6"),ge.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!q?.isStreaming()&&(he.textContent=o.copy?.sendButtonLabel??"Send"),Ae.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Ae.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let a=d.sessionId;return typeof a=="string"?a:null},setStoredSessionId:a=>{C(f=>({...f,sessionId:a}))}});let Mo=null,qf=()=>{Mo==null&&(Mo=setInterval(()=>{let a=we.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(Mo),Mo=null;return}let f=Date.now();a.forEach(b=>{let x=Number(b.getAttribute("data-tool-elapsed"));x&&(b.textContent=hi(f-x))})},100))},Ua=(a,f)=>{if(Object.is(a,f))return!0;if(a===null||f===null||typeof a!="object"||typeof f!="object")return!1;if(Array.isArray(a)||Array.isArray(f))return!Array.isArray(a)||!Array.isArray(f)||a.length!==f.length?!1:a.every((Z,U)=>Ua(Z,f[U]));let b=a,x=f,S=Object.keys(b),H=Object.keys(x);return S.length===H.length&&S.every(Z=>Object.prototype.hasOwnProperty.call(x,Z)&&Ua(b[Z],x[Z]))},id=a=>{let{content:f,rawContent:b,llmContent:x,...S}=a;return S},ja=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!vc(a),Vf=(a,f,b)=>{if(a.length!==f.length)return!1;let x=a[b.index],S=f[b.index];return!x||!S||x.id!==b.id||S.id!==b.id?!1:(!Object.is(x.content,S.content)||!Object.is(x.rawContent,S.rawContent)||!Object.is(x.llmContent,S.llmContent))&&ja(x)&&ja(S)&&Ua(id(x),id(S))},ad=null,Vo=null,To=null,Wn=null,Gs=a=>{ad=a;let f,b;Vo=null;for(let S=a.length-1;S>=0;S-=1){let H=a[S];if(!f&&H.role==="user"&&(f=H),!b&&H.role==="assistant"&&(b=H),!Vo&&ja(H)&&(Vo={index:S,id:H.id}),f&&b&&Vo)break}Hr(we,a,pe),jl(we,bn.artifacts,{suppressTransition:vn}),qf(),Pa(a),Yn(!vn),Ff(a),a.length===0&&(Wr(),Pr=!0,Ha=!1),!Ra||js?(Ra=!0,Wa=f?.id??null,Ba=b?.id??null):f&&f.id!==Wa?(Wa=f.id,Nf(f.id)):b&&b.id!==Ba&&Of(),b&&(Ba=b.id);let x=Xe.lastUserMessageId;f&&f.id!==x&&(Xe.lastUserMessageId=f.id,l.emit("user:message",f)),Xe.lastUserMessageWasVoice=!!f?.viaVoice,Oa(a),qo()},qa=()=>{Wn!==null&&(cancelAnimationFrame(Wn),Wn=null);let a=To;To=null,a&&Gs(a)},ld=()=>{Wn!==null&&cancelAnimationFrame(Wn),Wn=null,To=null},Kf=a=>{let f=To??ad;if(vn&&f&&Vo&&Vf(f,a,Vo)){To=a,Wn===null&&(Wn=requestAnimationFrame(()=>{Wn=null;let b=To;To=null,b&&Gs(b)}));return}if(a.length===0){ld(),Gs(a);return}qa(),Gs(a)};q=new Ti(o,{onMessagesChanged(a){Kf(a)},onStatusChanged(a){let f=o.statusIndicator??{};kt(k,(x=>x==="idle"?f.idleText??Ht.idle:x==="connecting"?f.connectingText??Ht.connecting:x==="connected"?f.connectedText??Ht.connected:x==="error"?f.errorText??Ht.error:x==="paused"?f.pausedText??Ht.paused:x==="resuming"?f.resumingText??Ht.resuming:Ht[x])(a),f,a)},onStreamingChanged(a){a||(q?.getMessages().length===0?ld():qa()),vn=a,$a(a),q&&Hr(we,q.getMessages(),pe),a||Yn(!0),on(),Ic(a?"Responding\u2026":"Response complete."),qo()},onVoiceStatusChanged(a){if(l.emit("voice:status",{status:a,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(a){case"listening":Hn(),Go();break;case"processing":Hn(),rm();break;case"speaking":Hn(),sm();break;default:a==="idle"&&q.isBargeInActive()?(Hn(),Go(),X?.setAttribute("aria-label","End voice session")):(Xe.active=!1,Hn(),Rn("system"),Cn());break}},onArtifactsState(a){bn=a,a.artifacts.length===0&&(_o=!1),jl(we,a.artifacts,{suppressTransition:vn}),In(),Oa()},onReconnect(a){let{executionId:f,lastEventId:b}=a.handle;a.phase==="paused"?l.emit("stream:paused",{executionId:f,after:b}):a.phase==="resuming"?l.emit("stream:resuming",{executionId:f,after:b,attempt:a.attempt??1}):l.emit("stream:resumed",{executionId:f,after:b})}}),ct.current=q,je.push(()=>q.cancel());let Va=null;if(q.onReadAloudChange((a,f)=>{Nc=a,Oc=f,Fc();let b=a??Va;a&&(Va=a);let x=b?q.getMessages().find(S=>S.id===b)??null:null;l.emit("message:read-aloud",{messageId:b,message:x,state:f,timestamp:Date.now()}),f==="idle"&&(Va=null)}),Ra=!0,o.voiceRecognition?.provider?.type==="runtype")try{q.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}o.clientToken&&q.initClientSession().catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)}),(Se||o.onSSEEvent)&&q.setSSEEventCallback((a,f)=>{o.onSSEEvent?.(a,f),Fe?.processEvent(a,f),Se?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(f)})});let cd=()=>{o.resume&&typeof o.reconnectStream=="function"&&q.resumeFromHandle(o.resume)};u?u.then(a=>{if(a){if(a.metadata&&(d=xc(a.metadata),E.syncFromMetadata()),a.messages?.length){js=!0;try{q.hydrateMessages(a.messages)}finally{js=!1}}a.artifacts?.length&&q.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>cd()):cd();let dd=()=>{!L()||I||!(o.launcher?.composerBar?.expandOnSubmit??!0)||pt(!0,"auto")},Gf=(a,f)=>a?f?{refs:[...a.refs,...f.refs],finalize:async()=>{let[b,x]=await Promise.allSettled([a.finalize(),f.finalize()]),S=[];return b.status==="fulfilled"?S.push(b.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",b.reason),x.status==="fulfilled"?S.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),Rv(S)}}:a:f,Qf=()=>{let f=Ae.getInlineMessageFields?.();return f&&f.contentSegments.some(x=>x.kind==="mention")?f.contentSegments:void 0},Fr=!1,Xf=async a=>{let f=Ae.value.trim(),b=Mt?.hasAttachments()??!1,x=f?await(tn?.takeInlineCommand(f)??Promise.resolve(null)):null;if(x?.kind==="action"){Ae.value="",Ae.style.height="auto",_r(),tn?.clear();return}let S=tn?.collectForSubmit()??null,H=x?.kind==="server"?x.mentions:null,Z=Gf(S,H),U=x?.kind==="prompt"?x.sendText:f,J=!!S&&S.refs.length>0;if(!U&&!b&&!J&&!H)return;dd();let le;b&&(le=[],le.push(...Mt.getContentParts()),U&&le.push(ir(U)));let ve=x?.kind==="prompt"?void 0:Qf();Ae.value="",Ae.style.height="auto",_r(),q.sendMessage(U,{contentParts:le,mentions:Z??void 0,contentSegments:ve,viaVoice:a?.viaVoice}),b&&Mt.clearAttachments(),S&&tn?.clear()},Ka=async a=>{if(!Fr){Fr=!0;try{await Xf(a)}finally{Fr=!1}}},pd=a=>{if(a.preventDefault(),q.isStreaming()){q.cancel(),Fe?.reset(),ke?.update();return}Fr||Ka()},Jf=()=>o.features?.composerHistory!==!1,Ga={...Kl},Qa=!1,_r=()=>{Ga={...Kl}},Yf=()=>q.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),Zf=a=>{if(!Ae)return;Qa=!0,Ae.value=a,Ae.dispatchEvent(new Event("input",{bubbles:!0})),Qa=!1;let f=Ae.value.length;Ae.setSelectionRange(f,f)},em=a=>{Qa||(a.isComposing||tn?.handleInput(a.inputType??void 0),_r())},tm=a=>{if(Ae&&!(!a.isComposing&&tn?.handleKeydown(a))){if(Jf()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let f=Ae.selectionStart===0&&Ae.selectionEnd===0,b=sg({direction:a.key==="ArrowUp"?"up":"down",history:Yf(),currentValue:Ae.value,atStart:f,state:Ga});if(Ga=b.state,b.handled){a.preventDefault(),b.value!==void 0&&Zf(b.value);return}}if(a.key==="Enter"&&!a.shiftKey){if(q.isStreaming()){a.preventDefault();return}if(Fr){a.preventDefault();return}_r(),a.preventDefault(),he.click()}}},ud=a=>{a.key!=="Escape"||a.isComposing||q.isStreaming()&&a.composedPath().includes(ye)&&(q.cancel(),Fe?.reset(),ke?.update(),_r(),a.preventDefault(),a.stopImmediatePropagation())},nm=async a=>{if(o.attachments?.enabled!==!0||!Mt)return;let f=kv(a.clipboardData);f.length!==0&&(a.preventDefault(),await Mt.handleFiles(f))},pn=null,En=!1,Ko=null,wt=null,gd=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Qs=(a="user")=>{if(En||q.isStreaming())return;let f=gd();if(!f)return;pn=new f;let x=(o.voiceRecognition??{}).pauseDuration??2e3;pn.continuous=!0,pn.interimResults=!0,pn.lang="en-US";let S=Ae.value;pn.onresult=H=>{let Z="",U="";for(let le=0;le<H.results.length;le++){let ve=H.results[le],ie=ve[0].transcript;ve.isFinal?Z+=ie+" ":U=ie}let J=S+Z+U;Ae.value=J,Ko&&clearTimeout(Ko),(Z||U)&&(Ko=window.setTimeout(()=>{Ae.value.trim()&&pn&&En&&(Zn(),Ka({viaVoice:!0}))},x))},pn.onerror=H=>{H.error!=="no-speech"&&Zn()},pn.onend=()=>{if(En){let H=Ae.value.trim();H&&H!==S.trim()&&Ka({viaVoice:!0}),Zn()}};try{if(pn.start(),En=!0,Xe.active=!0,a!=="system"&&(Xe.manuallyDeactivated=!1),Rn(a),Cn(),X){let H=o.voiceRecognition??{};wt={backgroundColor:X.style.backgroundColor,color:X.style.color,borderColor:X.style.borderColor,iconName:H.iconName??"mic",iconSize:parseFloat(H.iconSize??o.sendButton?.size??"40")||24};let Z=H.recordingBackgroundColor,U=H.recordingIconColor,J=H.recordingBorderColor;if(X.classList.add("persona-voice-recording"),X.style.backgroundColor=Z??"var(--persona-voice-recording-bg, #ef4444)",X.style.color=U??"var(--persona-voice-recording-indicator, #ffffff)",U){let le=X.querySelector("svg");le&&le.setAttribute("stroke",U)}J&&(X.style.borderColor=J),X.setAttribute("aria-label","Stop voice recognition")}}catch{Zn("system")}},Zn=(a="user")=>{if(En){if(En=!1,Ko&&(clearTimeout(Ko),Ko=null),pn){try{pn.stop()}catch{}pn=null}if(Xe.active=!1,Rn(a),Cn(),X){if(X.classList.remove("persona-voice-recording"),wt){X.style.backgroundColor=wt.backgroundColor,X.style.color=wt.color,X.style.borderColor=wt.borderColor;let f=X.querySelector("svg");f&&f.setAttribute("stroke",wt.color||"currentColor"),wt=null}X.setAttribute("aria-label","Start voice recognition")}}},om=(a,f)=>{let b=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=a?.provider?.type==="runtype",S=a?.provider?.type==="custom";if(!(b||x||S))return null;let Z=h("div","persona-send-button-wrapper"),U=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");U.type="button";let J=a?.tooltipText??"Start voice recognition";U.setAttribute("aria-label",J);let le=a?.iconName??"mic",ve=f?.size??"40px",ie=a?.iconSize??ve,Me=parseFloat(ie)||24,qe=a?.backgroundColor??f?.backgroundColor,ut=a?.iconColor??f?.textColor;U.style.width=ie,U.style.height=ie,U.style.minWidth=ie,U.style.minHeight=ie,U.style.fontSize="18px",U.style.lineHeight="1",ut?U.style.color=ut:U.style.color="var(--persona-text, #111827)";let rn=se(le,Me,ut||"currentColor",1.5);rn?U.appendChild(rn):U.textContent="\u{1F3A4}",qe?U.style.backgroundColor=qe:U.style.backgroundColor="",a?.borderWidth&&(U.style.borderWidth=a.borderWidth,U.style.borderStyle="solid"),a?.borderColor&&(U.style.borderColor=a.borderColor),a?.paddingX&&(U.style.paddingLeft=a.paddingX,U.style.paddingRight=a.paddingX),a?.paddingY&&(U.style.paddingTop=a.paddingY,U.style.paddingBottom=a.paddingY),Z.appendChild(U);let Tt=a?.showTooltip??!1;return _t({anchor:U,trigger:Z,text:()=>U.getAttribute("aria-label")??J,enabled:Tt}),{micButton:U,micButtonWrapper:Z}},Xa=()=>{if(!X||wt)return;let a=o.voiceRecognition??{};wt={backgroundColor:X.style.backgroundColor,color:X.style.color,borderColor:X.style.borderColor,iconName:a.iconName??"mic",iconSize:parseFloat(a.iconSize??o.sendButton?.size??"40")||24}},Ja=(a,f)=>{if(!X)return;let b=X.querySelector("svg");b&&b.remove();let x=wt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),S=se(a,x,f,1.5);S&&X.appendChild(S)},Xs=()=>{X&&X.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Go=()=>{if(!X)return;Xa();let a=o.voiceRecognition??{},f=a.recordingBackgroundColor,b=a.recordingIconColor,x=a.recordingBorderColor;if(Xs(),X.classList.add("persona-voice-recording"),X.style.backgroundColor=f??"var(--persona-voice-recording-bg, #ef4444)",X.style.color=b??"var(--persona-voice-recording-indicator, #ffffff)",b){let S=X.querySelector("svg");S&&S.setAttribute("stroke",b)}x&&(X.style.borderColor=x),X.setAttribute("aria-label","Stop voice recognition")},rm=()=>{if(!X)return;Xa();let a=o.voiceRecognition??{},f=q.getVoiceInterruptionMode(),b=a.processingIconName??"loader",x=a.processingIconColor??wt?.color??"",S=a.processingBackgroundColor??wt?.backgroundColor??"",H=a.processingBorderColor??wt?.borderColor??"";Xs(),X.classList.add("persona-voice-processing"),X.style.backgroundColor=S,X.style.borderColor=H;let Z=x||"currentColor";X.style.color=Z,Ja(b,Z),X.setAttribute("aria-label","Processing voice input"),f==="none"&&(X.style.cursor="default")},sm=()=>{if(!X)return;Xa();let a=o.voiceRecognition??{},f=q.getVoiceInterruptionMode(),b=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",x=a.speakingIconName??b,S=a.speakingIconColor??(f==="barge-in"?a.recordingIconColor??wt?.color??"":wt?.color??""),H=a.speakingBackgroundColor??(f==="barge-in"?a.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":wt?.backgroundColor??""),Z=a.speakingBorderColor??(f==="barge-in"?a.recordingBorderColor??"":wt?.borderColor??"");Xs(),X.classList.add("persona-voice-speaking"),X.style.backgroundColor=H,X.style.borderColor=Z;let U=S||"currentColor";X.style.color=U,Ja(x,U);let J=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";X.setAttribute("aria-label",J),f==="none"&&(X.style.cursor="default"),f==="barge-in"&&X.classList.add("persona-voice-recording")},Hn=()=>{X&&(Xs(),wt&&(X.style.backgroundColor=wt.backgroundColor??"",X.style.color=wt.color??"",X.style.borderColor=wt.borderColor??"",Ja(wt.iconName,wt.color||"currentColor"),wt=null),X.style.cursor="",X.setAttribute("aria-label","Start voice recognition"))},Js=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let a=q.getVoiceStatus(),f=q.getVoiceInterruptionMode();if(f==="none"&&(a==="processing"||a==="speaking"))return;if(f==="cancel"&&(a==="processing"||a==="speaking")){q.stopVoicePlayback();return}if(q.isBargeInActive()){q.stopVoicePlayback(),q.deactivateBargeIn().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,Cn(),Rn("user"),Hn()});return}q.toggleVoice().then(()=>{Xe.active=q.isVoiceActive(),Xe.manuallyDeactivated=!q.isVoiceActive(),Cn(),Rn("user"),q.isVoiceActive()?Go():Hn()});return}if(En){let a=Ae.value.trim();Xe.manuallyDeactivated=!0,Cn(),Zn("user"),a&&(Ae.value="",Ae.style.height="auto",q.sendMessage(a))}else Xe.manuallyDeactivated=!1,Cn(),Qs("user")};Wc=Js,X&&(X.addEventListener("click",Js),je.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(q.isVoiceActive()&&q.toggleVoice(),Hn()):Zn("system"),X&&X.removeEventListener("click",Js)}));let im=l.on("assistant:complete",()=>{Vc&&(Xe.active||Xe.manuallyDeactivated||Vc==="assistant"&&!Xe.lastUserMessageWasVoice||setTimeout(()=>{!Xe.active&&!Xe.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?q.toggleVoice().then(()=>{Xe.active=q.isVoiceActive(),Rn("auto"),q.isVoiceActive()&&Go()}):Qs("auto"))},600))});je.push(im);let am=l.on("action:resubmit",()=>{setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)});je.push(am);let fd=()=>{pt(!I,"user")},Ot=null,Kt=null;if(A&&!L()){let{instance:a,element:f}=Zl({config:o,plugins:r,onToggle:fd});Ot=a,a||(Kt=f)}Ot?t.appendChild(Ot.element):Kt&&t.appendChild(Kt),Or(),Pa(),sd(),$a(q.isStreaming()),ed()||(Yt()==="follow"?Yn(!0):Yc()),If(),z&&(!A||L()?setTimeout(()=>za(),0):I&&setTimeout(()=>za(),200));let $r=()=>{if(L()){Fo(),Or();return}let a=Nt(o),f=o.launcher?.sidebarMode??!1,b=a||f||(o.launcher?.fullHeight??!1),x=t.ownerDocument.defaultView??window,S=o.launcher?.mobileFullscreen??!0,H=o.launcher?.mobileBreakpoint??640,Z=x.innerWidth<=H,U=S&&Z&&A;try{if(U){Tr(),Er=Fs();return}let J=!1;N&&(N=!1,Tr(),J=!0);let le=Fs();if(!J&&le!==Er&&(Tr(),J=!0),Er=le,J&&ka(),!A&&!a){Ce.style.height="",Ce.style.width="";return}if(!f&&!a){let ie=o?.launcher?.width??o?.launcherWidth??zn;Ce.style.width=ie,Ce.style.maxWidth=ie}if(Os(),!b){let ve=x.innerHeight,ie=64,Me=o.launcher?.heightOffset??0,qe=Math.max(200,ve-ie),ut=Math.min(640,qe),rt=Math.max(200,ut-Me);Ce.style.height=`${rt}px`}}finally{if(Fo(),Or(),I&&A){let le=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ve=o.launcher?.sidebarMode??!1,ie=o.launcher?.mobileFullscreen??!0,Me=Nt(o)&&ie&&le,qe=ve||ie&&le&&A||Me;if(qe&&!Tn){let ut=t.getRootNode(),rt=ut instanceof ShadowRoot?ut.host:t.closest(".persona-host");rt&&!Mn&&(Mn=Xl(rt,o.launcher?.zIndex??Vt)),Tn=Jl(t.ownerDocument)}else qe||(Mn?.(),Mn=null,Tn?.(),Tn=null)}}};$r();let md=t.ownerDocument.defaultView??window;if(md.addEventListener("resize",$r),je.push(()=>md.removeEventListener("resize",$r)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{Fo()});a.observe(K),je.push(()=>a.disconnect())}cn=ge.scrollTop;let hd=Ln(ge),lm=()=>{let a=ge.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??ge.ownerDocument.getSelection()},Ya=()=>pg(lm(),ge),bd=()=>{let a=ge.scrollTop,f=Ln(ge),b=f<hd;if(hd=f,!jn()){cn=a,on();return}let{action:x,nextLastScrollTop:S}=ta({following:nn.isFollowing(),currentScrollTop:a,lastScrollTop:cn,nearBottom:uo(ge,qs),userScrollThreshold:Lf,isAutoScrolling:dn||Us||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(cn=S,x==="resume"){Ya()||Jn();return}x==="pause"&&Rr()};if(ge.addEventListener("scroll",bd,{passive:!0}),je.push(()=>ge.removeEventListener("scroll",bd)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{Df(),ol(we)});a.observe(we),a.observe(ge),je.push(()=>a.disconnect())}let yd=()=>{jn()&&nn.isFollowing()&&Ya()&&Rr()},vd=ge.ownerDocument;vd.addEventListener("selectionchange",yd),je.push(()=>{vd.removeEventListener("selectionchange",yd)});let cm=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),xd=a=>{kc()&&jn()&&nn.isFollowing()&&cm.has(a.key)&&Rr()},Cd=a=>{if(!kc()||!jn()||!nn.isFollowing())return;let f=a.target;f&&f.closest("a, button, [tabindex], input, textarea, select")&&Rr()};ge.addEventListener("keydown",xd),ge.addEventListener("focusin",Cd),je.push(()=>{ge.removeEventListener("keydown",xd),ge.removeEventListener("focusin",Cd)});let wd=a=>{if(!jn())return;let f=na({following:nn.isFollowing(),deltaY:a.deltaY,nearBottom:uo(ge,qs),resumeWhenNearBottom:!0});f==="pause"?Rr():f==="resume"&&!Ya()&&Jn()};ge.addEventListener("wheel",wd,{passive:!0}),je.push(()=>ge.removeEventListener("wheel",wd)),Pt.addEventListener("click",()=>{Wr(),ge.scrollTop=ge.scrollHeight,cn=ge.scrollTop,Jn(),Yn(!0),on()}),je.push(()=>Pt.remove()),je.push(()=>{Qc(),Wr()});let Ad=()=>{T&&(xo&&(T.removeEventListener("click",xo),xo=null),P()?(T.style.display="",xo=()=>{pt(!1,"user")},T.addEventListener("click",xo)):T.style.display="none")};Ad(),(()=>{let{clearChatButton:a}=Re;a&&a.addEventListener("click",()=>{q.clearMessages(),Co.clear(),Jn(),or(Re.composerOverlay);try{localStorage.removeItem(xr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xr}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==xr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(f),c?.clear&&Na(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),d={},E.syncFromMetadata(),Se?.clear(),Fe?.reset(),ke?.update()})})(),te&&te.addEventListener("submit",pd);let Sd=[["keydown",tm],["input",em],["paste",nm],["focus",Sf]],Md=a=>{if(a)for(let[f,b]of Sd)a.addEventListener(f,b)},Td=a=>{if(a)for(let[f,b]of Sd)a.removeEventListener(f,b)};Md(Ae),tn?.onComposerSwap((a,f)=>{Td(f),Ae=a,Md(a)});let Ed=t.ownerDocument??document;Ed.addEventListener("keydown",ud,!0);let kd="persona-attachment-drop-active",zr=0,Za=()=>{zr=0,ye.classList.remove(kd)},Qo=()=>o.attachments?.enabled===!0&&Mt!==null,Ld=a=>{!xa(a.dataTransfer)||!Qo()||(zr++,zr===1&&ye.classList.add(kd))},Pd=a=>{!xa(a.dataTransfer)||!Qo()||(zr--,zr<=0&&Za())},Id=a=>{!xa(a.dataTransfer)||!Qo()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},Rd=a=>{if(!xa(a.dataTransfer)||!Qo())return;a.preventDefault(),a.stopPropagation(),Za();let f=Array.from(a.dataTransfer.files??[]);f.length!==0&&Mt.handleFiles(f)},eo=!0;ye.addEventListener("dragenter",Ld,eo),ye.addEventListener("dragleave",Pd,eo),t.addEventListener("dragover",Id,eo),t.addEventListener("drop",Rd,eo);let Ys=t.ownerDocument,Wd=a=>{Qo()&&a.preventDefault()},Hd=a=>{Qo()&&a.preventDefault()};Ys.addEventListener("dragover",Wd),Ys.addEventListener("drop",Hd),je.push(()=>{te&&te.removeEventListener("submit",pd),Td(Ae),Ed.removeEventListener("keydown",ud,!0),tn?.destroy()}),je.push(()=>{ye.removeEventListener("dragenter",Ld,eo),ye.removeEventListener("dragleave",Pd,eo),t.removeEventListener("dragover",Id,eo),t.removeEventListener("drop",Rd,eo),Ys.removeEventListener("dragover",Wd),Ys.removeEventListener("drop",Hd),Za()}),je.push(()=>{q.cancel()}),Ot?je.push(()=>{Ot?.destroy()}):Kt&&je.push(()=>{Kt?.remove()});let It={update(a){let f=o.toolCall,b=o.messageActions,x=o.layout?.messages,S=o.colorScheme,H=o.loadingIndicator,Z=o.iterationDisplay,U=o.features?.showReasoning,J=o.features?.showToolCalls,le=o.features?.toolCallDisplay,ve=o.features?.reasoningDisplay,ie=o.features?.streamAnimation?.type;o=Qg(o,a),_s(),ps(t,o),Es(t,o),ks(t,o),In(),o.colorScheme!==S&&qc();let Me=fc.getForInstance(o.plugins);r.length=0,r.push(...Me),A=o.launcher?.enabled??!0,W=o.launcher?.autoExpand??!1,ee=o.features?.showReasoning??!0,oe=o.features?.showToolCalls??!0,ae=o.features?.scrollToBottom??{};let qe=Yt();ne=o.features?.scrollBehavior??{},qe!==Yt()&&(Wr(),Jn()),Rc(),on();let ut=V;if(V=o.features?.showEventStreamToggle??!1,V&&!ut){if(Se||(fe=new Ms(be),Se=new Ss(Te,fe),Fe=Fe??new Ts,fe.open().then(()=>Se?.restore()).catch(()=>{}),q.setSSEEventCallback((re,Ge)=>{o.onSSEEvent?.(re,Ge),Fe?.processEvent(re,Ge),Se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:re,timestamp:Date.now(),payload:JSON.stringify(Ge)})})),!ot&&$){let re=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"+(re?.toggleButton?" "+re.toggleButton:"");ot=h("button",Ge),ot.style.width="28px",ot.style.height="28px",ot.style.color=Xt.actionIconColor,ot.type="button",ot.setAttribute("aria-label","Event Stream"),ot.title="Event Stream";let ht=se("activity","18px","currentColor",1.5);ht&&ot.appendChild(ht);let st=Re.clearChatButtonWrapper,at=Re.closeButtonWrapper,jt=st||at;jt&&jt.parentNode===$?$.insertBefore(ot,jt):$.appendChild(ot),ot.addEventListener("click",()=>{Ve?Sr():Sa()})}}else!V&&ut&&(Sr(),ot&&(ot.remove(),ot=null),Se?.clear(),fe?.destroy(),Se=null,fe=null,Fe?.reset(),Fe=null);if(o.launcher?.enabled===!1&&Ot&&(Ot.destroy(),Ot=null),o.launcher?.enabled===!1&&Kt&&(Kt.remove(),Kt=null),o.launcher?.enabled!==!1&&!Ot&&!Kt){let{instance:re,element:Ge}=Zl({config:o,plugins:r,onToggle:fd});Ot=re,re||(Kt=Ge),t.appendChild(Ge)}Ot&&Ot.update(o),_&&o.launcher?.title!==void 0&&(_.textContent=o.launcher.title),Q&&o.launcher?.subtitle!==void 0&&(Q.textContent=o.launcher.subtitle);let rt=o.layout?.header;if(rt?.layout!==O&&$){let re=rt?ca(o,rt,{showClose:P(),onClose:()=>pt(!1,"user")}):Bo({config:o,showClose:P(),onClose:()=>pt(!1,"user")});vt.replaceHeader(re),$=vt.header.element,R=vt.header.iconHolder,_=vt.header.headerTitle,Q=vt.header.headerSubtitle,T=vt.header.closeButton,O=rt?.layout}else if(rt){if(R&&(R.style.display=rt.showIcon===!1?"none":""),_&&(_.style.display=rt.showTitle===!1?"none":""),Q&&(Q.style.display=rt.showSubtitle===!1?"none":""),T){let re=P()&&rt.showCloseButton!==!1;T.style.display=re?"":"none"}if(Re.clearChatButtonWrapper){let re=rt.showClearChat;if(re!==void 0){Re.clearChatButtonWrapper.style.display=re?"":"none";let{closeButtonWrapper:Ge}=Re;Ge&&!Ge.classList.contains("persona-absolute")&&(re?Ge.classList.remove("persona-ml-auto"):Ge.classList.add("persona-ml-auto"))}}}let Tt=o.layout?.showHeader!==!1;$&&($.style.display=Tt?"":"none");let Rt=o.layout?.showFooter!==!1;K&&(K.style.display=Rt?"":"none"),Fo(),on(),A!==w?A?pt(W,"auto"):(I=!0,Or()):W!==G&&pt(W,"auto"),G=W,w=A,$r(),Ad();let $e=JSON.stringify(o.toolCall)!==JSON.stringify(f),Le=JSON.stringify(o.messageActions)!==JSON.stringify(b),Et=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),gt=o.loadingIndicator?.render!==H?.render||o.loadingIndicator?.renderIdle!==H?.renderIdle||o.loadingIndicator?.showBubble!==H?.showBubble,Gt=o.iterationDisplay!==Z,ft=(o.features?.showReasoning??!0)!==(U??!0)||(o.features?.showToolCalls??!0)!==(J??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(le)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ve);($e||Le||Et||gt||Gt||ft)&&q&&(Ia++,Hr(we,q.getMessages(),pe));let Wt=o.features?.streamAnimation?.type;if(Wt!==ie&&Wt&&Wt!=="none"){let re=hr(Wt,o.features?.streamAnimation?.plugins);re&&ia(re,t)}let Be=o.launcher??{},ze=Be.headerIconHidden??!1,$t=o.layout?.header?.showIcon,zt=ze||$t===!1,At=Be.headerIconName,dt=Be.headerIconSize??"48px";if(R){let re=ye.querySelector(".persona-border-b-persona-divider"),Ge=re?.querySelector(".persona-flex-col");if(zt)R.style.display="none",re&&Ge&&!re.contains(Ge)&&re.insertBefore(Ge,re.firstChild);else{if(R.style.display="",R.style.height=dt,R.style.width=dt,re&&Ge&&(re.contains(R)?R.nextSibling!==Ge&&(R.remove(),re.insertBefore(R,Ge)):re.insertBefore(R,Ge)),At){let st=parseFloat(dt)||24,at=se(At,st*.6,"currentColor",1);at?R.replaceChildren(at):R.textContent=Be.agentIconText??"\u{1F4AC}"}else if(Be.iconUrl){let st=R.querySelector("img");if(st)st.src=Be.iconUrl,st.style.height=dt,st.style.width=dt;else{let at=document.createElement("img");at.src=Be.iconUrl,at.alt="",at.className="persona-rounded-xl persona-object-cover",at.style.height=dt,at.style.width=dt,R.replaceChildren(at)}}else{let st=R.querySelector("svg"),at=R.querySelector("img");(st||at)&&R.replaceChildren(),R.textContent=Be.agentIconText??"\u{1F4AC}"}let ht=R.querySelector("img");ht&&(ht.style.height=dt,ht.style.width=dt)}}let mt=o.layout?.header?.showTitle,tt=o.layout?.header?.showSubtitle;if(_&&(_.style.display=mt===!1?"none":""),Q&&(Q.style.display=tt===!1?"none":""),T){let re=P()&&o.layout?.header?.showCloseButton!==!1;T.style.display=re?"":"none";let Ge=Be.closeButtonSize??"32px",ht=Be.closeButtonPlacement??"inline";T.style.height=Ge,T.style.width=Ge;let{closeButtonWrapper:st}=Re,at=ht==="top-right",jt=st?.classList.contains("persona-absolute");if(st&&at!==jt)if(st.remove(),at)st.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ye.style.position="relative",ye.appendChild(st);else{let no=Be.clearChat?.placement??"inline",qr=Be.clearChat?.enabled??!0;st.className=qr&&no==="inline"?"":"persona-ml-auto";let Bd=ye.querySelector(".persona-border-b-persona-divider");Bd&&Bd.appendChild(st)}if(T.style.color=Be.closeButtonColor||Xt.actionIconColor,Be.closeButtonBackgroundColor?(T.style.backgroundColor=Be.closeButtonBackgroundColor,T.classList.remove("hover:persona-bg-gray-100")):(T.style.backgroundColor="",T.classList.add("hover:persona-bg-gray-100")),Be.closeButtonBorderWidth||Be.closeButtonBorderColor){let no=Be.closeButtonBorderWidth||"0px",qr=Be.closeButtonBorderColor||"transparent";T.style.border=`${no} solid ${qr}`,T.classList.remove("persona-border-none")}else T.style.border="",T.classList.add("persona-border-none");Be.closeButtonBorderRadius?(T.style.borderRadius=Be.closeButtonBorderRadius,T.classList.remove("persona-rounded-full")):(T.style.borderRadius="",T.classList.add("persona-rounded-full")),Be.closeButtonPaddingX?(T.style.paddingLeft=Be.closeButtonPaddingX,T.style.paddingRight=Be.closeButtonPaddingX):(T.style.paddingLeft="",T.style.paddingRight=""),Be.closeButtonPaddingY?(T.style.paddingTop=Be.closeButtonPaddingY,T.style.paddingBottom=Be.closeButtonPaddingY):(T.style.paddingTop="",T.style.paddingBottom="");let sn=Be.closeButtonIconName??"x",wn=Be.closeButtonIconText??"\xD7";T.innerHTML="";let Ft=se(sn,"28px","currentColor",1);Ft?(Ft.style.display="block",T.appendChild(Ft)):T.textContent=wn;let qt=Be.closeButtonTooltipText??"Close chat",Dn=Be.closeButtonShowTooltip??!0;T.setAttribute("aria-label",qt),st&&_t({anchor:T,trigger:st,text:()=>T?.getAttribute("aria-label")??qt,enabled:Dn})}let{clearChatButton:_e,clearChatButtonWrapper:yt}=Re;if(_e){let re=Be.clearChat??{},Ge=re.enabled??!0,ht=o.layout?.header?.showClearChat,st=ht!==void 0?ht:Ge,at=re.placement??"inline";if(yt){yt.style.display=st?"":"none";let{closeButtonWrapper:jt}=Re;!L()&&jt&&!jt.classList.contains("persona-absolute")&&(st?jt.classList.remove("persona-ml-auto"):jt.classList.add("persona-ml-auto"));let sn=at==="top-right",wn=yt.classList.contains("persona-absolute");if(!L()&&sn!==wn&&st){if(yt.remove(),sn)yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px",ye.style.position="relative",ye.appendChild(yt);else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let qt=ye.querySelector(".persona-border-b-persona-divider"),Dn=Re.closeButtonWrapper;qt&&Dn&&Dn.parentElement===qt?qt.insertBefore(yt,Dn):qt&&qt.appendChild(yt)}let Ft=Re.closeButtonWrapper;Ft&&!Ft.classList.contains("persona-absolute")&&(sn?Ft.classList.add("persona-ml-auto"):Ft.classList.remove("persona-ml-auto"))}}if(st){if(!L()){let no=re.size??"32px";_e.style.height=no,_e.style.width=no}let jt=re.iconName??"refresh-cw",sn=re.iconColor??"";_e.style.color=sn||Xt.actionIconColor,_e.innerHTML="";let wn=L()?"14px":"20px",Ft=se(jt,wn,"currentColor",1);if(Ft&&(Ft.style.display="block",_e.appendChild(Ft)),re.backgroundColor?(_e.style.backgroundColor=re.backgroundColor,_e.classList.remove("hover:persona-bg-gray-100")):(_e.style.backgroundColor="",_e.classList.add("hover:persona-bg-gray-100")),re.borderWidth||re.borderColor){let no=re.borderWidth||"0px",qr=re.borderColor||"transparent";_e.style.border=`${no} solid ${qr}`,_e.classList.remove("persona-border-none")}else _e.style.border="",_e.classList.add("persona-border-none");re.borderRadius?(_e.style.borderRadius=re.borderRadius,_e.classList.remove("persona-rounded-full")):(_e.style.borderRadius="",_e.classList.add("persona-rounded-full")),re.paddingX?(_e.style.paddingLeft=re.paddingX,_e.style.paddingRight=re.paddingX):(_e.style.paddingLeft="",_e.style.paddingRight=""),re.paddingY?(_e.style.paddingTop=re.paddingY,_e.style.paddingBottom=re.paddingY):(_e.style.paddingTop="",_e.style.paddingBottom="");let qt=re.tooltipText??"Clear chat",Dn=re.showTooltip??!0;_e.setAttribute("aria-label",qt),yt&&_t({anchor:_e,trigger:yt,text:()=>_e?.getAttribute("aria-label")??qt,enabled:Dn})}}let Ut=o.actionParsers&&o.actionParsers.length?o.actionParsers:[hc],gn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Ls.message,Ls.messageAndClick];E=bc({parsers:Ut,handlers:gn,getSessionMetadata:m,updateSessionMetadata:C,emit:l.emit,documentRef:typeof document<"u"?document:null}),pe=sf(o,E,ue),q.updateConfig(o),Hr(we,q.getMessages(),pe),Pa(),sd(),$a(q.isStreaming());let Ur=o.voiceRecognition?.enabled===!0,Zs=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Lt=o.voiceRecognition?.provider?.type==="runtype";if(Ur&&(Zs||Lt))if(!X||!Ue){let re=om(o.voiceRecognition,o.sendButton);re&&(X=re.micButton,Ue=re.micButtonWrapper,Ke.insertBefore(Ue,hn),X.addEventListener("click",Js),X.disabled=q.isStreaming())}else{let re=o.voiceRecognition??{},Ge=o.sendButton??{},ht=re.iconName??"mic",st=Ge.size??"40px",at=re.iconSize??st,jt=parseFloat(at)||24;X.style.width=at,X.style.height=at,X.style.minWidth=at,X.style.minHeight=at;let sn=re.iconColor??Ge.textColor;X.innerHTML="";let wn=se(ht,jt,sn||"currentColor",1.5);wn?X.appendChild(wn):X.textContent="\u{1F3A4}";let Ft=re.backgroundColor??Ge.backgroundColor;Ft?X.style.backgroundColor=Ft:X.style.backgroundColor="",sn?X.style.color=sn:X.style.color="var(--persona-text, #111827)",re.borderWidth?(X.style.borderWidth=re.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),re.borderColor?X.style.borderColor=re.borderColor:X.style.borderColor="",re.paddingX?(X.style.paddingLeft=re.paddingX,X.style.paddingRight=re.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),re.paddingY?(X.style.paddingTop=re.paddingY,X.style.paddingBottom=re.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let qt=re.tooltipText??"Start voice recognition",Dn=re.showTooltip??!1;X.setAttribute("aria-label",qt),Ue&&_t({anchor:X,trigger:Ue,text:()=>X?.getAttribute("aria-label")??qt,enabled:Dn}),Ue.style.display="",X.disabled=q.isStreaming()}else X&&Ue&&(Ue.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?q.isVoiceActive()&&q.toggleVoice():En&&Zn());if(o.attachments?.enabled===!0){if(!De||!Ee){let re=o.attachments??{},ht=(o.sendButton??{}).size??"40px";Ze||(Ze=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ze.style.display="none",te.insertBefore(Ze,Ae)),We||(We=document.createElement("input"),We.type="file",We.accept=(re.allowedTypes??$n).join(","),We.multiple=(re.maxFiles??4)>1,We.style.display="none",We.setAttribute("aria-label","Attach files"),te.insertBefore(We,Ae)),De=h("div","persona-send-button-wrapper"),Ee=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ee.type="button",Ee.setAttribute("aria-label",re.buttonTooltipText??"Attach file");let st=re.buttonIconName??"paperclip",at=ht,jt=parseFloat(at)||40,sn=Math.round(jt*.6);Ee.style.width=at,Ee.style.height=at,Ee.style.minWidth=at,Ee.style.minHeight=at,Ee.style.fontSize="18px",Ee.style.lineHeight="1";let wn=se(st,sn,"currentColor",1.5);wn?Ee.appendChild(wn):Ee.textContent="\u{1F4CE}",Ee.addEventListener("click",qt=>{qt.preventDefault(),We?.click()}),De.appendChild(Ee);let Ft=re.buttonTooltipText??"Attach file";_t({anchor:Ee,trigger:De,text:()=>Ee?.getAttribute("aria-label")??Ft}),Ie?Ie.append(De):te.appendChild(De),!Mt&&We&&Ze&&(Mt=os.fromConfig(re),Mt.setPreviewsContainer(Ze),We.addEventListener("change",async()=>{Mt&&We?.files&&(await Mt.handleFileSelect(We.files),We.value="")}))}else{De.style.display="";let re=o.attachments??{};We&&(We.accept=(re.allowedTypes??$n).join(","),We.multiple=(re.maxFiles??4)>1),Mt&&Mt.updateConfig({allowedTypes:re.allowedTypes,maxFileSize:re.maxFileSize,maxFiles:re.maxFiles})}if(ye.querySelector(".persona-attachment-drop-overlay")?.remove(),ye.appendChild(af(o.attachments?.dropOverlay)),Ee){let re=o.attachments??{},Ge=re.buttonTooltipText??"Attach file";Ee.setAttribute("aria-label",Ge),Ee.textContent="";let ht=parseFloat(o.sendButton?.size??"40px")||40,st=se(re.buttonIconName??"paperclip",Math.round(ht*.6),"currentColor",1.5);st?Ee.appendChild(st):Ee.textContent="\u{1F4CE}",De&&_t({anchor:Ee,trigger:De,text:()=>Ee?.getAttribute("aria-label")??Ge})}}else De&&(De.style.display="none"),Mt&&Mt.clearAttachments(),ye.querySelector(".persona-attachment-drop-overlay")?.remove();let Dt=o.sendButton??{},jr=Dt.useIcon??!1,ti=Dt.iconText??"\u2191",Xo=Dt.iconName,ni=Dt.tooltipText??"Send message",el=Dt.showTooltip??!1,Eo=Dt.size??"40px",Bn=Dt.backgroundColor,ko=Dt.textColor;if(jr){if(he.style.width=Eo,he.style.height=Eo,he.style.minWidth=Eo,he.style.minHeight=Eo,he.style.fontSize="18px",he.style.lineHeight="1",ko?he.style.color=ko:he.style.color="var(--persona-button-primary-fg, #ffffff)",!q.isStreaming())if(he.innerHTML="",Xo){let re=parseFloat(Eo)||24,Ge=ko?.trim()||"currentColor",ht=se(Xo,re,Ge,2);ht?he.appendChild(ht):he.textContent=ti}else he.textContent=ti;he.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Bn?(he.style.backgroundColor=Bn,he.classList.remove("persona-bg-persona-primary")):(he.style.backgroundColor="",he.classList.add("persona-bg-persona-primary"))}else he.textContent=o.copy?.sendButtonLabel??"Send",he.style.width="",he.style.height="",he.style.minWidth="",he.style.minHeight="",he.style.fontSize="",he.style.lineHeight="",he.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",Bn?(he.style.backgroundColor=Bn,he.classList.remove("persona-bg-persona-accent")):he.classList.add("persona-bg-persona-accent"),ko?he.style.color=ko:he.classList.add("persona-text-white");Dt.borderWidth?(he.style.borderWidth=Dt.borderWidth,he.style.borderStyle="solid"):(he.style.borderWidth="",he.style.borderStyle=""),Dt.borderColor?he.style.borderColor=Dt.borderColor:he.style.borderColor="",Dt.paddingX?(he.style.paddingLeft=Dt.paddingX,he.style.paddingRight=Dt.paddingX):(he.style.paddingLeft="",he.style.paddingRight=""),Dt.paddingY?(he.style.paddingTop=Dt.paddingY,he.style.paddingBottom=Dt.paddingY):(he.style.paddingTop="",he.style.paddingBottom=""),q.isStreaming()||he.setAttribute("aria-label",ni),hn&&_t({anchor:he,trigger:hn,text:()=>he.getAttribute("aria-label")??ni,enabled:el});let oi=o.layout?.contentMaxWidth??(L()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);oi?(we.style.maxWidth=oi,we.style.marginLeft="auto",we.style.marginRight="auto",we.style.width="100%",te&&(te.style.maxWidth=oi,te.style.marginLeft="auto",te.style.marginRight="auto"),xt&&(xt.style.maxWidth=oi,xt.style.marginLeft="auto",xt.style.marginRight="auto")):(we.style.maxWidth="",we.style.marginLeft="",we.style.marginRight="",we.style.width="",te&&(te.style.maxWidth="",te.style.marginLeft="",te.style.marginRight=""),xt&&(xt.style.maxWidth="",xt.style.marginLeft="",xt.style.marginRight=""));let to=o.statusIndicator??{},dm=to.visible??!0;if(k.style.display=dm?"":"none",q){let re=q.getStatus();kt(k,(ht=>ht==="idle"?to.idleText??Ht.idle:ht==="connecting"?to.connectingText??Ht.connecting:ht==="connected"?to.connectedText??Ht.connected:ht==="error"?to.errorText??Ht.error:Ht[ht])(re),to,re)}k.classList.remove("persona-text-left","persona-text-center","persona-text-right");let pm=to.align==="left"?"persona-text-left":to.align==="center"?"persona-text-center":"persona-text-right";k.classList.add(pm)},open(){P()&&pt(!0,"api")},close(){P()&&pt(!1,"api")},toggle(){P()&&pt(!I,"api")},reconnect(){q.reconnectNow()},clearChat(){Pn=!1,q.clearMessages(),Co.clear(),Jn();try{localStorage.removeItem(xr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xr}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==xr)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 a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),c?.clear&&Na(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),d={},E.syncFromMetadata(),Se?.clear(),Fe?.reset(),ke?.update()},setMessage(a){return!Ae||q.isStreaming()?!1:(!I&&P()&&pt(!0,"system"),Ae.value=a,Ae.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(q.isStreaming())return!1;let f=a?.trim()||Ae.value.trim();return f?(!I&&P()&&pt(!0,"system"),Ae.value="",Ae.style.height="auto",q.sendMessage(f),!0):!1},startVoiceRecognition(){return q.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(q.isVoiceActive()||(!I&&P()&&pt(!0,"system"),Xe.manuallyDeactivated=!1,Cn(),q.toggleVoice().then(()=>{Xe.active=q.isVoiceActive(),Rn("user"),q.isVoiceActive()&&Go()})),!0):En?!0:gd()?(!I&&P()&&pt(!0,"system"),Xe.manuallyDeactivated=!1,Cn(),Qs("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?q.isVoiceActive()?(q.toggleVoice().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,Cn(),Rn("user"),Hn()}),!0):!1:En?(Xe.manuallyDeactivated=!0,Cn(),Zn("user"),!0):!1},injectMessage(a){return!I&&P()&&pt(!0,"system"),q.injectMessage(a)},injectAssistantMessage(a){!I&&P()&&pt(!0,"system");let f=q.injectAssistantMessage(a);return Y&&(Y=!1,de&&(clearTimeout(de),de=null),setTimeout(()=>{q&&!q.isStreaming()&&q.continueConversation()},100)),f},injectUserMessage(a){return!I&&P()&&pt(!0,"system"),q.injectUserMessage(a)},injectSystemMessage(a){return!I&&P()&&pt(!0,"system"),q.injectSystemMessage(a)},injectMessageBatch(a){return!I&&P()&&pt(!0,"system"),q.injectMessageBatch(a)},injectComponentDirective(a){return!I&&P()&&pt(!0,"system"),q.injectComponentDirective(a)},injectTestMessage(a){!I&&P()&&pt(!0,"system"),q.injectTestEvent(a)},async connectStream(a,f){return q.connectStream(a,f)},__pushEventStreamEvent(a){Se&&(Fe?.processEvent(a.type,a.payload),Se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a.type,timestamp:Date.now(),payload:JSON.stringify(a.payload)}))},showEventStream(){!V||!Se||Sa()},hideEventStream(){Ve&&Sr()},isEventStreamVisible(){return Ve},showArtifacts(){Jt(o)&&(Pn=!1,_o=!0,In(),et?.setMobileOpen(!0))},hideArtifacts(){Jt(o)&&(Pn=!0,In())},upsertArtifact(a){return Jt(o)?(Lo(o.features?.artifacts,a.artifactType)==="panel"&&(Pn=!1,_o=!0),q.upsertArtifact(a)):null},selectArtifact(a){Jt(o)&&q.selectArtifact(a)},clearArtifacts(){Jt(o)&&q.clearArtifacts()},getArtifacts(){return q?.getArtifacts()??[]},getSelectedArtifactId(){return q?.getSelectedArtifactId()??null},focusInput(){return A&&!I&&!L()||!Ae?!1:(Ae.focus(),!0)},async resolveApproval(a,f,b){let S=q.getMessages().find(H=>H.variant==="approval"&&H.approval?.id===a);if(!S?.approval)throw new Error(`Approval not found: ${a}`);if(S.approval.toolType==="webmcp"){q.resolveWebMcpApproval(S.id,f);return}return q.resolveApproval(S.approval,f,b)},getMessages(){return q.getMessages()},getStatus(){return q.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(a){C(a)},on(a,f){return l.on(a,f)},off(a,f){l.off(a,f)},isOpen(){return P()&&I},isVoiceActive(){return Xe.active},toggleReadAloud(a){q.toggleReadAloud(a)},stopReadAloud(){q.stopSpeaking()},getReadAloudState(a){return q.getReadAloudState(a)},onReadAloudChange(a){return q.onReadAloudChange(a)},getState(){return{open:P()&&I,launcherEnabled:A,voiceActive:Xe.active,streaming:q.isStreaming()}},showCSATFeedback(a){!I&&P()&&pt(!0,"system");let f=we.querySelector(".persona-feedback-container");f&&f.remove();let b=nf({onSubmit:async(x,S)=>{q.isClientTokenMode()&&await q.submitCSATFeedback(x,S),a?.onSubmit?.(x,S)},onDismiss:a?.onDismiss,...a});we.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!I&&P()&&pt(!0,"system");let f=we.querySelector(".persona-feedback-container");f&&f.remove();let b=of({onSubmit:async(x,S)=>{q.isClientTokenMode()&&await q.submitNPSFeedback(x,S),a?.onSubmit?.(x,S)},onDismiss:a?.onDismiss,...a});we.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,f){return q.submitCSATFeedback(a,f)},async submitNPSFeedback(a,f){return q.submitNPSFeedback(a,f)},destroy(){qa(),Mo!=null&&(clearInterval(Mo),Mo=null),je.forEach(a=>a()),Oe.remove(),Qe?.remove(),Ot?.destroy(),Kt?.remove(),xo&&T.removeEventListener("click",xo)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,f={controller:It,getMessages:It.getMessages,getStatus:It.getStatus,getMetadata:It.getPersistentMetadata,updateMetadata:It.updatePersistentMetadata,clearHistory:()=>It.clearChat(),setVoiceActive:b=>b?It.startVoiceRecognition():It.stopVoiceRecognition()};window.AgentWidgetBrowser=f,je.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=a)})}if(typeof window<"u"){let a=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),f=U=>{let J=U.detail;(!J?.instanceId||J.instanceId===a)&&It.focusInput()};if(window.addEventListener("persona:focusInput",f),je.push(()=>{window.removeEventListener("persona:focusInput",f)}),V){let U=le=>{let ve=le.detail;(!ve?.instanceId||ve.instanceId===a)&&It.showEventStream()},J=le=>{let ve=le.detail;(!ve?.instanceId||ve.instanceId===a)&&It.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",J),je.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",J)})}let b=U=>{let J=U.detail;(!J?.instanceId||J.instanceId===a)&&It.showArtifacts()},x=U=>{let J=U.detail;(!J?.instanceId||J.instanceId===a)&&It.hideArtifacts()},S=U=>{let J=U.detail;J?.instanceId&&J.instanceId!==a||J?.artifact&&It.upsertArtifact(J.artifact)},H=U=>{let J=U.detail;J?.instanceId&&J.instanceId!==a||typeof J?.id=="string"&&It.selectArtifact(J.id)},Z=U=>{let J=U.detail;(!J?.instanceId||J.instanceId===a)&&It.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",H),window.addEventListener("persona:clearArtifacts",Z),je.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",H),window.removeEventListener("persona:clearArtifacts",Z)})}let un=Lv(o.persistState);if(un&&P()){let a=Pv(un.storage),f=`${un.keyPrefix}widget-open`,b=`${un.keyPrefix}widget-voice`,x=`${un.keyPrefix}widget-voice-mode`;if(a){let S=un.persist?.openState&&a.getItem(f)==="true",H=un.persist?.voiceState&&a.getItem(b)==="true",Z=un.persist?.voiceState&&a.getItem(x)==="true";if(S&&setTimeout(()=>{It.open(),setTimeout(()=>{if(H||Z)It.startVoiceRecognition();else if(un.persist?.focusInput){let U=t.querySelector("textarea");U&&U.focus()}},100)},0),un.persist?.openState&&(l.on("widget:opened",()=>{a.setItem(f,"true")}),l.on("widget:closed",()=>{a.setItem(f,"false")})),un.persist?.voiceState&&(l.on("voice:state",U=>{a.setItem(b,U.active?"true":"false")}),l.on("user:message",U=>{a.setItem(x,U.viaVoice?"true":"false")})),un.clearOnChatClear){let U=()=>{a.removeItem(f),a.removeItem(b),a.removeItem(x)},J=()=>U();window.addEventListener("persona:clear-chat",J),je.push(()=>{window.removeEventListener("persona:clear-chat",J)})}}}if(y&&P()&&setTimeout(()=>{It.open()},0),qo(),!kf){let a=ii(()=>{q&&(Ia++,Co.clear(),Hr(we,q.getMessages(),pe))});je.push(a)}return It};var cf=(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},Wv=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},Hv=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},Bv=(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.")},df=(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"},Sc=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=""},pf=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Sc(t)},Cc=t=>{t.style.transition=""},wc=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=""},Ac=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Ca=(t,e)=>{t.style.width="",t.style.minWidth="0",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},Dv=(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))},Nv=(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)},Ov=t=>{let e=pr(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:Qt(e,r)??r;return{inset:o(n?.inset,Ui),canvasBackground:o(n?.canvasBackground,ji)}},uf=(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},Fv=(t,e,n,o,r,s,i,l)=>{let p=mn(s),c=p.reveal==="push",d=l!=null,u=l?.inset??"",y=l?.canvasBackground??"";Dv(t,e,n,o,c),Nv(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 g=t.ownerDocument.defaultView,m=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,D=g!=null?g.innerWidth<=C:!1;if(m&&D&&i){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),wc(e),Cc(o),pf(o),Ac(n),Ca(r,o),uf(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??Vt),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"),pf(o),Wv(o,p.maxHeight),uf(o,d&&i,u,y),p.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",wc(e),Cc(o),Ac(n),Ca(r,o);let E=p.animate?"transform 180ms ease":"none",A=p.side==="right"?"translateX(100%)":"translateX(-100%)",W=i?"translateX(0)":A;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=E,o.style.transform=W,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",Cc(o),Sc(o),Ca(r,o);let E=cf(p.width,t.clientWidth),A=Math.max(0,t.clientWidth),W=p.animate?"margin-left 180ms ease":"none",z=p.side==="right"?i?-E:0:i?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=`${A+E}px`,e.style.transition=W,e.style.marginLeft=`${z}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${A}px`,n.style.maxWidth=`${A}px`,n.style.minWidth=`${A}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="",wc(e),Sc(o),Ac(n),Ca(r,o);let E=p.reveal==="emerge";E?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let A=i?p.width:"0px",W=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${d?", padding 180ms ease":""}`:"none",z=!i;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${A}`,o.style.width=A,o.style.maxWidth=A,o.style.minWidth=A,o.style.minHeight="0",Hv(o,p.maxHeight),o.style.overflow=E||z?"hidden":"visible",o.style.transition=W,E){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let G=d?`calc(${cf(p.width,t.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=G,r.style.minWidth=G,r.style.maxWidth=G,r.style.boxSizing="border-box"}}},_v=(t,e)=>{let n=t.ownerDocument.createElement("div");return df(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){df(n,o)},destroy(){n.remove()}}},$v=(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"),u=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 y=null,g=()=>{y?.disconnect(),y=null},m=null,C=()=>{m=e?.launcher?.detachedPanel===!0?Ov(e):null};C();let D=()=>{Fv(i,l,p,c,d,e,u,m)},B=null,E=()=>{B?.(),B=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(B=qi(()=>{C(),D()}))},A=()=>{g(),mn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(y=new ResizeObserver(()=>{D()}),y.observe(i)))},W=!1,z=()=>{D(),A(),u&&!W&&i.dataset.personaDockMobileFullscreen!=="true"&&(W=!0,Bv(i,mn(e)))},G=i.ownerDocument.defaultView,w=()=>{z()};return G?.addEventListener("resize",w),mn(e).reveal==="push"?(l.appendChild(p),l.appendChild(c),i.appendChild(l)):(i.appendChild(p),i.appendChild(c)),z(),E(),{mode:"docked",host:d,shell:i,syncWidgetState(O){let N=O.launcherEnabled?O.open:!0;u!==N&&(u=N,z())},updateConfig(O){e=O,(e?.launcher?.enabled??!0)===!1&&(u=!0),C(),z(),E()},destroy(){G?.removeEventListener("resize",w),B?.(),B=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),i.remove()}}},gf=(t,e)=>Nt(e)?$v(t,e):_v(t,e);var Ps={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ff=.15,mf=1.5,Mc="persona-preview-shell-theme",zv={load:()=>null,save:()=>{},clear:()=>{}},Uv=["How do I get started?","Pricing & plans","Talk to support"];function Tc(t){return t.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function jv(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 hf(t){let e=jv(t);return`* { box-sizing: border-box; }
314
314
  html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
315
315
  html { color-scheme: ${t}; }
316
316
  body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
@@ -393,10 +393,10 @@ _Details: ${n.message}_`:o}var ns=t=>({isError:!0,content:[{type:"text",text:t}]
393
393
  <body>
394
394
  ${n?s:r}
395
395
  </body>
396
- </html>`}var Kv=()=>[{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()}],Gv=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function Qv(t,e,n=[]){return t==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]: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"&&Gv(e)?[...Kv(),...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 Xv(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:Uv:t.suggestionChips,initialMessages:Qv(e,t,n),storageAdapter:zv};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),r}function Jv(t,e){let n=t.theme?dr(t.theme,{validate:!1}):dr();return{...ct,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function Cr(t,e){let n=t.scene??"conversation";return Xv(Jv(t,e),n,t.appendedMessages??[])}function vf(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:Cr(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Cr(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:Cr(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Cr(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Cr(t,n),shellMode:n}]}function xf(t,e){let n={...e},o=[],r=[],s=null,i=!1,l=1,p=1,c=0;function d(){return n.device??"desktop"}function u(){return n.zoom??l}function y(){let E=getComputedStyle(t),A=parseFloat(E.paddingLeft)+parseFloat(E.paddingRight),W=parseFloat(E.paddingTop)+parseFloat(E.paddingBottom),z=40,G=(n.compareMode??"off")!=="off",w=(t.clientWidth-A-z)/(G?2:1),O=t.clientHeight-W-z;if(w<=0||O<=0)return 1;let N=Ps[d()]??Ps.desktop;return Math.min(w/N.w,O/N.h,1)}function g(){l=y();let E=Math.max(ff,Math.min(mf,u()));p=E;let A=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let W of A){let z=W.dataset.device??"desktop",G=Ps[z]??Ps.desktop;W.style.width=`${G.w*E}px`,W.style.height=`${G.h*E}px`,z==="mobile"&&(W.style.borderRadius=`${32*E}px`);let w=W.querySelector("iframe");w&&(w.style.width=`${G.w}px`,w.style.height=`${G.h}px`,w.style.transformOrigin="top left",w.style.transition="none",w.style.transform=`scale(${E})`)}n.onScaleChange?.(E)}function m(){n.onBeforeDestroy?.();for(let E of o)E.destroy();for(let E of r)E();o=[],r=[]}function C(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function D(){if(i)return;m();let E=++c,A=vf(n),W=d(),z=(n.compareMode??"off")!=="off",G=(n.scene??"conversation")==="minimized",w=n.widgetCssPath??"/widget-dist/widget.css",O=n.buildSrcdoc??yf,N=W==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",L=pe=>`<div class="${N}" data-mount-id="${pe.mountId}" data-device="${W}" data-shell-mode="${pe.shellMode}">
396
+ </html>`}var Kv=()=>[{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()}],Gv=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function Qv(t,e,n=[]){return t==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]: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"&&Gv(e)?[...Kv(),...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 Xv(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:Uv:t.suggestionChips,initialMessages:Qv(e,t,n),storageAdapter:zv};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),r}function Jv(t,e){let n=t.theme?dr(t.theme,{validate:!1}):dr();return{...lt,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function Cr(t,e){let n=t.scene??"conversation";return Xv(Jv(t,e),n,t.appendedMessages??[])}function vf(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:Cr(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Cr(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:Cr(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Cr(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Cr(t,n),shellMode:n}]}function xf(t,e){let n={...e},o=[],r=[],s=null,i=!1,l=1,p=1,c=0;function d(){return n.device??"desktop"}function u(){return n.zoom??l}function y(){let E=getComputedStyle(t),A=parseFloat(E.paddingLeft)+parseFloat(E.paddingRight),W=parseFloat(E.paddingTop)+parseFloat(E.paddingBottom),z=40,G=(n.compareMode??"off")!=="off",w=(t.clientWidth-A-z)/(G?2:1),O=t.clientHeight-W-z;if(w<=0||O<=0)return 1;let N=Ps[d()]??Ps.desktop;return Math.min(w/N.w,O/N.h,1)}function g(){l=y();let E=Math.max(ff,Math.min(mf,u()));p=E;let A=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let W of A){let z=W.dataset.device??"desktop",G=Ps[z]??Ps.desktop;W.style.width=`${G.w*E}px`,W.style.height=`${G.h*E}px`,z==="mobile"&&(W.style.borderRadius=`${32*E}px`);let w=W.querySelector("iframe");w&&(w.style.width=`${G.w}px`,w.style.height=`${G.h}px`,w.style.transformOrigin="top left",w.style.transition="none",w.style.transform=`scale(${E})`)}n.onScaleChange?.(E)}function m(){n.onBeforeDestroy?.();for(let E of o)E.destroy();for(let E of r)E();o=[],r=[]}function C(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function D(){if(i)return;m();let E=++c,A=vf(n),W=d(),z=(n.compareMode??"off")!=="off",G=(n.scene??"conversation")==="minimized",w=n.widgetCssPath??"/widget-dist/widget.css",O=n.buildSrcdoc??yf,N=W==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",L=pe=>`<div class="${N}" data-mount-id="${pe.mountId}" data-device="${W}" data-shell-mode="${pe.shellMode}">
397
397
  ${z?`<div class="preview-frame-meta"><span class="preview-frame-label">${Tc(pe.label)}</span></div>`:""}
398
398
  <iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${pe.mountId}"></iframe>
399
- </div>`,P=z?`<div class="preview-compare-grid">${A.map(pe=>`<div class="preview-compare-cell">${L(pe)}</div>`).join("")}</div>`:`<div class="preview-single">${L(A[0])}</div>`;n.morphContainer?n.morphContainer(t,P):t.innerHTML=P,g();let I=C(),Y=0,de=I.length,ue=()=>{if(i||E!==c)return;for(let ee of I){let oe=ee.dataset.mountId;if(!oe||!ee.contentDocument)continue;let V=A.find(fe=>fe.mountId===oe);if(!V)continue;let ae=()=>{},ne=Ot(V.config),me=ne?(()=>{let fe=ee.contentDocument?.getElementById(`preview-content-${oe}`);if(!fe)return null;let Te=gf(fe,V.config),Se=ee.contentDocument.createElement("div");Se.id=oe,Se.style.height="100%",Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1",Se.style.minHeight="0",Te.host.appendChild(Se);let Fe=()=>Te.syncWidgetState(be.getState()),ke=ae;return ae=()=>{Te.destroy(),ke()},Se.__syncDock=Fe,Se.__hostLayout=Te,Se})():ee.contentDocument.getElementById(oe);if(!me)continue;let be=lf(me,V.config);if(o.push(be),ne&&me.__syncDock){let fe=me.__syncDock,Te=be.on("widget:opened",fe),Se=be.on("widget:closed",fe),Fe=ae;ae=()=>{Te(),Se(),Fe()},fe()}r.push(ae),G&&be.close()}if((n.scene??"conversation")==="artifact"||n.config?.features?.artifacts?.enabled)for(let ee of o)ee.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
399
+ </div>`,P=z?`<div class="preview-compare-grid">${A.map(pe=>`<div class="preview-compare-cell">${L(pe)}</div>`).join("")}</div>`:`<div class="preview-single">${L(A[0])}</div>`;n.morphContainer?n.morphContainer(t,P):t.innerHTML=P,g();let I=C(),Y=0,de=I.length,ue=()=>{if(i||E!==c)return;for(let ee of I){let oe=ee.dataset.mountId;if(!oe||!ee.contentDocument)continue;let V=A.find(fe=>fe.mountId===oe);if(!V)continue;let ae=()=>{},ne=Nt(V.config),me=ne?(()=>{let fe=ee.contentDocument?.getElementById(`preview-content-${oe}`);if(!fe)return null;let Te=gf(fe,V.config),Se=ee.contentDocument.createElement("div");Se.id=oe,Se.style.height="100%",Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1",Se.style.minHeight="0",Te.host.appendChild(Se);let Fe=()=>Te.syncWidgetState(be.getState()),ke=ae;return ae=()=>{Te.destroy(),ke()},Se.__syncDock=Fe,Se.__hostLayout=Te,Se})():ee.contentDocument.getElementById(oe);if(!me)continue;let be=lf(me,V.config);if(o.push(be),ne&&me.__syncDock){let fe=me.__syncDock,Te=be.on("widget:opened",fe),Se=be.on("widget:closed",fe),Fe=ae;ae=()=>{Te(),Se(),Fe()},fe()}r.push(ae),G&&be.close()}if((n.scene??"conversation")==="artifact"||n.config?.features?.artifacts?.enabled)for(let ee of o)ee.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
400
400
 
401
401
  This is a preview of the artifact sidebar.
402
402
 
@@ -404,4 +404,4 @@ This is a preview of the artifact sidebar.
404
404
 
405
405
  - Markdown rendering
406
406
  - Document toolbar
407
- - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:I,controllers:[...o]})};for(let pe of I){let ee=pe.dataset.mountId;if(!ee)continue;let oe=A.find(V=>V.mountId===ee);oe&&(pe.addEventListener("load",()=>{Y++,Y>=de&&ue()},{once:!0}),pe.srcdoc=O(ee,oe.shellMode,Ot(oe.config),w))}de===0&&ue()}function B(){if(i)return;let E=vf(n);if(o.length!==E.length){D();return}if(E.some(W=>{let z=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${W.mountId}"]`);return!z||z.dataset.shellMode!==W.shellMode})){D();return}o.forEach((W,z)=>{W.update(E[z].config),(n.scene??"conversation")==="minimized"&&W.close()});for(let W of E){let z=t.querySelector(`iframe[data-mount-id="${W.mountId}"]`);z&&bf(z,W.shellMode)}n.onAfterUpdate?.({iframes:C(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{i||g()}),s.observe(t)),D(),{update(E){if(i)return;let A=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},A?D():B()},destroy(){i||(i=!0,m(),s?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){i||(n={...n,zoom:void 0},g())},getIframes(){return C()},getScale(){return p},setZoom(E){i||(n={...n,zoom:E},g())}}}0&&(module.exports={createThemePreview});
407
+ - Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:I,controllers:[...o]})};for(let pe of I){let ee=pe.dataset.mountId;if(!ee)continue;let oe=A.find(V=>V.mountId===ee);oe&&(pe.addEventListener("load",()=>{Y++,Y>=de&&ue()},{once:!0}),pe.srcdoc=O(ee,oe.shellMode,Nt(oe.config),w))}de===0&&ue()}function B(){if(i)return;let E=vf(n);if(o.length!==E.length){D();return}if(E.some(W=>{let z=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${W.mountId}"]`);return!z||z.dataset.shellMode!==W.shellMode})){D();return}o.forEach((W,z)=>{W.update(E[z].config),(n.scene??"conversation")==="minimized"&&W.close()});for(let W of E){let z=t.querySelector(`iframe[data-mount-id="${W.mountId}"]`);z&&bf(z,W.shellMode)}n.onAfterUpdate?.({iframes:C(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{i||g()}),s.observe(t)),D(),{update(E){if(i)return;let A=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},A?D():B()},destroy(){i||(i=!0,m(),s?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){i||(n={...n,zoom:void 0},g())},getIframes(){return C()},getScale(){return p},setZoom(E){i||(n={...n,zoom:E},g())}}}0&&(module.exports={createThemePreview});