@runtypelabs/persona 4.9.0 → 4.10.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.
- package/README.md +13 -1
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/index.cjs +68 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +13 -2
- package/dist/index.d.ts +13 -2
- package/dist/index.global.js +46 -46
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +58 -58
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +2 -2
- package/dist/launcher.global.js.map +1 -1
- package/dist/theme-editor-preview.cjs +61 -61
- package/dist/theme-editor-preview.d.cts +12 -1
- package/dist/theme-editor-preview.d.ts +12 -1
- package/dist/theme-editor-preview.js +47 -47
- package/dist/widget.css +1 -1
- package/package.json +1 -1
- package/src/components/artifact-pane.test.ts +47 -0
- package/src/components/artifact-pane.ts +25 -2
- package/src/index-core.ts +1 -0
- package/src/runtime/init-update-reset.test.ts +81 -0
- package/src/runtime/init.test.ts +62 -0
- package/src/runtime/init.ts +7 -14
- package/src/styles/widget.css +14 -0
- package/src/types.ts +17 -0
- package/src/ui.artifact-pane-gating.test.ts +11 -1
- package/src/ui.attachments-drop.test.ts +90 -0
- package/src/ui.header-update-stability.test.ts +149 -0
- package/src/ui.launcher-update-merge.test.ts +83 -0
- package/src/ui.send-button-stream-update.test.ts +69 -0
- package/src/ui.ts +78 -33
- package/src/utils/config-merge.test.ts +131 -0
- package/src/utils/config-merge.ts +61 -0
- package/src/utils/theme.test.ts +26 -0
- package/src/utils/theme.ts +6 -3
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
"use strict";var om=Object.create;var li=Object.defineProperty;var rm=Object.getOwnPropertyDescriptor;var sm=Object.getOwnPropertyNames;var im=Object.getPrototypeOf,am=Object.prototype.hasOwnProperty;var vt=(t,e)=>()=>(t&&(e=t(t=0)),e);var nr=(t,e)=>{for(var n in e)li(t,n,{get:e[n],enumerable:!0})},Hd=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of sm(e))!am.call(t,r)&&r!==n&&li(t,r,{get:()=>e[r],enumerable:!(o=rm(e,r))||o.enumerable});return t};var Bd=(t,e,n)=>(n=t!=null?om(im(t)):{},Hd(e||!t||!t.__esModule?li(n,"default",{value:t,enumerable:!0}):n,t)),lm=t=>Hd(li({},"__esModule",{value:!0}),t);var Od={};nr(Od,{DOMPurify:()=>Nd.default,Marked:()=>Dd.Marked});var Dd,Nd,Fd=vt(()=>{"use strict";Dd=require("marked"),Nd=Bd(require("dompurify"),1)});var h,Ln,Jd,Ce,_n,nt=vt(()=>{"use strict";h=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},Ln=(t,e,n)=>{let o=t.createElement(e);return n&&(o.className=n),o},Jd=()=>document.createDocumentFragment(),Ce=(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},_n=(...t)=>t.filter(Boolean).join(" ")});var ur,bl=vt(()=>{"use strict";ur=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 yh(t){return t.replace(/\/+$/,"")}async function vh(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 ki,Lp=vt(()=>{"use strict";bl();ki=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 ur(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=`${yh(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 vh(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 Li,Pp=vt(()=>{"use strict";Li=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 Ip={};nr(Ip,{FallbackSpeechEngine:()=>Li,RuntypeSpeechEngine:()=>ki});var Rp=vt(()=>{"use strict";Lp();Pp()});var Hp={};nr(Hp,{createReconnectController:()=>Ch});function Ch(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)}),b=()=>{let m=t.getResumable();t.clearResumable(),t.setReconnecting(!1),e=0,d(),t.setAbortController(null);let C=!1;for(let D of t.getMessages())D.streaming&&(D.streaming=!1,C=!0);let k=t.buildErrorContent("Connection lost and the response could not be resumed.");k?t.appendMessage({id:`reconnect-failed-${m?.executionId??t.nextSequence()}`,role:"assistant",content:k,createdAt:new Date().toISOString(),streaming:!1,sequence:t.nextSequence()}):C&&t.notifyMessagesChanged(),t.setStreaming(!1),t.setStatus("idle"),t.onError(new Error("Durable session reconnect failed."))},f=async()=>{let m=t.config.reconnect?.backoffMs??xh,C=t.config.reconnect?.maxAttempts??m.length,k=t.config.reconnectStream;if(!k){t.setReconnecting(!1);return}for(;t.getResumable()&&e<C;){e+=1,t.setStatus("resuming");let D=t.getResumable(),M=D.lastEventId,A=new AbortController;t.setAbortController(A),t.emitReconnect({phase:"resuming",handle:D,attempt:e});let W=null;try{let z=await k({executionId:D.executionId,after:D.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===D.assistantMessageId)?.content,U=typeof z=="string"?z:"";try{await t.resumeConnect(W,D.assistantMessageId,U)}catch{}if(A.signal.aborted)return;if(!t.getResumable()){t.setReconnecting(!1),e=0,d(),t.emitReconnect({phase:"resumed",handle:D});return}t.getResumable().lastEventId!==M&&(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()&&b()};return{begin(){e=0,c(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,e=0,d()},wake:s}}var xh,Bp=vt(()=>{"use strict";xh=[1e3,2e3,4e3,8e3,8e3]});function Mh(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 S,Sh,se,kt=vt(()=>{"use strict";S=require("lucide"),Sh={activity:S.Activity,"arrow-down":S.ArrowDown,"arrow-up":S.ArrowUp,"arrow-up-right":S.ArrowUpRight,bot:S.Bot,"chevron-down":S.ChevronDown,"chevron-up":S.ChevronUp,"chevron-right":S.ChevronRight,"chevron-left":S.ChevronLeft,check:S.Check,clipboard:S.Clipboard,"clipboard-copy":S.ClipboardCopy,"code-xml":S.CodeXml,copy:S.Copy,file:S.File,"file-code":S.FileCode,"file-spreadsheet":S.FileSpreadsheet,"file-text":S.FileText,"image-plus":S.ImagePlus,loader:S.Loader,"loader-circle":S.LoaderCircle,mic:S.Mic,paperclip:S.Paperclip,"refresh-cw":S.RefreshCw,search:S.Search,send:S.Send,"shield-alert":S.ShieldAlert,"shield-check":S.ShieldCheck,"shield-x":S.ShieldX,square:S.Square,"thumbs-down":S.ThumbsDown,"thumbs-up":S.ThumbsUp,upload:S.Upload,"volume-2":S.Volume2,x:S.X,user:S.User,mail:S.Mail,phone:S.Phone,calendar:S.Calendar,clock:S.Clock,building:S.Building,"map-pin":S.MapPin,lock:S.Lock,key:S.Key,"credit-card":S.CreditCard,"at-sign":S.AtSign,hash:S.Hash,globe:S.Globe,link:S.Link,"circle-check":S.CircleCheck,"circle-x":S.CircleX,"triangle-alert":S.TriangleAlert,info:S.Info,ban:S.Ban,shield:S.Shield,"arrow-left":S.ArrowLeft,"arrow-right":S.ArrowRight,"external-link":S.ExternalLink,ellipsis:S.Ellipsis,"ellipsis-vertical":S.EllipsisVertical,menu:S.Menu,house:S.House,plus:S.Plus,minus:S.Minus,pencil:S.Pencil,trash:S.Trash,"trash-2":S.Trash2,save:S.Save,download:S.Download,share:S.Share,funnel:S.Funnel,settings:S.Settings,"rotate-cw":S.RotateCw,maximize:S.Maximize,minimize:S.Minimize,"shopping-cart":S.ShoppingCart,"shopping-bag":S.ShoppingBag,package:S.Package,truck:S.Truck,tag:S.Tag,gift:S.Gift,receipt:S.Receipt,wallet:S.Wallet,store:S.Store,"dollar-sign":S.DollarSign,percent:S.Percent,play:S.Play,pause:S.Pause,"volume-x":S.VolumeX,camera:S.Camera,image:S.Image,film:S.Film,headphones:S.Headphones,"message-circle":S.MessageCircle,"message-square":S.MessageSquare,bell:S.Bell,heart:S.Heart,star:S.Star,eye:S.Eye,"eye-off":S.EyeOff,bookmark:S.Bookmark,"calendar-days":S.CalendarDays,history:S.History,timer:S.Timer,folder:S.Folder,"folder-open":S.FolderOpen,files:S.Files,sparkles:S.Sparkles,zap:S.Zap,sun:S.Sun,moon:S.Moon,flag:S.Flag,monitor:S.Monitor,smartphone:S.Smartphone},se=(t,e=24,n="currentColor",o=2)=>{let r=Sh[t];return r?Mh(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 kh(t,e,n){if(n==="input-start")return e===0;let o=e>0?t[e-1]:"";return n==="line-start"?o===""||o===`
|
|
2
|
-
`:o===""||
|
|
3
|
-
`||i==="\uFFFC"||!r&&
|
|
4
|
-
`)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>e&&(e=o[1].length)}return e}function
|
|
1
|
+
"use strict";var im=Object.create;var li=Object.defineProperty;var am=Object.getOwnPropertyDescriptor;var lm=Object.getOwnPropertyNames;var cm=Object.getPrototypeOf,dm=Object.prototype.hasOwnProperty;var yt=(t,e)=>()=>(t&&(e=t(t=0)),e);var tr=(t,e)=>{for(var n in e)li(t,n,{get:e[n],enumerable:!0})},Bd=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of lm(e))!dm.call(t,r)&&r!==n&&li(t,r,{get:()=>e[r],enumerable:!(o=am(e,r))||o.enumerable});return t};var Dd=(t,e,n)=>(n=t!=null?im(cm(t)):{},Bd(e||!t||!t.__esModule?li(n,"default",{value:t,enumerable:!0}):n,t)),pm=t=>Bd(li({},"__esModule",{value:!0}),t);var Fd={};tr(Fd,{DOMPurify:()=>Od.default,Marked:()=>Nd.Marked});var Nd,Od,_d=yt(()=>{"use strict";Nd=require("marked"),Od=Dd(require("dompurify"),1)});var h,Ln,Yd,Ce,_n,st=yt(()=>{"use strict";h=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},Ln=(t,e,n)=>{let o=t.createElement(e);return n&&(o.className=n),o},Yd=()=>document.createDocumentFragment(),Ce=(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},_n=(...t)=>t.filter(Boolean).join(" ")});var pr,yl=yt(()=>{"use strict";pr=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 Ch(t){return t.replace(/\/+$/,"")}async function wh(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 ki,Pp=yt(()=>{"use strict";yl();ki=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 pr(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=`${Ch(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 wh(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 Li,Ip=yt(()=>{"use strict";Li=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 Rp={};tr(Rp,{FallbackSpeechEngine:()=>Li,RuntypeSpeechEngine:()=>ki});var Wp=yt(()=>{"use strict";Pp();Ip()});var Bp={};tr(Bp,{createReconnectController:()=>Sh});function Sh(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)}),b=()=>{let m=t.getResumable();t.clearResumable(),t.setReconnecting(!1),e=0,d(),t.setAbortController(null);let C=!1;for(let D of t.getMessages())D.streaming&&(D.streaming=!1,C=!0);let I=t.buildErrorContent("Connection lost and the response could not be resumed.");I?t.appendMessage({id:`reconnect-failed-${m?.executionId??t.nextSequence()}`,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!1,sequence:t.nextSequence()}):C&&t.notifyMessagesChanged(),t.setStreaming(!1),t.setStatus("idle"),t.onError(new Error("Durable session reconnect failed."))},f=async()=>{let m=t.config.reconnect?.backoffMs??Ah,C=t.config.reconnect?.maxAttempts??m.length,I=t.config.reconnectStream;if(!I){t.setReconnecting(!1);return}for(;t.getResumable()&&e<C;){e+=1,t.setStatus("resuming");let D=t.getResumable(),T=D.lastEventId,A=new AbortController;t.setAbortController(A),t.emitReconnect({phase:"resuming",handle:D,attempt:e});let W=null;try{let z=await I({executionId:D.executionId,after:D.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===D.assistantMessageId)?.content,U=typeof z=="string"?z:"";try{await t.resumeConnect(W,D.assistantMessageId,U)}catch{}if(A.signal.aborted)return;if(!t.getResumable()){t.setReconnecting(!1),e=0,d(),t.emitReconnect({phase:"resumed",handle:D});return}t.getResumable().lastEventId!==T&&(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()&&b()};return{begin(){e=0,c(),f()},teardown(){o&&(clearTimeout(o),o=null),n=null,e=0,d()},wake:s}}var Ah,Dp=yt(()=>{"use strict";Ah=[1e3,2e3,4e3,8e3,8e3]});function kh(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,Eh,se,Et=yt(()=>{"use strict";M=require("lucide"),Eh={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=Eh[t];return r?kh(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 Ih(t,e,n){if(n==="input-start")return e===0;let o=e>0?t[e-1]:"";return n==="line-start"?o===""||o===`
|
|
2
|
+
`:o===""||Fp.test(o)}function Rh(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 Ih(t,s,o)?{triggerIndex:s,query:t.slice(s+1,e)}:null;if(i===`
|
|
3
|
+
`||i==="\uFFFC"||!r&&Fp.test(i))return null;s--}return null}function ds(t,e,n){for(let o of n){let r=Rh(t,e,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function _p(t){return t?t!=="insertFromPaste"&&t!=="insertFromDrop":!0}function $p(t,e,n){return{value:t.slice(0,e.triggerIndex)+t.slice(n),caret:e.triggerIndex}}var Fp,Ri=yt(()=>{"use strict";Fp=/\s/});function Wi(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 Al=yt(()=>{"use strict"});function Up(t){let{ref:e,config:n,onRemove:o}=t;if(n.renderMentionChip){let f="resolving",m,C=n.renderMentionChip({ref:e,status:f,payload:m,remove:o});return{get el(){return C},setStatus:(D,T)=>{if(D===f&&T===m)return;f=D,m=T;let A=n.renderMentionChip({ref:e,status:f,payload:m,remove:o});C.replaceWith(A),C=A}}}let r=e.iconName??n.chipIconName??"at-sign",s=Ce("div",{className:"persona-mention-chip",attrs:{"data-persona-mention-chip":"","data-status":"resolving",title:e.label}}),i=h("span","persona-mention-chip-icon"),l=f=>{i.replaceChildren();let m=se(f,13,"currentColor",2);m&&i.appendChild(m)};l(r);let p=h("span","persona-mention-chip-spinner"),c=Ce("span",{className:"persona-mention-chip-label",text:e.label}),d=Ce("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",f=>{f.preventDefault(),f.stopPropagation(),o()}),s.appendChild(p),s.appendChild(c),s.appendChild(d),{el:s,setStatus:f=>{s.setAttribute("data-status",f),f==="resolving"?(p.parentNode!==s&&s.insertBefore(p,c),i.parentNode===s&&i.remove(),s.setAttribute("title",e.label)):(p.parentNode===s&&p.remove(),i.parentNode!==s&&s.insertBefore(i,c),f==="error"?(l("triangle-alert"),s.setAttribute("title",`Couldn't add ${e.label} to context`)):(l(r),s.setAttribute("title",e.label)))}}}var jp=yt(()=>{"use strict";st();Et()});function Wh(t){let e=0;for(let n of t.split(`
|
|
4
|
+
`)){let o=/^ {0,3}(`+)/.exec(n);o&&o[1].length>e&&(e=o[1].length)}return e}function Sl(t,e){let n="`".repeat(Math.max(3,Wh(e)+1));return`${n}${t}
|
|
5
5
|
${e}
|
|
6
|
-
${n}`}function
|
|
6
|
+
${n}`}function Hh(t,e,n){return e.includes("</document_content>")?Sl(t,e):`<document index="${n+1}">
|
|
7
7
|
<source>${t}</source>
|
|
8
8
|
<document_content>
|
|
9
9
|
${e}
|
|
10
10
|
</document_content>
|
|
11
|
-
</document>`}function
|
|
11
|
+
</document>`}function qp(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),Sl(t.label,t.text)}return n==="document"?Hh(t.label,t.text,e):Sl(t.label,t.text)}var Vp=yt(()=>{"use strict"});function Hi(t,e){return{sourceId:t.id,itemId:e.id,label:e.label,iconName:e.iconName,color:e.color}}var Kp,Bi,Ml=yt(()=>{"use strict";jp();Vp();Kp=(t,e)=>`${t}\0${e}`,Bi=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=Kp(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=Hi(e,n),i={key:r,source:e,item:n,ref:s,status:"resolving",args:o};return i.chip=Up({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:Hi(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(b){try{this.opts.mentionConfig.onMentionResolveError?.(u.item,b)}catch(f){typeof console<"u"&&console.warn("[Persona] onMentionResolveError callback threw",f)}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 b=e[u],f=s[u];if(!f)continue;let m=Kp(b.source.id,b.item.id);if(!c.has(m)){if(c.add(m),f.llmAppend&&f.llmAppend.trim())try{i.push(qp({label:b.ref.label,text:f.llmAppend,ref:b.ref,item:b.item},i.length,this.opts.mentionConfig.llmFormat))}catch(C){typeof console<"u"&&console.warn("[Persona] context-mention llmFormat threw",C)}f.contentParts?.length&&l.push(...f.contentParts),f.context&&((p[d=b.source.id]??(p[d]={}))[b.item.id]=f.context)}}return{blocks:i,contentParts:l,context:p}}}}updateRowVisibility(){this.opts.contextRow.style.display=this.mentions.length>0?"flex":"none"}}});function Gp(t){let e=t.getRootNode?.();return e instanceof ShadowRoot||e instanceof Document?e:t.ownerDocument??document}function Di(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 Qp(t,e,n){if(t instanceof Document||t instanceof ShadowRoot){Di(t,e,n);return}let o=t;if(o.isConnected){Di(Gp(o),e,n);return}let r=o.ownerDocument??document;Di(r,e,n),queueMicrotask(()=>{let s=Gp(o);s!==r&&Di(s,e,n)})}function Bh(t){let e=t.getRootNode?.();return e instanceof ShadowRoot?e:(t.ownerDocument??document).body}function Ni(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??Bh(e),b=!1,f=null,m=()=>{if(!b)return;let D=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${D.width}px`),i&&(n.style.maxWidth=`${D.width}px`);let T=n.getBoundingClientRect(),A=l?.()??null,W=A!=null?D.top+A:D.top,z=o==="top-start"||o==="top-end"?W-r-T.height:D.bottom+r,w=o==="bottom-end"||o==="top-end"?D.right-T.width:D.left,O=i?.()??null;if(O!=null){let N=Math.max(D.left,D.right-T.width);w=Math.min(Math.max(D.left+O,D.left),N)}n.style.top=`${z}px`,n.style.left=`${w}px`},C=()=>{b&&(b=!1,f&&(f(),f=null),n.remove())},I=()=>{if(b)return;b=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),m();let D=(e.ownerDocument??document).defaultView??window,T=e.ownerDocument??document,A=()=>{if(!e.isConnected){C(),d?.("anchor-removed");return}m()},W=U=>{let w=typeof U.composedPath=="function"?U.composedPath():[];w.includes(n)||w.includes(e)||(C(),d?.("outside"))},z=D.setTimeout(()=>{T.addEventListener("pointerdown",W,!0)},0);D.addEventListener("scroll",A,!0),D.addEventListener("resize",A),f=()=>{D.clearTimeout(z),T.removeEventListener("pointerdown",W,!0),D.removeEventListener("scroll",A,!0),D.removeEventListener("resize",A)},c?.()};return{get isOpen(){return b},open:I,close:C,toggle:()=>b?C():I(),reposition:m,destroy:C}}function Xp(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Tl=yt(()=>{"use strict"});var Jp,Yp=yt(()=>{"use strict";Jp=`
|
|
12
12
|
.persona-mention-menu {
|
|
13
13
|
box-sizing: border-box;
|
|
14
14
|
display: flex;
|
|
@@ -166,42 +166,42 @@ ${e}
|
|
|
166
166
|
min-height: 36px;
|
|
167
167
|
}
|
|
168
168
|
}
|
|
169
|
-
`});function Oi(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 Yp=vt(()=>{"use strict"});function eu(t){let{config:e,listboxId:n}=t,o=Ce("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=Ce("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=Ce("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=Ce("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,p);let c=[],d=[],u=-1,b=new Map,f=(L,P)=>`${L}\0${P}`,m=L=>`${n}-opt-${L}`,C=L=>`${n}-grp-${L}`,k=(L,P)=>{let H=c[L];H&&(P?H.setAttribute("data-active","true"):H.removeAttribute("data-active"),H.setAttribute("aria-selected",P?"true":"false"),d[L]?.(P))},D=(L,P=!0)=>{u>=0&&u!==L&&k(u,!1),u=L;let H=c[L];H?(k(L,!0),P&&H.scrollIntoView?.({block:"nearest"}),p.setAttribute("aria-activedescendant",H.id),l.setAttribute("aria-activedescendant",H.id)):(p.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},M=(L,P)=>{let H=C(P),ne=Ce("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":H}});return ne.appendChild(Ce("div",{className:"persona-mention-group-header",attrs:{id:H},text:L})),ne},A=()=>{let L=Ce("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),P=h("span","persona-mention-option-icon");L.appendChild(P);let H="",ne=h("span","persona-mention-option-text"),pe=h("span","persona-mention-option-labelline"),he=h("span","persona-mention-option-label");pe.appendChild(he),ne.appendChild(pe),L.appendChild(ne);let fe=null,ee=null,oe={el:L,index:0,update:(K,ae,te)=>{oe.index=ae,L.id=m(ae),L.setAttribute("aria-setsize",String(te)),L.setAttribute("aria-posinset",String(ae+1)),L.removeAttribute("data-active"),L.setAttribute("aria-selected","false");let ve=K.iconName??e.chipIconName??"at-sign";if(ve!==H){H=ve;let ge=Wh(ve,15,2);P.replaceChildren(...ge?[ge]:[])}he.textContent!==K.label&&(he.textContent=K.label);let xe=K.commandArgsPlaceholder?`\u2039${K.commandArgsPlaceholder}\u203A`:null;xe?(fe||(fe=h("span","persona-mention-option-arghint"),pe.appendChild(fe)),fe.textContent!==xe&&(fe.textContent=xe)):fe&&(fe.remove(),fe=null),K.description?(ee||(ee=h("span","persona-mention-option-desc"),ne.appendChild(ee)),ee.textContent!==K.description&&(ee.textContent=K.description)):ee&&(ee.remove(),ee=null)}};return L.addEventListener("mousedown",K=>{K.button===0&&(K.preventDefault(),t.onSelectIndex(oe.index))}),L.addEventListener("mouseenter",()=>t.onHoverIndex(oe.index)),oe},W=(L,P,H,ne,pe)=>{let he=Ce("div",{className:"persona-mention-option",attrs:{role:"option",id:m(ne),"aria-selected":"false","aria-setsize":String(pe),"aria-posinset":String(ne+1)}}),fe=ee=>{he.replaceChildren(e.renderMentionItem({item:L,source:P,query:H,active:ee,index:ne}))};return fe(!1),he.addEventListener("mousedown",ee=>{ee.button===0&&(ee.preventDefault(),t.onSelectIndex(ne))}),he.addEventListener("mouseenter",()=>t.onHoverIndex(ne)),{el:he,paint:fe}},z=L=>{let P=Ce("div",{className:"persona-mention-status persona-mention-error"});if(P.appendChild(Ce("span",{className:"persona-mention-error-text",text:`Couldn't load ${L.label}`})),t.onRetry){let H=Ce("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});H.addEventListener("mousedown",ne=>ne.preventDefault()),H.addEventListener("click",ne=>{ne.preventDefault(),t.onRetry(L.id)}),P.appendChild(H)}return P};return{el:o,render:L=>{p.replaceChildren(),c=[],d=[],u=-1;let P=new Set,H=0,ne=0,pe=0,he=0,fe=0,ee=L.groups.reduce((oe,K)=>K.status==="ready"?oe+K.items.length:oe,0);for(let oe of L.groups)if(oe.status==="loading"){pe++;let K=M(oe.source.label,fe++);K.appendChild(Ce("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),p.appendChild(K)}else if(oe.status==="error"){he++;let K=M(oe.source.label,fe++);K.appendChild(z(oe.source)),p.appendChild(K)}else if(oe.status==="ready"&&oe.items.length>0){let K=new Map;for(let te of oe.items){let ve=te.group??oe.source.label,xe=K.get(ve);xe?xe.push(te):K.set(ve,[te])}let ae=Array.from(K.entries());ae.forEach(([te,ve],xe)=>{let ge=M(te,fe++);for(let Te of ve){let Me=H++,Fe;if(e.renderMentionItem){let Pe=W(Te,oe.source,L.query,Me,ee);Fe=Pe.el,d.push(Pe.paint)}else{let Pe=f(oe.source.id,Te.id),Ee=P.has(Pe)?void 0:b.get(Pe);Ee||(Ee=A(),P.has(Pe)||b.set(Pe,Ee)),P.add(Pe),Ee.update(Te,Me,ee),Fe=Ee.el,d.push(null)}c.push(Fe),ge.appendChild(Fe),ne++}oe.truncated&&xe===ae.length-1&&ge.appendChild(Ce("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),p.appendChild(ge)})}for(let oe of b.keys())P.has(oe)||b.delete(oe);ne===0&&pe===0&&he===0&&p.appendChild(Ce("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),c.length>0?D(Math.min(Math.max(0,L.activeIndex),c.length-1)):(p.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:D,destroy:()=>{p.replaceChildren(),c=[],b.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 Zp,Wh,tu=vt(()=>{"use strict";nt();kt();Zp=new Map,Wh=(t,e,n)=>{let o=`${t}|${e}|${n}`,r=Zp.get(o);return r===void 0&&(r=se(t,e,"currentColor",n),Zp.set(o,r)),r?r.cloneNode(!0):null}});var Hh,Bh,Fi,nu=vt(()=>{"use strict";Ml();Jp();Ri();wl();Yp();tu();Sl();Hh=t=>!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function",Bh=0,Fi=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=Wi(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-${++Bh}`,this.menu=e.mentionConfig.renderMentionMenu?this.createHostMenu():eu({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=ds(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=ds(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=Ni({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(),Gp(this.menu.el,"persona-mention-menu",Xp),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}Hh(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 Oi(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=Hi(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}=Oi(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 Oi(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 Zp=yt(()=>{"use strict"});function tu(t){let{config:e,listboxId:n}=t,o=Ce("div",{className:"persona-mention-menu",attrs:{"data-persona-mention-menu":""}}),r=Ce("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=Ce("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",R=>t.onSearchKeydown?.(R));let p=Ce("div",{className:"persona-mention-list",attrs:{role:"listbox",id:n,"aria-label":"Context mentions"}});o.append(r,p);let c=[],d=[],u=-1,b=new Map,f=(R,L)=>`${R}\0${L}`,m=R=>`${n}-opt-${R}`,C=R=>`${n}-grp-${R}`,I=(R,L)=>{let H=c[R];H&&(L?H.setAttribute("data-active","true"):H.removeAttribute("data-active"),H.setAttribute("aria-selected",L?"true":"false"),d[R]?.(L))},D=(R,L=!0)=>{u>=0&&u!==R&&I(u,!1),u=R;let H=c[R];H?(I(R,!0),L&&H.scrollIntoView?.({block:"nearest"}),p.setAttribute("aria-activedescendant",H.id),l.setAttribute("aria-activedescendant",H.id)):(p.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},T=(R,L)=>{let H=C(L),ne=Ce("div",{className:"persona-mention-group",attrs:{role:"group","aria-labelledby":H}});return ne.appendChild(Ce("div",{className:"persona-mention-group-header",attrs:{id:H},text:R})),ne},A=()=>{let R=Ce("div",{className:"persona-mention-option",attrs:{role:"option","aria-selected":"false"}}),L=h("span","persona-mention-option-icon");R.appendChild(L);let H="",ne=h("span","persona-mention-option-text"),de=h("span","persona-mention-option-labelline"),me=h("span","persona-mention-option-label");de.appendChild(me),ne.appendChild(de),R.appendChild(ne);let ue=null,ee=null,re={el:R,index:0,update:(G,ie,te)=>{re.index=ie,R.id=m(ie),R.setAttribute("aria-setsize",String(te)),R.setAttribute("aria-posinset",String(ie+1)),R.removeAttribute("data-active"),R.setAttribute("aria-selected","false");let ye=G.iconName??e.chipIconName??"at-sign";if(ye!==H){H=ye;let fe=Dh(ye,15,2);L.replaceChildren(...fe?[fe]:[])}me.textContent!==G.label&&(me.textContent=G.label);let ve=G.commandArgsPlaceholder?`\u2039${G.commandArgsPlaceholder}\u203A`:null;ve?(ue||(ue=h("span","persona-mention-option-arghint"),de.appendChild(ue)),ue.textContent!==ve&&(ue.textContent=ve)):ue&&(ue.remove(),ue=null),G.description?(ee||(ee=h("span","persona-mention-option-desc"),ne.appendChild(ee)),ee.textContent!==G.description&&(ee.textContent=G.description)):ee&&(ee.remove(),ee=null)}};return R.addEventListener("mousedown",G=>{G.button===0&&(G.preventDefault(),t.onSelectIndex(re.index))}),R.addEventListener("mouseenter",()=>t.onHoverIndex(re.index)),re},W=(R,L,H,ne,de)=>{let me=Ce("div",{className:"persona-mention-option",attrs:{role:"option",id:m(ne),"aria-selected":"false","aria-setsize":String(de),"aria-posinset":String(ne+1)}}),ue=ee=>{me.replaceChildren(e.renderMentionItem({item:R,source:L,query:H,active:ee,index:ne}))};return ue(!1),me.addEventListener("mousedown",ee=>{ee.button===0&&(ee.preventDefault(),t.onSelectIndex(ne))}),me.addEventListener("mouseenter",()=>t.onHoverIndex(ne)),{el:me,paint:ue}},z=R=>{let L=Ce("div",{className:"persona-mention-status persona-mention-error"});if(L.appendChild(Ce("span",{className:"persona-mention-error-text",text:`Couldn't load ${R.label}`})),t.onRetry){let H=Ce("button",{className:"persona-mention-retry",attrs:{type:"button"},text:"Retry"});H.addEventListener("mousedown",ne=>ne.preventDefault()),H.addEventListener("click",ne=>{ne.preventDefault(),t.onRetry(R.id)}),L.appendChild(H)}return L};return{el:o,render:R=>{p.replaceChildren(),c=[],d=[],u=-1;let L=new Set,H=0,ne=0,de=0,me=0,ue=0,ee=R.groups.reduce((re,G)=>G.status==="ready"?re+G.items.length:re,0);for(let re of R.groups)if(re.status==="loading"){de++;let G=T(re.source.label,ue++);G.appendChild(Ce("div",{className:"persona-mention-status persona-mention-loading",attrs:{role:"presentation"},text:"Loading\u2026"})),p.appendChild(G)}else if(re.status==="error"){me++;let G=T(re.source.label,ue++);G.appendChild(z(re.source)),p.appendChild(G)}else if(re.status==="ready"&&re.items.length>0){let G=new Map;for(let te of re.items){let ye=te.group??re.source.label,ve=G.get(ye);ve?ve.push(te):G.set(ye,[te])}let ie=Array.from(G.entries());ie.forEach(([te,ye],ve)=>{let fe=T(te,ue++);for(let Ee of ye){let Te=H++,Fe;if(e.renderMentionItem){let Le=W(Ee,re.source,R.query,Te,ee);Fe=Le.el,d.push(Le.paint)}else{let Le=f(re.source.id,Ee.id),Ge=L.has(Le)?void 0:b.get(Le);Ge||(Ge=A(),L.has(Le)||b.set(Le,Ge)),L.add(Le),Ge.update(Ee,Te,ee),Fe=Ge.el,d.push(null)}c.push(Fe),fe.appendChild(Fe),ne++}re.truncated&&ve===ie.length-1&&fe.appendChild(Ce("div",{className:"persona-mention-hint",attrs:{role:"presentation"},text:"Keep typing to narrow\u2026"})),p.appendChild(fe)})}for(let re of b.keys())L.has(re)||b.delete(re);ne===0&&de===0&&me===0&&p.appendChild(Ce("div",{className:"persona-mention-empty",attrs:{role:"presentation"},text:"No matches"})),c.length>0?D(Math.min(Math.max(0,R.activeIndex),c.length-1)):(p.removeAttribute("aria-activedescendant"),l.removeAttribute("aria-activedescendant"))},setActiveIndex:D,destroy:()=>{p.replaceChildren(),c=[],b.clear(),o.remove()},showSearch:(R,L)=>{l.value=R,L&&(l.placeholder=L),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 eu,Dh,nu=yt(()=>{"use strict";st();Et();eu=new Map,Dh=(t,e,n)=>{let o=`${t}|${e}|${n}`,r=eu.get(o);return r===void 0&&(r=se(t,e,"currentColor",n),eu.set(o,r)),r?r.cloneNode(!0):null}});var Nh,Oh,Fi,ou=yt(()=>{"use strict";Tl();Yp();Ri();Al();Zp();nu();Ml();Nh=t=>!!t&&(typeof t=="object"||typeof t=="function")&&typeof t.then=="function",Oh=0,Fi=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=Wi(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-${++Oh}`,this.menu=e.mentionConfig.renderMentionMenu?this.createHostMenu():tu({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=ds(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=ds(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=Ni({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(),Qp(this.menu.el,"persona-mention-menu",Jp),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}Nh(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 Oi(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=Hi(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}=Oi(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}=Oi(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
|
|
172
|
-
`,c=
|
|
173
|
-
`?0:1);return{doc:{blocks:c},caret:d}}function
|
|
174
|
-
`});function
|
|
175
|
-
`),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(
|
|
176
|
-
`):t};var Fn="webmcp:",
|
|
171
|
+
`)[0]];for(let r of o){if(!r.startsWith(n.trigger))continue;let{name:s,args:i}=Oi(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=$p(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 El(t){t&&(typeof t.requestSubmit=="function"?t.requestSubmit():t.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})))}function ru(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:()=>El(t.form),dispatchInput:e,focus:()=>t.focus()}}var kl=yt(()=>{"use strict"});function Ll(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,Fh),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 Fh,su=yt(()=>{"use strict";Fh={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 iu(t){let e=t.composerInput??ru(t.textarea),n=Ll("polite",t.liveRegionHost),o=Ll("assertive",t.liveRegionHost),r=c=>n.announce(c),s=c=>o.announce(c),i=new Bi({mentionConfig:t.mentionConfig,contextRow:t.contextRow,getMessages:t.getMessages,getConfig:t.getConfig,getComposerText:()=>e.getValue(),announce:r,announceError:s,emit:t.emit}),l=()=>new Fi({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,b)=>i.track(c,d,u,b,f=>e.setMentionStatus?.(c,f)),admitMention:(c,d)=>i.admit(c,d),announce:r,popoverContainer:t.popoverContainer,onPickerOpenChange:t.onPickerOpenChange,emit:t.emit}),p=l();return{openMenu:c=>p.openFromButton(c),isMenuOpen:()=>p.isOpen(),handleInput:()=>p.onInput(),handleKeydown:c=>p.handleKeydown(c),hasMentions:()=>i.hasMentions(),removeLastChip:()=>i.removeLast(),dispatchInlineCommand:c=>p.dispatchInlineCommand(c),collectForSubmit:()=>i.hasMentions()?i.collectForSubmit():null,untrackMention:c=>i.remove(c),rebindComposer:c=>{c!==e&&(p.destroy(),e=c,p=l())},clear:()=>i.clear(),destroy:()=>{p.destroy(),i.clear(),n.destroy(),o.destroy()}}}var au=yt(()=>{"use strict";Ml();ou();kl();su()});var lu={};tr(lu,{mountContextMentions:()=>iu});var cu=yt(()=>{"use strict";au()});function Rl(t){return t.kind==="text"?t.value.length:1}function Wl(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 du(){return{blocks:[{kind:"text",value:""}]}}function Hl(t){return{blocks:[{kind:"text",value:t}]}}function Bl(t){return t.blocks.map(e=>e.kind==="text"?e.value:`${$h}${e.ref.label}`).join("")}function $i(t){return t.blocks.map(e=>e.kind==="text"?e.value:"\uFFFC").join("")}function zi(t){return t.blocks.reduce((e,n)=>e+Rl(n),0)}function zh(t){let e=[];for(let n of t.blocks)n.kind==="mention"&&e.push({id:n.id,ref:n.ref});return e}function _i(t,e){let n=[],o=[],r=0;for(let s of t){let i=Rl(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 Dl(t,e,n,o){let r=_i(t.blocks,e.start).left,s=_i(t.blocks,e.end).right,i=s[0],l=i?.kind==="text"?i.value.charAt(0):"",p=l!==" "&&l!==" "&&l!==`
|
|
172
|
+
`,c=Wl([...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 pu(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+=Rl(i);return r?{doc:{blocks:Wl(t.blocks.filter(i=>!(i.kind==="mention"&&i.id===e)))},caret:n}:{doc:t,caret:o}}function Ui(t,e,n,o){let r=zi(t),s=Math.max(0,Math.min(e,n,r)),i=Math.min(r,Math.max(e,n,0)),l=_i(t.blocks,s).left,p=_i(t.blocks,i).right;return{doc:{blocks:Wl([...l,{kind:"text",value:o},...p])},caret:s+o.length}}function uu(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:Bl(t),contextMentions:zh(t).map(n=>n.ref),contentSegments:e}}var $h,Nl=yt(()=>{"use strict";Ri();$h="@"});function gs(t){return t.nodeType===1&&t.hasAttribute(fs)}function mu(t){return t.nodeType===1&&t.tagName==="BR"}function ji(t){return t.nodeType===3?t.data.length:gs(t)||mu(t)?1:t.textContent?.length??0}function fu(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?ji(r):0);if(r.contains(e))return gs(r)?o+1:o+jh(r,e,n);o+=ji(r)}if(e===t){let r=0,s=Array.from(t.childNodes);for(let i=0;i<Math.min(n,s.length);i++)r+=ji(s[i]);return r}return o}function jh(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 us(t,e){let n=0,o=Array.from(t.childNodes);for(let r=0;r<o.length;r++){let s=o[r],i=ji(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 qh(t,e){let n=[];for(let o of Array.from(t.childNodes))if(gs(o)){let r=o.getAttribute(fs),s=e.get(r);s&&n.push({kind:"mention",id:r,ref:s})}else if(mu(o))n.push({kind:"text",value:gu});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 hu(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=()=>qh(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 R=e(N.ref);R.setAttribute("contenteditable","false"),R.setAttribute(fs,N.id),o.appendChild(R)}},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 R=typeof window<"u"?window.getSelection():null;if(!R)return;let L=us(o,O);try{let H=document.createRange();H.setStart(L.node,L.offset),H.collapse(!0),R.removeAllRanges(),R.addRange(H)}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 R=N.getRangeAt(0);if(!o.contains(R.startContainer))return O;let L=fu(o,R.startContainer,R.startOffset),H=R.collapsed?L:fu(o,R.endContainer,R.endOffset);return{start:Math.min(L,H),end:Math.max(L,H)}},b=()=>{let O=new Set;for(let N of Array.from(o.childNodes))gs(N)&&O.add(N.getAttribute(fs));for(let N of Array.from(n.keys()))O.has(N)||(n.delete(N),t.onMentionRemoved?.(N))},f=()=>{r||n.size!==0&&b()},m=()=>{r=!0},C=()=>{r=!1,b()},I=O=>{O.preventDefault();let N=O.clipboardData?.getData("text/plain")??"";if(typeof document.execCommand=="function")document.execCommand("insertText",!1,N);else{let{start:R,end:L}=u(),H=Ui(i(),R,L,N);l(H.doc),c(H.caret,{focus:!0}),b()}d()},D=O=>{if(r)return;let N=O.inputType;if(N==="insertParagraph"){O.preventDefault();let{start:re,end:G}=u(),ie=Ui(i(),re,G,gu);l(ie.doc),c(ie.caret,{focus:!0}),n.size>0&&b(),d();return}if(N!=="deleteContentBackward"&&N!=="deleteContentForward"||n.size===0)return;let{start:R,end:L}=u();if(R!==L)return;let H=i(),ne=$i(H),de=N==="deleteContentBackward"?R-1:R;if(de<0||de>=ne.length||ne[de]!=="\uFFFC")return;let me=0,ue=null;for(let re of H.blocks){let G=re.kind==="text"?re.value.length:1;if(re.kind==="mention"&&de>=me&&de<me+G){ue=re.id;break}me+=G}if(!ue)return;O.preventDefault();let ee=pu(H,ue);l(ee.doc),c(ee.caret,{focus:!0}),b(),d()},T=(O,N)=>{l(Hl(O)),c(N)},A=(O,N)=>{if(!Number.isFinite(O)||!Number.isFinite(N)||N<=O)return null;try{let R=us(o,O),L=us(o,N),H=document.createRange();H.setStart(R.node,R.offset),H.setEnd(L.node,L.offset);let ne=H.getBoundingClientRect();return ne.width===0&&ne.height===0?null:ne}catch{return null}},W=(O,N,R)=>{let L=Ui(i(),O,N,R);l(L.doc),c(L.caret,{focus:!0})},z=(O,N)=>{let R=i(),L=$i(R),H=N.triggerIndex,ne=N.triggerIndex+1+N.query.length;if(H<0||ne>L.length||L.slice(H+1,ne)!==N.query)return null;let de=t.generateId(),me=Dl(R,{start:H,end:ne},O,de);return l(me.doc),c(me.caret,{focus:!0}),t.onMentionInserted?.(de,O),d(),de},U=O=>{let N=i(),R=u(),H=typeof window<"u"&&!!window.getSelection()?.rangeCount&&o.contains(window.getSelection().getRangeAt(0).startContainer)?{start:R.start,end:R.end}:{start:zi(N),end:zi(N)},ne=t.generateId(),de=Dl(N,H,O,ne);return l(de.doc),c(de.caret,{focus:!0}),t.onMentionInserted?.(ne,O),d(),ne},w=(O,N)=>{for(let R of Array.from(o.childNodes))if(gs(R)&&R.getAttribute(fs)===O){let L=N==="error";if(R.classList.toggle(Uh,L),L){R.hasAttribute(ps)||(R.setAttribute(ps,R.getAttribute("aria-label")??""),R.setAttribute(Ol,R.getAttribute("title")??""));let H=n.get(O)?.label??"";R.setAttribute("title",`${H}: failed to attach context`),R.setAttribute("aria-label",`${H}, failed to attach context`)}else if(R.hasAttribute(ps)){let H=R.getAttribute(ps),ne=R.getAttribute(Ol);H?R.setAttribute("aria-label",H):R.removeAttribute("aria-label"),ne?R.setAttribute("title",ne):R.removeAttribute("title"),R.removeAttribute(ps),R.removeAttribute(Ol)}return}};return o.addEventListener("input",f),o.addEventListener("compositionstart",m),o.addEventListener("compositionend",C),o.addEventListener("paste",I),o.addEventListener("beforeinput",D),l(du()),{element:o,getValue:()=>Bl(i()),getLogicalText:()=>$i(i()),getDocument:i,getSelection:u,setSelection:(O,N=O)=>{let R=typeof window<"u"?window.getSelection():null;if(R)try{let L=us(o,O),H=us(o,N),ne=document.createRange();ne.setStart(L.node,L.offset),ne.setEnd(H.node,H.offset),R.removeAllRanges(),R.addRange(ne)}catch{}},setValueWithCaret:T,getLogicalRangeRect:A,setValue:O=>{l(Hl(O)),o.focus(),c(O.length,{focus:!0}),d()},replaceLogicalRange:W,insertMentionAtTrigger:z,insertMentionAtSelection:U,setMentionStatus:w,submit:()=>El(o.closest("form")),dispatchInput:d,focus:()=>o.focus(),destroy:()=>{o.removeEventListener("input",f),o.removeEventListener("compositionstart",m),o.removeEventListener("compositionend",C),o.removeEventListener("paste",I),o.removeEventListener("beforeinput",D)}}}var Uh,fs,ps,Ol,gu,bu=yt(()=>{"use strict";Nl();kl();Uh="persona-mention-token-error",fs="data-mention-id",ps="data-mention-prev-label",Ol="data-mention-prev-title",gu=`
|
|
174
|
+
`});function Gh(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 Qh(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 yu(t){let{textarea:e}=t,n={generateId:Kh,renderToken:t.renderToken,onMentionRemoved:t.onMentionRemoved,placeholder:e.getAttribute("placeholder")??void 0},o=hu(n),r=o.element,s=e.getAttribute("aria-label")!=null;Gh(e,r),Qh(r,o,s),r.getInlineMessageFields=()=>uu(o.getDocument?.()??{blocks:[]});let i=e.selectionStart??e.value.length;return o.setValueWithCaret(e.value,i),{input:o,element:r,destroy:o.destroy}}var Vh,Kh,vu=yt(()=>{"use strict";bu();Nl();Vh=0,Kh=()=>`pmention-${++Vh}`});var xu={};tr(xu,{mountInlineComposer:()=>yu});var Cu=yt(()=>{"use strict";vu()});var Uv={};tr(Uv,{createThemePreview:()=>gg});module.exports=pm(Uv);var nr=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:Xv,load:um,provide:Jv,getSync:rl}=nr({fallbackImport:()=>Promise.resolve().then(()=>(_d(),Fd))}),ci=new Set,fm=()=>{let t=[...ci];ci.clear();for(let e of t)try{e()}catch{}};var gm=()=>{let t=rl();return t?Promise.resolve(t):um().then(e=>(fm(),e))},di=t=>rl()?()=>{}:(ci.add(t),gm().catch(()=>{}),()=>{ci.delete(t)});var On=rl;var mm=t=>{if(t)return t},sl=t=>{let e=null;return n=>{let o=On();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=mm(t?.renderer);i&&e.use({renderer:i})}return e.parse(n)}},pi=t=>t?sl({markedOptions:t.options,renderer:t.renderer}):sl(),ex=sl();var oo=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var hm={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"]},bm=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,ym=()=>{let t=null;return e=>{let n=On();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:")&&!bm.test(i)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,hm)}},ui=t=>t===!1?null:typeof t=="function"?t:ym();var $d=/^\s*\|?[\s:|-]*-[\s:|-]*$/,zd=t=>t.includes("|"),Ud=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())},vm=t=>`| ${t.join(" | ")} |`,xm=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,Cm=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),jd=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
|
|
175
|
+
`),n=!1;for(let o=0;o<e.length-1;o++){let r=e[o],s=e[o+1];if(!zd(r)||$d.test(r)||!$d.test(s))continue;let i=Ud(r).length;if(i<1)continue;let l=xm(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()===""||!zd(c))break;let d=vm(Cm(Ud(c),i));e[p]!==d&&(e[p]=d,n=!0)}o=p-1}return n?e.join(`
|
|
176
|
+
`):t};var Fn="webmcp:",il=new Map,qd=t=>{il.clear();for(let e of t){let n=e.title?.trim();n&&il.set(e.name,n)}},Yr=t=>il.get(Qd(t)),fi={warn(t,...e){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${t}`,...e)}},Vd=null;function Gd(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}:${wm(e.join(""))}`}function Kd(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 wm(t){let e=Kd(t,0).toString(36),n=Kd(t,2654435761).toString(36);return`${e}.${n}`}var gi=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 fi.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}qd(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=Sm(r.inputSchema);return i&&(s.parametersSchema=i),s})}async executeToolCall(e,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return Sn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let m=typeof document<"u"&&!!document.modelContext;return Sn(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=Qd(e),i;try{i=await r.getTools()}catch(m){let C=m instanceof Error?m.message:String(m);return Sn(`Failed to read WebMCP registry: ${C}`)}qd(i);let l=i.find(m=>m.name===s);if(!l)return Sn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return Sn(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return Sn("Aborted by cancel()");let p=Yr(s),c={toolName:s,args:n,description:l.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(c))return Sn("User declined the tool call.");if(o?.aborted)return Sn("Aborted by cancel()");let d=new AbortController,u=!1,b=setTimeout(()=>{u=!0,d.abort()},this.timeoutMs),f=()=>d.abort();o&&(o.aborted?d.abort():o.addEventListener("abort",f,{once:!0}));try{let m=await r.executeTool(l,km(n),{signal:d.signal});return Mm(m)}catch(m){if(u)return Sn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return Sn("Aborted by cancel()");let C=m instanceof Error?m.message:String(m);return Sn(C)}finally{clearTimeout(b),o&&o.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Vd?await Vd():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){fi.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,fi.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??Tm;try{return await n(e)}catch(o){return fi.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=>Am(e,o))}},Qd=t=>t.startsWith(Fn)?t.slice(Fn.length):t,or=t=>t.startsWith(Fn),Am=(t,e)=>{if(e==="*")return!0;let n=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(t)},Sm=t=>{if(!(t===void 0||t===""))try{let e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Mm=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:Lm(e)}]}},Sn=t=>({isError:!0,content:[{type:"text",text:t}]}),Tm=async t=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let e=Em(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)},Sm=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)}},Mm=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},Tm=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};function Wo(t,e){let n=t?.display;return n?typeof n=="string"?n:n.byType?.[e]??n.default??"panel":"panel"}function mi(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 Em="agent_",km="flow_";function Qd(t){return t.startsWith(Em)?{kind:"agentId",agentId:t}:t.startsWith(km)?{kind:"flowId",flowId:t}:null}function Xd(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=Qd(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=Qd(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 il="ask_user_question",Zr=8,sr="data-persona-ask-sheet-for",Lm="Other",Pm="Other\u2026",Zd="Type your own answer here",ep="Send",Im="Next",Rm="Back",Wm="Submit all",Hm="Skip",Bm=3,al="data-ask-current-index",ll="data-ask-question-count",tp="data-ask-answers",cl="data-ask-grouped",np="data-ask-layout",Dm=t=>t.layout==="pills"?"pills":"rows",Nm=t=>t.getAttribute(np)==="pills"?"pills":"rows",Yd=!1,op=t=>t.replace(/["\\]/g,"\\$&"),Ho=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===il,dl=t=>t?.features?.askUserQuestion??{},ir=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let o=e.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=(0,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}},es=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>Zr&&!Yd&&(Yd=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Zr}.`)),e.slice(0,Zr)},Om=t=>es(t)[0]??null,Fm=(t,e)=>es(t)[e]??null,_m=(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))},rp=(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},$m=(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=rp(n,o,e);p&&s.appendChild(p)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},zm=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},Um=(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<Bm;d++)s.appendChild(zm(o));return s}if(p.forEach((d,u)=>{s.appendChild($m(d,u,o,i))}),t?.allowFreeText!==!1){let d=o==="rows"?Lm:Pm;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 b=h("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=e.freeTextPlaceholder??Zd,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",e.freeTextLabel??d),b.appendChild(f),u.appendChild(b);let m=rp(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},sp=(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??Zd,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??ep,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},jm=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??ep,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},qm=(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??Rm,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??Hm,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??Wm:n.nextLabel??Im,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Bo=t=>{let e=t.getAttribute(tp);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},ip=(t,e)=>{t.setAttribute(tp,JSON.stringify(e))},hn=t=>{let e=Number(t.getAttribute(al)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Vm=(t,e)=>{t.setAttribute(al,String(Math.max(0,Math.floor(e))))},ar=t=>{let e=Number(t.getAttribute(ll)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},so=t=>t.getAttribute(cl)==="true",Km=(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},Gm=(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)))},hi=(t,e)=>{let{payload:n}=ir(e),o=es(n),r=Bo(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},ap=t=>{let e=Bo(t),n=hn(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="")},lp=t=>{if(!so(t))return;let e=Bo(t),n=hn(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}},pl=(t,e,n)=>{let o=dl(n),r=Nm(t),{payload:s,complete:i}=ir(e),l=so(t),p=hn(t),c=ar(t),d=l?Fm(s,p):Om(s),u=!!d?.multiSelect,b=t.querySelector('[data-ask-step-inline="true"]');b&&(b.textContent=l?`${p+1}/${c}`:"");let f=t.querySelector('[data-ask-stepper="true"]');f&&f.remove();let m=t.querySelector('[data-ask-question="true"]');if(m){let M=typeof d?.question=="string"?d.question:"";m.textContent=M,m.classList.toggle("persona-ask-question-skeleton",!M&&!i)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let M=Um(d,o,i,r);C.replaceWith(M)}if(r!=="rows"){let M=t.querySelector('[data-ask-free-text-row="true"]');M&&M.replaceWith(sp(o,r))}let k=t.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!k?t.appendChild(jm(o)):(!u||l)&&k&&k.remove(),t.setAttribute("data-multi-select",u?"true":"false");let D=t.querySelector('[data-ask-nav-row="true"]');if(l){let M=qm(p,c,o);D?D.replaceWith(M):t.appendChild(M)}else D&&D.remove();ap(t),lp(t)},Qm=(t,e,n)=>{let o=dl(e),r=Dm(o),s=t.toolCall.id,i=es(n),l=Math.max(1,i.length),p=l>1,c=Km(t,i),d=p?Gm(t,l):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(sr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",t.id),u.setAttribute(ll,String(l)),u.setAttribute(al,String(d)),u.setAttribute(cl,p?"true":"false"),u.setAttribute(np,r),ip(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`),_m(u,o);let b=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=h("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",b.appendChild(f);let m=h("span","persona-ask-sheet-step-inline");m.setAttribute("data-ask-step-inline","true"),m.textContent="",b.appendChild(m),u.appendChild(b);let k=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 k.setAttribute("data-ask-pill-list","true"),k.setAttribute("role","group"),u.appendChild(k),r!=="rows"&&u.appendChild(sp(o,r)),pl(u,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Xm=(t,e,n)=>{let{payload:o}=ir(e),r=Math.max(1,es(o).length);r>ar(t)&&(t.setAttribute(ll,String(r)),r>1&&!so(t)&&t.setAttribute(cl,"true")),pl(t,e,n)};var bi=(t,e,n)=>{if(!n||!Ho(t)||dl(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${sr}]`).forEach(c=>{c.getAttribute(sr)!==r&&c.remove()});let i=n.querySelector(`[${sr}="${op(r)}"]`);if(i){Xm(i,t,e);return}let{payload:l}=ir(t),p=Qm(t,e,l);n.appendChild(p)},lr=(t,e)=>{if(!t)return;let n=e?`[${sr}="${op(e)}"]`:`[${sr}]`;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)})},ul=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=Bo(t),o=hn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,ip(t,n),ap(t),lp(t)},yi=(t,e,n,o)=>{let r=ar(t),s=Math.max(0,Math.min(r-1,o));Vm(t,s),pl(t,e,n)};var $n="suggest_replies";var Jm={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},cp={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:Jm,origin:"sdk",annotations:{readOnlyHint:!0}},fl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),gl=t=>t.variant==="tool"&&t.toolCall?.name===$n,Ym=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},dp=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=Ym(n.toolCall?.args);return o.length>0?o:null}return null},pp=t=>{let e=t?.features?.suggestReplies;return e?.expose===!0&&e.enabled!==!1};var Zm={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Zr,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},eh={name:il,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:Zm,origin:"sdk",annotations:{readOnlyHint:!0}},vi=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(eh),pp(t)&&e.push(cp),e};var cr=require("partial-json"),up=t=>t.replace(/\\n/g,`
|
|
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)}},
|
|
181
|
+
${t.description}`:"");return window.confirm(n)},Em=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)}},km=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},Lm=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};function Wo(t,e){let n=t?.display;return n?typeof n=="string"?n:n.byType?.[e]??n.default??"panel":"panel"}function mi(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 Pm="agent_",Im="flow_";function Xd(t){return t.startsWith(Pm)?{kind:"agentId",agentId:t}:t.startsWith(Im)?{kind:"flowId",flowId:t}:null}function Jd(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=Xd(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=Xd(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");st();var al="ask_user_question",Zr=8,rr="data-persona-ask-sheet-for",Rm="Other",Wm="Other\u2026",ep="Type your own answer here",tp="Send",Hm="Next",Bm="Back",Dm="Submit all",Nm="Skip",Om=3,ll="data-ask-current-index",cl="data-ask-question-count",np="data-ask-answers",dl="data-ask-grouped",op="data-ask-layout",Fm=t=>t.layout==="pills"?"pills":"rows",_m=t=>t.getAttribute(op)==="pills"?"pills":"rows",Zd=!1,rp=t=>t.replace(/["\\]/g,"\\$&"),Ho=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===al,pl=t=>t?.features?.askUserQuestion??{},sr=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}},es=t=>{let e=Array.isArray(t?.questions)?t.questions:[];return e.length>Zr&&!Zd&&(Zd=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Zr}.`)),e.slice(0,Zr)},$m=t=>es(t)[0]??null,zm=(t,e)=>es(t)[e]??null,Um=(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))},sp=(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},jm=(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=sp(n,o,e);p&&s.appendChild(p)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},qm=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},Vm=(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<Om;d++)s.appendChild(qm(o));return s}if(p.forEach((d,u)=>{s.appendChild(jm(d,u,o,i))}),t?.allowFreeText!==!1){let d=o==="rows"?Rm:Wm;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 b=h("span","persona-ask-row-content"),f=document.createElement("input");f.type="text",f.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",f.placeholder=e.freeTextPlaceholder??ep,f.setAttribute("data-ask-free-text-input","true"),f.setAttribute("aria-label",e.freeTextLabel??d),b.appendChild(f),u.appendChild(b);let m=sp(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},ip=(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??ep,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??tp,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},Km=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??tp,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},Gm=(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??Bm,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??Nm,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??Dm:n.nextLabel??Hm,l.setAttribute("data-ask-user-action",p?"submit-all":"next"),l.disabled=!0,s.appendChild(l),o.appendChild(s),o},Bo=t=>{let e=t.getAttribute(np);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},ap=(t,e)=>{t.setAttribute(np,JSON.stringify(e))},mn=t=>{let e=Number(t.getAttribute(ll)??"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Qm=(t,e)=>{t.setAttribute(ll,String(Math.max(0,Math.floor(e))))},ir=t=>{let e=Number(t.getAttribute(cl)??"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},so=t=>t.getAttribute(dl)==="true",Xm=(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},Jm=(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)))},hi=(t,e)=>{let{payload:n}=sr(e),o=es(n),r=Bo(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},lp=t=>{let e=Bo(t),n=mn(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="")},cp=t=>{if(!so(t))return;let e=Bo(t),n=mn(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}},ul=(t,e,n)=>{let o=pl(n),r=_m(t),{payload:s,complete:i}=sr(e),l=so(t),p=mn(t),c=ir(t),d=l?zm(s,p):$m(s),u=!!d?.multiSelect,b=t.querySelector('[data-ask-step-inline="true"]');b&&(b.textContent=l?`${p+1}/${c}`:"");let f=t.querySelector('[data-ask-stepper="true"]');f&&f.remove();let m=t.querySelector('[data-ask-question="true"]');if(m){let T=typeof d?.question=="string"?d.question:"";m.textContent=T,m.classList.toggle("persona-ask-question-skeleton",!T&&!i)}let C=t.querySelector('[data-ask-pill-list="true"]');if(C){let T=Vm(d,o,i,r);C.replaceWith(T)}if(r!=="rows"){let T=t.querySelector('[data-ask-free-text-row="true"]');T&&T.replaceWith(ip(o,r))}let I=t.querySelector('[data-ask-multi-actions="true"]');!l&&u&&!I?t.appendChild(Km(o)):(!u||l)&&I&&I.remove(),t.setAttribute("data-multi-select",u?"true":"false");let D=t.querySelector('[data-ask-nav-row="true"]');if(l){let T=Gm(p,c,o);D?D.replaceWith(T):t.appendChild(T)}else D&&D.remove();lp(t),cp(t)},Ym=(t,e,n)=>{let o=pl(e),r=Fm(o),s=t.toolCall.id,i=es(n),l=Math.max(1,i.length),p=l>1,c=Xm(t,i),d=p?Jm(t,l):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(rr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",t.id),u.setAttribute(cl,String(l)),u.setAttribute(ll,String(d)),u.setAttribute(dl,p?"true":"false"),u.setAttribute(op,r),ap(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`),Um(u,o);let b=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=h("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",b.appendChild(f);let m=h("span","persona-ask-sheet-step-inline");m.setAttribute("data-ask-step-inline","true"),m.textContent="",b.appendChild(m),u.appendChild(b);let I=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 I.setAttribute("data-ask-pill-list","true"),I.setAttribute("role","group"),u.appendChild(I),r!=="rows"&&u.appendChild(ip(o,r)),ul(u,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Zm=(t,e,n)=>{let{payload:o}=sr(e),r=Math.max(1,es(o).length);r>ir(t)&&(t.setAttribute(cl,String(r)),r>1&&!so(t)&&t.setAttribute(dl,"true")),ul(t,e,n)};var bi=(t,e,n)=>{if(!n||!Ho(t)||pl(e).enabled===!1)return;let r=t.toolCall.id;n.querySelectorAll(`[${rr}]`).forEach(c=>{c.getAttribute(rr)!==r&&c.remove()});let i=n.querySelector(`[${rr}="${rp(r)}"]`);if(i){Zm(i,t,e);return}let{payload:l}=sr(t),p=Ym(t,e,l);n.appendChild(p)},ar=(t,e)=>{if(!t)return;let n=e?`[${rr}="${rp(e)}"]`:`[${rr}]`;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)})},fl=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=Bo(t),o=mn(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[o]:n[o]=e,ap(t,n),lp(t),cp(t)},yi=(t,e,n,o)=>{let r=ir(t),s=Math.max(0,Math.min(r-1,o));Qm(t,s),ul(t,e,n)};var $n="suggest_replies";var eh={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},dp={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:eh,origin:"sdk",annotations:{readOnlyHint:!0}},gl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ml=t=>t.variant==="tool"&&t.toolCall?.name===$n,th=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},pp=t=>{for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="user")return null;if(!ml(n))continue;let o=th(n.toolCall?.args);return o.length>0?o:null}return null},up=t=>{let e=t?.features?.suggestReplies;return e?.expose===!0&&e.enabled!==!1};var nh={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Zr,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},oh={name:al,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:nh,origin:"sdk",annotations:{readOnlyHint:!0}},vi=t=>{let e=[],n=t?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&e.push(oh),up(t)&&e.push(dp),e};var lr=require("partial-json"),fp=t=>t.replace(/\\n/g,`
|
|
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)}},rh=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`},gp=t=>t.status==="complete"?rh(t):t.status==="pending"?"Waiting":"",sh=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 mp=t=>t.status==="complete"?sh(t):"Using tool...",xi=t=>{let e=t/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},ns=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 xi(e)},Ci=t=>{let e=t.durationMs!==void 0?t.durationMs:Math.max(0,(t.completedAt??Date.now())-(t.startedAt??t.completedAt??Date.now()));return xi(e)},hl=(t,e,n)=>{if(!e)return n;let o=t.name?.trim()||"tool",r=ns(t);return e.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},wi=(t,e)=>{let n=t.replace(/\{toolName\}/g,e),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,i;for(;(i=r.exec(n))!==null;)i.index>s&&ts(o,n.slice(s,i.index),[]),i[1]!==void 0?ts(o,i[1],["bold"]):i[2]!==void 0?ts(o,i[2],["italic"]):i[3]!==void 0&&ts(o,i[3],["dim"]),s=i.index+i[0].length;return s<n.length&&ts(o,n.slice(s),[]),o},ts=(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})},ih=()=>{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()=>{}}},os=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},mp=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},hp=()=>{let t=oh();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)}},bp=()=>{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,cr.parse)(n,cr.STR|cr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?up(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=up(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var yp=()=>{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 vp="4.9.0";var rs=vp;var sh="https://api.runtype.com/v1/dispatch",Ai="https://api.runtype.com";function ih(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 hl=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 ah(t){switch(t){case"json":return bp;case"regex-json":return hp;case"xml":return yp;default:return mp}}var xp=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function lh(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=xp(n);if(!xp(o))return t;if(!r||o===n||o.startsWith(n))return e;let i=os(t);return os(e)!==null&&i===null?e:t}var ss=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??sh,this.headers={"Content-Type":"application/json","X-Persona-Version":rs,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??ah(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 gi(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=Xd(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$/,"")||Ai}/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":rs},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$/,"")||Ai}/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":rs},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(hl).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":rs},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$/,"")||Ai}/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?Kd(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 b=0;;b++){if(u=await o({...s&&(d||!p)&&n?{clientTools:n}:{},...c?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),u.status===409&&b===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(/\/+$/,"")||Ai}/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=[...vi(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:d,commit:u}=await this.sendWithClientToolsDiff(i,c,b=>{let f={...p,...b};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(s,{method:"POST",headers:l,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return d.ok&&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(hl).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=[...vi(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(hl).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=[...vi(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=I=>{let Y=I.reasoning?{...I.reasoning,chunks:[...I.reasoning.chunks]}:void 0,x=I.toolCall?{...I.toolCall,chunks:I.toolCall.chunks?[...I.toolCall.chunks]:void 0}:void 0,E=I.tools?I.tools.map(R=>({...R,chunks:R.chunks?[...R.chunks]:void 0})):void 0;return{...I,reasoning:Y,toolCall:x,tools:E}},b=I=>{if(I.role!=="assistant"||I.variant)return!0;let Y=Array.isArray(I.contentParts)&&I.contentParts.length>0,x=typeof I.rawContent=="string"&&I.rawContent.trim()!=="";return typeof I.content=="string"&&I.content.trim()!==""||Y||x||!!I.stopReason},f=I=>{b(I)&&n({type:"message",message:u(I)})},m=null,C=null,k={current:null},D={current:null},M=null,A="",W=new Map,z=new Map,U=new Map,w=new Map,O=new Map,N={lastId:null,byStep:new Map},L={lastId:null,byCall:new Map},P=I=>{if(I==null)return null;try{return String(I)}catch{return null}},H=I=>P(I.stepId??I.step_id??I.step??I.parentId??I.flowStepId??I.flow_step_id),ne=I=>P(I.callId??I.call_id??I.requestId??I.request_id??I.toolCallId??I.tool_call_id??I.stepId??I.step_id),pe=o,he=!1,fe=()=>{if(m)return m;let I,Y="",x=M;return!he&&pe?(I=pe,he=!0,Y=r??""):pe&&x?I=`${pe}_${x}`:I=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:I,role:"assistant",content:Y,createdAt:new Date().toISOString(),streaming:!0,sequence:d()},f(m),m},ee=(I,Y)=>{N.lastId=Y,I&&N.byStep.set(I,Y)},oe=(I,Y)=>{let x=I.reasoningId??I.id,E=H(I);if(x){let _=String(x);return ee(E,_),_}if(E){let _=N.byStep.get(E);if(_)return N.lastId=_,_}if(N.lastId&&!Y)return N.lastId;if(!Y)return null;let R=`reason-${d()}`;return ee(E,R),R},K=I=>{let Y=w.get(I);if(Y)return Y;let x={id:`reason-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:d(),reasoning:{id:I,status:"streaming",chunks:[]}};return w.set(I,x),f(x),x},ae=(I,Y)=>{L.lastId=Y,I&&L.byCall.set(I,Y)},te=new Set,ve=new Map,xe=new Set,ge=new Map,Te=I=>{if(!I)return!1;let Y=I.replace(/_+/g,"_").replace(/^_|_$/g,"");return Y==="emit_artifact_markdown"||Y==="emit_artifact_component"},Me=(I,Y)=>{let x=I.toolId??I.id,E=ne(I);if(x){let _=String(x);return ae(E,_),_}if(E){let _=L.byCall.get(E);if(_)return L.lastId=_,_}if(L.lastId&&!Y)return L.lastId;if(!Y)return null;let R=`tool-${d()}`;return ae(E,R),R},Fe=I=>{let Y=O.get(I);if(Y)return Y;let x={id:`tool-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:d(),toolCall:{id:I,status:"pending"}};return O.set(I,x),f(x),x},Pe=I=>{if(typeof I=="number"&&Number.isFinite(I))return I;if(typeof I=="string"){let Y=Number(I);if(!Number.isNaN(Y)&&Number.isFinite(Y))return Y;let x=Date.parse(I);if(!Number.isNaN(x))return x}return Date.now()},Ee=I=>{if(typeof I=="string")return I;if(I==null)return"";try{return JSON.stringify(I)}catch{return String(I)}},Ne=new Map,lt=new Map,ze=new Map,Je=(I,Y,x)=>{let E=ze.get(I);E||(E=[],ze.set(I,E));let R=0,_=E.length;for(;R<_;){let $=R+_>>>1;E[$].seq<Y?R=$+1:_=$}E[R]?.seq===Y?E[R]={seq:Y,text:x}:E.splice(R,0,{seq:Y,text:x});let J="";for(let $=0;$<E.length;$++)J+=E[$].text;return J},pn=(I,Y)=>{let x=Ee(Y),E=lt.get(I.id),R=lh(E,x);I.rawContent=R;let _=Ne.get(I.id),J=Ie=>{let dt=I.content??"";Ie.trim()!==""&&(dt.trim().length===0||Ie.startsWith(dt)||Ie.trimStart().startsWith(dt.trim()))&&(I.content=Ie)},$=()=>{if(_){let Ie=_.close?.();Ie instanceof Promise&&Ie.catch(()=>{})}Ne.delete(I.id),lt.delete(I.id),I.streaming=!1,f(I)};if(!_){J(x),$();return}let G=os(R);if(G!==null&&G.trim()!==""){J(G),$();return}let de=Ie=>{let dt=typeof Ie=="string"?Ie:Ie?.text??null;if(dt!==null&&dt.trim()!=="")return dt;let Q=_.getExtractedText();return Q!==null&&Q.trim()!==""?Q:x},ot;try{ot=_.processChunk(R)}catch{J(x),$();return}if(ot instanceof Promise){ot.then(Ie=>{J(de(Ie)),$()}).catch(()=>{J(x),$()});return}J(de(ot)),$()},It=null,mt=(I,Y,x,E)=>{I.rawContent=Y,Ne.has(I.id)||Ne.set(I.id,this.createStreamParser());let R=Ne.get(I.id),_=Y.trim().startsWith("{")||Y.trim().startsWith("[");if(_&<.set(I.id,Y),R.__isPlainTextParser===!0){I.content=E!==void 0?Y:I.content+x,lt.delete(I.id),Ne.delete(I.id),I.rawContent=void 0,f(I);return}let $=R.processChunk(Y);if($ instanceof Promise)$.then(G=>{let de=typeof G=="string"?G:G?.text??null;de!==null&&de.trim()!==""?(I.content=de,f(I)):!_&&!Y.trim().startsWith("<")&&(I.content=E!==void 0?Y:I.content+x,lt.delete(I.id),Ne.delete(I.id),I.rawContent=void 0,f(I))}).catch(()=>{I.content=E!==void 0?Y:I.content+x,lt.delete(I.id),Ne.delete(I.id),I.rawContent=void 0,f(I)});else{let G=typeof $=="string"?$:$?.text??null;G!==null&&G.trim()!==""?(I.content=G,f(I)):!_&&!Y.trim().startsWith("<")&&(I.content=E!==void 0?Y:I.content+x,lt.delete(I.id),Ne.delete(I.id),I.rawContent=void 0,f(I))}},Re=(I,Y)=>{let x=Y??I.content;if(x==null||x===""){I.streaming=!1,f(I);return}let R=lt.get(I.id)??Ee(x);I.rawContent=R;let _=Ne.get(I.id),J=null,$=!1;if(_&&(J=_.getExtractedText(),J===null&&(J=os(R)),J===null)){let G=_.processChunk(R);G instanceof Promise?($=!0,G.then(de=>{let ot=typeof de=="string"?de:de?.text??null;ot!==null&&(I.content=ot,I.streaming=!1,Ne.delete(I.id),lt.delete(I.id),f(I))}).catch(()=>{})):J=typeof G=="string"?G:G?.text??null}if(!$){J!==null&&J.trim()!==""?I.content=J:lt.has(I.id)||(I.content=Ee(x));let G=Ne.get(I.id);if(G){let de=G.close?.();de instanceof Promise&&de.catch(()=>{}),Ne.delete(I.id)}lt.delete(I.id),I.streaming=!1,f(I)}},we=(I,Y,x)=>{let E=z.get(I);if(E)return E;let R={id:`nested-${Y}-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),...x?{variant:x}:{},...x==="reasoning"?{reasoning:{id:I,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:Y}};return z.set(I,R),f(R),R},ct=[],He,ye=new Map,ue=0,Ae="agent",Ct=!1,j=null,ie=null,_e=new Map,Le=this.config.iterationDisplay??"separate";for(He=()=>{for(let I=0;I<ct.length;I++){let Y=ct[I].payloadType,x=ct[I].payload;if(!Ct&&Ae!=="flow"&&typeof x.stepType=="string"&&(Ae="flow"),Y==="reasoning_start"){let E=typeof x.id=="string"?x.id:null,R=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(E&&R){W.set(E,R),we(E,R,"reasoning");continue}let _=oe(x,!0)??`reason-${d()}`,J=K(_);J.reasoning=J.reasoning??{id:_,status:"streaming",chunks:[]},J.reasoning.startedAt=J.reasoning.startedAt??Pe(x.startedAt??x.timestamp),J.reasoning.completedAt=void 0,J.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(J.reasoning.scope=x.scope),J.streaming=!0,J.reasoning.status="streaming",f(J)}else if(Y==="reasoning_delta"){let E=typeof x.id=="string"?x.id:null;if(E&&W.has(E)&&z.has(E)){let $=z.get(E),G=x.reasoningText??x.text??x.delta??"";G&&x.hidden!==!0&&$.reasoning&&($.reasoning.chunks.push(String(G)),f($));continue}let R=oe(x,!1)??oe(x,!0)??`reason-${d()}`,_=K(R);_.reasoning=_.reasoning??{id:R,status:"streaming",chunks:[]},_.reasoning.startedAt=_.reasoning.startedAt??Pe(x.startedAt??x.timestamp);let J=x.reasoningText??x.text??x.delta??"";if(J&&x.hidden!==!0){let $=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if($!==void 0){let G=Je(R,$,String(J));_.reasoning.chunks=[G]}else _.reasoning.chunks.push(String(J))}if(_.reasoning.status=x.done?"complete":"streaming",x.done){_.reasoning.completedAt=Pe(x.completedAt??x.timestamp);let $=_.reasoning.startedAt??Date.now();_.reasoning.durationMs=Math.max(0,(_.reasoning.completedAt??Date.now())-$)}_.streaming=_.reasoning.status!=="complete",f(_)}else if(Y==="reasoning_complete"){let E=typeof x.id=="string"?x.id:null;if(E&&W.has(E)&&z.has(E)){let G=z.get(E);if(G.reasoning){let de=typeof x.text=="string"?x.text:"";de&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(de),G.reasoning.status="complete",G.streaming=!1,f(G)}W.delete(E),z.delete(E);continue}let R=oe(x,!1)??oe(x,!0)??`reason-${d()}`,_=typeof x.text=="string"?x.text:"";!w.get(R)&&(_||x.scope==="loop")&&K(R);let J=w.get(R);if(J?.reasoning){(x.scope==="loop"||x.scope==="turn")&&(J.reasoning.scope=x.scope),_&&J.reasoning.chunks.length===0&&J.reasoning.chunks.push(_),J.reasoning.status="complete",J.reasoning.completedAt=Pe(x.completedAt??x.timestamp);let G=J.reasoning.startedAt??Date.now();J.reasoning.durationMs=Math.max(0,(J.reasoning.completedAt??Date.now())-G),J.streaming=!1,f(J)}let $=H(x);$&&N.byStep.delete($)}else if(Y==="tool_start"){m&&(m.streaming=!1,f(m),m=null),typeof x.iteration=="number"&&(ue=x.iteration);let E=(typeof x.toolCallId=="string"?x.toolCallId:void 0)??Me(x,!0)??`tool-${d()}`,R=x.toolName??x.name;if(Te(R)){te.add(E);continue}ae(ne(x),E);let _=Fe(E),J=_.toolCall??{id:E,status:"pending"};J.name=R??J.name,J.status="running",x.parameters!==void 0?J.args=x.parameters:x.args!==void 0&&(J.args=x.args),J.startedAt=J.startedAt??Pe(x.startedAt??x.timestamp),J.completedAt=void 0,J.durationMs=void 0,_.toolCall=J,_.streaming=!0,x.executionId&&(_.agentMetadata={executionId:x.executionId,iteration:x.iteration}),f(_)}else if(Y==="tool_output_delta"){let E=Me(x,!1)??Me(x,!0)??`tool-${d()}`;if(te.has(E))continue;let R=Fe(E),_=R.toolCall??{id:E,status:"running"};_.startedAt=_.startedAt??Pe(x.startedAt??x.timestamp);let J=x.text??x.delta??x.message??"";J&&(_.chunks=_.chunks??[],_.chunks.push(String(J))),_.status="running",R.toolCall=_,R.streaming=!0;let $=x.agentContext;($||x.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:$?.executionId??x.executionId,iteration:$?.iteration??x.iteration}),f(R)}else if(Y==="tool_complete"){let E=Me(x,!1)??Me(x,!0)??`tool-${d()}`;if(te.has(E)){te.delete(E);continue}let R=Fe(E),_=R.toolCall??{id:E,status:"running"};_.status="complete",x.result!==void 0&&(_.result=x.result),typeof x.duration=="number"&&(_.duration=x.duration),_.completedAt=Pe(x.completedAt??x.timestamp);let J=x.duration??x.executionTime;if(typeof J=="number")_.durationMs=J;else{let de=_.startedAt??Date.now();_.durationMs=Math.max(0,(_.completedAt??Date.now())-de)}R.toolCall=_,R.streaming=!1;let $=x.agentContext;($||x.executionId)&&(R.agentMetadata=R.agentMetadata??{executionId:$?.executionId??x.executionId,iteration:$?.iteration??x.iteration}),f(R);let G=ne(x);G&&L.byCall.delete(G)}else if(Y==="await"&&x.toolName){let E=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,R=E??x.toolId??`local-${d()}`,_=Fe(R),J=x.toolName,$=x.origin==="webmcp"&&!rr(J)?`webmcp:${J}`:J,G=rr($),de=_.toolCall??{id:R,status:"pending"};de.name=$,de.args=x.parameters,de.status=G?"running":"complete",de.chunks=de.chunks??[],de.startedAt=de.startedAt??Pe(x.startedAt??x.timestamp??x.awaitedAt),G?(de.completedAt=void 0,de.duration=void 0,de.durationMs=void 0):de.completedAt=de.completedAt??de.startedAt,_.toolCall=de,_.streaming=!1,_.agentMetadata={..._.agentMetadata,executionId:x.executionId??_.agentMetadata?.executionId,awaitingLocalTool:!0,...E?{webMcpToolCallId:E}:{}},f(_)}else if(Y==="text_start"){let E=typeof x.id=="string"?x.id:null,R=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(E&&R){W.set(E,R);continue}let _=m;_&&(Ae==="flow"?(Re(_),It=_):(_.streaming=!1,f(_)),m=null),M=typeof x.id=="string"?x.id:M,A=""}else if(Y==="text_delta"){let E=typeof x.id=="string"?x.id:null,R=E?W.get(E):void 0;if(E&&R){let J=typeof x.delta=="string"?x.delta:"",$=(U.get(E)??"")+J;if(U.set(E,$),$.trim()==="")continue;let G=we(E,R);G.agentMetadata={...G.agentMetadata,executionId:x.executionId,parentToolId:R},mt(G,$,J,void 0);continue}if(M=typeof x.id=="string"?x.id:M,Ae==="flow"){let J=typeof x.delta=="string"?x.delta:"";if(A+=J,A.trim()==="")continue;let $=fe();$.agentMetadata={executionId:x.executionId,iteration:x.iteration},mt($,A,J,void 0),C=$;continue}let _=fe();_.content+=x.delta??"",_.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:j??void 0,agentName:ie?.agentName},C=_,f(_)}else if(Y==="text_complete"){let E=typeof x.id=="string"?x.id:null;if(E&&W.has(E)){let _=z.get(E);_&&Re(_),W.delete(E),U.delete(E),z.delete(E);continue}let R=m;R&&(Ae==="flow"?(Re(R),It=R):((R.content??"")===""&&typeof x.text=="string"&&(R.content=x.text),R.streaming=!1,f(R)),m=null),M=null,A=""}else if(Y==="step_complete"){let E=x.stepType,R=x.executionType;if(E==="tool"||R==="context")continue;if(x.success===!1){let _=x.error,J=typeof _=="string"&&_!==""?_:_!=null&&typeof _=="object"&&Reflect.has(_,"message")?String(_.message??"Step failed"):"Step failed";n({type:"error",error:new Error(J)});let $=m;$&&$.streaming&&($.streaming=!1,f($)),n({type:"status",status:"idle"});continue}{let _=It;It=null;let J=x.stopReason,$=x.result?.response;if(_)J&&(_.stopReason=J),$!=null?pn(_,$):_.streaming!==!1&&(Ne.delete(_.id),lt.delete(_.id),_.streaming=!1,f(_));else{let G=$!=null&&$!=="";if(G||J){let de=fe();J&&(de.stopReason=J),G?Re(de,$):(de.streaming=!1,f(de))}}continue}}else if(Y==="execution_start")Ae=x.kind==="flow"?"flow":"agent",Ct=!0,Ae==="agent"&&(ie={executionId:x.executionId,agentId:x.agentId??"virtual",agentName:x.agentName??"",status:"running",currentIteration:0,maxTurns:x.maxTurns??1,startedAt:Pe(x.startedAt)});else if(Y==="turn_start"){let E=typeof x.iteration=="number"?x.iteration:ue;if(E!==ue){if(ie&&(ie.currentIteration=E),Le==="separate"&&E>1){let R=m;R&&(R.streaming=!1,f(R),_e.set(E-1,R),m=null)}ue=E}j=typeof x.id=="string"?x.id:null,C=null}else if(Y==="tool_input_delta"){let E=x.toolCallId??L.lastId;if(E){let R=O.get(E);R?.toolCall&&(R.toolCall.chunks=R.toolCall.chunks??[],R.toolCall.chunks.push(x.delta??""),f(R))}}else{if(Y==="tool_input_complete")continue;if(Y==="turn_complete"){let E=x.stopReason,R=m??C;if(E&&R!==null){let _=x.id;(!_||R.agentMetadata?.turnId===_)&&(R.stopReason=E,f(R))}j===x.id&&(j=null)}else if(Y==="media_start"){let E=String(x.id);ye.set(E,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(Y==="media_delta"){let E=ye.get(String(x.id));E&&typeof x.delta=="string"&&E.parts.push(x.delta)}else if(Y==="media_complete"){let E=String(x.id),R=ye.get(E);ye.delete(E);let _=(typeof x.mediaType=="string"?x.mediaType:void 0)??R?.mediaType??"application/octet-stream",J=typeof x.data=="string"?x.data:void 0,$=typeof x.url=="string"?x.url:R&&R.parts.length>0?R.parts.join(""):void 0,G=null;if(J)G={type:"media",data:J,mediaType:_};else if($){let dt=_.toLowerCase();G={type:dt==="image"||dt.startsWith("image/")?"image-url":"file-url",url:$,mediaType:_}}let de=x.toolCallId??R?.toolCallId,ot=G?[G]:[],Ie=[];for(let dt of ot){if(!dt||typeof dt!="object")continue;let Q=dt,je=typeof Q.type=="string"?Q.type:void 0,Be=typeof Q.mediaType=="string"?Q.mediaType.toLowerCase():"",De=null,We="";if(je==="media"){let Ye=typeof Q.data=="string"?Q.data:void 0;if(!Ye)continue;We=Be.length>0?Be:"application/octet-stream",De=`data:${We};base64,${Ye}`}else if(je==="image-url"){let Ye=typeof Q.url=="string"?Q.url:void 0;if(!Ye)continue;We=Be,De=Ye}else if(je==="file-url"){let Ye=typeof Q.url=="string"?Q.url:void 0;if(!Ye)continue;We=Be,De=Ye}else continue;if(De)if(je==="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 Ye=We||"application/octet-stream";Ie.push({type:"file",data:De,mimeType:Ye,filename:ih(Ye)})}}if(Ie.length>0){let dt=d(),Q=de,Be={id:`agent-media-${typeof Q=="string"&&Q.length>0?`${Q}-${dt}`:String(dt)}`,role:"assistant",content:"",contentParts:Ie,createdAt:new Date().toISOString(),streaming:!1,sequence:dt,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:ue}};f(Be);let De=m;De&&(De.streaming=!1,f(De)),m=null,k.current=null}}else if(Y==="execution_complete"){let E=x.kind??Ae;E==="agent"&&ie&&(ie.status=x.success?"complete":"error",ie.completedAt=Pe(x.completedAt),ie.stopReason=x.stopReason);let R=m;R&&(E==="flow"&&R.streaming!==!1?Re(R):(R.streaming=!1,f(R)),m=null),M=null,A="",It=null,n({type:"status",status:"idle",terminal:!0})}else if(Y==="execution_error"){let E=typeof x.error=="string"?x.error:x.error?.message??"Execution error";n({type:"error",error:new Error(E)})}else if(Y!=="ping"){if(Y==="approval_start"){let E=x.approvalId??`approval-${d()}`,R={id:`approval-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:E,status:"pending",agentId:ie?.agentId??"virtual",executionId:x.executionId??ie?.executionId??"",toolName:x.toolName??"",toolType:x.toolType,description:x.description??`Execute ${x.toolName??"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};f(R)}else if(Y==="step_await"&&x.awaitReason==="approval_required"){let E=x.approvalId??`approval-${d()}`,R={id:`approval-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:E,status:"pending",agentId:ie?.agentId??"virtual",executionId:x.executionId??ie?.executionId??"",toolName:x.toolName??"",toolType:x.toolType,description:x.description??`Execute ${x.toolName??"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};f(R)}else if(Y==="approval_complete"){let E=x.approvalId;if(E){let _={id:`approval-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:E,status:x.decision??"approved",agentId:ie?.agentId??"virtual",executionId:x.executionId??ie?.executionId??"",toolName:x.toolName??"",description:x.description??"",resolvedAt:Date.now()}};f(_)}}else if(Y==="artifact_start"||Y==="artifact_delta"||Y==="artifact_update"||Y==="artifact_complete"){if(Y==="artifact_start"){let E=x.artifactType,R=String(x.id),_=typeof x.title=="string"?x.title:void 0,J=x.file,$;J&&typeof J=="object"&&!Array.isArray(J)&&typeof J.path=="string"&&typeof J.mimeType=="string"&&($={path:J.path,mimeType:J.mimeType,...typeof J.language=="string"?{language:J.language}:{}}),n({type:"artifact_start",id:R,artifactType:E,title:_,component:typeof x.component=="string"?x.component:void 0,...$?{file:$}:{}});let G=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?{...x.props}:void 0;if(ge.set(R,{markdown:"",title:_,file:$,...G?{props:G}:{}}),!xe.has(R)){xe.add(R);let de=Wo(this.config.features?.artifacts,E),ot=typeof x.component=="string"?x.component:void 0,Ie={id:`artifact-ref-${R}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:mi(de,{artifactId:R,title:_,artifactType:E,status:"streaming",...$?{file:$}:{},...ot?{component:ot}:{}})};ve.set(R,Ie),f(Ie)}}else if(Y==="artifact_delta"){let E=String(x.id),R=typeof x.delta=="string"?x.delta:String(x.delta??"");n({type:"artifact_delta",id:E,artDelta:R});let _=ge.get(E);_&&(_.markdown+=R)}else if(Y==="artifact_update"){let E=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};n({type:"artifact_update",id:String(x.id),props:E,component:typeof x.component=="string"?x.component:void 0});let R=ge.get(String(x.id));R&&(R.props={...R.props??{},...E})}else if(Y==="artifact_complete"){let E=String(x.id);n({type:"artifact_complete",id:E});let R=ve.get(E);if(R){R.streaming=!1;try{let _=JSON.parse(R.rawContent??"{}");if(_.props){_.props.status="complete";let J=ge.get(E);J?.markdown&&(_.props.markdown=J.markdown),J?.file&&(_.props.file=J.file),_.component==="PersonaArtifactInline"&&J?.props&&Object.keys(J.props).length>0&&(_.props.componentProps=J.props)}R.rawContent=JSON.stringify(_)}catch{}ge.delete(E),f(R),ve.delete(E)}}}else if(Y==="transcript_insert"){let E=x.message;if(!E||typeof E!="object")continue;let R=String(E.id??`msg-${d()}`),_=E.role,$={id:R,role:_==="user"?"user":_==="system"?"system":"assistant",content:typeof E.content=="string"?E.content:"",rawContent:typeof E.rawContent=="string"?E.rawContent:void 0,createdAt:typeof E.createdAt=="string"?E.createdAt:new Date().toISOString(),streaming:E.streaming===!0,...typeof E.variant=="string"?{variant:E.variant}:{},sequence:d()};if(f($),$.rawContent)try{let de=JSON.parse($.rawContent)?.props?.artifactId;typeof de=="string"&&xe.add(de)}catch{}m=null,k.current=null,Ne.delete(R),lt.delete(R)}else if(Y==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let E=typeof x.error=="string"?x.error:x.error?.message!=null?String(x.error.message):"Execution error";n({type:"error",error:new Error(E)});let R=m;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}else if(Y==="step_error"||Y==="dispatch_error"||Y==="flow_error"){let E=null;if(x.error instanceof Error)E=x.error;else if(Y==="dispatch_error"){let R=x.message??x.error;R!=null&&R!==""&&(E=new Error(String(R)))}else{let R=x.error;typeof R=="string"&&R!==""?E=new Error(R):R!=null&&typeof R=="object"&&Reflect.has(R,"message")&&(E=new Error(String(R.message??R)))}if(E){n({type:"error",error:E});let R=m;R&&R.streaming&&(R.streaming=!1,f(R)),n({type:"status",status:"idle"})}}}}}ct.length=0};;){let{done:I,value:Y}=await s.read();if(I)break;l+=i.decode(Y,{stream:!0});let x=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()=>{}}},os=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},hp=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},bp=()=>{let t=ih();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)}},yp=()=>{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,lr.parse)(n,lr.STR|lr.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?t=typeof r.text=="string"?fp(r.text):"":r.type==="init"&&r.form?t="":typeof r.text=="string"&&(t=fp(r.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var vp=()=>{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 xp="4.10.0";var rs=xp;var lh="https://api.runtype.com/v1/dispatch",Ai="https://api.runtype.com";function ch(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 bl=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 dh(t){switch(t){case"json":return yp;case"regex-json":return bp;case"xml":return vp;default:return hp}}var Cp=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function ph(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=Cp(n);if(!Cp(o))return t;if(!r||o===n||o.startsWith(n))return e;let i=os(t);return os(e)!==null&&i===null?e:t}var ss=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??lh,this.headers={"Content-Type":"application/json","X-Persona-Version":rs,...e.headers},this.debug=!!e.debug,this.createStreamParser=e.streamParser??dh(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 gi(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=Jd(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$/,"")||Ai}/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":rs},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$/,"")||Ai}/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":rs},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(bl).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":rs},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$/,"")||Ai}/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?Gd(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 b=0;;b++){if(u=await o({...s&&(d||!p)&&n?{clientTools:n}:{},...c?{clientTools:[]}:{},...i?{clientToolsFingerprint:i}:{}}),u.status===409&&b===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(/\/+$/,"")||Ai}/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=[...vi(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:d,commit:u}=await this.sendWithClientToolsDiff(i,c,b=>{let f={...p,...b};return this.debug&&console.debug("[AgentWidgetClient] client token resume",f),fetch(s,{method:"POST",headers:l,body:JSON.stringify(f),signal:o?.signal})},{emptyMeansReplace:!0});return d.ok&&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(bl).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=[...vi(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(bl).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=[...vi(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,S=k.tools?k.tools.map(P=>({...P,chunks:P.chunks?[...P.chunks]:void 0})):void 0;return{...k,reasoning:j,toolCall:v,tools:S}},b=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},f=k=>{b(k)&&n({type:"message",message:u(k)})},m=null,C=null,I={current:null},D={current:null},T=null,A="",W=new Map,z=new Map,U=new Map,w=new Map,O=new Map,N={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},L=k=>{if(k==null)return null;try{return String(k)}catch{return null}},H=k=>L(k.stepId??k.step_id??k.step??k.parentId??k.flowStepId??k.flow_step_id),ne=k=>L(k.callId??k.call_id??k.requestId??k.request_id??k.toolCallId??k.tool_call_id??k.stepId??k.step_id),de=o,me=!1,ue=()=>{if(m)return m;let k,j="",v=T;return!me&&de?(k=de,me=!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()},f(m),m},ee=(k,j)=>{N.lastId=j,k&&N.byStep.set(k,j)},re=(k,j)=>{let v=k.reasoningId??k.id,S=H(k);if(v){let _=String(v);return ee(S,_),_}if(S){let _=N.byStep.get(S);if(_)return N.lastId=_,_}if(N.lastId&&!j)return N.lastId;if(!j)return null;let P=`reason-${d()}`;return ee(S,P),P},G=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),f(v),v},ie=(k,j)=>{R.lastId=j,k&&R.byCall.set(k,j)},te=new Set,ye=new Map,ve=new Set,fe=new Map,Ee=k=>{if(!k)return!1;let j=k.replace(/_+/g,"_").replace(/^_|_$/g,"");return j==="emit_artifact_markdown"||j==="emit_artifact_component"},Te=(k,j)=>{let v=k.toolId??k.id,S=ne(k);if(v){let _=String(v);return ie(S,_),_}if(S){let _=R.byCall.get(S);if(_)return R.lastId=_,_}if(R.lastId&&!j)return R.lastId;if(!j)return null;let P=`tool-${d()}`;return ie(S,P),P},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),f(v),v},Le=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()},Ge=k=>{if(typeof k=="string")return k;if(k==null)return"";try{return JSON.stringify(k)}catch{return String(k)}},Ze=new Map,Be=new Map,Pe=new Map,et=(k,j,v)=>{let S=Pe.get(k);S||(S=[],Pe.set(k,S));let P=0,_=S.length;for(;P<_;){let $=P+_>>>1;S[$].seq<j?P=$+1:_=$}S[P]?.seq===j?S[P]={seq:j,text:v}:S.splice(P,0,{seq:j,text:v});let Q="";for(let $=0;$<S.length;$++)Q+=S[$].text;return Q},dn=(k,j)=>{let v=Ge(j),S=Be.get(k.id),P=ph(S,v);k.rawContent=P;let _=Ze.get(k.id),Q=Ie=>{let dt=k.content??"";Ie.trim()!==""&&(dt.trim().length===0||Ie.startsWith(dt)||Ie.trimStart().startsWith(dt.trim()))&&(k.content=Ie)},$=()=>{if(_){let Ie=_.close?.();Ie instanceof Promise&&Ie.catch(()=>{})}Ze.delete(k.id),Be.delete(k.id),k.streaming=!1,f(k)};if(!_){Q(v),$();return}let K=os(P);if(K!==null&&K.trim()!==""){Q(K),$();return}let ae=Ie=>{let dt=typeof Ie=="string"?Ie:Ie?.text??null;if(dt!==null&&dt.trim()!=="")return dt;let X=_.getExtractedText();return X!==null&&X.trim()!==""?X:v},Qe;try{Qe=_.processChunk(P)}catch{Q(v),$();return}if(Qe instanceof Promise){Qe.then(Ie=>{Q(ae(Ie)),$()}).catch(()=>{Q(v),$()});return}Q(ae(Qe)),$()},Pt=null,xt=(k,j,v,S)=>{k.rawContent=j,Ze.has(k.id)||Ze.set(k.id,this.createStreamParser());let P=Ze.get(k.id),_=j.trim().startsWith("{")||j.trim().startsWith("[");if(_&&Be.set(k.id,j),P.__isPlainTextParser===!0){k.content=S!==void 0?j:k.content+v,Be.delete(k.id),Ze.delete(k.id),k.rawContent=void 0,f(k);return}let $=P.processChunk(j);if($ instanceof Promise)$.then(K=>{let ae=typeof K=="string"?K:K?.text??null;ae!==null&&ae.trim()!==""?(k.content=ae,f(k)):!_&&!j.trim().startsWith("<")&&(k.content=S!==void 0?j:k.content+v,Be.delete(k.id),Ze.delete(k.id),k.rawContent=void 0,f(k))}).catch(()=>{k.content=S!==void 0?j:k.content+v,Be.delete(k.id),Ze.delete(k.id),k.rawContent=void 0,f(k)});else{let K=typeof $=="string"?$:$?.text??null;K!==null&&K.trim()!==""?(k.content=K,f(k)):!_&&!j.trim().startsWith("<")&&(k.content=S!==void 0?j:k.content+v,Be.delete(k.id),Ze.delete(k.id),k.rawContent=void 0,f(k))}},De=(k,j)=>{let v=j??k.content;if(v==null||v===""){k.streaming=!1,f(k);return}let P=Be.get(k.id)??Ge(v);k.rawContent=P;let _=Ze.get(k.id),Q=null,$=!1;if(_&&(Q=_.getExtractedText(),Q===null&&(Q=os(P)),Q===null)){let K=_.processChunk(P);K instanceof Promise?($=!0,K.then(ae=>{let Qe=typeof ae=="string"?ae:ae?.text??null;Qe!==null&&(k.content=Qe,k.streaming=!1,Ze.delete(k.id),Be.delete(k.id),f(k))}).catch(()=>{})):Q=typeof K=="string"?K:K?.text??null}if(!$){Q!==null&&Q.trim()!==""?k.content=Q:Be.has(k.id)||(k.content=Ge(v));let K=Ze.get(k.id);if(K){let ae=K.close?.();ae instanceof Promise&&ae.catch(()=>{}),Ze.delete(k.id)}Be.delete(k.id),k.streaming=!1,f(k)}},we=(k,j,v)=>{let S=z.get(k);if(S)return S;let P={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,P),f(P),P},Je=[],We,xe=new Map,pe=0,Se="agent",Ct=!1,Ae=null,be=null,bn=new Map,Z=this.config.iterationDisplay??"separate";for(We=()=>{for(let k=0;k<Je.length;k++){let j=Je[k].payloadType,v=Je[k].payload;if(!Ct&&Se!=="flow"&&typeof v.stepType=="string"&&(Se="flow"),j==="reasoning_start"){let S=typeof v.id=="string"?v.id:null,P=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(S&&P){W.set(S,P),we(S,P,"reasoning");continue}let _=re(v,!0)??`reason-${d()}`,Q=G(_);Q.reasoning=Q.reasoning??{id:_,status:"streaming",chunks:[]},Q.reasoning.startedAt=Q.reasoning.startedAt??Le(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",f(Q)}else if(j==="reasoning_delta"){let S=typeof v.id=="string"?v.id:null;if(S&&W.has(S)&&z.has(S)){let $=z.get(S),K=v.reasoningText??v.text??v.delta??"";K&&v.hidden!==!0&&$.reasoning&&($.reasoning.chunks.push(String(K)),f($));continue}let P=re(v,!1)??re(v,!0)??`reason-${d()}`,_=G(P);_.reasoning=_.reasoning??{id:P,status:"streaming",chunks:[]},_.reasoning.startedAt=_.reasoning.startedAt??Le(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=et(P,$,String(Q));_.reasoning.chunks=[K]}else _.reasoning.chunks.push(String(Q))}if(_.reasoning.status=v.done?"complete":"streaming",v.done){_.reasoning.completedAt=Le(v.completedAt??v.timestamp);let $=_.reasoning.startedAt??Date.now();_.reasoning.durationMs=Math.max(0,(_.reasoning.completedAt??Date.now())-$)}_.streaming=_.reasoning.status!=="complete",f(_)}else if(j==="reasoning_complete"){let S=typeof v.id=="string"?v.id:null;if(S&&W.has(S)&&z.has(S)){let K=z.get(S);if(K.reasoning){let ae=typeof v.text=="string"?v.text:"";ae&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(ae),K.reasoning.status="complete",K.streaming=!1,f(K)}W.delete(S),z.delete(S);continue}let P=re(v,!1)??re(v,!0)??`reason-${d()}`,_=typeof v.text=="string"?v.text:"";!w.get(P)&&(_||v.scope==="loop")&&G(P);let Q=w.get(P);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=Le(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,f(Q)}let $=H(v);$&&N.byStep.delete($)}else if(j==="tool_start"){m&&(m.streaming=!1,f(m),m=null),typeof v.iteration=="number"&&(pe=v.iteration);let S=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??Te(v,!0)??`tool-${d()}`,P=v.toolName??v.name;if(Ee(P)){te.add(S);continue}ie(ne(v),S);let _=Fe(S),Q=_.toolCall??{id:S,status:"pending"};Q.name=P??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??Le(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}),f(_)}else if(j==="tool_output_delta"){let S=Te(v,!1)??Te(v,!0)??`tool-${d()}`;if(te.has(S))continue;let P=Fe(S),_=P.toolCall??{id:S,status:"running"};_.startedAt=_.startedAt??Le(v.startedAt??v.timestamp);let Q=v.text??v.delta??v.message??"";Q&&(_.chunks=_.chunks??[],_.chunks.push(String(Q))),_.status="running",P.toolCall=_,P.streaming=!0;let $=v.agentContext;($||v.executionId)&&(P.agentMetadata=P.agentMetadata??{executionId:$?.executionId??v.executionId,iteration:$?.iteration??v.iteration}),f(P)}else if(j==="tool_complete"){let S=Te(v,!1)??Te(v,!0)??`tool-${d()}`;if(te.has(S)){te.delete(S);continue}let P=Fe(S),_=P.toolCall??{id:S,status:"running"};_.status="complete",v.result!==void 0&&(_.result=v.result),typeof v.duration=="number"&&(_.duration=v.duration),_.completedAt=Le(v.completedAt??v.timestamp);let Q=v.duration??v.executionTime;if(typeof Q=="number")_.durationMs=Q;else{let ae=_.startedAt??Date.now();_.durationMs=Math.max(0,(_.completedAt??Date.now())-ae)}P.toolCall=_,P.streaming=!1;let $=v.agentContext;($||v.executionId)&&(P.agentMetadata=P.agentMetadata??{executionId:$?.executionId??v.executionId,iteration:$?.iteration??v.iteration}),f(P);let K=ne(v);K&&R.byCall.delete(K)}else if(j==="await"&&v.toolName){let S=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,P=S??v.toolId??`local-${d()}`,_=Fe(P),Q=v.toolName,$=v.origin==="webmcp"&&!or(Q)?`webmcp:${Q}`:Q,K=or($),ae=_.toolCall??{id:P,status:"pending"};ae.name=$,ae.args=v.parameters,ae.status=K?"running":"complete",ae.chunks=ae.chunks??[],ae.startedAt=ae.startedAt??Le(v.startedAt??v.timestamp??v.awaitedAt),K?(ae.completedAt=void 0,ae.duration=void 0,ae.durationMs=void 0):ae.completedAt=ae.completedAt??ae.startedAt,_.toolCall=ae,_.streaming=!1,_.agentMetadata={..._.agentMetadata,executionId:v.executionId??_.agentMetadata?.executionId,awaitingLocalTool:!0,...S?{webMcpToolCallId:S}:{}},f(_)}else if(j==="text_start"){let S=typeof v.id=="string"?v.id:null,P=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(S&&P){W.set(S,P);continue}let _=m;_&&(Se==="flow"?(De(_),Pt=_):(_.streaming=!1,f(_)),m=null),T=typeof v.id=="string"?v.id:T,A=""}else if(j==="text_delta"){let S=typeof v.id=="string"?v.id:null,P=S?W.get(S):void 0;if(S&&P){let Q=typeof v.delta=="string"?v.delta:"",$=(U.get(S)??"")+Q;if(U.set(S,$),$.trim()==="")continue;let K=we(S,P);K.agentMetadata={...K.agentMetadata,executionId:v.executionId,parentToolId:P},xt(K,$,Q,void 0);continue}if(T=typeof v.id=="string"?v.id:T,Se==="flow"){let Q=typeof v.delta=="string"?v.delta:"";if(A+=Q,A.trim()==="")continue;let $=ue();$.agentMetadata={executionId:v.executionId,iteration:v.iteration},xt($,A,Q,void 0),C=$;continue}let _=ue();_.content+=v.delta??"",_.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:Ae??void 0,agentName:be?.agentName},C=_,f(_)}else if(j==="text_complete"){let S=typeof v.id=="string"?v.id:null;if(S&&W.has(S)){let _=z.get(S);_&&De(_),W.delete(S),U.delete(S),z.delete(S);continue}let P=m;P&&(Se==="flow"?(De(P),Pt=P):((P.content??"")===""&&typeof v.text=="string"&&(P.content=v.text),P.streaming=!1,f(P)),m=null),T=null,A=""}else if(j==="step_complete"){let S=v.stepType,P=v.executionType;if(S==="tool"||P==="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,f($)),n({type:"status",status:"idle"});continue}{let _=Pt;Pt=null;let Q=v.stopReason,$=v.result?.response;if(_)Q&&(_.stopReason=Q),$!=null?dn(_,$):_.streaming!==!1&&(Ze.delete(_.id),Be.delete(_.id),_.streaming=!1,f(_));else{let K=$!=null&&$!=="";if(K||Q){let ae=ue();Q&&(ae.stopReason=Q),K?De(ae,$):(ae.streaming=!1,f(ae))}}continue}}else if(j==="execution_start")Se=v.kind==="flow"?"flow":"agent",Ct=!0,Se==="agent"&&(be={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:Le(v.startedAt)});else if(j==="turn_start"){let S=typeof v.iteration=="number"?v.iteration:pe;if(S!==pe){if(be&&(be.currentIteration=S),Z==="separate"&&S>1){let P=m;P&&(P.streaming=!1,f(P),bn.set(S-1,P),m=null)}pe=S}Ae=typeof v.id=="string"?v.id:null,C=null}else if(j==="tool_input_delta"){let S=v.toolCallId??R.lastId;if(S){let P=O.get(S);P?.toolCall&&(P.toolCall.chunks=P.toolCall.chunks??[],P.toolCall.chunks.push(v.delta??""),f(P))}}else{if(j==="tool_input_complete")continue;if(j==="turn_complete"){let S=v.stopReason,P=m??C;if(S&&P!==null){let _=v.id;(!_||P.agentMetadata?.turnId===_)&&(P.stopReason=S,f(P))}Ae===v.id&&(Ae=null)}else if(j==="media_start"){let S=String(v.id);xe.set(S,{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 S=xe.get(String(v.id));S&&typeof v.delta=="string"&&S.parts.push(v.delta)}else if(j==="media_complete"){let S=String(v.id),P=xe.get(S);xe.delete(S);let _=(typeof v.mediaType=="string"?v.mediaType:void 0)??P?.mediaType??"application/octet-stream",Q=typeof v.data=="string"?v.data:void 0,$=typeof v.url=="string"?v.url:P&&P.parts.length>0?P.parts.join(""):void 0,K=null;if(Q)K={type:"media",data:Q,mediaType:_};else if($){let dt=_.toLowerCase();K={type:dt==="image"||dt.startsWith("image/")?"image-url":"file-url",url:$,mediaType:_}}let ae=v.toolCallId??P?.toolCallId,Qe=K?[K]:[],Ie=[];for(let dt of Qe){if(!dt||typeof dt!="object")continue;let X=dt,ze=typeof X.type=="string"?X.type:void 0,Re=typeof X.mediaType=="string"?X.mediaType.toLowerCase():"",Ne=null,He="";if(ze==="media"){let tt=typeof X.data=="string"?X.data:void 0;if(!tt)continue;He=Re.length>0?Re:"application/octet-stream",Ne=`data:${He};base64,${tt}`}else if(ze==="image-url"){let tt=typeof X.url=="string"?X.url:void 0;if(!tt)continue;He=Re,Ne=tt}else if(ze==="file-url"){let tt=typeof X.url=="string"?X.url:void 0;if(!tt)continue;He=Re,Ne=tt}else continue;if(Ne)if(ze==="image-url"||He.startsWith("image/"))Ie.push({type:"image",image:Ne,...He.includes("/")?{mimeType:He}:{}});else if(He.startsWith("audio/"))Ie.push({type:"audio",audio:Ne,mimeType:He});else if(He.startsWith("video/"))Ie.push({type:"video",video:Ne,mimeType:He});else{let tt=He||"application/octet-stream";Ie.push({type:"file",data:Ne,mimeType:tt,filename:ch(tt)})}}if(Ie.length>0){let dt=d(),X=ae,Re={id:`agent-media-${typeof X=="string"&&X.length>0?`${X}-${dt}`:String(dt)}`,role:"assistant",content:"",contentParts:Ie,createdAt:new Date().toISOString(),streaming:!1,sequence:dt,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:pe}};f(Re);let Ne=m;Ne&&(Ne.streaming=!1,f(Ne)),m=null,I.current=null}}else if(j==="execution_complete"){let S=v.kind??Se;S==="agent"&&be&&(be.status=v.success?"complete":"error",be.completedAt=Le(v.completedAt),be.stopReason=v.stopReason);let P=m;P&&(S==="flow"&&P.streaming!==!1?De(P):(P.streaming=!1,f(P)),m=null),T=null,A="",Pt=null,n({type:"status",status:"idle",terminal:!0})}else if(j==="execution_error"){let S=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(S)})}else if(j!=="ping"){if(j==="approval_start"){let S=v.approvalId??`approval-${d()}`,P={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:S,status:"pending",agentId:be?.agentId??"virtual",executionId:v.executionId??be?.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}};f(P)}else if(j==="step_await"&&v.awaitReason==="approval_required"){let S=v.approvalId??`approval-${d()}`,P={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:S,status:"pending",agentId:be?.agentId??"virtual",executionId:v.executionId??be?.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}};f(P)}else if(j==="approval_complete"){let S=v.approvalId;if(S){let _={id:`approval-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:d(),approval:{id:S,status:v.decision??"approved",agentId:be?.agentId??"virtual",executionId:v.executionId??be?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};f(_)}}else if(j==="artifact_start"||j==="artifact_delta"||j==="artifact_update"||j==="artifact_complete"){if(j==="artifact_start"){let S=v.artifactType,P=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:P,artifactType:S,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(P,{markdown:"",title:_,file:$,...K?{props:K}:{}}),!ve.has(P)){ve.add(P);let ae=Wo(this.config.features?.artifacts,S),Qe=typeof v.component=="string"?v.component:void 0,Ie={id:`artifact-ref-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:d(),rawContent:mi(ae,{artifactId:P,title:_,artifactType:S,status:"streaming",...$?{file:$}:{},...Qe?{component:Qe}:{}})};ye.set(P,Ie),f(Ie)}}else if(j==="artifact_delta"){let S=String(v.id),P=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:S,artDelta:P});let _=fe.get(S);_&&(_.markdown+=P)}else if(j==="artifact_update"){let S=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:S,component:typeof v.component=="string"?v.component:void 0});let P=fe.get(String(v.id));P&&(P.props={...P.props??{},...S})}else if(j==="artifact_complete"){let S=String(v.id);n({type:"artifact_complete",id:S});let P=ye.get(S);if(P){P.streaming=!1;try{let _=JSON.parse(P.rawContent??"{}");if(_.props){_.props.status="complete";let Q=fe.get(S);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)}P.rawContent=JSON.stringify(_)}catch{}fe.delete(S),f(P),ye.delete(S)}}}else if(j==="transcript_insert"){let S=v.message;if(!S||typeof S!="object")continue;let P=String(S.id??`msg-${d()}`),_=S.role,$={id:P,role:_==="user"?"user":_==="system"?"system":"assistant",content:typeof S.content=="string"?S.content:"",rawContent:typeof S.rawContent=="string"?S.rawContent:void 0,createdAt:typeof S.createdAt=="string"?S.createdAt:new Date().toISOString(),streaming:S.streaming===!0,...typeof S.variant=="string"?{variant:S.variant}:{},sequence:d()};if(f($),$.rawContent)try{let ae=JSON.parse($.rawContent)?.props?.artifactId;typeof ae=="string"&&ve.add(ae)}catch{}m=null,I.current=null,Ze.delete(P),Be.delete(P)}else if(j==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let S=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(S)});let P=m;P&&P.streaming&&(P.streaming=!1,f(P)),n({type:"status",status:"idle"})}}else if(j==="step_error"||j==="dispatch_error"||j==="flow_error"){let S=null;if(v.error instanceof Error)S=v.error;else if(j==="dispatch_error"){let P=v.message??v.error;P!=null&&P!==""&&(S=new Error(String(P)))}else{let P=v.error;typeof P=="string"&&P!==""?S=new Error(P):P!=null&&typeof P=="object"&&Reflect.has(P,"message")&&(S=new Error(String(P.message??P)))}if(S){n({type:"error",error:S});let P=m;P&&P.streaming&&(P.streaming=!1,f(P)),n({type:"status",status:"idle"})}}}}}Je.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
|
-
`);l=
|
|
187
|
-
`),_="message",J="",$=null;for(let Ie of R)Ie.startsWith("event:")?_=Ie.replace("event:","").trim():Ie.startsWith("data:")?J+=Ie.replace("data:","").trim():Ie.startsWith("id:")&&($=Ie.slice(3).trim());let G=()=>{$!==null&&$!==""&&n({type:"cursor",id:$})};if(!J){G();continue}let de;try{de=JSON.parse(J)}catch(Ie){n({type:"error",error:Ie instanceof Error?Ie:new Error("Failed to parse chat stream payload")});continue}let ot=_!=="message"?_:de.type??"message";if(this.onSSEEvent?.(ot,de),this.parseSSEEvent){k.current=m;let Ie=await this.handleCustomSSEEvent(de,n,k,f,d,D);if(k.current&&k.current!==m&&(m=k.current),Ie){G();continue}}ct.push({payloadType:ot,payload:de}),He(),G()}}He()}};function Si(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function dr(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var Mi="[Image]";function Cp(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function pr(t){return{type:"text",text:t}}var wp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ch=["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"],zn=[...wp,...ch];function dh(t){return wp.includes(t)||t.startsWith("image/")}function Ti(t){return dh(t.type)}async function Ap(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ti(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 Sp(t,e=zn,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 ph(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Mp(t,e){let n=ph(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"}bl();var Tp=16e3,uh=24e3,fh=4096,gh=1380533830;function mh(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===gh?new Uint8Array(t,44):new Uint8Array(t)}function hh(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 is=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:Tp,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:Tp});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new ur(uh);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=`${hh(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 b=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${b}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let i=e.createScriptProcessor(fh,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=mh(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 Do=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 fr(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new is(t.runtype);case"browser":if(!Do.isSupported())throw new Error("Browser speech recognition not supported");return new Do(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 Ep(t){if(t?.type==="custom"&&t.custom)return fr({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return fr({type:"runtype",runtype:t.runtype});if(Do.isSupported())return fr({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function yl(t){try{return Ep(t),!0}catch{return!1}}function Ei(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 gr=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):Ei(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 as=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 vl(t){if(!t)return"";let e=bh(t);return kp(e!==null?e:t)}function bh(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 kp(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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|
|
186
|
+
`);l=v.pop()??"";for(let S of v){let P=S.split(`
|
|
187
|
+
`),_="message",Q="",$=null;for(let Ie of P)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 ae;try{ae=JSON.parse(Q)}catch(Ie){n({type:"error",error:Ie instanceof Error?Ie:new Error("Failed to parse chat stream payload")});continue}let Qe=_!=="message"?_:ae.type??"message";if(this.onSSEEvent?.(Qe,ae),this.parseSSEEvent){I.current=m;let Ie=await this.handleCustomSSEEvent(ae,n,I,f,d,D);if(I.current&&I.current!==m&&(m=I.current),Ie){K();continue}}Je.push({payloadType:Qe,payload:ae}),We(),K()}}We()}};function Si(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function cr(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var Mi="[Image]";function wp(t){return typeof t=="string"?!1:t.some(e=>e.type==="image")}function dr(t){return{type:"text",text:t}}var Ap=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],uh=["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"],zn=[...Ap,...uh];function fh(t){return Ap.includes(t)||t.startsWith("image/")}function Ti(t){return fh(t.type)}async function Sp(t){return new Promise((e,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ti(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 Mp(t,e=zn,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 gh(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Tp(t,e){let n=gh(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"}yl();var Ep=16e3,mh=24e3,hh=4096,bh=1380533830;function yh(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===bh?new Uint8Array(t,44):new Uint8Array(t)}function vh(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 is=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:Ep,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:Ep});l.state==="suspended"&&await l.resume().catch(()=>{}),this.captureContext=l;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new pr(mh);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=`${vh(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 b=u.code?` (code ${u.code})`:"";this.emitError(new Error(`Voice connection closed${b}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(s){throw this.cleanup(),this.emitError(s),this.emitStatus("error"),s}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,n,o,r){let s=e.createMediaStreamSource(n);this.sourceNode=s;let i=e.createScriptProcessor(hh,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=yh(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 Do=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 ur(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new is(t.runtype);case"browser":if(!Do.isSupported())throw new Error("Browser speech recognition not supported");return new Do(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 kp(t){if(t?.type==="custom"&&t.custom)return ur({type:"custom",custom:t.custom});if(t?.type==="runtype"&&t.runtype)return ur({type:"runtype",runtype:t.runtype});if(Do.isSupported())return ur({type:"browser",browser:t?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function vl(t){try{return kp(t),!0}catch{return!1}}function Ei(t){let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let n of e){let o=t.find(r=>r.name===n);if(o)return o}return t.find(n=>n.lang.startsWith("en"))??t[0]}var fr=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(e,n){if(!t.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(e.text),s=o.getVoices();if(e.voice){let i=s.find(l=>l.name===e.voice);i&&(r.voice=i)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):Ei(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 as=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 xl(t){if(!t)return"";let e=xh(t);return Lp(e!==null?e:t)}function xh(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 Lp(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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|
|
188
188
|
`),e=e.replace(/\n{2,}/g,`
|
|
189
|
-
`),e.trim()}var
|
|
189
|
+
`),e.trim()}var Hp=null;var Cl=()=>Hp?Hp():Promise.resolve().then(()=>(Wp(),Rp));var Mh=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Th(t,e){return Mh.some(n=>t[n]!==e[n])}function wl(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
|
|
|
191
|
-
_Details: ${n.message}_`:o}var ls=t=>({isError:!0,content:[{type:"text",text:t}]}),Dp=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Np=t=>rr(t)||t===$n,Pi=class{constructor(e={},n){this.config=e;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new as(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(rr(n.name)||n.name===$n&&this.config.features?.suggestReplies?.enabled!==!1);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.messages=[...e.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new ss(e),this.wireDefaultWebMcpConfirm();for(let o of e.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||xl().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return yl(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=gr.isSupported()?new gr({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,i=e.browserFallback!==!1;if(o&&r&&s)return xl().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let c=new l({host:o,agentId:r,clientToken:s,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return i&&n?new p(c,n,{onFallback:d=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${d.message}`)}):c});if(i&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=fr(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,i,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:i,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:i,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:i,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}updateConfig(e){let n={...this.config,...e};if(!Ah(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=n,this.client=new ss(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:r,contentParts:s,id:i,createdAt:l,sequence:p,streaming:c=!1,voiceProcessing:d,rawContent:u}=e,f={id:i??(n==="user"?Si():n==="assistant"?dr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:c,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...d!==void 0&&{voiceProcessing:d},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:r,content:s,llmContent:i,contentParts:l,id:p,createdAt:c,sequence:d,streaming:u=!1,voiceProcessing:b,rawContent:f}=o,C={id:p??(r==="user"?Si():r==="assistant"?dr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:c??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:u,...i!==void 0&&{llmContent:i},...l!==void 0&&{contentParts:l},...b!==void 0&&{voiceProcessing:b},...f!==void 0&&{rawContent:f}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:r="",llmContent:s,id:i,createdAt:l,sequence:p}=e,c={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...i!==void 0&&{id:i},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(e,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
191
|
+
_Details: ${n.message}_`:o}var ls=t=>({isError:!0,content:[{type:"text",text:t}]}),Np=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,Op=t=>or(t)||t===$n,Pi=class{constructor(e={},n){this.config=e;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new as(()=>this.createSpeechEngine());this.handleEvent=e=>{if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let n=e.message.toolCall,o=!!n?.name&&(or(n.name)||n.name===$n&&this.config.features?.suggestReplies?.enabled!==!1);e.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(e.message),e.message.agentMetadata?.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:e.message.agentMetadata.agentName??"",status:"running",currentIteration:e.message.agentMetadata.iteration??0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let n=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;this.agentExecution?.status==="running"&&(e.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),this.agentExecution?.status==="running"&&(this.agentExecution.status="error"),this.callbacks.onError?.(e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};this.messages=[...e.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new ss(e),this.wireDefaultWebMcpConfirm();for(let o of e.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let e=this.config.textToSpeech;if(e?.provider!=="runtype"||e.createEngine)return;let n=e.host??this.config.apiUrl,o=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||Cl().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return vl(this.config.voiceRecognition?.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){return this.voiceProvider?.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){this.voiceProvider?.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){return this.voiceProvider?.isBargeInActive?.()??!1}async deactivateBargeIn(){this.voiceProvider?.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){let e=this.config.textToSpeech;if(e?.createEngine)return e.createEngine();let n=fr.isSupported()?new fr({pickVoice:e?.pickVoice}):null;if(e?.provider==="runtype"){let o=e.host??this.config.apiUrl,r=e.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,i=e.browserFallback!==!1;if(o&&r&&s)return Cl().then(({RuntypeSpeechEngine:l,FallbackSpeechEngine:p})=>{let c=new l({host:o,agentId:r,clientToken:s,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return i&&n?new p(c,n,{onFallback:d=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${d.message}`)}):c});if(i&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){try{let n=e||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=ur(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,i,l)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:i,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:i,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:i,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(s=>{this.config.voiceRecognition?.onMetrics?.(s)}),this.voiceProvider.onError(s=>{console.error("Voice error:",s),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:r,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(s=>{this.voiceStatus=s,this.voiceActive=s==="listening",this.callbacks.onVoiceStatusChanged?.(s)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:e.runtype?.agentId??this.config.agentId??"",clientToken:e.runtype?.clientToken??this.config.clientToken,host:e.runtype?.host??this.config.apiUrl,voiceId:e.runtype?.voiceId,createPlaybackEngine:e.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:e.browser?.language||"en-US",continuous:e.browser?.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return this.callbacks.onError?.(e instanceof Error?e:new Error(String(e))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}updateConfig(e){let n={...this.config,...e};if(!Th(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=n,this.client=new ss(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:o,llmContent:r,contentParts:s,id:i,createdAt:l,sequence:p,streaming:c=!1,voiceProcessing:d,rawContent:u}=e,f={id:i??(n==="user"?Si():n==="assistant"?cr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:l??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:c,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...d!==void 0&&{voiceProcessing:d},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let o of e){let{role:r,content:s,llmContent:i,contentParts:l,id:p,createdAt:c,sequence:d,streaming:u=!1,voiceProcessing:b,rawContent:f}=o,C={id:p??(r==="user"?Si():r==="assistant"?cr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:c??new Date().toISOString(),sequence:d??this.nextSequence(),streaming:u,...i!==void 0&&{llmContent:i},...l!==void 0&&{contentParts:l},...b!==void 0&&{voiceProcessing:b},...f!==void 0&&{rawContent:f}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:o={},text:r="",llmContent:s,id:i,createdAt:l,sequence:p}=e,c={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...i!==void 0&&{id:i},...l!==void 0&&{createdAt:l},...p!==void 0&&{sequence:p}})}async applyMentionBundle(e,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
|
|
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(pr(s)),c.push(...r.contentParts),c.push(...e.contentParts),e.contentParts=c}else if(p){let c=[];i&&c.push(pr(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=Si(),s=dr();this.activeAssistantMessageId=null;let i=n?.contentParts&&Cp(n.contentParts)?Mi:"",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 b=Cl(d,this.config.errorMessage);if(b){let f={id:s,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,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=dr();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=Cl(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 b=await d.json().catch(()=>null);throw new Error(b?.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 b=typeof u[0]?.question=="string"?u[0].question:"";b&&(i={[b]:n})}}this.markAskUserQuestionResolved(e,i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,p=e.toolCall?.args,c=Array.isArray(p?.questions)?p.questions:[];if(c.length===0){let d=typeof n=="string"?n:Object.entries(n).map(([u,b])=>`${u}: ${Array.isArray(b)?b.join(", "):b}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let d=i??{};c.forEach((u,b)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let m=d[f],C=Array.isArray(m)?m.join(", "):typeof m=="string"?m:"";this.appendMessage({id:`ask-user-q-${l}-${b}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${b}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let d=await this.client.resumeFlow(r,{[s]:n});if(!d.ok){let 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 b=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??c;if(c===$n)return{dedupeKey:u,resumeKey:f,output:fl(),toolMessage:p,startedAt:b,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),k;if(!C)k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{k=await C}catch(D){let M=D instanceof Error&&(D.name==="AbortError"||D.message.includes("aborted")||D.message.includes("abort"));return M||this.callbacks.onError?.(D instanceof Error?D:new Error(String(D))),this.markWebMcpToolComplete(p,ls(M?"Aborted by cancel()":Dp(D)),b),this.webMcpInflightKeys.delete(u),null}return m.signal.aborted?(this.markWebMcpToolComplete(p,ls("Aborted by cancel()"),b),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:k,toolMessage:p,startedAt:b,completedAt:Date.now()}})),l=[];try{if(l=i.filter(d=>d!==null),l.length===0)return;let p={};for(let d of l)p[d.resumeKey]=d.output;let c=await this.client.resumeFlow(e,p,{signal:s.signal});if(!c.ok){let d=await c.json().catch(()=>null);throw new Error(d?.error??`Resume failed: ${c.status}`)}for(let d of l)this.webMcpResolvedKeys.add(d.dedupeKey),this.markWebMcpToolComplete(d.toolMessage,d.output,d.startedAt,d.completedAt,d.toolMessage.toolCall?.name===$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,ls("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),b="execute",f=i;try{let m;if(c?m=fl():u?m=await u:m={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(e,ls("Aborted by cancel()"),i);return}let C=e.agentMetadata?.webMcpToolCallId??o;b="resume",await this.resumeWithToolOutput(n,C,m,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,m,i,f,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"));(b==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(e,ls(C||p.aborted?"Aborted by cancel()":Dp(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=Wo(this.config.features?.artifacts,e.artifactType),r=mi(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(()=>(Bp(),Hp)).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=>Cl(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=dr(),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=vl(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Ei(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=vl(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&&Np(l)&&p&&c&&n.agentMetadata?.awaitingLocalTool===!0){let d=`${p}:${c}`,u=this.webMcpInflightKeys.has(d),b=this.webMcpResolvedKeys.has(d),f=r.toolCall?.name,m=r.agentMetadata?.executionId===p&&r.toolCall?.id===c&&f!==void 0&&Np(f)&&r.toolCall?.status==="complete";(u||b||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();kt();var Ii={allowedTypes:zn,maxFileSize:10*1024*1024,maxFiles:4};function Th(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Eh(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 cs=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:e.allowedTypes??Ii.allowedTypes,maxFileSize:e.maxFileSize??Ii.maxFileSize,maxFiles:e.maxFiles??Ii.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:Ii.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=Sp(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 Ap(n),s=Ti(n)?URL.createObjectURL(n):null,i={id:Th(),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=Ti(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=Eh(e.file.type),p=se(l,20,"var(--persona-muted, #6b7280)",1.5);p&&i.appendChild(p);let c=h("span");c.textContent=Mp(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();Ri();wl();nt();kt();function $p(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=Ce("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);d?c.appendChild(d):c.textContent="+",c.addEventListener("click",b=>{b.preventDefault(),b.stopPropagation(),n()}),p.appendChild(c);let u=h("div","persona-send-button-tooltip");return u.textContent=l,p.appendChild(u),{button:c,wrapper:p}}var{setLoader:UC,load:Nh}=or({fallbackImport:()=>Promise.resolve().then(()=>(lu(),au))});var Ll=Nh;var{setLoader:tw,load:Kh}=or({fallbackImport:()=>Promise.resolve().then(()=>(xu(),vu)),resetOnSetLoader:!0});var Cu=Kh;nt();kt();function ms(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=Ce("span",{className:_n("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(Ce("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function wu(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=Wi(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(dr(s)),c.push(...r.contentParts),c.push(...e.contentParts),e.contentParts=c}else if(p){let c=[];i&&c.push(dr(i)),c.push(...r.contentParts),e.contentParts=c}else s&&(e.llmContent=i);Object.keys(r.context).length>0&&(e.mentionContext=r.context)}async sendMessage(e,n){let o=e.trim();if(!o&&(!n?.contentParts||n.contentParts.length===0)&&(!n?.mentions||n.mentions.refs.length===0))return;this.stopSpeaking(),this.abortController?.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let r=Si(),s=cr();this.activeAssistantMessageId=null;let i=n?.contentParts&&wp(n.contentParts)?Mi:"",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 b=wl(d,this.config.errorMessage);if(b){let f={id:s,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,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=cr();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=wl(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 b=await d.json().catch(()=>null);throw new Error(b?.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 b=typeof u[0]?.question=="string"?u[0].question:"";b&&(i={[b]:n})}}this.markAskUserQuestionResolved(e,i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let l=e.toolCall.id,p=e.toolCall?.args,c=Array.isArray(p?.questions)?p.questions:[];if(c.length===0){let d=typeof n=="string"?n:Object.entries(n).map(([u,b])=>`${u}: ${Array.isArray(b)?b.join(", "):b}`).join(" | ");this.appendMessage({id:`ask-user-answer-${l}`,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let d=i??{};c.forEach((u,b)=>{let f=typeof u?.question=="string"?u.question:"";if(!f)return;let m=d[f],C=Array.isArray(m)?m.join(", "):typeof m=="string"?m:"";this.appendMessage({id:`ask-user-q-${l}-${b}`,role:"assistant",content:f,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${l}-${b}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let d=await this.client.resumeFlow(r,{[s]:n});if(!d.ok){let 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 b=this.markWebMcpToolRunning(p),f=p.agentMetadata?.webMcpToolCallId??c;if(c===$n)return{dedupeKey:u,resumeKey:f,output:gl(),toolMessage:p,startedAt:b,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),I;if(!C)I={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{I=await C}catch(D){let T=D instanceof Error&&(D.name==="AbortError"||D.message.includes("aborted")||D.message.includes("abort"));return T||this.callbacks.onError?.(D instanceof Error?D:new Error(String(D))),this.markWebMcpToolComplete(p,ls(T?"Aborted by cancel()":Np(D)),b),this.webMcpInflightKeys.delete(u),null}return m.signal.aborted?(this.markWebMcpToolComplete(p,ls("Aborted by cancel()"),b),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:f,output:I,toolMessage:p,startedAt:b,completedAt:Date.now()}})),l=[];try{if(l=i.filter(d=>d!==null),l.length===0)return;let p={};for(let d of l)p[d.resumeKey]=d.output;let c=await this.client.resumeFlow(e,p,{signal:s.signal});if(!c.ok){let d=await c.json().catch(()=>null);throw new Error(d?.error??`Resume failed: ${c.status}`)}for(let d of l)this.webMcpResolvedKeys.add(d.dedupeKey),this.markWebMcpToolComplete(d.toolMessage,d.output,d.startedAt,d.completedAt,d.toolMessage.toolCall?.name===$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,ls("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),b="execute",f=i;try{let m;if(c?m=gl():u?m=await u:m={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),p.aborted){this.markWebMcpToolComplete(e,ls("Aborted by cancel()"),i);return}let C=e.agentMetadata?.webMcpToolCallId??o;b="resume",await this.resumeWithToolOutput(n,C,m,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,m,i,f,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"));(b==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(e,ls(C||p.aborted?"Aborted by cancel()":Np(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=Wo(this.config.features?.artifacts,e.artifactType),r=mi(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(()=>(Dp(),Bp)).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=>wl(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=cr(),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=xl(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Ei(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let o=xl(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&&Op(l)&&p&&c&&n.agentMetadata?.awaitingLocalTool===!0){let d=`${p}:${c}`,u=this.webMcpInflightKeys.has(d),b=this.webMcpResolvedKeys.has(d),f=r.toolCall?.name,m=r.agentMetadata?.executionId===p&&r.toolCall?.id===c&&f!==void 0&&Op(f)&&r.toolCall?.status==="complete";(u||b||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)})}};st();Et();var Ii={allowedTypes:zn,maxFileSize:10*1024*1024,maxFiles:4};function Lh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ph(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 cs=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:e.allowedTypes??Ii.allowedTypes,maxFileSize:e.maxFileSize??Ii.maxFileSize,maxFiles:e.maxFiles??Ii.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:Ii.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=Mp(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 Sp(n),s=Ti(n)?URL.createObjectURL(n):null,i={id:Lh(),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=Ti(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=Ph(e.file.type),p=se(l,20,"var(--persona-muted, #6b7280)",1.5);p&&i.appendChild(p);let c=h("span");c.textContent=Tp(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})}};st();Ri();Al();st();Et();function zp(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=Ce("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);d?c.appendChild(d):c.textContent="+",c.addEventListener("click",b=>{b.preventDefault(),b.stopPropagation(),n()}),p.appendChild(c);let u=h("div","persona-send-button-tooltip");return u.textContent=l,p.appendChild(u),{button:c,wrapper:p}}var{setLoader:KC,load:_h}=nr({fallbackImport:()=>Promise.resolve().then(()=>(cu(),lu))});var Pl=_h;var{setLoader:sw,load:Xh}=nr({fallbackImport:()=>Promise.resolve().then(()=>(Cu(),xu)),resetOnSetLoader:!0});var wu=Xh;st();Et();function ms(t,e={}){if(e.render)return e.render({ref:t,readonly:!!e.readonly});let n=Ce("span",{className:_n("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(Ce("span",{className:"persona-mention-token-label",text:`@${t.label}`})),n}function Au(t){let e=t.config.contextMentions;if(!e?.enabled)return null;let n=Wi(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(U=>U.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=Ce("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,c=t.textarea,d=null,u=null,b=null,f=null,m=()=>{if(l)return Promise.resolve(l);if(p)return p;let A=Ll().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:M,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=()=>{Cu().then(A=>{let W=A.mountInlineComposer({textarea:t.textarea,renderToken:U=>ms(U,{render:e.renderMentionToken}),onMentionRemoved:U=>l?.untrackMention(U)});d=W.input,u=W.destroy;let z=c;z.replaceWith(W.element),c=W.element,f={next:W.element,prev:z},b?.(W.element,z),l?l.rebindComposer(W.input):p&&p.then(U=>U?.rebindComposer(W.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};e.display==="inline"&&C();let k=[],D=new Map;for(let A of n){if(!A.showButton)continue;let W=$p({config:{...e,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},buttonSize:t.config.sendButton?.size,onOpen:()=>{m().then(z=>z?.openMenu(A.trigger))}});k.push(W),D.set(A.trigger,W.button)}let M=(A,W,z)=>{let U=D.get(W);U&&(U.setAttribute("aria-expanded",A?"true":"false"),A?U.setAttribute("aria-controls",z):U.removeAttribute("aria-controls"))};return{affordanceButtons:k.map(A=>A.wrapper),contextRow:i,handleInput:A=>{if(l){l.handleInput();return}if(!Fp(A))return;let W=c,z=W.selectionStart??0;ds(W.value,z,n)&&m().then(U=>U?.handleInput())},handleKeydown:A=>{if(l?.isMenuOpen())return l.handleKeydown(A);if(A.key==="Backspace"&&l?.hasMentions()&&!f){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:()=>{Ll().catch(()=>{})},onComposerSwap:A=>{b=A,f&&A(f.next,f.prev)},destroy:()=>{l?.destroy(),u?.();for(let A of k)A.wrapper.remove();i.remove()}}}var Au=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function hs(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];Au(s)&&Au(r)?n[o]=hs(s,r):n[o]=r}return n}var Un="min(440px, calc(100vw - 24px))",Mu="440px",Gh={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:Un,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)"},ut={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:Gh,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 Su(t,e){if(!(!t&&!e))return t?e?hs(t,e):t:e}function Tu(t){return t?{...ut,...t,theme:Su(ut.theme,t.theme),darkTheme:Su(ut.darkTheme,t.darkTheme),launcher:{...ut.launcher,...t.launcher,dock:{...ut.launcher?.dock,...t.launcher?.dock},clearChat:{...ut.launcher?.clearChat,...t.launcher?.clearChat}},copy:{...ut.copy,...t.copy},sendButton:{...ut.sendButton,...t.sendButton},statusIndicator:{...ut.statusIndicator,...t.statusIndicator},voiceRecognition:{...ut.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=ut.features?.artifacts,n=t.features?.artifacts,o=ut.features?.scrollToBottom,r=t.features?.scrollToBottom,s=ut.features?.scrollBehavior,i=t.features?.scrollBehavior,l=ut.features?.streamAnimation,p=t.features?.streamAnimation,c=ut.features?.askUserQuestion,d=t.features?.askUserQuestion,u=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},b=o===void 0&&r===void 0?void 0:{...o,...r},f=s===void 0&&i===void 0?void 0:{...s,...i},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{...ut.features,...t.features,...b!==void 0?{scrollToBottom:b}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...m!==void 0?{streamAnimation:m}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:t.suggestionChips??ut.suggestionChips,suggestionChipsConfig:{...ut.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...ut.layout,...t.layout,header:{...ut.layout?.header,...t.layout?.header},messages:{...ut.layout?.messages,...t.layout?.messages,avatar:{...ut.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...ut.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...ut.layout?.slots,...t.layout?.slots}},markdown:{...ut.markdown,...t.markdown,options:{...ut.markdown?.options,...t.markdown?.options}},messageActions:{...ut.messageActions,...t.messageActions}}:ut}var qi="16px",Vi="transparent",Qh={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"}},Xh={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"}},Jh={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:Un,maxWidth:Mu,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:qi,canvasBackground:Vi},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 Jt(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."))?Jt(t,o):o}function Eu(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=Jt(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 Yh(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 ku(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]=ku(s,r):n[o]=r}return n}function Zh(t,e){return e?ku(t,e):t}function No(t,e={}){let n={palette:Qh,semantic:Xh,components:Jh},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:Zh(n.components,t?.components)};if(e.validate!==!1){let r=Yh(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 Lu(t){let e=Eu(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"]??qi,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Vi,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 b=c?.toggleGroup;b&&(b.gap&&(n["--persona-toggle-group-gap"]=b.gap),b.borderRadius&&(n["--persona-toggle-group-radius"]=b.borderRadius));let f=c?.artifact;if(f?.toolbar){let w=f.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"]=Jt(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(f?.tab){let w=f.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(f?.pane){let w=f.pane;if(w.toolbarBackground){let O=Jt(t,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=O}}if(f?.card){let w=f.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(f?.inline){let w=f.inline;w.background&&(n["--persona-artifact-inline-bg"]=Jt(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"]=Jt(t,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Jt(t,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Jt(t,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Jt(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"]=Jt(t,m.background)??m.background));let C=n["--persona-surface"],k=n["--persona-container"],D=n["--persona-palette-colors-gray-100"]??"#f3f4f6",M=n["--persona-palette-colors-gray-200"]??"#e5e7eb",A=n["--persona-palette-colors-gray-300"]??"#d1d5db",W=!k||k===C,z=W?D:k,U=W?M:k;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"]??U,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 eb={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"}}},Pu=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Ol=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",tb=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Ol()},Iu=t=>tb(t),nb=t=>No(t),ob=t=>{let e=No(void 0,{validate:!1});return No({...t,palette:{...e.palette,colors:{...eb.colors,...t?.palette?.colors}}},{validate:!1})},mr=t=>{let e=Iu(t),n=Pu(t?.theme),o=Pu(t?.darkTheme);return e==="dark"?ob(hs(n??{},o??{})):nb(n)},rb=t=>Lu(t),bs=(t,e)=>{let n=mr(e),o=rb(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",Iu(e))},Ki=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Ol())});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(Ol());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())}};kt();nt();function Pn(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function Ru(t){let e=Pn(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function Gi(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=Ce("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),l=null,p=null,c=t.textarea,d=null,u=null,b=null,f=null,m=()=>{if(l)return Promise.resolve(l);if(p)return p;let A=Pl().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:T,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=()=>{wu().then(A=>{let W=A.mountInlineComposer({textarea:t.textarea,renderToken:U=>ms(U,{render:e.renderMentionToken}),onMentionRemoved:U=>l?.untrackMention(U)});d=W.input,u=W.destroy;let z=c;z.replaceWith(W.element),c=W.element,f={next:W.element,prev:z},b?.(W.element,z),l?l.rebindComposer(W.input):p&&p.then(U=>U?.rebindComposer(W.input))}).catch(A=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",A)})};e.display==="inline"&&C();let I=[],D=new Map;for(let A of n){if(!A.showButton)continue;let W=zp({config:{...e,buttonIconName:A.buttonIconName,buttonTooltipText:A.buttonTooltipText},buttonSize:t.config.sendButton?.size,onOpen:()=>{m().then(z=>z?.openMenu(A.trigger))}});I.push(W),D.set(A.trigger,W.button)}let T=(A,W,z)=>{let U=D.get(W);U&&(U.setAttribute("aria-expanded",A?"true":"false"),A?U.setAttribute("aria-controls",z):U.removeAttribute("aria-controls"))};return{affordanceButtons:I.map(A=>A.wrapper),contextRow:i,handleInput:A=>{if(l){l.handleInput();return}if(!_p(A))return;let W=c,z=W.selectionStart??0;ds(W.value,z,n)&&m().then(U=>U?.handleInput())},handleKeydown:A=>{if(l?.isMenuOpen())return l.handleKeydown(A);if(A.key==="Backspace"&&l?.hasMentions()&&!f){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:()=>{Pl().catch(()=>{})},onComposerSwap:A=>{b=A,f&&A(f.next,f.prev)},destroy:()=>{l?.destroy(),u?.();for(let A of I)A.wrapper.remove();i.remove()}}}var Su=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function hs(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];Su(s)&&Su(r)?n[o]=hs(s,r):n[o]=r}return n}var Un="min(440px, calc(100vw - 24px))",Tu="440px",Jh={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:Un,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)"},pt={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:Jh,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 Mu(t,e){if(!(!t&&!e))return t?e?hs(t,e):t:e}function qi(t){return t?{...pt,...t,theme:Mu(pt.theme,t.theme),darkTheme:Mu(pt.darkTheme,t.darkTheme),launcher:{...pt.launcher,...t.launcher,dock:{...pt.launcher?.dock,...t.launcher?.dock},clearChat:{...pt.launcher?.clearChat,...t.launcher?.clearChat}},copy:{...pt.copy,...t.copy},sendButton:{...pt.sendButton,...t.sendButton},statusIndicator:{...pt.statusIndicator,...t.statusIndicator},voiceRecognition:{...pt.voiceRecognition,...t.voiceRecognition},features:(()=>{let e=pt.features?.artifacts,n=t.features?.artifacts,o=pt.features?.scrollToBottom,r=t.features?.scrollToBottom,s=pt.features?.scrollBehavior,i=t.features?.scrollBehavior,l=pt.features?.streamAnimation,p=t.features?.streamAnimation,c=pt.features?.askUserQuestion,d=t.features?.askUserQuestion,u=e===void 0&&n===void 0?void 0:{...e,...n,layout:{...e?.layout,...n?.layout}},b=o===void 0&&r===void 0?void 0:{...o,...r},f=s===void 0&&i===void 0?void 0:{...s,...i},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{...pt.features,...t.features,...b!==void 0?{scrollToBottom:b}:{},...f!==void 0?{scrollBehavior:f}:{},...u!==void 0?{artifacts:u}:{},...m!==void 0?{streamAnimation:m}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:t.suggestionChips??pt.suggestionChips,suggestionChipsConfig:{...pt.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...pt.layout,...t.layout,header:{...pt.layout?.header,...t.layout?.header},messages:{...pt.layout?.messages,...t.layout?.messages,avatar:{...pt.layout?.messages?.avatar,...t.layout?.messages?.avatar},timestamp:{...pt.layout?.messages?.timestamp,...t.layout?.messages?.timestamp}},slots:{...pt.layout?.slots,...t.layout?.slots}},markdown:{...pt.markdown,...t.markdown,options:{...pt.markdown?.options,...t.markdown?.options}},messageActions:{...pt.messageActions,...t.messageActions}}:pt}var Vi="16px",Ki="transparent",Yh={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"}},Zh={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"}},eb={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:Un,maxWidth:Tu,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Vi,canvasBackground:Ki},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 Xt(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."))?Xt(t,o):o}function Eu(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=Xt(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 tb(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 ku(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]=ku(s,r):n[o]=r}return n}function nb(t,e){return e?ku(t,e):t}function gr(t,e={}){let n={palette:Yh,semantic:Zh,components:eb},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:nb(n.components,t?.components)};if(e.validate!==!1){let r=tb(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 Lu(t){let e=Eu(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"]??Vi,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Ki,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 b=c?.toggleGroup;b&&(b.gap&&(n["--persona-toggle-group-gap"]=b.gap),b.borderRadius&&(n["--persona-toggle-group-radius"]=b.borderRadius));let f=c?.artifact;if(f?.toolbar){let w=f.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"]=Xt(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(f?.tab){let w=f.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(f?.pane){let w=f.pane;if(w.toolbarBackground){let O=Xt(t,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=O}}if(f?.card){let w=f.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(f?.inline){let w=f.inline;w.background&&(n["--persona-artifact-inline-bg"]=Xt(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"]=Xt(t,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Xt(t,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Xt(t,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Xt(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"]=Xt(t,m.background)??m.background));let C=n["--persona-surface"],I=n["--persona-container"],D=n["--persona-palette-colors-gray-100"]??"#f3f4f6",T=n["--persona-palette-colors-gray-200"]??"#e5e7eb",A=n["--persona-palette-colors-gray-300"]??"#d1d5db",W=!I||I===C,z=W?D:I,U=W?T:I;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"]??U,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 ob={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"}}},Pu=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Fl=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",rb=t=>{let e=t?.colorScheme??"light";return e==="light"?"light":e==="dark"?"dark":Fl()},Iu=t=>rb(t),sb=t=>gr(t),ib=t=>gr({...t,palette:{...t?.palette,colors:{...ob.colors,...t?.palette?.colors}}},{validate:!1}),mr=t=>{let e=Iu(t),n=Pu(t?.theme),o=Pu(t?.darkTheme);return e==="dark"?ib(hs(n??{},o??{})):sb(n)},ab=t=>Lu(t),bs=(t,e)=>{let n=mr(e),o=ab(n);for(let[r,s]of Object.entries(o))t.style.setProperty(r,s);t.setAttribute("data-persona-color-scheme",Iu(e))},Gi=t=>{let e=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{t(Fl())});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(Fl());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())}};Et();st();function Pn(t){let e=String(t).split(/[\\/]/);return e[e.length-1]??""}function Ru(t){let e=Pn(t),n=e.lastIndexOf(".");return n<=0?"":e.slice(n+1).toLowerCase()}function Qi(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 ys(t){let e=Ru(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(ys(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=Ru(t.path);return e?e.toUpperCase():"File"}}}function Wu(t){let e=t.markdown??"";return t.file?{filename:Pn(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:
|
|
200
|
-
`).length,f=t.artifactType==="markdown"?t.file:void 0,m={artifactId:i,artifactType:t.artifactType,title:t.title,typeLabel:o,file:f,chars:u,lines:b,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
|
|
199
|
+
`);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function ys(t){let e=Ru(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(ys(t)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let e=Ru(t.path);return e?e.toUpperCase():"File"}}}function Wu(t){let e=t.markdown??"";return t.file?{filename:Pn(t.file.path)||"artifact",mime:t.file.mimeType||"application/octet-stream",content:Qi(e)}:{filename:`${t.title||"artifact"}.md`,mime:"text/markdown",content:e}}st();st();var _l="http://www.w3.org/2000/svg";function Hu(t){let e=document.createElementNS(_l,"svg");e.setAttribute("class",_n("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}st();st();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 Bu(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 $l="persona-artifact-status-label",Du="persona-artifact-status-detail",Nu="data-artifact-status-label",zl=new Map,Ou=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function hr(t){t&&zl.delete(t)}function lb(t){let e=t.artifactType==="markdown"?t.file:void 0;return e?lo(e):t.artifactType==="component"?"Component":"Document"}function br(t,e,n){let o=lb(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=zl.get(i);t.status!=="complete"&&l===void 0&&(l=Ou(),zl.set(i,l));let p=l===void 0?0:Math.max(0,Ou()-l),c=t.artifactType==="component",d=!c&&typeof t.markdown=="string"?t.markdown:"",u=c?0:d.length,b=c||d===""?0:d.split(`
|
|
200
|
+
`).length,f=t.artifactType==="markdown"?t.file:void 0,m={artifactId:i,artifactType:t.artifactType,title:t.title,typeLabel:o,file:f,chars:u,lines:b,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 cb(t){t.className=$l,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 No(t,e,n){let o=t.querySelector(`:scope > .${$l}`);o||(o=h("span",$l),t.appendChild(o)),o.getAttribute(Nu)!==e.label&&(cb(o),Bu(o,e.label,n),o.setAttribute(Nu,e.label));let r=t.querySelector(`:scope > .${Du}`),s=e.detail;s?(r||(r=h("span",Du),t.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}st();var db={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"},pb=15e4,Xi={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 ub(t,e){let n=(t||"").trim().toLowerCase();if(n&&Xi[n])return Xi[n];if(e){let o=e.lastIndexOf(".");if(o>=0){let r=e.slice(o+1).toLowerCase();if(Xi[r])return Xi[r]}}return null}function Ji(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 fb=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"]),gb=[{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=>fb.has(t)?"keyword":"plain"}];function Fu(t){return Ji(t,gb)}var mb=[{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 hb(t){let e=Ji(t,mb);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 bb=[{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 _u(t){let e=Ji(t,bb),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 yb=[{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 vb(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 Ji(p,yb))e.push(d);r=l;let c=/^<\s*(script|style)\b/i.exec(p);if(c&&!/\/>\s*$/.test(p)){let d=c[1].toLowerCase(),b=new RegExp("</\\s*"+d+"\\s*>","i").exec(t.slice(r)),f=b?r+b.index:o,m=t.slice(r,f),C=d==="script"?Fu(m):_u(m);for(let I of C)e.push(I);r=f}continue}let s=t.indexOf("<",r);if(s===r)n("plain",t[r]),r+=1;else{let i=s===-1?o:s;n("plain",t.slice(r,i)),r=i}}return e}function xb(t,e){switch(e){case"html":return vb(t);case"css":return _u(t);case"js":return Fu(t);case"json":return hb(t)}}function Cb(t){let e=Yd(),n=h("span","persona-code-line"),o=(r,s)=>{if(!s)return;let i=db[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 $u(t,e,n){let o=t.length<=lb?cb(e,n):null,r=o?bb(t,o):[{type:"plain",value:t}];return yb(r)}nt();kt();nt();kt();var Dt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Vt=1e5,po=Vt+1;function yr(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(po)):(i.style.position="absolute",i.style.top="100%",i.style.marginTop="4px",r==="bottom-right"?i.style.right="0":i.style.left="0");for(let f of e){if(f.dividerBefore){let k=document.createElement("hr");i.appendChild(k)}let m=document.createElement("button");if(m.type="button",m.setAttribute("role","menuitem"),m.setAttribute("data-dropdown-item-id",f.id),f.destructive&&m.setAttribute("data-destructive",""),f.icon){let k=se(f.icon,16,"currentColor",1.5);k&&m.appendChild(k)}let C=document.createElement("span");C.textContent=f.label,m.appendChild(C),m.addEventListener("click",k=>{k.stopPropagation(),d(),n(f.id)}),i.appendChild(m)}let l=null;function p(){if(!s)return;let f=o.getBoundingClientRect();i.style.top=`${f.bottom+4}px`,r==="bottom-right"?(i.style.right=`${window.innerWidth-f.right}px`,i.style.left="auto"):(i.style.left=`${f.left}px`,i.style.right="auto")}function c(){p(),i.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=m=>{!i.contains(m.target)&&!o.contains(m.target)&&d()};document.addEventListener("click",f,!0),l=()=>document.removeEventListener("click",f,!0)})}function d(){i.classList.add("persona-hidden"),l?.(),l=null}function u(){i.classList.contains("persona-hidden")?c():d()}function b(){d(),i.remove()}return s&&s.appendChild(i),{element:i,show:c,hide:d,toggle:u,destroy:b}}function Nt(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 Fo(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 b=se(e,s??14,"currentColor",2);b&&d.appendChild(b)}let u=h("span");if(u.textContent=n,d.appendChild(u),l&&d.addEventListener("click",l),p)for(let[b,f]of Object.entries(p))d.setAttribute(b,f);return d}function Ji(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=Nt({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 zu(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 b=yr({items:o,onSelect:f=>{c.setAttribute("aria-expanded","false"),r(f)},anchor:c,position:s,portal:i});return i||c.appendChild(b.element),c.addEventListener("click",f=>{f.stopPropagation();let m=!b.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",m?"false":"true"),b.toggle()}),c.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),c.click())}),{element:c,setLabel:f=>{d.textContent=f,c.setAttribute("aria-label",f)},open:()=>{c.setAttribute("aria-expanded","true"),b.show()},close:()=>{c.setAttribute("aria-expanded","false"),b.hide()},toggle:()=>{let f=!b.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",f?"false":"true"),b.toggle()},destroy:()=>{b.destroy(),c.remove()}}}nt();var Yi="persona-artifact-custom-action-btn";function vr(t,e){let n=e?.documentChrome??!1,o;if(typeof t.icon=="function"){if(t.showLabel){let r="persona-label-btn persona-label-btn--sm "+Yi+(n?" persona-artifact-doc-copy-btn":"");o=h("button",r)}else{let r="persona-icon-btn "+Yi+(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=Fo({icon:t.icon,label:t.label,className:Yi+(n?" persona-artifact-doc-copy-btn":"")}):o=Nt({icon:t.icon,label:t.label,className:Yi+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function vs(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 Uu(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?Pn(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 b=document.createElement("div");b.className="persona-truncate persona-text-sm persona-font-medium",b.style.color="var(--persona-text, #1f2937)",b.textContent=r;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",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}:{}},k=br(C,m,"card");Oo(f,k,m)}else s&&hr(s),f.textContent=p;if(u.append(b,f),c.append(d,u),i==="complete"){let m=e?.config?.features?.artifacts?.cardActions;if(m&&m.length>0){let k={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let D of m)try{if(D.visible===void 0||D.visible(k)){let M=vr(D);M.setAttribute("data-artifact-custom-action",D.id),M.className=`${M.className} persona-flex-shrink-0`,c.append(M)}}catch{}}let C=Fo({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${r}`,C.setAttribute("data-download-artifact",s),c.append(C)}return c}var Zi=(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:()=>Uu(t,e)});if(l)return l}return Uu(t,e)};nt();kt();var uo=new WeakMap;function zl(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=uo.get(r);if(!s)return;let i=o.get(r.getAttribute("data-artifact-inline")??"");i&&s(i,n)})}function Gu(t){return uo.has(t)}function vb(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 ju(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?Pn(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 xb(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 qu=180,Cb=240,wb=.8,Ab=300,Sb=500,Mb="cubic-bezier(0.2, 0, 0, 1)",Vu=240,Tb=.35;function Eb(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:qu,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let D of i)D.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(Sb,Math.max(Ab,Cb+c*wb))),u=Math.round(d*Tb),b=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,f=b?b.animate([{opacity:0},{opacity:1}],{duration:Vu,delay:u,easing:"ease-out",fill:"backwards"}):null,m=t.animate([{height:`${e}px`},{height:`${p}px`}],{duration:d,easing:Mb});t.style.height=`${p}px`;let C=!1,k=()=>{C||(C=!0,l(),r())};Promise.allSettled([m.finished,f?.finished].filter(Boolean)).then(k),window.setTimeout(k,Math.max(d,u+Vu)+120)},qu)}function kb(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 xs="--persona-artifact-inline-body-height";function Lb(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 b=e?.transition==="none"?"none":"auto",f=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:l,fadeTop:c,fadeBottom:d,transition:b,completeDisplay:f}}function Ku(t,e){let n=vb(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:i,showViewToggle:l}=kb(o),p=o?.inlineActions??[],c=Lb(o),d=c.completeDisplay==="card",u=null,b=n,f=h("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let m=K=>Zi(xb(K),e),C=K=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(xs),f.replaceChildren(m(K)),uo.set(f,ae=>{f.replaceChildren(m(ae))})};if(d&&n.status==="complete")return C(n),f;let k=ea(n,{config:e.config,bodyLayout:c,resolveViewMode:()=>u??c.viewMode}),D=h("div","persona-artifact-inline-body");D.appendChild(k.el);let M=K=>{let ae=K.status!=="complete",te=ae?c.streamingHeight:c.completeHeight,ve=typeof te=="number";ve?f.style.setProperty(xs,`${te}px`):f.style.removeProperty(xs);let xe=!!k.el.querySelector(".persona-code-pre"),ge=!!k.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");D.classList.toggle("persona-artifact-content-flush",xe),D.classList.toggle("persona-artifact-inline-body--sized",ve&&ge),D.classList.toggle("persona-artifact-inline-body--cap",!ae&&!ge&&typeof c.completeHeight=="number")},A=n.status,W=(K,ae)=>{A!=="complete"&&K.status==="complete"?(typeof c.completeHeight=="number"?f.style.setProperty(xs,`${c.completeHeight}px`):f.style.removeProperty(xs),Xu(D,ae?.suppressTransition?"none":c.transition,K.id,()=>{k.update(K),M(K)})):k.update(K),M(K),A=K.status};M(n);let z=c.overflow==="clip"&&i&&!!n.id;if(z&&(D.setAttribute("data-expand-artifact-inline",n.id),D.setAttribute("role","button"),D.setAttribute("tabindex","0"),D.classList.add("persona-cursor-pointer"),D.setAttribute("aria-label",`Open ${ju(n).title} in panel`)),!r)return f.appendChild(D),uo.set(f,W),f;let U=h("div","persona-artifact-inline-chrome");U.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 H=h("div","persona-artifact-inline-chrome-actions"),ne=h("span","persona-flex persona-items-center persona-gap-1"),pe=()=>u??c.viewMode,he=l?Ji({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:pe(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:K=>{let ae=K==="source"?"source":"rendered";ae!==pe()&&(u=ae,k.update(b),M(b))}}):null,fe=s?Nt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;fe&&n.id&&fe.setAttribute("data-copy-artifact",n.id);let ee=i?Nt({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),H.appendChild(ne),he&&H.appendChild(he.element),fe&&H.appendChild(fe),ee&&H.appendChild(ee),U.append(w,H),f.append(U,D);let oe=K=>{let{title:ae,typeLabel:te}=ju(K);L.textContent=ae,L.title=ae,z&&D.setAttribute("aria-label",`Open ${ae} in panel`);let ve=K.status!=="complete";if(ve){P.classList.contains("persona-artifact-inline-status")||(P.className="persona-artifact-inline-status",P.removeAttribute("data-preserve-animation"),P.replaceChildren());let xe=br(K,o,"inline-chrome");Oo(P,xe,o)}else hr(K.id),P.className="persona-artifact-inline-type",P.removeAttribute("data-preserve-animation"),P.replaceChildren(),P.textContent=te;if(fe&&fe.classList.toggle("persona-hidden",ve),he){let xe=K.artifactType==="markdown"?K.file:void 0,ge=!1;if(!ve&&xe&&c.viewMode!=="source"){let Te=ys(xe);Te==="markdown"?ge=!0:(Te==="html"||Te==="svg")&&(ge=o?.filePreview?.enabled!==!1)}he.element.classList.toggle("persona-hidden",!ge),he.setSelected(pe())}if(ne.replaceChildren(),!ve&&p.length>0){let xe=vs(K);if(xe)for(let ge of p)try{if(ge.visible===void 0||ge.visible(xe)){let Te=vr(ge,{documentChrome:!0});Te.setAttribute("data-artifact-custom-action",ge.id),Te.classList.add("persona-flex-shrink-0"),ne.appendChild(Te)}}catch{}}};return oe(n),uo.set(f,(K,ae)=>{if(d&&A!=="complete"&&K.status==="complete"){let te=f.isConnected?f.getBoundingClientRect().height:0;A="complete";let ve=K,xe=!1,ge=Te=>{ve=Te,xe=!0};uo.set(f,ge),Eb(f,te,{swap:()=>{C(ve),xe=!1,uo.set(f,ge)},onSettled:()=>{xe?C(ve):uo.set(f,Te=>{f.replaceChildren(m(Te))})}});return}(K.status!=="complete"||K.id!==b.id)&&(u=null),b=K,W(K,ae),oe(K)}),f}var Qu=(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:()=>Ku(t,e)});if(l)return l}return Ku(t,e)};var Ul=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)})}},jn=new Ul;jn.register("PersonaArtifactCard",Zi,{bubbleChrome:!1});jn.register("PersonaArtifactInline",Qu,{bubbleChrome:!1});function Cs(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?Gi(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}var jl=!1;function Pb(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Xu(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"||jl||s){o();return}jl=!0;let i=Pb(n);t.style.setProperty("view-transition-name",i);let l=()=>{jl=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Ib="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Rb="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Wb(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 Hb(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 Bb=220;function Db(){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 Nb(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 Ob(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(Hu());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 Fb(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)},b=()=>{i&&i.parentElement&&i.remove(),i=null},f=()=>{if(i||p)return;let A=Ob(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(b,Bb))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",D):e.removeEventListener("load",M)},k=()=>{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 D(A){if(n===null)return;let W=A.data;!W||W.persona!=="artifact-preview-ready"||W.token!==n||A.source===e.contentWindow&&k()}function M(){let A=W=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>W()):setTimeout(W,0)};A(()=>A(()=>k()))}return u(f,o.delayMs),u(k,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",D):e.addEventListener("load",M),()=>{p=!0,d(),C(),b()}}function ea(t,e){let{config:n}=e,o=e.registry??jn,r=e.bodyLayout,s=n.markdown?pi(n.markdown):null,i=ui(n.sanitize),l=t,p=!1,c=ee=>{let oe=On()!==null;s&&!oe&&!p&&(p=!0,di(()=>fe(l)));let K=s?s(ee):oo(ee);return s&&oe&&i?i(K):K},d=h("div","persona-artifact-preview-body"),u=null,b=null,f=null,m=()=>{f&&(f(),f=null),u=null,b=null},C=null,k=null,D=null,M=!1,A=()=>{C=null,k=null,D=null,M=!1},W=null,z=null,U=()=>{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,K=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&&K>1)},H=ee=>{O||(O=N(()=>{O=0,ee.scrollTop=ee.scrollHeight,P(ee)}))},ne=(ee,oe,K,ae)=>{let te=!!r,ve=K.id+"|"+(te?"w":"p");if(!C||D!==ve||C.parentElement!==d){m(),U(),d.replaceChildren();let Te=h("pre",Ib+" persona-code-pre"),Me=h("code","persona-code");if(Te.appendChild(Me),te){let Fe=h("div","persona-artifact-source-window");if(Fe.appendChild(Te),d.appendChild(Fe),!(r?.overflow==="clip")&&typeof Fe.addEventListener=="function"){let Ee=()=>Fe.scrollHeight-Fe.clientHeight>1;Fe.addEventListener("scroll",()=>{L(Fe)&&(M=!1),P(Fe)},{passive:!0}),Fe.addEventListener("wheel",Ne=>{Ee()&&Ne.deltaY<0&&(M=!0)},{passive:!0}),Fe.addEventListener("touchmove",()=>{Ee()&&(M=!0)},{passive:!0})}C=Fe}else d.appendChild(Te),C=Te;k=Me,D=ve}let xe=te?C:null;xe&&(xe.classList.toggle("persona-artifact-source-window--fixed",ae),xe.classList.toggle("persona-artifact-source-window--clip",ae&&r?.overflow==="clip"));let ge=xe?L(xe):!0;if(k.replaceChildren($u(ee,oe?.language,oe?.path)),xe){let Te=K.status!=="complete";ae&&Te&&r?.followOutput&&!M&&ge?H(xe):Te||(M=!1),P(xe)}},pe=ee=>{m(),A(),U(),d.replaceChildren();let oe=h("div",Rb);oe.innerHTML=c(ee),d.appendChild(oe)},he=ee=>{let oe=ee.id,K=n.features?.artifacts,ae=br(ee,K,"status-body");if(W&&z===oe&&W.parentElement===d){let xe=W.querySelector(".persona-artifact-status-view-text");xe&&Oo(xe,ae,K);return}m(),A(),d.replaceChildren();let te=h("div","persona-artifact-status-view"),ve=h("div","persona-artifact-status-view-text");Oo(ve,ae,K),te.appendChild(ve),d.appendChild(te),W=te,z=oe},fe=ee=>{l=ee;let oe=e.resolveViewMode?.(ee)??r?.viewMode??"rendered",K=ee.artifactType==="markdown"?ee.file:void 0,ae=ee.status!=="complete";ae||hr(ee.id);let te=ae?r?.streamingHeight:r?.completeHeight,ve=!!r&&typeof te=="number";if(r?.streamingView==="status"&&ae){he(ee);return}if(K){let ge=Gi(ee.markdown??""),Te=ys(K),Me=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ae&&oe==="rendered"&&Me&&(Te==="html"||Te==="svg")){let Pe=ee.id+"\0"+ge;if(u&&b===Pe&&u.parentElement===d)return;A(),U(),m(),d.replaceChildren();let Ee=n.features?.artifacts?.filePreview,Ne=Ee?.iframeSandbox??"allow-scripts";!Ee?.dangerouslyAllowSameOrigin&&Ne.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."),Ne=Ne.split(/\s+/).filter(It=>It&&It!=="allow-same-origin").join(" "));let lt=Hb(Ee?.loading),ze=h("div","persona-artifact-frame"),Je=h("iframe","persona-artifact-iframe");Je.setAttribute("sandbox",Ne),Je.setAttribute("data-artifact-id",ee.id);let pn=null;lt.enabled&<.injectReadySignal?(pn=Db(),Je.srcdoc=ge+Nb(pn)):Je.srcdoc=ge,ze.appendChild(Je),d.appendChild(ze),lt.enabled&&(f=Fb(ze,Je,pn,lt,ee.id,n)),u=ze,b=Pe;return}if(m(),!ae&&Te==="markdown"&&oe==="rendered"){pe(ge);return}ne(ge,{language:K.language,path:K.path},ee,ve);return}if(ee.artifactType==="markdown"){if(oe==="source"){m(),ne(ee.markdown??"",void 0,ee,ve);return}pe(ee.markdown??"");return}m(),A(),U(),d.replaceChildren();let xe=ee.component?o.get(ee.component):void 0;if(xe){let Te={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Me=xe(ee.props??{},Te);if(Me){d.appendChild(Me);return}}catch{}}d.appendChild(Wb(ee))};return fe(t),{el:d,update(ee){fe(ee)}}}var Ju=require("idiomorph"),ta=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;Ju.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 Yu=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var ql={index:-1,draft:""};function Zu(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 ef(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 tf(){return new Map}function nf(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function of(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function rf(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}function na(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function In(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function fo(t,e){return In(t)-t.scrollTop<=e}function oa(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 ra(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 sf(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function af(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 lf(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var ws={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},_b=["pre","code","a","script","style"],sa=t=>({type:t?.type??ws.type,placeholder:t?.placeholder??ws.placeholder,speed:t?.speed??ws.speed,duration:t?.duration??ws.duration,buffer:t?.buffer??ws.buffer}),$b=[{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"}],df=new Map;for(let t of $b)df.set(t.name,t);var xr=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:df.get(t)??null,ia=(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},zb=(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},Ub=(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},Vl=/\s/,jb=(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},qb=(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(Vl.test(s[l])){let p=l;for(;p<s.length&&Vl.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&&!Vl.test(s[c]);)p.appendChild(zb(o,s[c],e,n.value)),n.value+=1,c+=1;i.appendChild(p),l=c}r.replaceChild(i,t)},Vb=(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(Ub(o,p,e,n.value)),n.value+=1));r.replaceChild(i,t)},As=(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??_b).map(u=>u.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=i.nextNode();for(;p;)jb(p,s)||l.push(p),p=i.nextNode();let c={value:o?.startIndex??0},d=e==="char"?qb:Vb;for(let u of l)d(u,n,c);return r.innerHTML},aa=(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},Ss=(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},cf=new WeakMap,Kb=(t,e)=>{if(!t.styles)return;let n=cf.get(e);if(n||(n=new Set,cf.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)},Kl=new WeakMap,Gb=(t,e)=>{if(!t.onAttach)return;let n=Kl.get(e);if(n||(n=new Map,Kl.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},pf=t=>{let e=Kl.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},la=(t,e)=>{Kb(t,e),Gb(t,e)};function Gl(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 Ms=0,go=null;function Ql(t=document){if(Ms++,Ms===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,Ms=Math.max(0,Ms-1),Ms===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 Ts={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},zt=t=>(t?.launcher?.mountMode??"floating")==="docked",Es=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",bn=t=>{let e=t?.launcher?.dock;return{side:e?.side??Ts.side,width:e?.width??Ts.width,animate:e?.animate??Ts.animate,reveal:e?.reveal??Ts.reveal,maxHeight:e?.maxHeight??Ts.maxHeight}};nt();var Mn={"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();kt();nt();kt();var Qb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ca=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=Qb,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",b=i.closeButtonIconText??"\xD7",f=!!(i.closeButtonBorderWidth||i.closeButtonBorderColor),m=Ce("button",{className:_n("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!i.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!i.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:l,width:l,display:n?void 0:"none",color:i.closeButtonColor||Yt.actionIconColor,backgroundColor:i.closeButtonBackgroundColor||void 0,border:f?`${i.closeButtonBorderWidth||"0px"} solid ${i.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:i.closeButtonBorderRadius||void 0,paddingLeft:i.closeButtonPaddingX||void 0,paddingRight:i.closeButtonPaddingX||void 0,paddingTop:i.closeButtonPaddingY||void 0,paddingBottom:i.closeButtonPaddingY||void 0}}),C=se(u,s,"currentColor",1);if(C?(C.style.display="block",m.appendChild(C)):m.textContent=b,p.appendChild(m),d&&c){let k=null,D=()=>{if(k)return;let A=m.ownerDocument,W=A.body;if(!W)return;k=Ln(A,"div","persona-clear-chat-tooltip"),k.textContent=c;let z=Ln(A,"div");z.className="persona-clear-chat-tooltip-arrow",k.appendChild(z);let U=m.getBoundingClientRect();k.style.position="fixed",k.style.zIndex=String(po),k.style.left=`${U.left+U.width/2}px`,k.style.top=`${U.top-8}px`,k.style.transform="translate(-50%, -100%)",W.appendChild(k)},M=()=>{k&&k.parentNode&&(k.parentNode.removeChild(k),k=null)};p.addEventListener("mouseenter",D),p.addEventListener("mouseleave",M),m.addEventListener("focus",D),m.addEventListener("blur",M),p._cleanupTooltip=()=>{M(),p.removeEventListener("mouseenter",D),p.removeEventListener("mouseleave",M),m.removeEventListener("focus",D),m.removeEventListener("blur",M)}}return{button:m,wrapper:p}},Xb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",da=(t,e={})=>{let{wrapperClassName:n=Xb,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??"",b=i.borderColor??"",f=i.borderRadius??"",m=i.paddingX??"",C=i.paddingY??"",k=i.tooltipText??"Clear chat",D=i.showTooltip??!0,M=h("div",n),A=!!(u||b),W=Ce("button",{className:_n("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"hover:persona-bg-gray-100",!A&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":k},style:{height:l,width:l,color:c||Yt.actionIconColor,backgroundColor:d||void 0,border:A?`${u||"0px"} solid ${b||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:m||void 0,paddingRight:m||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),z=se(p,r,"currentColor",1);if(z&&(z.style.display="block",W.appendChild(z)),M.appendChild(W),D&&k){let U=null,w=()=>{if(U)return;let N=W.ownerDocument,L=N.body;if(!L)return;U=Ln(N,"div","persona-clear-chat-tooltip"),U.textContent=k;let P=Ln(N,"div");P.className="persona-clear-chat-tooltip-arrow",U.appendChild(P);let H=W.getBoundingClientRect();U.style.position="fixed",U.style.zIndex=String(po),U.style.left=`${H.left+H.width/2}px`,U.style.top=`${H.top-8}px`,U.style.transform="translate(-50%, -100%)",L.appendChild(U)},O=()=>{U&&U.parentNode&&(U.parentNode.removeChild(U),U=null)};M.addEventListener("mouseenter",w),M.addEventListener("mouseleave",O),W.addEventListener("focus",w),W.addEventListener("blur",O),M._cleanupTooltip=()=>{O(),M.removeEventListener("mouseenter",w),M.removeEventListener("mouseleave",O),W.removeEventListener("focus",w),W.removeEventListener("blur",O)}}return{button:W,wrapper:M}};var Yt={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},_o=t=>{let{config:e,showClose:n=!0}=t,o=Ce("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=Ce("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,U=se(p,z*.6,"currentColor",1);U?c.replaceChildren(U):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=Ce("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Yt.titleColor}}),b=Ce("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Yt.subtitleColor}});d.append(u,b),l?o.append(d):o.append(c,d);let f=r.clearChat??{},m=f.enabled??!0,C=f.placement??"inline",k=null,D=null;if(m){let U=da(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});k=U.button,D=U.wrapper,C==="top-right"&&(D.style.right="48px"),C==="inline"&&o.appendChild(D)}let M=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}=ca(e,{showClose:n,wrapperClassName:M});return i!=="top-right"&&o.appendChild(W),{header:o,iconHolder:c,headerTitle:u,headerSubtitle:b,closeButton:A,closeButtonWrapper:W,clearChatButton:k,clearChatButtonWrapper:D}},ks=(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();kt();var Jb=t=>{let e=_o({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 Yb(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=yr({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 Zb=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=zu({label:i.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,c.style.color=Yt.titleColor,d=c.querySelector(".persona-combo-btn-label")??c;else{if(c=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=Yt.titleColor,d.textContent=i.title??"Chat Assistant",c.appendChild(d),Yb(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 M=r?.titleRowHover;M&&(c.style.borderRadius=M.borderRadius??"10px",c.style.padding=M.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=M.background??"",c.style.borderColor=M.border??""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}l.appendChild(c);let u=i.closeButtonSize??"32px",b=h("div",""),f=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");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=i.closeButtonColor||Yt.actionIconColor;let m=i.closeButtonIconName??"x",C=se(m,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),b.appendChild(f),l.appendChild(b);let k=h("div");k.style.display="none";let D=h("span");return D.style.display="none",{header:l,iconHolder:k,headerTitle:d,headerSubtitle:D,closeButton:f,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}},uf={default:Jb,minimal:Zb},ey=t=>uf[t]??uf.default,pa=(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=ey(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();kt();var ua=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}},fa=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",b=e.backgroundColor,f=e.textColor,m=h("div","persona-send-button-wrapper"),C=Ce("button",{className:_n("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!b&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?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?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&b||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),k=null,D=null;if(n){let z=parseFloat(u)||24,U=f?.trim()||"currentColor";r?(k=se(r,z,U,2),k?C.appendChild(k):C.textContent=o):C.textContent=o,D=se(s,z,U,2)}else C.textContent=p;let M=null;d&&i&&(M=h("div","persona-send-button-tooltip"),M.textContent=i,m.appendChild(M)),C.setAttribute("aria-label",i),m.appendChild(C);let A="send";return{button:C,wrapper:m,setMode:z=>{if(z===A)return;A=z;let U=z==="stop"?l:i;if(C.setAttribute("aria-label",U),M&&(M.textContent=U),n){if(k&&D){let w=z==="stop"?D:k;C.replaceChildren(w)}}else C.textContent=z==="stop"?c:p}}},ga=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,b=h("div","persona-send-button-wrapper"),f=Ce("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width: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?f.appendChild(C):f.textContent="\u{1F3A4}",b.appendChild(f);let k=e.tooltipText??"Start voice recognition";if((e.showTooltip??!1)&&k){let M=h("div","persona-send-button-tooltip");M.textContent=k,b.appendChild(M)}return{button:f,wrapper:b}},ma=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??zn).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=Ce("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",m=>{m.preventDefault(),r.click()}),c.appendChild(d);let b=e.buttonTooltipText??"Attach file",f=h("div","persona-send-button-tooltip");return f.textContent=b,c.appendChild(f),{button:d,wrapper:c,input:r,previewsContainer:o}},ha=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},ba=()=>Ce("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ya=t=>{let{config:e}=t,n=Ce("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=ba(),r=Ce("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}=ua(e);i();let l=fa(e),p=ga(e),c=ma(e),d=ha(e);c&&(c.previewsContainer.style.gap="8px",r.append(c.previewsContainer,c.input)),r.append(s);let u=Ce("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),b=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&b.append(c.wrapper),p&&f.append(p.wrapper),f.append(l.wrapper),u.append(b,f),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:b,rightActions:f,setSendButtonMode:l.setMode}};nt();kt();var ff=()=>{let t=Ce("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}},gf=t=>{let{config:e}=t,n=Ce("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ba(),r=ha(e);r.style.display="none";let{textarea:s,attachAutoResize:i}=ua(e);s.style.maxHeight="100px",i();let l=fa(e),p=ga(e),c=ma(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let d=Ce("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 b=h("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&b.append(p.wrapper),b.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,b),c&&n.append(c.previewsContainer),n.append(o,d,r);let f=d;return{footer:n,suggestions:o,composerForm:d,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:c?.button??null,attachmentButtonWrapper:c?.wrapper??null,attachmentInput:c?.input??null,attachmentPreviewsContainer:c?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:b,setSendButtonMode:l.setMode}};var mf=t=>{let e=t?.launcher?.enabled??!0,n=zt(t);if(Es(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 b=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");b.style.width="100%",u.appendChild(b);let f=h("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=d.expandedSize??"anchored",f.style.zIndex=String(t?.launcher?.zIndex??Vt),{wrapper:u,panel:b,pillRoot:f}}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"),b=t?.launcher?.width??"100%";return d.style.width=b,u.style.width="100%",d.appendChild(u),{wrapper:d,panel:u}}let r=t?.launcher??{},s=r.position&&Mn[r.position]?Mn[r.position]:Mn["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??Un;return l.style.width=c,l.style.maxWidth=c,i.appendChild(l),{wrapper:i,panel:l}},ty=(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}=ca(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=da(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=Ce("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Ce("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=Ce("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Ce("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),b=Ce("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),f=h("div","persona-flex persona-flex-col persona-gap-3"),m=t?.layout?.contentMaxWidth;m&&(f.style.maxWidth=m,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(b.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(b,f);let k=Ce("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"}}),D=gf({config:t}),{root:M,textNode:A}=ff();return n.append(p,r,c,k),l&&n.appendChild(l),{container:n,body:c,messagesWrapper:f,composerOverlay:k,suggestions:D.suggestions,textarea:D.textarea,sendButton:D.sendButton,sendButtonWrapper:D.sendButtonWrapper,micButton:D.micButton,micButtonWrapper:D.micButtonWrapper,composerForm:D.composerForm,statusText:D.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:D.footer,attachmentButton:D.attachmentButton,attachmentButtonWrapper:D.attachmentButtonWrapper,attachmentInput:D.attachmentInput,attachmentPreviewsContainer:D.attachmentPreviewsContainer,actionsRow:D.actionsRow,leftActions:D.leftActions,rightActions:D.rightActions,setSendButtonMode:D.setSendButtonMode,peekBanner:M,peekTextNode:A}},hf=(t,e=!0)=>{if(Es(t))return ty(t,e);let n=Ce("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?pa(t,o,{showClose:e}):_o({config:t,showClose:e}),i=Ce("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=Ce("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=Ce("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),c=Ce("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:zt(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 f=ya({config:t}),m=t?.layout?.showFooter!==!1;r?ks(n,s,t):(s.header.style.display="none",ks(n,s,t)),n.append(i);let C=Ce("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||(f.footer.style.display="none"),n.append(f.footer),n.append(C),{container:n,body:i,messagesWrapper:d,composerOverlay:C,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.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:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};nt();kt();var Xl=(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 $u(t,e,n){let o=t.length<=pb?ub(e,n):null,r=o?xb(t,o):[{type:"plain",value:t}];return Cb(r)}st();Et();st();Et();var Bt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Vt=1e5,po=Vt+1;function yr(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(po)):(i.style.position="absolute",i.style.top="100%",i.style.marginTop="4px",r==="bottom-right"?i.style.right="0":i.style.left="0");for(let f of e){if(f.dividerBefore){let I=document.createElement("hr");i.appendChild(I)}let m=document.createElement("button");if(m.type="button",m.setAttribute("role","menuitem"),m.setAttribute("data-dropdown-item-id",f.id),f.destructive&&m.setAttribute("data-destructive",""),f.icon){let I=se(f.icon,16,"currentColor",1.5);I&&m.appendChild(I)}let C=document.createElement("span");C.textContent=f.label,m.appendChild(C),m.addEventListener("click",I=>{I.stopPropagation(),d(),n(f.id)}),i.appendChild(m)}let l=null;function p(){if(!s)return;let f=o.getBoundingClientRect();i.style.top=`${f.bottom+4}px`,r==="bottom-right"?(i.style.right=`${window.innerWidth-f.right}px`,i.style.left="auto"):(i.style.left=`${f.left}px`,i.style.right="auto")}function c(){p(),i.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=m=>{!i.contains(m.target)&&!o.contains(m.target)&&d()};document.addEventListener("click",f,!0),l=()=>document.removeEventListener("click",f,!0)})}function d(){i.classList.add("persona-hidden"),l?.(),l=null}function u(){i.classList.contains("persona-hidden")?c():d()}function b(){d(),i.remove()}return s&&s.appendChild(i),{element:i,show:c,hide:d,toggle:u,destroy:b}}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 Oo(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 b=se(e,s??14,"currentColor",2);b&&d.appendChild(b)}let u=h("span");if(u.textContent=n,d.appendChild(u),l&&d.addEventListener("click",l),p)for(let[b,f]of Object.entries(p))d.setAttribute(b,f);return d}function Yi(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 zu(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 b=yr({items:o,onSelect:f=>{c.setAttribute("aria-expanded","false"),r(f)},anchor:c,position:s,portal:i});return i||c.appendChild(b.element),c.addEventListener("click",f=>{f.stopPropagation();let m=!b.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",m?"false":"true"),b.toggle()}),c.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),c.click())}),{element:c,setLabel:f=>{d.textContent=f,c.setAttribute("aria-label",f)},open:()=>{c.setAttribute("aria-expanded","true"),b.show()},close:()=>{c.setAttribute("aria-expanded","false"),b.hide()},toggle:()=>{let f=!b.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",f?"false":"true"),b.toggle()},destroy:()=>{b.destroy(),c.remove()}}}st();var Zi="persona-artifact-custom-action-btn";function vr(t,e){let n=e?.documentChrome??!1,o;if(typeof t.icon=="function"){if(t.showLabel){let r="persona-label-btn persona-label-btn--sm "+Zi+(n?" persona-artifact-doc-copy-btn":"");o=h("button",r)}else{let r="persona-icon-btn "+Zi+(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=Oo({icon:t.icon,label:t.label,className:Zi+(n?" persona-artifact-doc-copy-btn":"")}):o=Dt({icon:t.icon,label:t.label,className:Zi+(n?" persona-artifact-doc-icon-btn":"")});return e?.onClick&&o.addEventListener("click",e.onClick),o}function vs(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 Uu(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?Pn(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 b=document.createElement("div");b.className="persona-truncate persona-text-sm persona-font-medium",b.style.color="var(--persona-text, #1f2937)",b.textContent=r;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",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}:{}},I=br(C,m,"card");No(f,I,m)}else s&&hr(s),f.textContent=p;if(u.append(b,f),c.append(d,u),i==="complete"){let m=e?.config?.features?.artifacts?.cardActions;if(m&&m.length>0){let I={artifactId:s||null,title:r,artifactType:l,markdown:typeof t.markdown=="string"?t.markdown:void 0,file:n};for(let D of m)try{if(D.visible===void 0||D.visible(I)){let T=vr(D);T.setAttribute("data-artifact-custom-action",D.id),T.className=`${T.className} persona-flex-shrink-0`,c.append(T)}}catch{}}let C=Oo({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${r}`,C.setAttribute("data-download-artifact",s),c.append(C)}return c}var ea=(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:()=>Uu(t,e)});if(l)return l}return Uu(t,e)};st();Et();var uo=new WeakMap;function Ul(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=uo.get(r);if(!s)return;let i=o.get(r.getAttribute("data-artifact-inline")??"");i&&s(i,n)})}function Gu(t){return uo.has(t)}function wb(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 ju(t){let e=t.artifactType==="markdown"?t.file:void 0,n=e?Pn(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 Ab(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 qu=180,Sb=240,Mb=.8,Tb=300,Eb=500,kb="cubic-bezier(0.2, 0, 0, 1)",Vu=240,Lb=.35;function Pb(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:qu,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let D of i)D.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(Eb,Math.max(Tb,Sb+c*Mb))),u=Math.round(d*Lb),b=t.firstElementChild instanceof HTMLElement?t.firstElementChild:null,f=b?b.animate([{opacity:0},{opacity:1}],{duration:Vu,delay:u,easing:"ease-out",fill:"backwards"}):null,m=t.animate([{height:`${e}px`},{height:`${p}px`}],{duration:d,easing:kb});t.style.height=`${p}px`;let C=!1,I=()=>{C||(C=!0,l(),r())};Promise.allSettled([m.finished,f?.finished].filter(Boolean)).then(I),window.setTimeout(I,Math.max(d,u+Vu)+120)},qu)}function Ib(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 xs="--persona-artifact-inline-body-height";function Rb(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 b=e?.transition==="none"?"none":"auto",f=e?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:l,fadeTop:c,fadeBottom:d,transition:b,completeDisplay:f}}function Ku(t,e){let n=wb(t),o=e.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:i,showViewToggle:l}=Ib(o),p=o?.inlineActions??[],c=Rb(o),d=c.completeDisplay==="card",u=null,b=n,f=h("div","persona-artifact-inline persona-w-full persona-max-w-full");f.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&f.setAttribute("data-artifact-inline",n.id);let m=G=>ea(Ab(G),e),C=G=>{f.classList.add("persona-artifact-inline--card"),f.style.removeProperty(xs),f.replaceChildren(m(G)),uo.set(f,ie=>{f.replaceChildren(m(ie))})};if(d&&n.status==="complete")return C(n),f;let I=ta(n,{config:e.config,bodyLayout:c,resolveViewMode:()=>u??c.viewMode}),D=h("div","persona-artifact-inline-body");D.appendChild(I.el);let T=G=>{let ie=G.status!=="complete",te=ie?c.streamingHeight:c.completeHeight,ye=typeof te=="number";ye?f.style.setProperty(xs,`${te}px`):f.style.removeProperty(xs);let ve=!!I.el.querySelector(".persona-code-pre"),fe=!!I.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");D.classList.toggle("persona-artifact-content-flush",ve),D.classList.toggle("persona-artifact-inline-body--sized",ye&&fe),D.classList.toggle("persona-artifact-inline-body--cap",!ie&&!fe&&typeof c.completeHeight=="number")},A=n.status,W=(G,ie)=>{A!=="complete"&&G.status==="complete"?(typeof c.completeHeight=="number"?f.style.setProperty(xs,`${c.completeHeight}px`):f.style.removeProperty(xs),Xu(D,ie?.suppressTransition?"none":c.transition,G.id,()=>{I.update(G),T(G)})):I.update(G),T(G),A=G.status};T(n);let z=c.overflow==="clip"&&i&&!!n.id;if(z&&(D.setAttribute("data-expand-artifact-inline",n.id),D.setAttribute("role","button"),D.setAttribute("tabindex","0"),D.classList.add("persona-cursor-pointer"),D.setAttribute("aria-label",`Open ${ju(n).title} in panel`)),!r)return f.appendChild(D),uo.set(f,W),f;let U=h("div","persona-artifact-inline-chrome");U.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 R=h("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),L=h("span","persona-artifact-inline-type");w.append(O,R,L);let H=h("div","persona-artifact-inline-chrome-actions"),ne=h("span","persona-flex persona-items-center persona-gap-1"),de=()=>u??c.viewMode,me=l?Yi({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:G=>{let ie=G==="source"?"source":"rendered";ie!==de()&&(u=ie,I.update(b),T(b))}}):null,ue=s?Dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;ue&&n.id&&ue.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),H.appendChild(ne),me&&H.appendChild(me.element),ue&&H.appendChild(ue),ee&&H.appendChild(ee),U.append(w,H),f.append(U,D);let re=G=>{let{title:ie,typeLabel:te}=ju(G);R.textContent=ie,R.title=ie,z&&D.setAttribute("aria-label",`Open ${ie} in panel`);let ye=G.status!=="complete";if(ye){L.classList.contains("persona-artifact-inline-status")||(L.className="persona-artifact-inline-status",L.removeAttribute("data-preserve-animation"),L.replaceChildren());let ve=br(G,o,"inline-chrome");No(L,ve,o)}else hr(G.id),L.className="persona-artifact-inline-type",L.removeAttribute("data-preserve-animation"),L.replaceChildren(),L.textContent=te;if(ue&&ue.classList.toggle("persona-hidden",ye),me){let ve=G.artifactType==="markdown"?G.file:void 0,fe=!1;if(!ye&&ve&&c.viewMode!=="source"){let Ee=ys(ve);Ee==="markdown"?fe=!0:(Ee==="html"||Ee==="svg")&&(fe=o?.filePreview?.enabled!==!1)}me.element.classList.toggle("persona-hidden",!fe),me.setSelected(de())}if(ne.replaceChildren(),!ye&&p.length>0){let ve=vs(G);if(ve)for(let fe of p)try{if(fe.visible===void 0||fe.visible(ve)){let Ee=vr(fe,{documentChrome:!0});Ee.setAttribute("data-artifact-custom-action",fe.id),Ee.classList.add("persona-flex-shrink-0"),ne.appendChild(Ee)}}catch{}}};return re(n),uo.set(f,(G,ie)=>{if(d&&A!=="complete"&&G.status==="complete"){let te=f.isConnected?f.getBoundingClientRect().height:0;A="complete";let ye=G,ve=!1,fe=Ee=>{ye=Ee,ve=!0};uo.set(f,fe),Pb(f,te,{swap:()=>{C(ye),ve=!1,uo.set(f,fe)},onSettled:()=>{ve?C(ye):uo.set(f,Ee=>{f.replaceChildren(m(Ee))})}});return}(G.status!=="complete"||G.id!==b.id)&&(u=null),b=G,W(G,ie),re(G)}),f}var Qu=(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:()=>Ku(t,e)});if(l)return l}return Ku(t,e)};var jl=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)})}},jn=new jl;jn.register("PersonaArtifactCard",ea,{bubbleChrome:!1});jn.register("PersonaArtifactInline",Qu,{bubbleChrome:!1});function Cs(t){if(!t)return"";if(t.artifactType==="markdown"){let e=t.markdown??"";return t.file?Qi(e):e}return JSON.stringify({component:t.component,props:t.props},null,2)}var ql=!1;function Wb(t){return"persona-artifact-vt-"+((t||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Xu(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"||ql||s){o();return}ql=!0;let i=Wb(n);t.style.setProperty("view-transition-name",i);let l=()=>{ql=!1,t.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(l,l)}catch{l(),o()}}var Hb="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Bb="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Db(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 Nb(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 Ob=220;function Fb(){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 _b(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 $b(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(Hu());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 zb(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)},b=()=>{i&&i.parentElement&&i.remove(),i=null},f=()=>{if(i||p)return;let A=$b(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(b,Ob))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",D):e.removeEventListener("load",T)},I=()=>{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 D(A){if(n===null)return;let W=A.data;!W||W.persona!=="artifact-preview-ready"||W.token!==n||A.source===e.contentWindow&&I()}function T(){let A=W=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>W()):setTimeout(W,0)};A(()=>A(()=>I()))}return u(f,o.delayMs),u(I,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",D):e.addEventListener("load",T),()=>{p=!0,d(),C(),b()}}function ta(t,e){let{config:n}=e,o=e.registry??jn,r=e.bodyLayout,s=n.markdown?pi(n.markdown):null,i=ui(n.sanitize),l=t,p=!1,c=ee=>{let re=On()!==null;s&&!re&&!p&&(p=!0,di(()=>ue(l)));let G=s?s(ee):oo(ee);return s&&re&&i?i(G):G},d=h("div","persona-artifact-preview-body"),u=null,b=null,f=null,m=()=>{f&&(f(),f=null),u=null,b=null},C=null,I=null,D=null,T=!1,A=()=>{C=null,I=null,D=null,T=!1},W=null,z=null,U=()=>{W=null,z=null},w=40,O=0,N=ee=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>ee()):setTimeout(ee,0),R=ee=>ee.scrollHeight-ee.clientHeight-ee.scrollTop<=w,L=ee=>{if(!r)return;let re=ee.scrollHeight-ee.clientHeight>1,G=ee.scrollHeight-ee.clientHeight-ee.scrollTop;ee.classList.toggle("persona-artifact-fade-top",r.fadeTop&&re&&ee.scrollTop>1),ee.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&re&&G>1)},H=ee=>{O||(O=N(()=>{O=0,ee.scrollTop=ee.scrollHeight,L(ee)}))},ne=(ee,re,G,ie)=>{let te=!!r,ye=G.id+"|"+(te?"w":"p");if(!C||D!==ye||C.parentElement!==d){m(),U(),d.replaceChildren();let Ee=h("pre",Hb+" persona-code-pre"),Te=h("code","persona-code");if(Ee.appendChild(Te),te){let Fe=h("div","persona-artifact-source-window");if(Fe.appendChild(Ee),d.appendChild(Fe),!(r?.overflow==="clip")&&typeof Fe.addEventListener=="function"){let Ge=()=>Fe.scrollHeight-Fe.clientHeight>1;Fe.addEventListener("scroll",()=>{R(Fe)&&(T=!1),L(Fe)},{passive:!0}),Fe.addEventListener("wheel",Ze=>{Ge()&&Ze.deltaY<0&&(T=!0)},{passive:!0}),Fe.addEventListener("touchmove",()=>{Ge()&&(T=!0)},{passive:!0})}C=Fe}else d.appendChild(Ee),C=Ee;I=Te,D=ye}let ve=te?C:null;ve&&(ve.classList.toggle("persona-artifact-source-window--fixed",ie),ve.classList.toggle("persona-artifact-source-window--clip",ie&&r?.overflow==="clip"));let fe=ve?R(ve):!0;if(I.replaceChildren($u(ee,re?.language,re?.path)),ve){let Ee=G.status!=="complete";ie&&Ee&&r?.followOutput&&!T&&fe?H(ve):Ee||(T=!1),L(ve)}},de=ee=>{m(),A(),U(),d.replaceChildren();let re=h("div",Bb);re.innerHTML=c(ee),d.appendChild(re)},me=ee=>{let re=ee.id,G=n.features?.artifacts,ie=br(ee,G,"status-body");if(W&&z===re&&W.parentElement===d){let ve=W.querySelector(".persona-artifact-status-view-text");ve&&No(ve,ie,G);return}m(),A(),d.replaceChildren();let te=h("div","persona-artifact-status-view"),ye=h("div","persona-artifact-status-view-text");No(ye,ie,G),te.appendChild(ye),d.appendChild(te),W=te,z=re},ue=ee=>{l=ee;let re=e.resolveViewMode?.(ee)??r?.viewMode??"rendered",G=ee.artifactType==="markdown"?ee.file:void 0,ie=ee.status!=="complete";ie||hr(ee.id);let te=ie?r?.streamingHeight:r?.completeHeight,ye=!!r&&typeof te=="number";if(r?.streamingView==="status"&&ie){me(ee);return}if(G){let fe=Qi(ee.markdown??""),Ee=ys(G),Te=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ie&&re==="rendered"&&Te&&(Ee==="html"||Ee==="svg")){let Le=ee.id+"\0"+fe;if(u&&b===Le&&u.parentElement===d)return;A(),U(),m(),d.replaceChildren();let Ge=n.features?.artifacts?.filePreview,Ze=Ge?.iframeSandbox??"allow-scripts";!Ge?.dangerouslyAllowSameOrigin&&Ze.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."),Ze=Ze.split(/\s+/).filter(Pt=>Pt&&Pt!=="allow-same-origin").join(" "));let Be=Nb(Ge?.loading),Pe=h("div","persona-artifact-frame"),et=h("iframe","persona-artifact-iframe");et.setAttribute("sandbox",Ze),et.setAttribute("data-artifact-id",ee.id);let dn=null;Be.enabled&&Be.injectReadySignal?(dn=Fb(),et.srcdoc=fe+_b(dn)):et.srcdoc=fe,Pe.appendChild(et),d.appendChild(Pe),Be.enabled&&(f=zb(Pe,et,dn,Be,ee.id,n)),u=Pe,b=Le;return}if(m(),!ie&&Ee==="markdown"&&re==="rendered"){de(fe);return}ne(fe,{language:G.language,path:G.path},ee,ye);return}if(ee.artifactType==="markdown"){if(re==="source"){m(),ne(ee.markdown??"",void 0,ee,ye);return}de(ee.markdown??"");return}m(),A(),U(),d.replaceChildren();let ve=ee.component?o.get(ee.component):void 0;if(ve){let Ee={message:{id:ee.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let Te=ve(ee.props??{},Ee);if(Te){d.appendChild(Te);return}}catch{}}d.appendChild(Db(ee))};return ue(t),{el:d,update(ee){ue(ee)}}}var Ju=require("idiomorph"),na=(t,e,n={})=>{let{preserveTypingAnimation:o=!0}=n;Ju.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 Yu=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Vl={index:-1,draft:""};function Zu(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 ef(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 tf(){return new Map}function nf(t,e,n){let o=t.get(e);return o&&o.fingerprint===n?o.wrapper:null}function of(t,e,n,o){t.set(e,{fingerprint:n,wrapper:o})}function rf(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}function oa(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function In(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function fo(t,e){return In(t)-t.scrollTop<=e}function ra(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 sa(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 sf(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function af(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 lf(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var ws={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Ub=["pre","code","a","script","style"],ia=t=>({type:t?.type??ws.type,placeholder:t?.placeholder??ws.placeholder,speed:t?.speed??ws.speed,duration:t?.duration??ws.duration,buffer:t?.buffer??ws.buffer}),jb=[{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"}],df=new Map;for(let t of jb)df.set(t.name,t);var xr=(t,e)=>t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?e[t]??null:df.get(t)??null,aa=(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},qb=(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},Vb=(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},Kl=/\s/,Kb=(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},Gb=(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(Kl.test(s[l])){let p=l;for(;p<s.length&&Kl.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&&!Kl.test(s[c]);)p.appendChild(qb(o,s[c],e,n.value)),n.value+=1,c+=1;i.appendChild(p),l=c}r.replaceChild(i,t)},Qb=(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(Vb(o,p,e,n.value)),n.value+=1));r.replaceChild(i,t)},As=(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??Ub).map(u=>u.toLowerCase())),i=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),l=[],p=i.nextNode();for(;p;)Kb(p,s)||l.push(p),p=i.nextNode();let c={value:o?.startIndex??0},d=e==="char"?Gb:Qb;for(let u of l)d(u,n,c);return r.innerHTML},la=(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},Ss=(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},cf=new WeakMap,Xb=(t,e)=>{if(!t.styles)return;let n=cf.get(e);if(n||(n=new Set,cf.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)},Gl=new WeakMap,Jb=(t,e)=>{if(!t.onAttach)return;let n=Gl.get(e);if(n||(n=new Map,Gl.set(e,n)),n.has(t.name))return;let o=t.onAttach(e);n.set(t.name,o)},pf=t=>{let e=Gl.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},ca=(t,e)=>{Xb(t,e),Jb(t,e)};function Ql(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 Ms=0,go=null;function Xl(t=document){if(Ms++,Ms===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,Ms=Math.max(0,Ms-1),Ms===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 Ts={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},$t=t=>(t?.launcher?.mountMode??"floating")==="docked",Es=t=>(t?.launcher?.mountMode??"floating")==="composer-bar",hn=t=>{let e=t?.launcher?.dock;return{side:e?.side??Ts.side,width:e?.width??Ts.width,animate:e?.animate??Ts.animate,reveal:e?.reveal??Ts.reveal,maxHeight:e?.maxHeight??Ts.maxHeight}};st();var Mn={"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"};st();Et();st();Et();var Yb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",da=(t,e={})=>{let{showClose:n=!0,wrapperClassName:o=Yb,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",b=i.closeButtonIconText??"\xD7",f=!!(i.closeButtonBorderWidth||i.closeButtonBorderColor),m=Ce("button",{className:_n("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!i.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!i.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:l,width:l,display:n?void 0:"none",color:i.closeButtonColor||Jt.actionIconColor,backgroundColor:i.closeButtonBackgroundColor||void 0,border:f?`${i.closeButtonBorderWidth||"0px"} solid ${i.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:i.closeButtonBorderRadius||void 0,paddingLeft:i.closeButtonPaddingX||void 0,paddingRight:i.closeButtonPaddingX||void 0,paddingTop:i.closeButtonPaddingY||void 0,paddingBottom:i.closeButtonPaddingY||void 0}}),C=se(u,s,"currentColor",1);if(C?(C.style.display="block",m.appendChild(C)):m.textContent=b,p.appendChild(m),d&&c){let I=null,D=()=>{if(I)return;let A=m.ownerDocument,W=A.body;if(!W)return;I=Ln(A,"div","persona-clear-chat-tooltip"),I.textContent=c;let z=Ln(A,"div");z.className="persona-clear-chat-tooltip-arrow",I.appendChild(z);let U=m.getBoundingClientRect();I.style.position="fixed",I.style.zIndex=String(po),I.style.left=`${U.left+U.width/2}px`,I.style.top=`${U.top-8}px`,I.style.transform="translate(-50%, -100%)",W.appendChild(I)},T=()=>{I&&I.parentNode&&(I.parentNode.removeChild(I),I=null)};p.addEventListener("mouseenter",D),p.addEventListener("mouseleave",T),m.addEventListener("focus",D),m.addEventListener("blur",T),p._cleanupTooltip=()=>{T(),p.removeEventListener("mouseenter",D),p.removeEventListener("mouseleave",T),m.removeEventListener("focus",D),m.removeEventListener("blur",T)}}return{button:m,wrapper:p}},Zb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",pa=(t,e={})=>{let{wrapperClassName:n=Zb,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??"",b=i.borderColor??"",f=i.borderRadius??"",m=i.paddingX??"",C=i.paddingY??"",I=i.tooltipText??"Clear chat",D=i.showTooltip??!0,T=h("div",n),A=!!(u||b),W=Ce("button",{className:_n("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!d&&"hover:persona-bg-gray-100",!A&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":I},style:{height:l,width:l,color:c||Jt.actionIconColor,backgroundColor:d||void 0,border:A?`${u||"0px"} solid ${b||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:m||void 0,paddingRight:m||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),z=se(p,r,"currentColor",1);if(z&&(z.style.display="block",W.appendChild(z)),T.appendChild(W),D&&I){let U=null,w=()=>{if(U)return;let N=W.ownerDocument,R=N.body;if(!R)return;U=Ln(N,"div","persona-clear-chat-tooltip"),U.textContent=I;let L=Ln(N,"div");L.className="persona-clear-chat-tooltip-arrow",U.appendChild(L);let H=W.getBoundingClientRect();U.style.position="fixed",U.style.zIndex=String(po),U.style.left=`${H.left+H.width/2}px`,U.style.top=`${H.top-8}px`,U.style.transform="translate(-50%, -100%)",R.appendChild(U)},O=()=>{U&&U.parentNode&&(U.parentNode.removeChild(U),U=null)};T.addEventListener("mouseenter",w),T.addEventListener("mouseleave",O),W.addEventListener("focus",w),W.addEventListener("blur",O),T._cleanupTooltip=()=>{O(),T.removeEventListener("mouseenter",w),T.removeEventListener("mouseleave",O),W.removeEventListener("focus",w),W.removeEventListener("blur",O)}}return{button:W,wrapper:T}};var Jt={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))"},Fo=t=>{let{config:e,showClose:n=!0}=t,o=Ce("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=Ce("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,U=se(p,z*.6,"currentColor",1);U?c.replaceChildren(U):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=Ce("span",{className:"persona-text-base persona-font-semibold",text:e?.launcher?.title??"Chat Assistant",style:{color:Jt.titleColor}}),b=Ce("span",{className:"persona-text-xs",text:e?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Jt.subtitleColor}});d.append(u,b),l?o.append(d):o.append(c,d);let f=r.clearChat??{},m=f.enabled??!0,C=f.placement??"inline",I=null,D=null;if(m){let U=pa(e,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});I=U.button,D=U.wrapper,C==="top-right"&&(D.style.right="48px"),C==="inline"&&o.appendChild(D)}let T=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}=da(e,{showClose:n,wrapperClassName:T});return i!=="top-right"&&o.appendChild(W),{header:o,iconHolder:c,headerTitle:u,headerSubtitle:b,closeButton:A,closeButtonWrapper:W,clearChatButton:I,clearChatButtonWrapper:D}},ks=(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))};st();Et();var ey=t=>{let e=Fo({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 ty(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=yr({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 ny=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=zu({label:i.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,c.style.color=Jt.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=Jt.titleColor,d.textContent=i.title??"Chat Assistant",c.appendChild(d),ty(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 T=r?.titleRowHover;T&&(c.style.borderRadius=T.borderRadius??"10px",c.style.padding=T.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=T.background??"",c.style.borderColor=T.border??""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}l.appendChild(c);let u=i.closeButtonSize??"32px",b=h("div",""),f=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");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=i.closeButtonColor||Jt.actionIconColor;let m=i.closeButtonIconName??"x",C=se(m,"28px","currentColor",1);C?f.appendChild(C):f.textContent="\xD7",o&&f.addEventListener("click",o),b.appendChild(f),l.appendChild(b);let I=h("div");I.style.display="none";let D=h("span");return D.style.display="none",{header:l,iconHolder:I,headerTitle:d,headerSubtitle:D,closeButton:f,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}},uf={default:ey,minimal:ny},oy=t=>uf[t]??uf.default,ua=(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=oy(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};st();st();Et();var fa=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}},ga=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",b=e.backgroundColor,f=e.textColor,m=h("div","persona-send-button-wrapper"),C=Ce("button",{className:_n("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!b&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?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?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&b||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),I=null,D=null;if(n){let z=parseFloat(u)||24,U=f?.trim()||"currentColor";r?(I=se(r,z,U,2),I?C.appendChild(I):C.textContent=o):C.textContent=o,D=se(s,z,U,2)}else C.textContent=p;let T=null;d&&i&&(T=h("div","persona-send-button-tooltip"),T.textContent=i,m.appendChild(T)),C.setAttribute("aria-label",i),m.appendChild(C);let A="send";return{button:C,wrapper:m,setMode:z=>{if(z===A)return;A=z;let U=z==="stop"?l:i;if(C.setAttribute("aria-label",U),T&&(T.textContent=U),n){if(I&&D){let w=z==="stop"?D:I;C.replaceChildren(w)}}else C.textContent=z==="stop"?c:p}}},ma=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,b=h("div","persona-send-button-wrapper"),f=Ce("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width: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?f.appendChild(C):f.textContent="\u{1F3A4}",b.appendChild(f);let I=e.tooltipText??"Start voice recognition";if((e.showTooltip??!1)&&I){let T=h("div","persona-send-button-tooltip");T.textContent=I,b.appendChild(T)}return{button:f,wrapper:b}},ha=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??zn).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=Ce("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",m=>{m.preventDefault(),r.click()}),c.appendChild(d);let b=e.buttonTooltipText??"Attach file",f=h("div","persona-send-button-tooltip");return f.textContent=b,c.appendChild(f),{button:d,wrapper:c,input:r,previewsContainer:o}},ba=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},ya=()=>Ce("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var va=t=>{let{config:e}=t,n=Ce("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=ya(),r=Ce("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}=fa(e);i();let l=ga(e),p=ma(e),c=ha(e),d=ba(e);c&&(c.previewsContainer.style.gap="8px",r.append(c.previewsContainer,c.input)),r.append(s);let u=Ce("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),b=h("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=h("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&b.append(c.wrapper),p&&f.append(p.wrapper),f.append(l.wrapper),u.append(b,f),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:b,rightActions:f,setSendButtonMode:l.setMode}};st();Et();var ff=()=>{let t=Ce("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}},gf=t=>{let{config:e}=t,n=Ce("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ya(),r=ba(e);r.style.display="none";let{textarea:s,attachAutoResize:i}=fa(e);s.style.maxHeight="100px",i();let l=ga(e),p=ma(e),c=ha(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let d=Ce("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 b=h("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&b.append(p.wrapper),b.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,b),c&&n.append(c.previewsContainer),n.append(o,d,r);let f=d;return{footer:n,suggestions:o,composerForm:d,textarea:s,sendButton:l.button,sendButtonWrapper:l.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:c?.button??null,attachmentButtonWrapper:c?.wrapper??null,attachmentInput:c?.input??null,attachmentPreviewsContainer:c?.previewsContainer??null,actionsRow:f,leftActions:u,rightActions:b,setSendButtonMode:l.setMode}};var mf=t=>{let e=t?.launcher?.enabled??!0,n=$t(t);if(Es(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 b=h("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");b.style.width="100%",u.appendChild(b);let f=h("div","persona-widget-pill-root");return f.setAttribute("data-persona-composer-bar",""),f.dataset.state="collapsed",f.dataset.expandedSize=d.expandedSize??"anchored",f.style.zIndex=String(t?.launcher?.zIndex??Vt),{wrapper:u,panel:b,pillRoot:f}}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"),b=t?.launcher?.width??"100%";return d.style.width=b,u.style.width="100%",d.appendChild(u),{wrapper:d,panel:u}}let r=t?.launcher??{},s=r.position&&Mn[r.position]?Mn[r.position]:Mn["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??Un;return l.style.width=c,l.style.maxWidth=c,i.appendChild(l),{wrapper:i,panel:l}},ry=(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}=da(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=pa(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=Ce("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Ce("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=Ce("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Ce("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),b=Ce("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),f=h("div","persona-flex persona-flex-col persona-gap-3"),m=t?.layout?.contentMaxWidth;m&&(f.style.maxWidth=m,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),t?.copy?.showWelcomeCard!==!1||(b.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(b,f);let I=Ce("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"}}),D=gf({config:t}),{root:T,textNode:A}=ff();return n.append(p,r,c,I),l&&n.appendChild(l),{container:n,body:c,messagesWrapper:f,composerOverlay:I,suggestions:D.suggestions,textarea:D.textarea,sendButton:D.sendButton,sendButtonWrapper:D.sendButtonWrapper,micButton:D.micButton,micButtonWrapper:D.micButtonWrapper,composerForm:D.composerForm,statusText:D.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:D.footer,attachmentButton:D.attachmentButton,attachmentButtonWrapper:D.attachmentButtonWrapper,attachmentInput:D.attachmentInput,attachmentPreviewsContainer:D.attachmentPreviewsContainer,actionsRow:D.actionsRow,leftActions:D.leftActions,rightActions:D.rightActions,setSendButtonMode:D.setSendButtonMode,peekBanner:T,peekTextNode:A}},hf=(t,e=!0)=>{if(Es(t))return ry(t,e);let n=Ce("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?ua(t,o,{showClose:e}):Fo({config:t,showClose:e}),i=Ce("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=Ce("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:t?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=Ce("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:t?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),c=Ce("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:$t(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 f=va({config:t}),m=t?.layout?.showFooter!==!1;r?ks(n,s,t):(s.header.style.display="none",ks(n,s,t)),n.append(i);let C=Ce("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||(f.footer.style.display="none"),n.append(f.footer),n.append(C),{container:n,body:i,messagesWrapper:d,composerOverlay:C,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.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:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};st();Et();var Jl=(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 ls=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=zt(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 b=n.querySelector("[data-role='launcher-image']");if(b){let A=i.agentIconSize??"40px";b.style.height=A,b.style.width=A,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(b.src=i.iconUrl,b.style.display="block"):b.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let A=i.callToActionIconSize??"32px";f.style.height=A,f.style.width=A,i.callToActionIconBackgroundColor?(f.style.backgroundColor=i.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(f.style.color=i.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let W=0;if(i.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=i.callToActionIconPadding,W=(parseFloat(i.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),i.callToActionIconHidden)f.style.display="none";else if(f.style.display=l?"none":"",f.innerHTML="",i.callToActionIconName){let z=parseFloat(A)||24,U=Math.max(z-W,8),w=se(i.callToActionIconName,U,"currentColor",2);w?f.appendChild(w):f.textContent=i.callToActionIconText??"\u2197"}else f.textContent=i.callToActionIconText??"\u2197"}let m=i.position&&Mn[i.position]?Mn[i.position]:Mn["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",k="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?k:`${C} ${m}`,l||(n.style.zIndex=String(i.zIndex??Vt));let D="1px solid var(--persona-border, #e5e7eb)",M="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??D,n.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:M,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 bf=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=mf(t),s=hf(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:b=>(p.element.replaceWith(b.header),p.element=b.header,p.iconHolder=b.iconHolder,p.headerTitle=b.headerTitle,p.headerSubtitle=b.headerSubtitle,p.closeButton=b.closeButton,p.closeButtonWrapper=b.closeButtonWrapper,p.clearChatButton=b.clearChatButton,p.clearChatButtonWrapper=b.clearChatButtonWrapper,b),replaceComposer:b=>{c.footer.replaceWith(b),c.footer=b}}},Jl=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>Xl(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Xl(t,n);return{instance:r,element:r.element}};nt();kt();var ny=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}},oy=(t,e)=>{if(!t)return null;let n=ny(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},ry=(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},sy=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Yl=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(":"))},Zl=320,Cf=320,iy=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),ay=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),ly=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),dy=t=>{if(!t||t.length===0)return null;let e=Ce("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=Ce("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(Ce("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},py=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(ms(o.ref,{readonly:!0,render:e}))}return n},yf="\uE000",vf="\uE001",uy=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=b=>`${yf}${r}:${b}${vf}`,i=e.map((b,f)=>b.kind==="text"?b.text:s(f)).join(""),l=n(i);if(!e.every((b,f)=>b.kind==="text"||l.includes(s(f)))){t.replaceChildren(py(e,o));return}t.innerHTML=l;let c=new RegExp(`${yf}${r}:(\\d+)${vf}`),d=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),u=[];for(let b=d.nextNode();b;b=d.nextNode())u.push(b);for(let b of u){let f=b;for(let m=c.exec(f.data);m;m=c.exec(f.data)){let C=e[Number(m[1])],k=f.splitText(m.index);k.data=k.data.slice(m[0].length),C?.kind==="mention"&&k.parentNode?.insertBefore(ms(C.ref,{readonly:!0,render:o}),k),f=k}}},fy=(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=`${Zl}px`,c.style.maxHeight=`${Cf}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}),sy(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}},gy=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(!Yl(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=`${Zl}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},my=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(!Yl(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=`${Zl}px`,r.style.maxHeight=`${Cf}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}},hy=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(!Yl(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}},Ls=()=>{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},by=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:Ls};if(e){let r=e(o);if(r!==null)return r}return Ls()},yy=(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},xf=(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},vy=(t,e="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];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},xy=(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],b=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${d} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);b.id=`actions-${t.id}`,b.setAttribute("data-actions-for",t.id);let f=(m,C,k)=>{let D=Nt({icon:m,label:C,size:14,className:"persona-message-action-btn"});return D.setAttribute("data-action",k),D};return o&&b.appendChild(f("copy","Copy message","copy")),i&&b.appendChild(f("volume-2","Read aloud","read-aloud")),r&&b.appendChild(f("thumbs-up","Upvote","upvote")),s&&b.appendChild(f("thumbs-down","Downvote","downvote")),b},ec=(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,b=p?.position??"left",f=c?.position??"below",m=vy(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"),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 k=iy(t),D=t.content?.trim()??"",A=k.length>0&&D===Mi,W=sa(s?.widgetConfig?.features?.streamAnimation),z=s?.widgetConfig?.features?.streamAnimation?.plugins,U=t.role==="assistant"&&W.type!=="none"?xr(W.type,z):null,w=t.role==="assistant"&&U?.isAnimating?.(t)===!0,O=t.role==="assistant"&&U!==null&&(!!t.streaming||w);O&&U?.bubbleClass&&C.classList.add(U.bubbleClass);let N=document.createElement("div");N.classList.add("persona-message-content"),t.streaming&&N.classList.add("persona-content-streaming"),O&&U&&(U.containerClass&&N.classList.add(U.containerClass),N.style.setProperty("--persona-stream-step",`${W.speed}ms`),N.style.setProperty("--persona-stream-duration",`${W.duration}ms`));let L=O?ia(t.content??"",W.buffer,U,t,!!t.streaming):t.content??"",P=()=>{let te=e({text:L,message:t,streaming:!!t.streaming,raw:t.rawContent});return O&&U?.wrap==="char"?As(te,"char",t.id,{skipTags:U.skipTags}):O&&U?.wrap==="word"?As(te,"word",t.id,{skipTags:U.skipTags}):te},H=null;if(A?(H=document.createElement("div"),H.innerHTML=P(),H.style.display="none",N.appendChild(H)):t.contentSegments?.length?uy(N,t.contentSegments,te=>e({text:te,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):N.innerHTML=P(),O&&U?.useCaret&&!A&&D){let te=aa(),ve=N.querySelectorAll(".persona-stream-char, .persona-stream-word"),xe=ve[ve.length-1];if(xe?.parentNode)xe.parentNode.insertBefore(te,xe.nextSibling);else{let ge=N.lastElementChild;ge?ge.appendChild(te):N.appendChild(te)}}if(u&&f==="inline"&&t.createdAt){let te=xf(t,c,"span");te.classList.add("persona-timestamp-inline");let ve=N.lastElementChild;ve?ve.appendChild(te):N.appendChild(te)}if(k.length>0){let te=fy(k,!A&&!!D,()=>{A&&H&&(H.style.display="")});te?C.appendChild(te):A&&H&&(H.style.display="")}let ne=ay(t);if(ne.length>0){let te=gy(ne);te&&C.appendChild(te)}let pe=ly(t);if(pe.length>0){let te=my(pe);te&&C.appendChild(te)}let he=cy(t);if(he.length>0){let te=hy(he);te&&C.appendChild(te)}let fe=t.contentSegments?.length?null:dy(t.contextMentions);if(fe&&C.appendChild(fe),C.appendChild(N),u&&f==="below"&&t.createdAt){let te=xf(t,c);te.classList.add("persona-mt-1"),C.appendChild(te)}let ee=t.role==="assistant"?oy(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let te=!!(L&&L.trim()),ve=W.placeholder==="skeleton",xe=ve&&W.buffer==="line"&&te;if(te)xe&&C.appendChild(Ss());else if(ve)C.appendChild(Ss());else{let ge=by("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);ge&&C.appendChild(ge)}}if(ee&&t.stopReason&&!t.streaming&&(D||(N.style.display="none"),C.appendChild(ry(t.stopReason,ee))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1&&o){let te=xy(t,o,r);C.appendChild(te)}if(!d||t.role==="system")return C;let K=h("div",`persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),ae=yy(p,t.role);return b==="right"||b==="left"&&t.role==="user"?K.append(C,ae):K.append(ae,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),K};nt();kt();var Cr=new Set,Cy=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),wy=(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
|
-
`):""},wf=(t,e)=>{let n=Cr.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")},
|
|
212
|
+
`,n.addEventListener("click",e);let o=s=>{let i=s.launcher??{},l=$t(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 b=n.querySelector("[data-role='launcher-image']");if(b){let A=i.agentIconSize??"40px";b.style.height=A,b.style.width=A,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(b.src=i.iconUrl,b.style.display="block"):b.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let A=i.callToActionIconSize??"32px";f.style.height=A,f.style.width=A,i.callToActionIconBackgroundColor?(f.style.backgroundColor=i.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),i.callToActionIconColor?(f.style.color=i.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let W=0;if(i.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=i.callToActionIconPadding,W=(parseFloat(i.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),i.callToActionIconHidden)f.style.display="none";else if(f.style.display=l?"none":"",f.innerHTML="",i.callToActionIconName){let z=parseFloat(A)||24,U=Math.max(z-W,8),w=se(i.callToActionIconName,U,"currentColor",2);w?f.appendChild(w):f.textContent=i.callToActionIconText??"\u2197"}else f.textContent=i.callToActionIconText??"\u2197"}let m=i.position&&Mn[i.position]?Mn[i.position]:Mn["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",I="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?I:`${C} ${m}`,l||(n.style.zIndex=String(i.zIndex??Vt));let D="1px solid var(--persona-border, #e5e7eb)",T="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??D,n.style.boxShadow=i.shadow!==void 0?i.shadow.trim()===""?"none":i.shadow:T,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 bf=({config:t,showClose:e})=>{let{wrapper:n,panel:o,pillRoot:r}=mf(t),s=hf(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:b=>(p.element.replaceWith(b.header),p.element=b.header,p.iconHolder=b.iconHolder,p.headerTitle=b.headerTitle,p.headerSubtitle=b.headerSubtitle,p.closeButton=b.closeButton,p.closeButtonWrapper=b.closeButtonWrapper,p.clearChatButton=b.clearChatButton,p.clearChatButtonWrapper=b.clearChatButtonWrapper,b),replaceComposer:b=>{c.footer.replaceWith(b),c.footer=b}}},Yl=({config:t,plugins:e,onToggle:n})=>{let o=e.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:t,defaultRenderer:()=>Jl(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=Jl(t,n);return{instance:r,element:r.element}};st();Et();var sy=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}},iy=(t,e)=>{if(!t)return null;let n=sy(t);if(n===null)return null;let o=e?.[t],r=o!==void 0?o:n;return r||null},ay=(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},ly=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Zl=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(":"))},ec=320,Cf=320,cy=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),dy=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),py=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),uy=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),fy=t=>{if(!t||t.length===0)return null;let e=Ce("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});e.style.display="flex";for(let n of t){let o=Ce("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(Ce("span",{className:"persona-mention-chip-label",text:n.label})),e.appendChild(o)}return e},gy=(t,e)=>{let n=document.createDocumentFragment();for(let o of t){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(ms(o.ref,{readonly:!0,render:e}))}return n},yf="\uE000",vf="\uE001",my=(t,e,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=b=>`${yf}${r}:${b}${vf}`,i=e.map((b,f)=>b.kind==="text"?b.text:s(f)).join(""),l=n(i);if(!e.every((b,f)=>b.kind==="text"||l.includes(s(f)))){t.replaceChildren(gy(e,o));return}t.innerHTML=l;let c=new RegExp(`${yf}${r}:(\\d+)${vf}`),d=document.createTreeWalker(t,NodeFilter.SHOW_TEXT),u=[];for(let b=d.nextNode();b;b=d.nextNode())u.push(b);for(let b of u){let f=b;for(let m=c.exec(f.data);m;m=c.exec(f.data)){let C=e[Number(m[1])],I=f.splitText(m.index);I.data=I.data.slice(m[0].length),C?.kind==="mention"&&I.parentNode?.insertBefore(ms(C.ref,{readonly:!0,render:o}),I),f=I}}},hy=(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=`${ec}px`,c.style.maxHeight=`${Cf}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}),ly(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}},by=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(!Zl(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=`${ec}px`,e.appendChild(r),n+=1}),n===0?(e.remove(),null):e}catch{return null}},yy=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(!Zl(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=`${ec}px`,r.style.maxHeight=`${Cf}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}},vy=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(!Zl(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}},Ls=()=>{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},xy=(t,e,n)=>{let o={config:n??{},streaming:!0,location:t,defaultRenderer:Ls};if(e){let r=e(o);if(r!==null)return r}return Ls()},Cy=(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},xf=(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},wy=(t,e="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];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},Ay=(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],b=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${d} ${u} ${l==="hover"?"persona-message-actions-hover":""}`);b.id=`actions-${t.id}`,b.setAttribute("data-actions-for",t.id);let f=(m,C,I)=>{let D=Dt({icon:m,label:C,size:14,className:"persona-message-action-btn"});return D.setAttribute("data-action",I),D};return o&&b.appendChild(f("copy","Copy message","copy")),i&&b.appendChild(f("volume-2","Read aloud","read-aloud")),r&&b.appendChild(f("thumbs-up","Upvote","upvote")),s&&b.appendChild(f("thumbs-down","Downvote","downvote")),b},tc=(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,b=p?.position??"left",f=c?.position??"below",m=wy(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"),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 I=cy(t),D=t.content?.trim()??"",A=I.length>0&&D===Mi,W=ia(s?.widgetConfig?.features?.streamAnimation),z=s?.widgetConfig?.features?.streamAnimation?.plugins,U=t.role==="assistant"&&W.type!=="none"?xr(W.type,z):null,w=t.role==="assistant"&&U?.isAnimating?.(t)===!0,O=t.role==="assistant"&&U!==null&&(!!t.streaming||w);O&&U?.bubbleClass&&C.classList.add(U.bubbleClass);let N=document.createElement("div");N.classList.add("persona-message-content"),t.streaming&&N.classList.add("persona-content-streaming"),O&&U&&(U.containerClass&&N.classList.add(U.containerClass),N.style.setProperty("--persona-stream-step",`${W.speed}ms`),N.style.setProperty("--persona-stream-duration",`${W.duration}ms`));let R=O?aa(t.content??"",W.buffer,U,t,!!t.streaming):t.content??"",L=()=>{let te=e({text:R,message:t,streaming:!!t.streaming,raw:t.rawContent});return O&&U?.wrap==="char"?As(te,"char",t.id,{skipTags:U.skipTags}):O&&U?.wrap==="word"?As(te,"word",t.id,{skipTags:U.skipTags}):te},H=null;if(A?(H=document.createElement("div"),H.innerHTML=L(),H.style.display="none",N.appendChild(H)):t.contentSegments?.length?my(N,t.contentSegments,te=>e({text:te,message:t,streaming:!!t.streaming,raw:t.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):N.innerHTML=L(),O&&U?.useCaret&&!A&&D){let te=la(),ye=N.querySelectorAll(".persona-stream-char, .persona-stream-word"),ve=ye[ye.length-1];if(ve?.parentNode)ve.parentNode.insertBefore(te,ve.nextSibling);else{let fe=N.lastElementChild;fe?fe.appendChild(te):N.appendChild(te)}}if(u&&f==="inline"&&t.createdAt){let te=xf(t,c,"span");te.classList.add("persona-timestamp-inline");let ye=N.lastElementChild;ye?ye.appendChild(te):N.appendChild(te)}if(I.length>0){let te=hy(I,!A&&!!D,()=>{A&&H&&(H.style.display="")});te?C.appendChild(te):A&&H&&(H.style.display="")}let ne=dy(t);if(ne.length>0){let te=by(ne);te&&C.appendChild(te)}let de=py(t);if(de.length>0){let te=yy(de);te&&C.appendChild(te)}let me=uy(t);if(me.length>0){let te=vy(me);te&&C.appendChild(te)}let ue=t.contentSegments?.length?null:fy(t.contextMentions);if(ue&&C.appendChild(ue),C.appendChild(N),u&&f==="below"&&t.createdAt){let te=xf(t,c);te.classList.add("persona-mt-1"),C.appendChild(te)}let ee=t.role==="assistant"?iy(t.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let te=!!(R&&R.trim()),ye=W.placeholder==="skeleton",ve=ye&&W.buffer==="line"&&te;if(te)ve&&C.appendChild(Ss());else if(ye)C.appendChild(Ss());else{let fe=xy("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);fe&&C.appendChild(fe)}}if(ee&&t.stopReason&&!t.streaming&&(D||(N.style.display="none"),C.appendChild(ay(t.stopReason,ee))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&o?.enabled!==!1&&o){let te=Ay(t,o,r);C.appendChild(te)}if(!d||t.role==="system")return C;let G=h("div",`persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),ie=Cy(p,t.role);return b==="right"||b==="left"&&t.role==="user"?G.append(C,ie):G.append(ie,C),C.classList.remove("persona-max-w-[85%]"),C.classList.add("persona-max-w-[calc(85%-2.5rem)]"),G};st();Et();var Cr=new Set,Sy=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),My=(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
|
+
`):""},wf=(t,e)=>{let n=Cr.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")},nc=(t,e)=>{let n=t.reasoning,o=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.id),!n)return o;let r=e?.features?.reasoningDisplay??{},s=r.expandable!==!1,i=s&&Cr.has(t.id),l=n.status!=="complete",p=My(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"),b="Thinking...",f=e?.reasoning??{},m=String(n.startedAt??Date.now()),C=()=>{let de=h("span","");return de.setAttribute("data-tool-elapsed",m),de.textContent=Ci(n),de},I=f.renderCollapsedSummary?.({message:t,reasoning:n,defaultSummary:b,previewText:p,isActive:l,config:e??{},elapsed:Ci(n),createElapsedElement:C});typeof I=="string"&&I.trim()?(u.textContent=I,d.appendChild(u)):I instanceof HTMLElement?d.appendChild(I):(u.textContent=b,d.appendChild(u));let D=h("span","persona-text-xs persona-text-persona-primary");D.textContent=gp(n),d.appendChild(D);let T=r.loadingAnimation??"none",A=f.activeTextTemplate,W=f.completeTextTemplate,z=l?A:W,U=I instanceof HTMLElement,w=(de,me)=>{u.textContent="";let ue=wi(de,""),ee=0;for(let re of ue){let G=re.styles.length>0?(()=>{let ie=h("span",re.styles.map(te=>`persona-tool-text-${te}`).join(" "));return u.appendChild(ie),ie})():u;if(re.isDuration&&l)G.appendChild(C());else{let ie=re.isDuration?Ci(n):re.text;me?ee=co(G,ie,ee):G.appendChild(document.createTextNode(ie))}}};if(!U&&z)if(D.style.display="none",u.style.display="",l&&T!=="none"){let de=f.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),T==="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-${T}`),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`),T==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),w(z,!0))}else w(z,!1);else if(!U&&l&&T!=="none"){u.style.display="";let de=f.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),T==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`);else{u.classList.add(`persona-tool-loading-${T}`),u.style.setProperty("--persona-tool-anim-duration",`${de}ms`),T==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let me=u.textContent||b;u.textContent="",co(u,me,0)}n.status==="complete"&&(u.style.display="none")}else U||(n.status==="complete"?u.style.display="none":u.style.display="");let O=null;if(s){O=h("div","persona-flex persona-items-center");let me=se(i?"chevron-up":"chevron-down",16,"currentColor",2);me?O.appendChild(me):O.textContent=i?"Hide":"Show";let ue=h("div","persona-flex persona-items-center persona-ml-auto");ue.append(O),c.append(d,ue)}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??{}});Sy(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 R=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");R.style.display=i?"":"none";let L=n.chunks.join(""),H=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return H.textContent=L||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),R.appendChild(H),(()=>{if(c.setAttribute("aria-expanded",i?"true":"false"),O){O.innerHTML="";let me=se(i?"chevron-up":"chevron-down",16,"currentColor",2);me?O.appendChild(me):O.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",N.style.display=i?"none":N.textContent||N.childNodes.length?"":"none"})(),o.append(c,N,R),o};st();Et();var wr=new Set,Ty=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),Ey=(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
|
-
`):""},nc=(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)"},My=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=Sy(t,o?.previewMaxLines??3),i=n?gp(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=ml(n,p.activeTextTemplate,c):!l&&p.completeTextTemplate&&(c=ml(n,p.completeTextTemplate,c)),{summary:c,previewText:s,isActive:l}},Af=(t,e,n)=>{let o=wr.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")},oc=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${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&&wr.has(t.id),{summary:p,previewText:c,isActive:d}=My(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 b=h("div","persona-flex persona-flex-col persona-text-left"),f=h("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.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=ns(n),P},k=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:p,previewText:c,collapsedMode:s.collapsedMode??"tool-call",isActive:d,config:e??{},elapsed:ns(n),createElapsedElement:C});typeof k=="string"&&k.trim()?(f.textContent=k,b.appendChild(f)):k instanceof HTMLElement?b.appendChild(k):(f.textContent=p,b.appendChild(f));let D=s.loadingAnimation??"none",M=o.activeTextTemplate,A=o.completeTextTemplate,W=d?M:A,z=k instanceof HTMLElement,U=(P,H)=>{f.textContent="";let ne=n.name?.trim()||"tool",pe=wi(P,ne),he=0;for(let fe of pe){let ee=fe.styles.length>0?(()=>{let oe=h("span",fe.styles.map(K=>`persona-tool-text-${K}`).join(" "));return f.appendChild(oe),oe})():f;if(fe.isDuration&&d)ee.appendChild(C());else{let oe=fe.isDuration?ns(n):fe.text;H?he=co(ee,oe,he):ee.appendChild(document.createTextNode(oe))}}};if(!z)if(d&&D!=="none"){let P=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),D==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${P}ms`),W&&U(W,!1);else if(f.classList.add(`persona-tool-loading-${D}`),f.style.setProperty("--persona-tool-anim-duration",`${P}ms`),D==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),W)U(W,!0);else{let H=f.textContent||p;f.textContent="",co(f,H,0)}}else W&&U(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)",H=se(l?"chevron-up":"chevron-down",16,P,2);H?w.appendChild(H):w.textContent=l?"Hide":"Show";let ne=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ne.append(w),u.append(b,ne)}else u.append(b);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??{}});Ay(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"),H=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(H.style.color=o.labelTextColor),H.textContent="Arguments";let ne=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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",nc(ne,o),ne.textContent=ao(n.args),P.append(H,ne),N.appendChild(P)}if(n.chunks&&n.chunks.length){let P=h("div","persona-space-y-1"),H=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(H.style.color=o.labelTextColor),H.textContent="Activity";let ne=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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",nc(ne,o),ne.textContent=n.chunks.join(""),P.append(H,ne),N.appendChild(P)}if(n.status==="complete"&&n.result!==void 0){let P=h("div","persona-space-y-1"),H=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(H.style.color=o.labelTextColor),H.textContent="Result";let ne=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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",nc(ne,o),ne.textContent=ao(n.result),P.append(H,ne),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)",H=se(l?"chevron-up":"chevron-down",16,P,2);H?w.appendChild(H):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();kt();var $o=new Map,va=t=>{let n=(t.startsWith(Fn)?t.slice(Fn.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)},Sf=t=>t?.approval!==!1?t?.approval:void 0,Mf=(t,e)=>{let n=Sf(e)?.detailsDisplay??"collapsed";return $o.get(t)??n==="expanded"},Tf=(t,e,n)=>{let o=Sf(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)}},Ef=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=Mf(t,n);Tf(o,s,n),r.style.display=s?"":"none"};var xa=(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-max-w-[85%]","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"),b=h("div","persona-flex persona-items-center persona-gap-2"),f=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",b.appendChild(f),!r){let 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"),b.appendChild(w)}u.appendChild(b);let C=n.toolType==="webmcp"||n.toolName.startsWith(Fn)?Yr(n.toolName):void 0,k=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),D=!n.toolName,M=k||(D?n.description:`The assistant wants to use \u201C${C??va(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=M,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&&!D,U=z||!!n.parameters;if(W!=="hidden"&&U){let w=Mf(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),Tf(O,w,e),u.appendChild(O);let P=h("div");if(P.setAttribute("data-approval-details","true"),P.style.display=w?"":"none",z){let H=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(H.style.color=o.descriptionColor),H.textContent=n.description,P.appendChild(H)}if(n.parameters){let H=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&&(H.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(H.style.color=o.parameterTextColor),H.style.fontSize="0.75rem",H.style.lineHeight="1rem",H.textContent=ao(n.parameters),P.appendChild(H)}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 H=se("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);H&&(H.style.marginRight="4px",P.appendChild(H));let ne=document.createTextNode(o?.denyLabel??"Deny");P.appendChild(ne),w.append(O,P),u.appendChild(w)}return i.append(l,u),s.appendChild(i),s};nt();kt();Ml();var Ty=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),kf=(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))},zo=(t,e)=>{kf(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)},Ey=t=>t?.approval!==!1?t?.approval:void 0,ky=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return $o.get(t)??n==="expanded"},rc=t=>{let e=h("span","persona-approval-kbd");return e.textContent=t,e},Ly=(t,e)=>{let n=h("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(Fn)?Yr(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??va(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},Py=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?va(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},Iy=(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,b=u&&ky(e.id,o),f=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",b?"true":"false"),C.setAttribute("aria-label",b?m:f)):C.setAttribute("data-static","true");let k=h("span","persona-approval-logo"),D=se("shield-check",16,"currentColor",2);D&&k.appendChild(D),C.appendChild(k);let M=Ly(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),M.append(" "),M.appendChild(O)}C.appendChild(M),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=!b,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,U=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"),U(N),N.append(o?.approveLabel??"Always allow",rc("\u23CE"));let L=h("button","persona-approval-caret");L.type="button",L.setAttribute("data-action","toggle-menu"),L.setAttribute("aria-label","More options"),U(L);let P=se("chevron-down",15,"currentColor",2);P&&L.appendChild(P),O.append(N,L),W.append(O,w),w.append(rc("Esc"));let H=h("div","persona-approval-menu"),ne=h("button","persona-approval-menu-item");ne.type="button",ne.append("Allow once",rc("\u2318\u23CE")),H.appendChild(ne),z=Ni({anchor:O,content:H,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,z),ne.addEventListener("click",()=>{zo(t,e.id),r()})}else{let O=h("button","persona-approval-primary persona-approval-primary--solo");O.type="button",O.setAttribute("data-action","allow"),U(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 H=P.hidden;P.hidden=!H,C.setAttribute("aria-expanded",H?"true":"false"),C.setAttribute("aria-label",H?m:f),$o.set(e.id,H)}return}if(L==="toggle-menu"){z?.toggle();return}if(L==="always"){zo(t,e.id),r({remember:!0});return}if(L==="allow"){zo(t,e.id),r();return}if(L==="deny"){zo(t,e.id),s();return}}),l},Lf=()=>{let t=Ty();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=Ey(i);if(l.status!=="pending"){if(zo(t,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Py(l)}kf(t,o.id);let c=p?.enableAlwaysAllow===!0,d=Iy(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=b=>{Qp(b)||o.id===t.latestPendingApprovalId&&(b.key!=="Escape"&&b.key!=="Enter"||(b.preventDefault(),b.stopImmediatePropagation(),zo(t,o.id),b.key==="Escape"?s():b.metaKey||b.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()])zo(t,o);t.latestPendingApprovalId=null}}};nt();var Pf=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(k=>k.role==="user"))return;let u=document.createDocumentFragment(),b=s?s.isStreaming():!1,f=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=b,p?.fontFamily&&(C.style.fontFamily=f(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 Ps=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 Is=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 Ry=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Wy=new Set(["step_start","execution_start"]),Hy=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),By=new Set(["step_complete","agent_turn_complete"]),Dy=new Set(["flow_complete","agent_complete"]),If=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Wf=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),dn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Uo=(t,e)=>{let n=t[e];return Wf(n)?n:void 0};function sc(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function Ca(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function Ny(t,e){return typeof e.type=="string"?e.type:t}function Oy(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 Fy(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 Rf(t){let e=Uo(t,"result"),n=[Uo(t,"tokens"),Uo(t,"totalTokens"),e?Uo(e,"tokens"):void 0,Uo(t,"usage"),e?Uo(e,"usage"):void 0];for(let o of n){if(!o)continue;let r=dn(o.output)??dn(o.outputTokens)??dn(o.completionTokens);if(r!==void 0)return r}return dn(t.outputTokens)??dn(t.completionTokens)??(e?dn(e.outputTokens)??dn(e.completionTokens):void 0)}function _y(t){let e=Uo(t,"result");return dn(t.executionTime)??dn(t.executionTimeMs)??dn(t.execution_time)??dn(t.duration)??(e?dn(e.executionTime)??dn(e.executionTimeMs):void 0)}function $y(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Rs=class{constructor(e=$y){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:Ca(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(!Wf(n)){If.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Ny(e,n),r=this.now();if(Ry.has(o)){this.startRun(r);return}if(Wy.has(o)){this.run||this.startRun(r);return}if(Hy.has(o)){if(!Fy(o,n))return;let s=Oy(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+sc(i.visibleCharCount),p=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ca(l,p),outputTokens:l,durationMs:p,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(By.has(o)){if(!this.run)return;let s=this.run,i=Rf(n);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+sc(s.visibleCharCount),c=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:Ca(p,c),outputTokens:p,durationMs:c,source:l?"usage":"estimate"};return}if(Dy.has(o)){if(!this.run)return;let s=this.run,i=Rf(n),l=i??s.exactOutputTokens+sc(s.visibleCharCount),p=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",c=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:Ca(l,c),outputTokens:l,durationMs:c,source:p},this.run=null;return}if(If.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:_y(n)??o-e.startedAt}};nt();kt();function Ar(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}var zy={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)"}},Uy={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},jy=["flowName","stepName","reasoningText","text","name","tool","toolName"],qy=100;function Vy(t,e){let n={...zy,...e};if(n[t])return n[t];for(let o of Object.keys(n))if(o.endsWith("_")&&t.startsWith(o))return n[o];return Uy}function Ky(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function Gy(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 Qy(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 Xy(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 Jy(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 Yy(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function Zy(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 ev(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 ic(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");Ar(c,o.classNames?.eventRow);let d=i.find(b=>b.renderEventStreamRow);if(d?.renderEventStreamRow&&l){let b=d.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(t.id)});if(b)return c.appendChild(b),c}return c.appendChild(u()),c;function u(){let b=h("div",""),f=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");f.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 k=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),D=o.timestampFormat??"relative";k.textContent=D==="relative"?Ky(t.timestamp,n):Gy(t.timestamp);let M=null;o.showSequenceNumbers!==!1&&(M=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),M.textContent=String(e+1));let A=Vy(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??jy,U=Qy(t.payload,z),w=null;U&&(w=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=U);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 Xy(Jy(t)),N.innerHTML="";let H=se("check","12px","currentColor",1.5);H&&N.appendChild(H),setTimeout(()=>{N.innerHTML="";let ne=se("clipboard","12px","currentColor",1.5);ne&&N.appendChild(ne)},1500)}),f.appendChild(m),f.appendChild(k),M&&f.appendChild(M),f.appendChild(W),w&&f.appendChild(w),f.appendChild(O),f.appendChild(N),b.appendChild(f),p&&b.appendChild(ev(t,i,l)),b}}function Hf(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??{},b=s.find(m=>m.renderEventStreamView);if(b?.renderEventStreamView&&r){let m=b.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>f().element,onClose:o});if(m)return{element:m,update:()=>{},destroy:()=>{}}}return f();function f(){let m=u.classNames,C=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ar(C,m?.panel);let k=[],D="",M="",A=null,W=[],z={},U=0,w=na(),O=0,N=0,L=!1,P=null,H=!1,ne=0,pe=new Set,he=new Map,fe="",ee="",oe=null,K,ae,te,ve,xe=null,ge=null,Te=null;function Me(){let $=h("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),G=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(Ar(G,m?.headerBar),i){ge=h("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),ge.style.cursor="help",xe=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"),xe.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=ge,mo=Te,ho=()=>{if(!mo.textContent)return;let Ns=Ye.getBoundingClientRect(),en=$.getBoundingClientRect();mo.style.left=`${Ns.left-en.left}px`,mo.style.top=`${Ns.bottom-en.top+4}px`,mo.style.display="block"},Sa=()=>{mo.style.display="none"};ge.addEventListener("mouseenter",ho),ge.addEventListener("mouseleave",Sa),ge.appendChild(xe)}let de=h("div","persona-flex-1");K=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 ot=h("option","");ot.value="",ot.textContent="All events (0)",K.appendChild(ot),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 dt=se("clipboard-copy","12px","currentColor",1.5);dt&&ae.appendChild(dt);let Q=h("span","persona-event-copy-all persona-text-xs");Q.textContent="Copy All",ae.appendChild(Q),ge&&G.appendChild(ge),G.appendChild(de),G.appendChild(K),G.appendChild(ae);let je=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ar(je,m?.searchBar);let Be=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");Be&&De.appendChild(Be),te=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"),Ar(te,m?.searchInput),te.type="text",te.placeholder="Search event payloads...",ve=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"),ve.type="button",ve.style.display="none";let We=se("x","12px","currentColor",2);return We&&ve.appendChild(We),je.appendChild(De),je.appendChild(te),je.appendChild(ve),$.appendChild(G),$.appendChild(je),Te&&$.appendChild(Te),$}let Fe,Pe=s.find($=>$.renderEventStreamToolbar);Pe?.renderEventStreamToolbar&&r?Fe=Pe.renderEventStreamToolbar({config:r,defaultRenderer:()=>Me(),eventCount:e.getSize(),filteredCount:0,onFilterChange:G=>{D=G,He(),Ae()},onSearchChange:G=>{M=G,He(),Ae()}})??Me():Fe=Me();let Ee=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");Ee.style.display="none";function Ne(){if(!i||!xe||!ge)return;let $=i(),G=Yy($);xe.textContent=G;let de=Zy($);Te&&(Te.textContent=de,de||(Te.style.display="none")),ge.setAttribute("aria-label",de?`Throughput: ${G}, ${de}`:`Throughput: ${G}`)}let lt=h("div","persona-flex-1 persona-min-h-0 persona-relative"),ze=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ze.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");Ar(Je,m?.scrollIndicator),Je.style.display="none",Je.setAttribute("data-persona-scroll-to-bottom-has-label",d?"true":"false");let pn=se(c,"14px","currentColor",2);pn&&Je.appendChild(pn);let It=h("span","");It.textContent=d,Je.appendChild(It);let mt=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");mt.style.display="none",lt.appendChild(ze),lt.appendChild(mt),lt.appendChild(Je),C.setAttribute("tabindex","0"),C.appendChild(Fe),C.appendChild(Ee),C.appendChild(lt);function Re(){let $=e.getAll(),G={};for(let je of $)G[je.type]=(G[je.type]||0)+1;let de=Object.keys(G).sort(),ot=de.length!==W.length||!de.every((je,Be)=>je===W[Be]),Ie=!ot&&de.some(je=>G[je]!==z[je]),dt=$.length!==Object.values(z).reduce((je,Be)=>je+Be,0);if(!ot&&!Ie&&!dt||(W=de,z=G,!K))return;let Q=K.value;if(K.options[0].textContent=`All events (${$.length})`,ot){for(;K.options.length>1;)K.remove(1);for(let je of de){let Be=h("option","");Be.value=je,Be.textContent=`${je} (${G[je]||0})`,K.appendChild(Be)}Q&&de.includes(Q)?K.value=Q:Q&&(K.value="",D="")}else for(let je=1;je<K.options.length;je++){let Be=K.options[je];Be.textContent=`${Be.value} (${G[Be.value]||0})`}}function we(){let $=e.getAll();if(D&&($=$.filter(G=>G.type===D)),M){let G=M.toLowerCase();$=$.filter(de=>de.type.toLowerCase().includes(G)||de.payload.toLowerCase().includes(G))}return $}function ct(){return D!==""||M!==""}function He(){U=0,O=0,w.resume(),Je.style.display="none"}function ye($){pe.has($)?pe.delete($):pe.add($),oe=$;let G=ze.scrollTop,de=w.isFollowing();H=!0,w.pause(),Ae(),ze.scrollTop=G,de&&w.resume(),H=!1}function ue(){return fo(ze,50)}function Ae(){N=Date.now(),L=!1,Ne(),Re();let $=e.getEvictedCount();$>0?(Ee.textContent=`${$.toLocaleString()} older events truncated`,Ee.style.display=""):Ee.style.display="none",k=we();let G=k.length,de=e.getSize()>0;G===0&&de&&ct()?(mt.textContent=M?`No events matching '${M}'`:"No events matching filter",mt.style.display="",ze.style.display="none"):(mt.style.display="none",ze.style.display=""),ae&&(ae.title=ct()?`Copy Filtered (${G})`:"Copy All"),p&&!w.isFollowing()&&G>U&&(O+=G-U,It.textContent=d?`${d}${O>0?` (${O})`:""}`:"",Je.style.display=""),U=G;let ot=e.getAll(),Ie=ot.length>0?ot[0].timestamp:0,dt=new Set(k.map(Be=>Be.id));for(let Be of pe)dt.has(Be)||pe.delete(Be);let Q=D!==fe||M!==ee,je=he.size===0&&k.length>0;if(Q||je||k.length===0){ze.innerHTML="",he.clear();let Be=document.createDocumentFragment();for(let De=0;De<k.length;De++){let We=ic(k[De],De,Ie,u,pe,ye,s,r);he.set(k[De].id,We),Be.appendChild(We)}ze.appendChild(Be),fe=D,ee=M,oe=null}else{if(oe!==null){let De=he.get(oe);if(De&&De.parentNode===ze){let We=k.findIndex(Ye=>Ye.id===oe);if(We>=0){let Ye=ic(k[We],We,Ie,u,pe,ye,s,r);ze.insertBefore(Ye,De),De.remove(),he.set(oe,Ye)}}oe=null}let Be=new Set(k.map(De=>De.id));for(let[De,We]of he)Be.has(De)||(We.remove(),he.delete(De));for(let De=0;De<k.length;De++){let We=k[De];if(!he.has(We.id)){let Ye=ic(We,De,Ie,u,pe,ye,s,r);he.set(We.id,Ye),ze.appendChild(Ye)}}}w.isFollowing()&&(ze.scrollTop=ze.scrollHeight)}function Ct(){if(Date.now()-N>=qy){P!==null&&(cancelAnimationFrame(P),P=null),Ae();return}L||(L=!0,P=requestAnimationFrame(()=>{P=null,Ae()}))}let j=($,G)=>{if(!ae)return;ae.innerHTML="";let de=se($,"12px","currentColor",1.5);de&&ae.appendChild(de);let ot=h("span","persona-text-xs");ot.textContent="Copy All",ae.appendChild(ot),setTimeout(()=>{ae.innerHTML="";let Ie=se("clipboard-copy","12px","currentColor",1.5);Ie&&ae.appendChild(Ie);let dt=h("span","persona-text-xs");dt.textContent="Copy All",ae.appendChild(dt),ae.disabled=!1},G)},ie=async()=>{if(ae){ae.disabled=!0;try{let $;ct()?$=k:n?($=await n(),$.length===0&&($=e.getAll())):$=e.getAll();let G=$.map(de=>{try{return JSON.parse(de.payload)}catch{return de.payload}});await navigator.clipboard.writeText(JSON.stringify(G,null,2)),j("check",1500)}catch{j("x",1500)}}},_e=()=>{K&&(D=K.value,He(),Ae())},Le=()=>{!te||!ve||(ve.style.display=te.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{M=te.value,He(),Ae()},150))},I=()=>{!te||!ve||(te.value="",M="",ve.style.display="none",A&&clearTimeout(A),He(),Ae())},Y=()=>{if(H)return;let $=ze.scrollTop,{action:G,nextLastScrollTop:de}=oa({following:w.isFollowing(),currentScrollTop:$,lastScrollTop:ne,nearBottom:ue(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ne=de,G==="resume"?(w.resume(),O=0,Je.style.display="none"):G==="pause"&&(w.pause(),p&&(It.textContent=d,Je.style.display=""))},x=$=>{let G=ra({following:w.isFollowing(),deltaY:$.deltaY,nearBottom:ue(),resumeWhenNearBottom:!0});G==="pause"?(w.pause(),p&&(It.textContent=d,Je.style.display="")):G==="resume"&&(w.resume(),O=0,Je.style.display="none")},E=()=>{p&&(ze.scrollTop=ze.scrollHeight,w.resume(),O=0,Je.style.display="none")},R=$=>{let G=$.target;if(!G||G.closest("button"))return;let de=G.closest("[data-event-id]");if(!de)return;let ot=de.getAttribute("data-event-id");ot&&ye(ot)},_=$=>{if(($.metaKey||$.ctrlKey)&&$.key==="f"){$.preventDefault(),te?.focus(),te?.select();return}$.key==="Escape"&&(te&&document.activeElement===te?(I(),te.blur(),C.focus()):o&&o())};ae&&ae.addEventListener("click",ie),K&&K.addEventListener("change",_e),te&&te.addEventListener("input",Le),ve&&ve.addEventListener("click",I),ze.addEventListener("scroll",Y),ze.addEventListener("wheel",x,{passive:!0}),ze.addEventListener("click",R),Je.addEventListener("click",E),C.addEventListener("keydown",_);function J(){A&&clearTimeout(A),P!==null&&(cancelAnimationFrame(P),P=null),L=!1,he.clear(),ae&&ae.removeEventListener("click",ie),K&&K.removeEventListener("change",_e),te&&te.removeEventListener("input",Le),ve&&ve.removeEventListener("click",I),ze.removeEventListener("scroll",Y),ze.removeEventListener("wheel",x),ze.removeEventListener("click",R),Je.removeEventListener("click",E),C.removeEventListener("keydown",_)}return{element:C,update:Ct,destroy:J}}}nt();kt();function Bf(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 b=u;return s.findIndex(f=>f===b||f.contains(b))},c=u=>{let b=p(u.target);if(b<0)return;let f=b;if(u.key===r)f=Math.min(b+1,s.length-1);else if(u.key===o)f=Math.max(b-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=s.length-1;else return;u.preventDefault(),f!==b&&e.onSelect(f)},d=u=>{let b=p(u.target);b>=0&&l(s[b])};return t.addEventListener("keydown",c),t.addEventListener("focusin",d),{beforeRender(){i=typeof document<"u"&&t.contains(document.activeElement)},render(u,b){if(s=u,u.forEach((f,m)=>{f.setAttribute("role","tab");let C=m===b;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||b<0&&m===0?0:-1}),i){let f=(b>=0?u[b]:void 0)??u[0];f&&typeof f.focus=="function"&&(l(f),f.focus())}},destroy(){t.removeEventListener("keydown",c),t.removeEventListener("focusin",d)}}}function Df(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=j=>({start:j===!1?!1:typeof j=="object"&&j?j.start!==!1:!0,end:j===!1?!1:typeof j=="object"&&j?j.end!==!1:!0}),{start:d,end:u}=c(n?.tabFade),b=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,f=()=>{b?.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),H?.hide()};b&&b.addEventListener("click",()=>{f(),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 k=h("span","persona-text-xs persona-font-medium persona-truncate");k.textContent=s;let D=Nt({icon:"x",label:i});D.addEventListener("click",()=>{f(),e.onDismiss?.()});let M="rendered",A=Ji({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:j=>{M=j==="source"?"source":"rendered",ue()}}),W=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),z=n?.documentToolbarShowCopyLabel===!0,U=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,O=!!(U&&w&&w.length>0),N=null,L,P=null,H=null;if(r&&(z||U)&&!O){if(L=z?Fo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Nt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),U){let j=se("chevron-down",14,"currentColor",2);j&&L.appendChild(j)}}else r&&O?(N=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),L=z?Fo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Nt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P=Nt({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=Nt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(L=Nt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&L.classList.add("persona-hidden"));let ne=r?Nt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Nt({icon:"refresh-cw",label:"Refresh"}),pe=r?Nt({icon:"x",label:i,className:"persona-artifact-doc-icon-btn"}):Nt({icon:"x",label:i}),he=Nt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&he.classList.add("persona-hidden");let fe=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 j=Ee.find(I=>I.id===Ne)??Ee[Ee.length-1],ie=j?.id??null,_e=j?.artifactType==="markdown"?j.markdown??"":"",Le=j?JSON.stringify({component:j.component,props:j.props},null,2):"";return{markdown:_e,jsonPayload:Le,id:ie}},K=async()=>{let j=Ee.find(ie=>ie.id===Ne)??Ee[Ee.length-1];try{await navigator.clipboard.writeText(Cs(j))}catch{}};if(L.addEventListener("click",async()=>{let j=n?.onDocumentToolbarCopyMenuSelect;if(j&&O){let{markdown:ie,jsonPayload:_e,id:Le}=oe();try{await j({actionId:"primary",artifactId:Le,markdown:ie,jsonPayload:_e})}catch{}return}await K()}),P&&w?.length){let j=()=>m.closest("[data-persona-root]")??document.body,ie=()=>{H=yr({items:w.map(_e=>({id:_e.id,label:_e.label})),onSelect:async _e=>{let{markdown:Le,jsonPayload:I,id:Y}=oe(),x=n?.onDocumentToolbarCopyMenuSelect;try{x?await x({actionId:_e,artifactId:Y,markdown:Le,jsonPayload:I}):_e==="markdown"||_e==="md"?await navigator.clipboard.writeText(Le):_e==="json"||_e==="source"?await navigator.clipboard.writeText(I):await navigator.clipboard.writeText(Le||I)}catch{}},anchor:N??P,position:"bottom-right",portal:j()})};m.isConnected?ie():requestAnimationFrame(ie),P.addEventListener("click",_e=>{_e.stopPropagation(),H?.toggle()})}ne.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}ue()}),pe.addEventListener("click",()=>{f(),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,ne,pe):W.append(L,ne,pe),W.insertBefore(fe,pe),W.insertBefore(he,pe),C.append(A.element,ae,W);else{let j=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");j.append(L,fe,he,D),C.appendChild(k),C.appendChild(j)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let te=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&&te.style.setProperty("--persona-artifact-tab-fade-size",p);let ve=t.features?.artifacts?.renderTabBar,xe=h("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),ge=Bf(te,{onSelect:j=>e.onSelect(Ee[j].id)}),Te=j=>{let ie=j.scrollWidth-j.clientWidth,_e=ie>1,Le=Math.abs(j.scrollLeft);j.classList.toggle("persona-artifact-tab-fade-start",d&&_e&&Le>1),j.classList.toggle("persona-artifact-tab-fade-end",u&&_e&&Le<ie-1)},Me=0,Fe=()=>{if(Me)return;let j=()=>{Me=0,Te(te)};Me=typeof requestAnimationFrame=="function"?requestAnimationFrame(j):setTimeout(j,0)};te.addEventListener("scroll",()=>Fe(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Te(te)).observe(te);let Pe=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");if(l){for(let j of[te,xe])j.style.paddingLeft=l,j.style.paddingRight=l;Pe.style.padding=l}m.appendChild(C),m.appendChild(te),m.appendChild(xe),m.appendChild(Pe);let Ee=[],Ne=null,lt=!1,ze=!0,Je=!1,pn=null,It="",mt=null,Re=!1,we=j=>j.artifactType==="markdown"&&!!j.file||r?M:"rendered",ct=j=>{r||(j&&!Re?(C.insertBefore(A.element,k),Re=!0):!j&&Re&&(A.element.remove(),Re=!1))},He=()=>Ne&&Ee.find(j=>j.id===Ne)||Ee[Ee.length-1],ye=()=>{let j=vs(He());if(!j){fe.replaceChildren();return}let ie=ee.filter(_e=>_e.visible===void 0||_e.visible(j)).map(_e=>vr(_e,{documentChrome:r,onClick:()=>{let Le=vs(He());if(Le)try{Promise.resolve(_e.onClick(Le)).catch(()=>{})}catch{}}}));fe.replaceChildren(...ie)},ue=()=>{ye();let j=r&&Ee.length<=1,ie=!!ve;if(te.classList.toggle("persona-hidden",j||ie),xe.classList.toggle("persona-hidden",j||!ie),ie&&ve){let I=Ee.map(Y=>Y.id).join("|")+" "+(Ne??"");if(I!==It){It=I;let Y=ve({records:Ee,selectedId:Ne,onSelect:e.onSelect});xe.firstElementChild!==Y&&xe.replaceChildren(Y)}}else{ge.beforeRender(),te.replaceChildren();let I=[],Y=-1;for(let[x,E]of Ee.entries()){let R=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");R.type="button";let _=E.artifactType==="markdown"?E.file:void 0,J=_?Pn(_.path):E.title||E.id.slice(0,8),$=_?.path||E.title||J;R.textContent=J,R.title=$,R.setAttribute("aria-label",$),E.id===Ne&&(R.classList.add("persona-bg-persona-container","persona-border-persona-border"),Y=x),R.addEventListener("click",()=>e.onSelect(E.id)),te.appendChild(R),I.push(R)}if(ge.render(I,Y),Y>=0&&Ne!==pn){pn=Ne;let x=I[Y];typeof x.scrollIntoView=="function"&&x.scrollIntoView({block:"nearest",inline:"nearest"})}Te(te)}let _e=Ne&&Ee.find(I=>I.id===Ne)||Ee[Ee.length-1];if(!_e){Pe.replaceChildren(),mt=null,ct(!1);return}let Le=_e.artifactType==="markdown"?_e.file:void 0;if(ct(!!Le),r){let I=Le?lo(Le):_e.artifactType==="markdown"?"MD":_e.component??"Component",Y=(_e.title||"Document").trim(),x=Le?Pn(Le.path):Y.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ae.textContent=`${x} \xB7 ${I}`}else k.textContent=Le?Pn(Le.path):s;mt?(mt.el.parentElement!==Pe&&Pe.replaceChildren(mt.el),mt.update(_e)):(mt=ea(_e,{config:t,resolveViewMode:we}),Pe.replaceChildren(mt.el)),Pe.classList.toggle("persona-artifact-content-flush",!!Pe.querySelector(".persona-code-pre"))},Ae=()=>{let j=Ee.length>0;if(m.classList.toggle("persona-hidden",!j),b){let Le=((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;j&&Le&<?(b.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(b.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}},Ct=()=>{Je=!1,ue(),Ae()};return{element:m,backdrop:b,update(j){Ee=j.artifacts,Ne=j.selectedId??j.artifacts[j.artifacts.length-1]?.id??null,Ee.length>0&&(lt=!0),Je=!0,ze&&Ct()},setMobileOpen(j){lt=j,!j&&b?(b.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):Ae()},setExpanded(j){let ie=se(j?"minimize":"maximize",16,"currentColor",2);ie&&he.replaceChildren(ie);let _e=j?"Collapse artifacts panel":"Expand artifacts panel";he.setAttribute("aria-label",_e),he.title=_e},setExpandToggleVisible(j){he.classList.toggle("persona-hidden",!j)},setCopyButtonVisible(j){r||L.classList.toggle("persona-hidden",!j)},setCustomActions(j){ee=j,ye()},setTabFade(j){let ie=c(j);ie.start===d&&ie.end===u||(d=ie.start,u=ie.end,Te(te))},setRenderTabBar(j){j!==ve&&(ve=j,It="",ue())},setVisible(j){j!==ze&&(ze=j,j&&Je&&Ct())}}}function Zt(t){return t?.features?.artifacts?.enabled===!0}function Nf(t,e){if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!Zt(e))return;let n=e.features?.artifacts?.layout,o=n?.paneBorder?.trim(),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 tv(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 Of=["panel","seamless","detached"];function ac(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&Of.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function lc(t){return!t||!Zt(t)?!1:ac(t)==="detached"}function Ws(t,e){if(!Zt(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),tv(t),Nf(t,e);return}let n=e.features?.artifacts?.layout,o=ac(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"),Nf(t,e)}function Hs(t,e){for(let l of Of)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"),!Zt(e))return;let n=e.features?.artifacts?.layout,o=ac(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 Ff(t,e){return!e||!Zt(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function nv(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 ov(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 rv(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function sv(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function cc(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 _f(t,e,n,o,r,s){let i=nv(r,200),l=sv(e,n,o,200);l=Math.max(i,l);let p=ov(s);return p!==null&&(l=Math.min(l,p)),rv(t,i,l)}nt();var $f={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"}},dc=(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=$f[i]??$f.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 k=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=m.label,C.appendChild(k);let D=m.type??"text",M;D==="textarea"?(M=document.createElement("textarea"),M.rows=3):(M=document.createElement("input"),M.type=D),M.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",M.id=`${e.id}-${i}-${m.name}`,M.name=m.name,M.placeholder=m.placeholder??"",m.required&&(M.required=!0),C.appendChild(M),d.appendChild(C)});let u=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),b=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=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");f.type="submit",f.textContent=l.submitLabel??"Submit",u.appendChild(b),u.appendChild(f),d.appendChild(u),s.replaceChildren(p,d),d.addEventListener("submit",async m=>{m.preventDefault();let C=n.formEndpoint??"/form",k=new FormData(d),D={};k.forEach((M,A)=>{D[A]=M}),D.type=i,f.disabled=!0,b.textContent="Submitting\u2026";try{let M=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let A=await M.json();b.textContent=A.message??"Thanks! We'll be in touch soon.",A.success&&A.nextPrompt&&await o.sendMessage(String(A.nextPrompt))}catch(M){b.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var pc=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()}},uc=new pc;var zf=()=>{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 iv=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},av=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},gc=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=iv(t),n=av(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}},fc=t=>typeof t=="string"?t:t==null?"":String(t),Bs={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:fc(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=fc(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:fc(n.text)}}},Uf=t=>Array.isArray(t)?t.map(e=>String(e)):[],mc=t=>{let e=new Set(Uf(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(Uf(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 b=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:b,resubmit:u.resubmit}}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:n}};var lv=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}},cv=t=>t.map(e=>({...e,streaming:!1})),dv=t=>t.map(e=>({...e,status:"complete"})),jf=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?lv(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?cv(n.messages):void 0,artifacts:n.artifacts?dv(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 hc=require("partial-json");function qf(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=jn.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 Vf(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 bc(t){let e=Vf(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 Kf(t){let e=Vf(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 pv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Gf(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=pv}=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,b=document.createElement("div");b.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let m=document.createElement("h3");m.className="persona-feedback-title",m.textContent=o,f.appendChild(m);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,f.appendChild(C),b.appendChild(f);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-csat",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Satisfaction rating from 1 to 5");let D=[];for(let U=1;U<=5;U++){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",`${U} star${U>1?"s":""}: ${c[U-1]}`),w.title=c[U-1],w.dataset.rating=String(U),w.innerHTML=`
|
|
215
|
+
`):""},oc=(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)"},ky=(t,e)=>{let n=t.toolCall,o=e?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=Ey(t,o?.previewMaxLines??3),i=n?mp(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=hl(n,p.activeTextTemplate,c):!l&&p.completeTextTemplate&&(c=hl(n,p.completeTextTemplate,c)),{summary:c,previewText:s,isActive:l}},Af=(t,e,n)=>{let o=wr.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")},rc=(t,e)=>{let n=t.toolCall,o=e?.toolCall??{},r=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${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&&wr.has(t.id),{summary:p,previewText:c,isActive:d}=ky(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 b=h("div","persona-flex persona-flex-col persona-text-left"),f=h("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(f.style.color=o.headerTextColor);let m=String(n.startedAt??Date.now()),C=()=>{let L=h("span","");return L.setAttribute("data-tool-elapsed",m),L.textContent=ns(n),L},I=o.renderCollapsedSummary?.({message:t,toolCall:n,defaultSummary:p,previewText:c,collapsedMode:s.collapsedMode??"tool-call",isActive:d,config:e??{},elapsed:ns(n),createElapsedElement:C});typeof I=="string"&&I.trim()?(f.textContent=I,b.appendChild(f)):I instanceof HTMLElement?b.appendChild(I):(f.textContent=p,b.appendChild(f));let D=s.loadingAnimation??"none",T=o.activeTextTemplate,A=o.completeTextTemplate,W=d?T:A,z=I instanceof HTMLElement,U=(L,H)=>{f.textContent="";let ne=n.name?.trim()||"tool",de=wi(L,ne),me=0;for(let ue of de){let ee=ue.styles.length>0?(()=>{let re=h("span",ue.styles.map(G=>`persona-tool-text-${G}`).join(" "));return f.appendChild(re),re})():f;if(ue.isDuration&&d)ee.appendChild(C());else{let re=ue.isDuration?ns(n):ue.text;H?me=co(ee,re,me):ee.appendChild(document.createTextNode(re))}}};if(!z)if(d&&D!=="none"){let L=o.loadingAnimationDuration??2e3;if(f.setAttribute("data-preserve-animation","true"),D==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${L}ms`),W&&U(W,!1);else if(f.classList.add(`persona-tool-loading-${D}`),f.style.setProperty("--persona-tool-anim-duration",`${L}ms`),D==="shimmer-color"&&(o.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),W)U(W,!0);else{let H=f.textContent||p;f.textContent="",co(f,H,0)}}else W&&U(W,!1);let w=null;if(i){w=h("div","persona-flex persona-items-center");let L=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",H=se(l?"chevron-up":"chevron-down",16,L,2);H?w.appendChild(H):w.textContent=l?"Hide":"Show";let ne=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ne.append(w),u.append(b,ne)}else u.append(b);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 L=o.renderCollapsedPreview?.({message:t,toolCall:n,defaultPreview:c,isActive:d,config:e??{}});Ty(O,L)||(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 L=h("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?L.style.color=o.contentTextColor:o.headerTextColor&&(L.style.color=o.headerTextColor),L.textContent=n.name,N.appendChild(L)}if(n.args!==void 0){let L=h("div","persona-space-y-1"),H=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(H.style.color=o.labelTextColor),H.textContent="Arguments";let ne=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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",oc(ne,o),ne.textContent=ao(n.args),L.append(H,ne),N.appendChild(L)}if(n.chunks&&n.chunks.length){let L=h("div","persona-space-y-1"),H=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(H.style.color=o.labelTextColor),H.textContent="Activity";let ne=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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",oc(ne,o),ne.textContent=n.chunks.join(""),L.append(H,ne),N.appendChild(L)}if(n.status==="complete"&&n.result!==void 0){let L=h("div","persona-space-y-1"),H=h("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(H.style.color=o.labelTextColor),H.textContent="Result";let ne=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");ne.style.fontSize="0.75rem",ne.style.lineHeight="1rem",oc(ne,o),ne.textContent=ao(n.result),L.append(H,ne),N.appendChild(L)}if(n.status==="complete"&&typeof n.duration=="number"){let L=h("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(L.style.color=o.contentTextColor),L.textContent=`Duration: ${n.duration}ms`,N.appendChild(L)}return(()=>{if(u.setAttribute("aria-expanded",l?"true":"false"),w){w.innerHTML="";let L=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",H=se(l?"chevron-up":"chevron-down",16,L,2);H?w.appendChild(H):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};st();Et();var _o=new Map,xa=t=>{let n=(t.startsWith(Fn)?t.slice(Fn.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)},Sf=t=>t?.approval!==!1?t?.approval:void 0,Mf=(t,e)=>{let n=Sf(e)?.detailsDisplay??"collapsed";return _o.get(t)??n==="expanded"},Tf=(t,e,n)=>{let o=Sf(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)}},Ef=(t,e,n)=>{let o=e.querySelector('button[data-bubble-type="approval"]'),r=e.querySelector("[data-approval-details]");if(!o||!r)return;let s=Mf(t,n);Tf(o,s,n),r.style.display=s?"":"none"};var Ca=(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-max-w-[85%]","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"),b=h("div","persona-flex persona-items-center persona-gap-2"),f=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(f.style.color=o.titleColor),f.textContent=o?.title??"Approval Required",b.appendChild(f),!r){let 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"),b.appendChild(w)}u.appendChild(b);let C=n.toolType==="webmcp"||n.toolName.startsWith(Fn)?Yr(n.toolName):void 0,I=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),D=!n.toolName,T=I||(D?n.description:`The assistant wants to use \u201C${C??xa(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=T,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&&!D,U=z||!!n.parameters;if(W!=="hidden"&&U){let w=Mf(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 R=h("span","persona-inline-flex persona-items-center");R.setAttribute("data-approval-details-chevron","true"),O.append(N,R),Tf(O,w,e),u.appendChild(O);let L=h("div");if(L.setAttribute("data-approval-details","true"),L.style.display=w?"":"none",z){let H=h("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(H.style.color=o.descriptionColor),H.textContent=n.description,L.appendChild(H)}if(n.parameters){let H=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&&(H.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(H.style.color=o.parameterTextColor),H.style.fontSize="0.75rem",H.style.lineHeight="1rem",H.textContent=ao(n.parameters),L.appendChild(H)}u.appendChild(L)}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 R=document.createTextNode(o?.approveLabel??"Approve");O.appendChild(R);let L=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");L.type="button",L.style.backgroundColor=o?.denyButtonColor??"transparent",L.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",L.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,L.setAttribute("data-approval-action","deny");let H=se("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);H&&(H.style.marginRight="4px",L.appendChild(H));let ne=document.createTextNode(o?.denyLabel??"Deny");L.appendChild(ne),w.append(O,L),u.appendChild(w)}return i.append(l,u),s.appendChild(i),s};st();Et();Tl();var Ly=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),kf=(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))},$o=(t,e)=>{kf(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)},Py=t=>t?.approval!==!1?t?.approval:void 0,Iy=(t,e)=>{let n=e?.detailsDisplay??"collapsed";return _o.get(t)??n==="expanded"},sc=t=>{let e=h("span","persona-approval-kbd");return e.textContent=t,e},Ry=(t,e)=>{let n=h("span","persona-approval-title");e?.titleColor&&(n.style.color=e.titleColor);let r=t.toolType==="webmcp"||t.toolName.startsWith(Fn)?Yr(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??xa(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},Wy=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?xa(t.toolName):"Tool",e.append(o,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},Hy=(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,b=u&&Iy(e.id,o),f=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",b?"true":"false"),C.setAttribute("aria-label",b?m:f)):C.setAttribute("data-static","true");let I=h("span","persona-approval-logo"),D=se("shield-check",16,"currentColor",2);D&&I.appendChild(D),C.appendChild(I);let T=Ry(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),T.append(" "),T.appendChild(O)}C.appendChild(T),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=!b,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,U=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"),U(N),N.append(o?.approveLabel??"Always allow",sc("\u23CE"));let R=h("button","persona-approval-caret");R.type="button",R.setAttribute("data-action","toggle-menu"),R.setAttribute("aria-label","More options"),U(R);let L=se("chevron-down",15,"currentColor",2);L&&R.appendChild(L),O.append(N,R),W.append(O,w),w.append(sc("Esc"));let H=h("div","persona-approval-menu"),ne=h("button","persona-approval-menu-item");ne.type="button",ne.append("Allow once",sc("\u2318\u23CE")),H.appendChild(ne),z=Ni({anchor:O,content:H,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,z),ne.addEventListener("click",()=>{$o(t,e.id),r()})}else{let O=h("button","persona-approval-primary persona-approval-primary--solo");O.type="button",O.setAttribute("data-action","allow"),U(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 R=N.getAttribute("data-action");if(R==="toggle-params"){let L=l.querySelector('[data-role="params"]');if(L){let H=L.hidden;L.hidden=!H,C.setAttribute("aria-expanded",H?"true":"false"),C.setAttribute("aria-label",H?m:f),_o.set(e.id,H)}return}if(R==="toggle-menu"){z?.toggle();return}if(R==="always"){$o(t,e.id),r({remember:!0});return}if(R==="allow"){$o(t,e.id),r();return}if(R==="deny"){$o(t,e.id),s();return}}),l},Lf=()=>{let t=Ly();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=Py(i);if(l.status!=="pending"){if($o(t,o.id),l.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Wy(l)}kf(t,o.id);let c=p?.enableAlwaysAllow===!0,d=Hy(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=b=>{Xp(b)||o.id===t.latestPendingApprovalId&&(b.key!=="Escape"&&b.key!=="Enter"||(b.preventDefault(),b.stopImmediatePropagation(),$o(t,o.id),b.key==="Escape"?s():b.metaKey||b.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()])$o(t,o);t.latestPendingApprovalId=null}}};st();var Pf=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(I=>I.role==="user"))return;let u=document.createDocumentFragment(),b=s?s.isStreaming():!1,f=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=b,p?.fontFamily&&(C.style.fontFamily=f(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 Ps=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 Is=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 By=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Dy=new Set(["step_start","execution_start"]),Ny=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Oy=new Set(["step_complete","agent_turn_complete"]),Fy=new Set(["flow_complete","agent_complete"]),If=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Wf=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),cn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,zo=(t,e)=>{let n=t[e];return Wf(n)?n:void 0};function ic(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function wa(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function _y(t,e){return typeof e.type=="string"?e.type:t}function $y(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 zy(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 Rf(t){let e=zo(t,"result"),n=[zo(t,"tokens"),zo(t,"totalTokens"),e?zo(e,"tokens"):void 0,zo(t,"usage"),e?zo(e,"usage"):void 0];for(let o of n){if(!o)continue;let r=cn(o.output)??cn(o.outputTokens)??cn(o.completionTokens);if(r!==void 0)return r}return cn(t.outputTokens)??cn(t.completionTokens)??(e?cn(e.outputTokens)??cn(e.completionTokens):void 0)}function Uy(t){let e=zo(t,"result");return cn(t.executionTime)??cn(t.executionTimeMs)??cn(t.execution_time)??cn(t.duration)??(e?cn(e.executionTime)??cn(e.executionTimeMs):void 0)}function jy(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Rs=class{constructor(e=jy){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:wa(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(!Wf(n)){If.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=_y(e,n),r=this.now();if(By.has(o)){this.startRun(r);return}if(Dy.has(o)){this.run||this.startRun(r);return}if(Ny.has(o)){if(!zy(o,n))return;let s=$y(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+ic(i.visibleCharCount),p=r-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:wa(l,p),outputTokens:l,durationMs:p,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Oy.has(o)){if(!this.run)return;let s=this.run,i=Rf(n);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let l=s.exactOutputTokens>0,p=s.exactOutputTokens+ic(s.visibleCharCount),c=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:wa(p,c),outputTokens:p,durationMs:c,source:l?"usage":"estimate"};return}if(Fy.has(o)){if(!this.run)return;let s=this.run,i=Rf(n),l=i??s.exactOutputTokens+ic(s.visibleCharCount),p=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",c=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:wa(l,c),outputTokens:l,durationMs:c,source:p},this.run=null;return}if(If.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:Uy(n)??o-e.startedAt}};st();Et();function Ar(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}var qy={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)"}},Vy={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Ky=["flowName","stepName","reasoningText","text","name","tool","toolName"],Gy=100;function Qy(t,e){let n={...qy,...e};if(n[t])return n[t];for(let o of Object.keys(n))if(o.endsWith("_")&&t.startsWith(o))return n[o];return Vy}function Xy(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function Jy(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 Yy(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 Zy(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 ev(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 tv(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function nv(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 ov(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 ac(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");Ar(c,o.classNames?.eventRow);let d=i.find(b=>b.renderEventStreamRow);if(d?.renderEventStreamRow&&l){let b=d.renderEventStreamRow({event:t,index:e,config:l,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(t.id)});if(b)return c.appendChild(b),c}return c.appendChild(u()),c;function u(){let b=h("div",""),f=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");f.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 I=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),D=o.timestampFormat??"relative";I.textContent=D==="relative"?Xy(t.timestamp,n):Jy(t.timestamp);let T=null;o.showSequenceNumbers!==!1&&(T=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),T.textContent=String(e+1));let A=Qy(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??Ky,U=Yy(t.payload,z),w=null;U&&(w=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=U);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"),R=se("clipboard","12px","currentColor",1.5);return R&&N.appendChild(R),N.addEventListener("click",async L=>{L.stopPropagation(),await Zy(ev(t)),N.innerHTML="";let H=se("check","12px","currentColor",1.5);H&&N.appendChild(H),setTimeout(()=>{N.innerHTML="";let ne=se("clipboard","12px","currentColor",1.5);ne&&N.appendChild(ne)},1500)}),f.appendChild(m),f.appendChild(I),T&&f.appendChild(T),f.appendChild(W),w&&f.appendChild(w),f.appendChild(O),f.appendChild(N),b.appendChild(f),p&&b.appendChild(ov(t,i,l)),b}}function Hf(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??{},b=s.find(m=>m.renderEventStreamView);if(b?.renderEventStreamView&&r){let m=b.renderEventStreamView({config:r,events:e.getAll(),defaultRenderer:()=>f().element,onClose:o});if(m)return{element:m,update:()=>{},destroy:()=>{}}}return f();function f(){let m=u.classNames,C=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ar(C,m?.panel);let I=[],D="",T="",A=null,W=[],z={},U=0,w=oa(),O=0,N=0,R=!1,L=null,H=!1,ne=0,de=new Set,me=new Map,ue="",ee="",re=null,G,ie,te,ye,ve=null,fe=null,Ee=null;function Te(){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(Ar(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",ve=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"),ve.textContent="-- tok/s",Ee=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"),Ee.style.display="none",Ee.style.pointerEvents="none";let tt=fe,mo=Ee,ho=()=>{if(!mo.textContent)return;let Ns=tt.getBoundingClientRect(),Zt=$.getBoundingClientRect();mo.style.left=`${Ns.left-Zt.left}px`,mo.style.top=`${Ns.bottom-Zt.top+4}px`,mo.style.display="block"},Ma=()=>{mo.style.display="none"};fe.addEventListener("mouseenter",ho),fe.addEventListener("mouseleave",Ma),fe.appendChild(ve)}let ae=h("div","persona-flex-1");G=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 Qe=h("option","");Qe.value="",Qe.textContent="All events (0)",G.appendChild(Qe),ie=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"),ie.type="button",ie.title="Copy All";let dt=se("clipboard-copy","12px","currentColor",1.5);dt&&ie.appendChild(dt);let X=h("span","persona-event-copy-all persona-text-xs");X.textContent="Copy All",ie.appendChild(X),fe&&K.appendChild(fe),K.appendChild(ae),K.appendChild(G),K.appendChild(ie);let ze=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ar(ze,m?.searchBar);let Re=se("search","14px","var(--persona-muted, #9ca3af)",1.5),Ne=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");Re&&Ne.appendChild(Re),te=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"),Ar(te,m?.searchInput),te.type="text",te.placeholder="Search event payloads...",ye=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"),ye.type="button",ye.style.display="none";let He=se("x","12px","currentColor",2);return He&&ye.appendChild(He),ze.appendChild(Ne),ze.appendChild(te),ze.appendChild(ye),$.appendChild(K),$.appendChild(ze),Ee&&$.appendChild(Ee),$}let Fe,Le=s.find($=>$.renderEventStreamToolbar);Le?.renderEventStreamToolbar&&r?Fe=Le.renderEventStreamToolbar({config:r,defaultRenderer:()=>Te(),eventCount:e.getSize(),filteredCount:0,onFilterChange:K=>{D=K,We(),Se()},onSearchChange:K=>{T=K,We(),Se()}})??Te():Fe=Te();let Ge=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");Ge.style.display="none";function Ze(){if(!i||!ve||!fe)return;let $=i(),K=tv($);ve.textContent=K;let ae=nv($);Ee&&(Ee.textContent=ae,ae||(Ee.style.display="none")),fe.setAttribute("aria-label",ae?`Throughput: ${K}, ${ae}`:`Throughput: ${K}`)}let Be=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 et=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");Ar(et,m?.scrollIndicator),et.style.display="none",et.setAttribute("data-persona-scroll-to-bottom-has-label",d?"true":"false");let dn=se(c,"14px","currentColor",2);dn&&et.appendChild(dn);let Pt=h("span","");Pt.textContent=d,et.appendChild(Pt);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",Be.appendChild(Pe),Be.appendChild(xt),Be.appendChild(et),C.setAttribute("tabindex","0"),C.appendChild(Fe),C.appendChild(Ge),C.appendChild(Be);function De(){let $=e.getAll(),K={};for(let ze of $)K[ze.type]=(K[ze.type]||0)+1;let ae=Object.keys(K).sort(),Qe=ae.length!==W.length||!ae.every((ze,Re)=>ze===W[Re]),Ie=!Qe&&ae.some(ze=>K[ze]!==z[ze]),dt=$.length!==Object.values(z).reduce((ze,Re)=>ze+Re,0);if(!Qe&&!Ie&&!dt||(W=ae,z=K,!G))return;let X=G.value;if(G.options[0].textContent=`All events (${$.length})`,Qe){for(;G.options.length>1;)G.remove(1);for(let ze of ae){let Re=h("option","");Re.value=ze,Re.textContent=`${ze} (${K[ze]||0})`,G.appendChild(Re)}X&&ae.includes(X)?G.value=X:X&&(G.value="",D="")}else for(let ze=1;ze<G.options.length;ze++){let Re=G.options[ze];Re.textContent=`${Re.value} (${K[Re.value]||0})`}}function we(){let $=e.getAll();if(D&&($=$.filter(K=>K.type===D)),T){let K=T.toLowerCase();$=$.filter(ae=>ae.type.toLowerCase().includes(K)||ae.payload.toLowerCase().includes(K))}return $}function Je(){return D!==""||T!==""}function We(){U=0,O=0,w.resume(),et.style.display="none"}function xe($){de.has($)?de.delete($):de.add($),re=$;let K=Pe.scrollTop,ae=w.isFollowing();H=!0,w.pause(),Se(),Pe.scrollTop=K,ae&&w.resume(),H=!1}function pe(){return fo(Pe,50)}function Se(){N=Date.now(),R=!1,Ze(),De();let $=e.getEvictedCount();$>0?(Ge.textContent=`${$.toLocaleString()} older events truncated`,Ge.style.display=""):Ge.style.display="none",I=we();let K=I.length,ae=e.getSize()>0;K===0&&ae&&Je()?(xt.textContent=T?`No events matching '${T}'`:"No events matching filter",xt.style.display="",Pe.style.display="none"):(xt.style.display="none",Pe.style.display=""),ie&&(ie.title=Je()?`Copy Filtered (${K})`:"Copy All"),p&&!w.isFollowing()&&K>U&&(O+=K-U,Pt.textContent=d?`${d}${O>0?` (${O})`:""}`:"",et.style.display=""),U=K;let Qe=e.getAll(),Ie=Qe.length>0?Qe[0].timestamp:0,dt=new Set(I.map(Re=>Re.id));for(let Re of de)dt.has(Re)||de.delete(Re);let X=D!==ue||T!==ee,ze=me.size===0&&I.length>0;if(X||ze||I.length===0){Pe.innerHTML="",me.clear();let Re=document.createDocumentFragment();for(let Ne=0;Ne<I.length;Ne++){let He=ac(I[Ne],Ne,Ie,u,de,xe,s,r);me.set(I[Ne].id,He),Re.appendChild(He)}Pe.appendChild(Re),ue=D,ee=T,re=null}else{if(re!==null){let Ne=me.get(re);if(Ne&&Ne.parentNode===Pe){let He=I.findIndex(tt=>tt.id===re);if(He>=0){let tt=ac(I[He],He,Ie,u,de,xe,s,r);Pe.insertBefore(tt,Ne),Ne.remove(),me.set(re,tt)}}re=null}let Re=new Set(I.map(Ne=>Ne.id));for(let[Ne,He]of me)Re.has(Ne)||(He.remove(),me.delete(Ne));for(let Ne=0;Ne<I.length;Ne++){let He=I[Ne];if(!me.has(He.id)){let tt=ac(He,Ne,Ie,u,de,xe,s,r);me.set(He.id,tt),Pe.appendChild(tt)}}}w.isFollowing()&&(Pe.scrollTop=Pe.scrollHeight)}function Ct(){if(Date.now()-N>=Gy){L!==null&&(cancelAnimationFrame(L),L=null),Se();return}R||(R=!0,L=requestAnimationFrame(()=>{L=null,Se()}))}let Ae=($,K)=>{if(!ie)return;ie.innerHTML="";let ae=se($,"12px","currentColor",1.5);ae&&ie.appendChild(ae);let Qe=h("span","persona-text-xs");Qe.textContent="Copy All",ie.appendChild(Qe),setTimeout(()=>{ie.innerHTML="";let Ie=se("clipboard-copy","12px","currentColor",1.5);Ie&&ie.appendChild(Ie);let dt=h("span","persona-text-xs");dt.textContent="Copy All",ie.appendChild(dt),ie.disabled=!1},K)},be=async()=>{if(ie){ie.disabled=!0;try{let $;Je()?$=I:n?($=await n(),$.length===0&&($=e.getAll())):$=e.getAll();let K=$.map(ae=>{try{return JSON.parse(ae.payload)}catch{return ae.payload}});await navigator.clipboard.writeText(JSON.stringify(K,null,2)),Ae("check",1500)}catch{Ae("x",1500)}}},bn=()=>{G&&(D=G.value,We(),Se())},Z=()=>{!te||!ye||(ye.style.display=te.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{T=te.value,We(),Se()},150))},k=()=>{!te||!ye||(te.value="",T="",ye.style.display="none",A&&clearTimeout(A),We(),Se())},j=()=>{if(H)return;let $=Pe.scrollTop,{action:K,nextLastScrollTop:ae}=ra({following:w.isFollowing(),currentScrollTop:$,lastScrollTop:ne,nearBottom:pe(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ne=ae,K==="resume"?(w.resume(),O=0,et.style.display="none"):K==="pause"&&(w.pause(),p&&(Pt.textContent=d,et.style.display=""))},v=$=>{let K=sa({following:w.isFollowing(),deltaY:$.deltaY,nearBottom:pe(),resumeWhenNearBottom:!0});K==="pause"?(w.pause(),p&&(Pt.textContent=d,et.style.display="")):K==="resume"&&(w.resume(),O=0,et.style.display="none")},S=()=>{p&&(Pe.scrollTop=Pe.scrollHeight,w.resume(),O=0,et.style.display="none")},P=$=>{let K=$.target;if(!K||K.closest("button"))return;let ae=K.closest("[data-event-id]");if(!ae)return;let Qe=ae.getAttribute("data-event-id");Qe&&xe(Qe)},_=$=>{if(($.metaKey||$.ctrlKey)&&$.key==="f"){$.preventDefault(),te?.focus(),te?.select();return}$.key==="Escape"&&(te&&document.activeElement===te?(k(),te.blur(),C.focus()):o&&o())};ie&&ie.addEventListener("click",be),G&&G.addEventListener("change",bn),te&&te.addEventListener("input",Z),ye&&ye.addEventListener("click",k),Pe.addEventListener("scroll",j),Pe.addEventListener("wheel",v,{passive:!0}),Pe.addEventListener("click",P),et.addEventListener("click",S),C.addEventListener("keydown",_);function Q(){A&&clearTimeout(A),L!==null&&(cancelAnimationFrame(L),L=null),R=!1,me.clear(),ie&&ie.removeEventListener("click",be),G&&G.removeEventListener("change",bn),te&&te.removeEventListener("input",Z),ye&&ye.removeEventListener("click",k),Pe.removeEventListener("scroll",j),Pe.removeEventListener("wheel",v),Pe.removeEventListener("click",P),et.removeEventListener("click",S),C.removeEventListener("keydown",_)}return{element:C,update:Ct,destroy:Q}}}st();Et();function Bf(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 b=u;return s.findIndex(f=>f===b||f.contains(b))},c=u=>{let b=p(u.target);if(b<0)return;let f=b;if(u.key===r)f=Math.min(b+1,s.length-1);else if(u.key===o)f=Math.max(b-1,0);else if(u.key==="Home")f=0;else if(u.key==="End")f=s.length-1;else return;u.preventDefault(),f!==b&&e.onSelect(f)},d=u=>{let b=p(u.target);b>=0&&l(s[b])};return t.addEventListener("keydown",c),t.addEventListener("focusin",d),{beforeRender(){i=typeof document<"u"&&t.contains(document.activeElement)},render(u,b){if(s=u,u.forEach((f,m)=>{f.setAttribute("role","tab");let C=m===b;f.setAttribute("aria-selected",C?"true":"false"),f.tabIndex=C||b<0&&m===0?0:-1}),i){let f=(b>=0?u[b]:void 0)??u[0];f&&typeof f.focus=="function"&&(l(f),f.focus())}},destroy(){t.removeEventListener("keydown",c),t.removeEventListener("focusin",d)}}}function Df(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=Z=>({start:Z===!1?!1:typeof Z=="object"&&Z?Z.start!==!1:!0,end:Z===!1?!1:typeof Z=="object"&&Z?Z.end!==!1:!0}),{start:d,end:u}=c(n?.tabFade),b=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,f=()=>{b?.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),H?.hide()};b&&b.addEventListener("click",()=>{f(),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 I=h("span","persona-text-xs persona-font-medium persona-truncate");I.textContent=s;let D=Dt({icon:"x",label:i});D.addEventListener("click",()=>{f(),e.onDismiss?.()});let T="rendered",A=Yi({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:Z=>{T=Z==="source"?"source":"rendered",Ae()}}),W=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),z=n?.documentToolbarShowCopyLabel===!0,U=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,O=!!(U&&w&&w.length>0),N=null,R,L=null,H=null;if(r&&(z||U)&&!O){if(R=z?Oo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),U){let Z=se("chevron-down",14,"currentColor",2);Z&&R.appendChild(Z)}}else r&&O?(N=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),R=z?Oo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L=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(R,L)):r?R=Dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(R=Dt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&R.classList.add("persona-hidden"));let ne=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}),me=Dt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>e.onToggleExpand?.()});n?.showExpandToggle!==!0&&me.classList.add("persona-hidden");let ue=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),ee=t.features?.artifacts?.toolbarActions??[],re=()=>{let Z=Be.find(S=>S.id===Pe)??Be[Be.length-1],k=Z?.id??null,j=Z?.artifactType==="markdown"?Z.markdown??"":"",v=Z?JSON.stringify({component:Z.component,props:Z.props},null,2):"";return{markdown:j,jsonPayload:v,id:k}},G=async()=>{let Z=Be.find(k=>k.id===Pe)??Be[Be.length-1];try{await navigator.clipboard.writeText(Cs(Z))}catch{}};if(R.addEventListener("click",async()=>{let Z=n?.onDocumentToolbarCopyMenuSelect;if(Z&&O){let{markdown:k,jsonPayload:j,id:v}=re();try{await Z({actionId:"primary",artifactId:v,markdown:k,jsonPayload:j})}catch{}return}await G()}),L&&w?.length){let Z=()=>m.closest("[data-persona-root]")??document.body,k=()=>{H=yr({items:w.map(j=>({id:j.id,label:j.label})),onSelect:async j=>{let{markdown:v,jsonPayload:S,id:P}=re(),_=n?.onDocumentToolbarCopyMenuSelect;try{_?await _({actionId:j,artifactId:P,markdown:v,jsonPayload:S}):j==="markdown"||j==="md"?await navigator.clipboard.writeText(v):j==="json"||j==="source"?await navigator.clipboard.writeText(S):await navigator.clipboard.writeText(v||S)}catch{}},anchor:N??L,position:"bottom-right",portal:Z()})};m.isConnected?k():requestAnimationFrame(k),L.addEventListener("click",j=>{j.stopPropagation(),H?.toggle()})}ne.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}Ae()}),de.addEventListener("click",()=>{f(),e.onDismiss?.()});let ie=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,ne,de):W.append(R,ne,de),W.insertBefore(ue,de),W.insertBefore(me,de),C.append(A.element,ie,W);else{let Z=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");Z.append(R,ue,me,D),C.appendChild(I),C.appendChild(Z)}l&&(C.style.paddingLeft=l,C.style.paddingRight=l);let te=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&&te.style.setProperty("--persona-artifact-tab-fade-size",p);let ye=t.features?.artifacts?.renderTabBar,ve=h("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),fe=Bf(te,{onSelect:Z=>e.onSelect(Be[Z].id)}),Ee=Z=>{let k=Z.scrollWidth-Z.clientWidth,j=k>1,v=Math.abs(Z.scrollLeft);Z.classList.toggle("persona-artifact-tab-fade-start",d&&j&&v>1),Z.classList.toggle("persona-artifact-tab-fade-end",u&&j&&v<k-1)},Te=0,Fe=()=>{if(Te)return;let Z=()=>{Te=0,Ee(te)};Te=typeof requestAnimationFrame=="function"?requestAnimationFrame(Z):setTimeout(Z,0)};te.addEventListener("scroll",()=>Fe(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Ee(te)).observe(te);let Le=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Ge=()=>{Le.scrollLeft=0},Ze=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Ge):setTimeout(Ge,0)};if(l){for(let Z of[te,ve])Z.style.paddingLeft=l,Z.style.paddingRight=l;Le.style.padding=l}m.appendChild(C),m.appendChild(te),m.appendChild(ve),m.appendChild(Le);let Be=[],Pe=null,et=!1,dn=!1,Pt=!0,xt=!1,De=null,we="",Je=null,We=!1,xe=Z=>Z.artifactType==="markdown"&&!!Z.file||r?T:"rendered",pe=Z=>{r||(Z&&!We?(C.insertBefore(A.element,I),We=!0):!Z&&We&&(A.element.remove(),We=!1))},Se=()=>Pe&&Be.find(Z=>Z.id===Pe)||Be[Be.length-1],Ct=()=>{let Z=vs(Se());if(!Z){ue.replaceChildren();return}let k=ee.filter(j=>j.visible===void 0||j.visible(Z)).map(j=>vr(j,{documentChrome:r,onClick:()=>{let v=vs(Se());if(v)try{Promise.resolve(j.onClick(v)).catch(()=>{})}catch{}}}));ue.replaceChildren(...k)},Ae=()=>{Ct();let Z=r&&Be.length<=1,k=!!ye;if(te.classList.toggle("persona-hidden",Z||k),ve.classList.toggle("persona-hidden",Z||!k),k&&ye){let S=Be.map(P=>P.id).join("|")+" "+(Pe??"");if(S!==we){we=S;let P=ye({records:Be,selectedId:Pe,onSelect:e.onSelect});ve.firstElementChild!==P&&ve.replaceChildren(P)}}else{fe.beforeRender(),te.replaceChildren();let S=[],P=-1;for(let[_,Q]of Be.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,ae=K?Pn(K.path):Q.title||Q.id.slice(0,8),Qe=K?.path||Q.title||ae;$.textContent=ae,$.title=Qe,$.setAttribute("aria-label",Qe),Q.id===Pe&&($.classList.add("persona-bg-persona-container","persona-border-persona-border"),P=_),$.addEventListener("click",()=>e.onSelect(Q.id)),te.appendChild($),S.push($)}if(fe.render(S,P),P>=0&&Pe!==De){De=Pe;let _=S[P];typeof _.scrollIntoView=="function"&&_.scrollIntoView({block:"nearest",inline:"nearest"})}Ee(te)}let j=Pe&&Be.find(S=>S.id===Pe)||Be[Be.length-1];if(!j){Le.replaceChildren(),Je=null,pe(!1);return}let v=j.artifactType==="markdown"?j.file:void 0;if(pe(!!v),r){let S=v?lo(v):j.artifactType==="markdown"?"MD":j.component??"Component",P=(j.title||"Document").trim(),_=v?Pn(v.path):P.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ie.textContent=`${_} \xB7 ${S}`}else I.textContent=v?Pn(v.path):s;Je?(Je.el.parentElement!==Le&&Le.replaceChildren(Je.el),Je.update(j)):(Je=ta(j,{config:t,resolveViewMode:xe}),Le.replaceChildren(Je.el)),Le.classList.toggle("persona-artifact-content-flush",!!Le.querySelector(".persona-code-pre"))},be=()=>{let Z=Be.length>0;if(m.classList.toggle("persona-hidden",!Z),b){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;Z&&v&&et?(b.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(b.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}},bn=()=>{xt=!1,Ae(),be()};return{element:m,backdrop:b,update(Z){let k=Z.selectedId??Z.artifacts[Z.artifacts.length-1]?.id??null,j=k!==Pe;Be=Z.artifacts,Pe=k,Be.length>0&&(et=!0),xt=!0,Pt&&bn(),j&&Ge()},setMobileOpen(Z){et=Z,!Z&&b?(b.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):be()},setExpanded(Z){Z!==dn&&(dn=Z,Ze());let k=se(Z?"minimize":"maximize",16,"currentColor",2);k&&me.replaceChildren(k);let j=Z?"Collapse artifacts panel":"Expand artifacts panel";me.setAttribute("aria-label",j),me.title=j},setExpandToggleVisible(Z){me.classList.toggle("persona-hidden",!Z)},setCopyButtonVisible(Z){r||R.classList.toggle("persona-hidden",!Z)},setCustomActions(Z){ee=Z,Ct()},setTabFade(Z){let k=c(Z);k.start===d&&k.end===u||(d=k.start,u=k.end,Ee(te))},setRenderTabBar(Z){Z!==ye&&(ye=Z,we="",Ae())},setVisible(Z){Z!==Pt&&(Pt=Z,Z&&xt&&bn())}}}function Yt(t){return t?.features?.artifacts?.enabled===!0}function Nf(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"),!Yt(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 rv(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 Of=["panel","seamless","detached"];function lc(t){let e=t.features?.artifacts?.layout?.paneAppearance;return e&&Of.includes(e)?e:e?"panel":t.launcher?.detachedPanel?"detached":"panel"}function cc(t){return!t||!Yt(t)?!1:lc(t)==="detached"}function Ws(t,e){if(!Yt(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"),rv(t),Nf(t,e);return}let n=e.features?.artifacts?.layout,o=lc(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"),Nf(t,e)}function Hs(t,e){for(let l of Of)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"),!Yt(e))return;let n=e.features?.artifacts?.layout,o=lc(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 Ff(t,e){return!e||!Yt(t)?!1:t.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function sv(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 iv(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 av(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function lv(t,e,n,o){let r=t-o-2*e-n;return Math.max(0,r)}function dc(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 _f(t,e,n,o,r,s){let i=sv(r,200),l=lv(e,n,o,200);l=Math.max(i,l);let p=iv(s);return p!==null&&(l=Math.min(l,p)),av(t,i,l)}st();var $f={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"}},pc=(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=$f[i]??$f.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 I=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");I.textContent=m.label,C.appendChild(I);let D=m.type??"text",T;D==="textarea"?(T=document.createElement("textarea"),T.rows=3):(T=document.createElement("input"),T.type=D),T.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",T.id=`${e.id}-${i}-${m.name}`,T.name=m.name,T.placeholder=m.placeholder??"",m.required&&(T.required=!0),C.appendChild(T),d.appendChild(C)});let u=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),b=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=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");f.type="submit",f.textContent=l.submitLabel??"Submit",u.appendChild(b),u.appendChild(f),d.appendChild(u),s.replaceChildren(p,d),d.addEventListener("submit",async m=>{m.preventDefault();let C=n.formEndpoint??"/form",I=new FormData(d),D={};I.forEach((T,A)=>{D[A]=T}),D.type=i,f.disabled=!0,b.textContent="Submitting\u2026";try{let T=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(D)});if(!T.ok)throw new Error(`Form submission failed (${T.status})`);let A=await T.json();b.textContent=A.message??"Thanks! We'll be in touch soon.",A.success&&A.nextPrompt&&await o.sendMessage(String(A.nextPrompt))}catch(T){b.textContent=T instanceof Error?T.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var uc=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 uc;var zf=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),cv=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.streamAnimation.plugins"]),Uf=(t,e,n)=>{if(!zf(t)||!zf(e)||cv.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]=Uf(t[r],e[r],s)}return o};function jf(t,e){let n=Uf(t,e,"");return qi(n)}var qf=()=>{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 dv=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},pv=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},mc=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=dv(t),n=pv(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}},gc=t=>typeof t=="string"?t:t==null?"":String(t),Bs={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:gc(t.payload.text)},messageAndClick:(t,e)=>{if(t.type!=="message_and_click")return;let n=t.payload,o=gc(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:gc(n.text)}}},Vf=t=>Array.isArray(t)?t.map(e=>String(e)):[],hc=t=>{let e=new Set(Vf(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(Vf(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 b=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:b,resubmit:u.resubmit}}}catch(d){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",d)}return{text:"",persist:!0}},syncFromMetadata:n}};var uv=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}},fv=t=>t.map(e=>({...e,streaming:!1})),gv=t=>t.map(e=>({...e,status:"complete"})),Kf=(t="persona-state")=>{let e=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?uv(n.getItem(t)):null},save:n=>{let o=e();if(o)try{let r={...n,messages:n.messages?fv(n.messages):void 0,artifacts:n.artifacts?gv(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 bc=require("partial-json");function Gf(t,e){let{config:n,message:o,onPropsUpdate:r}=e,s=jn.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 Qf(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 yc(t){let e=Qf(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 Xf(t){let e=Qf(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 mv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Jf(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=mv}=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,b=document.createElement("div");b.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let m=document.createElement("h3");m.className="persona-feedback-title",m.textContent=o,f.appendChild(m);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,f.appendChild(C),b.appendChild(f);let I=document.createElement("div");I.className="persona-feedback-rating persona-feedback-rating-csat",I.setAttribute("role","radiogroup"),I.setAttribute("aria-label","Satisfaction rating from 1 to 5");let D=[];for(let U=1;U<=5;U++){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",`${U} star${U>1?"s":""}: ${c[U-1]}`),w.title=c[U-1],w.dataset.rating=String(U),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=U,D.forEach((O,N)=>{let L=N<U;O.classList.toggle("selected",L),O.setAttribute("aria-checked",N===U-1?"true":"false")})}),D.push(w),k.appendChild(w)}b.appendChild(k);let M=null;if(p){let U=document.createElement("div");U.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=s,M.rows=3,M.setAttribute("aria-label","Additional comments"),U.appendChild(M),b.appendChild(U)}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){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}z.disabled=!0,z.textContent="Submitting...";try{let U=M?.value.trim()||void 0;await e(u,U),d.remove()}catch(U){z.disabled=!1,z.textContent=i,console.error("[CSAT Feedback] Failed to submit:",U)}}),A.appendChild(W),A.appendChild(z),b.appendChild(A),d.appendChild(b),d}function Qf(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 b=null,f=document.createElement("div");f.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 k=document.createElement("p");k.className="persona-feedback-subtitle",k.textContent=r,m.appendChild(k),f.appendChild(m);let D=document.createElement("div");D.className="persona-feedback-rating persona-feedback-rating-nps",D.setAttribute("role","radiogroup"),D.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.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,M.appendChild(A),M.appendChild(W);let z=document.createElement("div");z.className="persona-feedback-numbers";let U=[];for(let P=0;P<=10;P++){let H=document.createElement("button");H.type="button",H.className="persona-feedback-rating-btn persona-feedback-number-btn",H.setAttribute("role","radio"),H.setAttribute("aria-checked","false"),H.setAttribute("aria-label",`Rating ${P} out of 10`),H.textContent=String(P),H.dataset.rating=String(P),P<=6?H.classList.add("persona-feedback-detractor"):P<=8?H.classList.add("persona-feedback-passive"):H.classList.add("persona-feedback-promoter"),H.addEventListener("click",()=>{b=P,U.forEach((ne,pe)=>{ne.classList.toggle("selected",pe===P),ne.setAttribute("aria-checked",pe===P?"true":"false")})}),U.push(H),z.appendChild(H)}D.appendChild(M),D.appendChild(z),f.appendChild(D);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),f.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(b===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(b,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),f.appendChild(O),u.appendChild(f),u}var Sr="persona-chat-history",uv=30*1e3,fv=641,gv={"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 mv(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=gv[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 wa(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 hv(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 bv(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var yc=t=>!t||typeof t!="object"?{}:{...t},Xf=t=>t.map(e=>({...e,streaming:!1})),Jf=(t,e,n)=>{let o=t?.markdown?pi(t.markdown):null,r=ui(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=On()!==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?Ud(i):i,u=o(d);c=r&&p?r(u):u}else c=oo(i);return c}};function Yf(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 yv=(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},vv=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:yv(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),Zf=(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=Tu(e),r=uc.getForInstance(o.plugins),{plugin:s,teardown:i}=Lf();o.components&&jn.registerAll(o.components);let l=zf(),c=o.persistState===!1?null:o.storageAdapter??jf(),d={},u=null,b=!1,f=a=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(a);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:v}=g;return v&&(b=!0),y}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return a};if(c?.load)try{let a=c.load();if(a&&typeof a.then=="function")u=a.then(g=>f(g??{messages:[],metadata:{}}));else{let y=f(a??{messages:[],metadata:{}});y.metadata&&(d=yc(y.metadata)),y.messages?.length&&(o={...o,initialMessages:y.messages}),y.artifacts?.length&&(o={...o,initialArtifacts:y.artifacts,initialSelectedArtifactId:y.selectedArtifactId??null})}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=f({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})??{},_a()},k=o.actionParsers&&o.actionParsers.length?o.actionParsers:[gc],D=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Bs.message,Bs.messageAndClick],M=mc({parsers:k,handlers:D,getSessionMetadata:m,updateSessionMetadata:C,emit:l.emit,documentRef:typeof document<"u"?document:null});M.syncFromMetadata();let A=o.launcher?.enabled??!0,W=o.launcher?.autoExpand??!1,z=o.autoFocusInput??!1,U=W,w=A,O=o.layout?.header?.layout,N=!1,L=()=>Es(o),P=()=>A||L(),H=L()?!1:A?W:!0,ne=!1,pe=null,he=()=>{ne=!0,pe&&clearTimeout(pe),pe=setTimeout(()=>{ne&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ne=!1)},1e4)},fe=Jf(o,M,he),ee=o.features?.showReasoning??!0,oe=o.features?.showToolCalls??!0,K=o.features?.showEventStreamToggle??!1,ae=o.features?.scrollToBottom??{},te=o.features?.scrollBehavior??{},xe=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,ge=K?new Is(xe):null,Te=o.features?.eventStream?.maxEvents??2e3,Me=K?new Ps(Te,ge):null,Fe=K?new Rs:null,Pe=null,Ee=!1,Ne=null,lt=0;ge?.open().then(()=>Me?.restore()).catch(a=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",a)});let ze={onCopy:a=>{l.emit("message:copy",a),V?.isClientTokenMode()&&V.submitMessageFeedback(a.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(a)},onFeedback:a=>{l.emit("message:feedback",a),V?.isClientTokenMode()&&V.submitMessageFeedback(a.messageId,a.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(a)}},Je=o.statusIndicator??{},pn=a=>a==="idle"?Je.idleText??Dt.idle:a==="connecting"?Je.connectingText??Dt.connecting:a==="connected"?Je.connectedText??Dt.connected:a==="error"?Je.errorText??Dt.error:a==="paused"?Je.pausedText??Dt.paused:a==="resuming"?Je.resumingText??Dt.resuming:Dt[a];function It(a,g,y,v){if(v==="idle"&&y.idleLink){a.textContent="";let T=document.createElement("a");T.href=y.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=g,T.style.color="inherit",T.style.textDecoration="none",a.appendChild(T)}else a.textContent=g}let mt=bf({config:o,showClose:P()}),{wrapper:Re,panel:we,pillRoot:ct}=mt.shell,He=mt.panelElements,{container:ye,body:ue,messagesWrapper:Ae,suggestions:Ct,textarea:j,sendButton:ie,sendButtonWrapper:_e,composerForm:Le,statusText:I,introTitle:Y,introSubtitle:x,closeButton:E,iconHolder:R,headerTitle:_,headerSubtitle:J,header:$,footer:G,actionsRow:de,rightActions:ot}=He,Ie=He.leftActions,dt=He.setSendButtonMode,Q=He.micButton,je=He.micButtonWrapper,Be=He.attachmentButton,De=He.attachmentButtonWrapper,We=He.attachmentInput,Ye=He.attachmentPreviewsContainer;ye.classList.add("persona-relative"),ue.classList.add("persona-relative");let mo=12,ho=()=>ae.label??"",Sa=()=>ae.iconName??"arrow-down",Ns=()=>ae.enabled!==!1,en=()=>te.mode??"anchor-top",qn=()=>en()==="follow"||en()==="anchor-top"&&Hr,Mc=()=>te.anchorTopOffset??16,ug=()=>te.restorePosition??"bottom",Tc=()=>te.pauseOnInteraction===!0,Ec=()=>te.showActivityWhilePinned!==!1,kc=()=>te.announce===!0,Ht=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");Ht.type="button",Ht.style.display="none",Ht.setAttribute("data-persona-scroll-to-bottom","true");let Tr=h("span","persona-flex persona-items-center"),Ma=h("span",""),bo=h("span","");bo.setAttribute("data-persona-scroll-to-bottom-count",""),bo.style.display="none",Ht.append(Tr,Ma,bo),ye.appendChild(Ht);let Vn=h("div","persona-stream-anchor-spacer");Vn.setAttribute("aria-hidden","true"),Vn.setAttribute("data-persona-anchor-spacer",""),Vn.style.flexShrink="0",Vn.style.pointerEvents="none",Vn.style.height="0px",ue.appendChild(Vn);let yo=h("div","persona-sr-only");yo.setAttribute("aria-live","polite"),yo.setAttribute("aria-atomic","true"),yo.setAttribute("role","status"),yo.setAttribute("data-persona-live-region",""),Object.assign(yo.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(yo);let Er=null,Os=null,Lc=a=>{!kc()||!a||(Os=a,Er===null&&(Er=setTimeout(()=>{Er=null,Os&&kc()&&(yo.textContent=Os),Os=null},400)))},jo=()=>{let g=G.style.display==="none"?0:G.offsetHeight;Ht.style.bottom=`${g+mo}px`};jo();let Pc=()=>{let a=!!ho();Ht.setAttribute("aria-label",ho()||"Jump to latest"),Ht.title=ho(),Ht.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),Tr.innerHTML="";let g=se(Sa(),"14px","currentColor",2);g?(Tr.appendChild(g),Tr.style.display=""):Tr.style.display="none",Ma.textContent=ho(),Ma.style.display=a?"":"none"};Pc();let Lt=null,on=null,Ic=null,Rc=r.find(a=>a.renderHeader);if(Rc?.renderHeader){let a=Rc.renderHeader({config:o,defaultRenderer:()=>{let g=_o({config:o,showClose:P()});return ks(ye,g,o),g.header},onClose:()=>bt(!1,"user")});if(a){let g=ye.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(a),$=a,mt.header.element=a)}}let Ta=()=>{if(!Me)return;if(Ee=!0,!Pe&&Me&&(Pe=Hf({buffer:Me,getFullHistory:()=>Me.getAllFromStore(),onClose:()=>kr(),config:o,plugins:r,getThroughput:()=>Fe?.getMetric()??{status:"idle"}})),Pe&&(ue.style.display="none",G.parentNode?.insertBefore(Pe.element,G),Pe.update()),it){it.style.boxShadow=`inset 0 0 0 1.5px ${Yt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(y=>y&&it.classList.add(y))}let a=()=>{if(!Ee)return;let g=Date.now();g-lt>=200&&(Pe?.update(),lt=g),Ne=requestAnimationFrame(a)};lt=0,Ne=requestAnimationFrame(a),sn(),l.emit("eventStream:opened",{timestamp:Date.now()})},kr=()=>{if(Ee){if(Ee=!1,Pe&&Pe.element.remove(),ue.style.display="",it){it.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(g=>g&&it.classList.remove(g))}Ne!==null&&(cancelAnimationFrame(Ne),Ne=null),sn(),l.emit("eventStream:closed",{timestamp:Date.now()})}},it=null;if(K){let a=o.features?.eventStream?.classNames,g="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:"");it=h("button",g),it.style.width="28px",it.style.height="28px",it.style.color=Yt.actionIconColor,it.type="button",it.setAttribute("aria-label","Event Stream"),it.title="Event Stream";let y=se("activity","18px","currentColor",1.5);y&&it.appendChild(y);let v=He.clearChatButtonWrapper,T=He.closeButtonWrapper,B=v||T;B&&B.parentNode===$?$.insertBefore(it,B):$.appendChild(it),it.addEventListener("click",()=>{Ee?kr():Ta()})}let fg=a=>{let g=o.attachments;if(!g?.enabled)return;let y=a.querySelector("[data-persona-composer-attachment-previews]")??a.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.setAttribute("data-persona-composer-attachment-previews",""),y.style.display="none";let T=a.querySelector("[data-persona-composer-form]");T?.parentNode?T.parentNode.insertBefore(y,T):a.insertBefore(y,a.firstChild)}if(!(a.querySelector("[data-persona-composer-attachment-input]")??a.querySelector('input[type="file"]'))){let T=h("input");T.type="file",T.setAttribute("data-persona-composer-attachment-input",""),T.accept=(g.allowedTypes??zn).join(","),T.multiple=(g.maxFiles??4)>1,T.style.display="none",T.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),a.appendChild(T)}},Wc=r.find(a=>a.renderComposer);if(Wc?.renderComposer){let a=o.composer,g=Wc.renderComposer({config:o,defaultRenderer:()=>ya({config:o}).footer,onSubmit:y=>{if(!V||V.isStreaming())return;let v=y.trim(),T=Lt?.hasAttachments()??!1;if(!v&&!T)return;ld();let B;T&&(B=[],B.push(...Lt.getContentParts()),v&&B.push(pr(v))),V.sendMessage(v,{contentParts:B}),T&&Lt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{We?.click()},models:a?.models,selectedModelId:a?.selectedModelId,onModelChange:y=>{o.composer={...o.composer,selectedModelId:y},o.agent&&(o.agent={...o.agent,model:y})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Ic?.()}:void 0});g&&(mt.replaceComposer(g),G=mt.composer.footer)}let gg=a=>{let g=(...me)=>{for(let ce of me){let Se=a.querySelector(ce);if(Se)return Se}return null},y=a.querySelector("[data-persona-composer-form]"),v=a.querySelector("[data-persona-composer-input]"),T=a.querySelector("[data-persona-composer-submit]"),B=a.querySelector("[data-persona-composer-mic]"),Z=a.querySelector("[data-persona-composer-status]");y&&(Le=y),v&&(j=v),T&&(ie=T),B&&(Q=B,je=B.parentElement),Z&&(I=Z);let q=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");q&&(Ct=q);let X=g("[data-persona-composer-attachment-button]",".persona-attachment-button");X&&(Be=X,De=X.parentElement),We=g("[data-persona-composer-attachment-input]",'input[type="file"]'),Ye=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let le=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");le&&(de=le),Ie=g(".persona-widget-composer__left-actions")};fg(G),gg(G);let Kn=o.layout?.contentMaxWidth??(L()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Kn&&(Ae.style.maxWidth=Kn,Ae.style.marginLeft="auto",Ae.style.marginRight="auto",Ae.style.width="100%"),Kn&&Le&&!L()&&(Le.style.maxWidth=Kn,Le.style.marginLeft="auto",Le.style.marginRight="auto"),Kn&&Ct&&!L()&&(Ct.style.maxWidth=Kn,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),Kn&&Ye&&!L()&&(Ye.style.maxWidth=Kn,Ye.style.marginLeft="auto",Ye.style.marginRight="auto"),o.attachments?.enabled&&We&&Ye){Lt=cs.fromConfig(o.attachments),Lt.setPreviewsContainer(Ye),We.addEventListener("change",y=>{let v=y.target;Lt?.handleFileSelect(v.files),v.value=""});let a=o.attachments.dropOverlay,g=Yf(a);ye.appendChild(g)}let mg=()=>on?.prefetch();if(o.contextMentions?.enabled&&j&&(on=wu({config:o,textarea:j,anchor:Le??j,getMessages:()=>V.getMessages(),liveRegionHost:ye}),on)){let a=j;a.parentElement?.insertBefore(on.contextRow,a);let g=on.affordanceButtons;for(let y=g.length-1;y>=0;y--){let v=g[y];Ie?Ie.insertBefore(v,Ie.firstChild):Le?.appendChild(v)}}(()=>{let a=o.layout?.slots??{},g=v=>{switch(v){case"body-top":return ye.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ae;case"footer-top":return Ct;case"composer":return Le;case"footer-bottom":return I;default:return null}},y=(v,T)=>{switch(v){case"header-left":case"header-center":case"header-right":if(v==="header-left")$.insertBefore(T,$.firstChild);else if(v==="header-right")$.appendChild(T);else{let B=$.querySelector(".persona-flex-col");B?B.parentNode?.insertBefore(T,B.nextSibling):$.appendChild(T)}break;case"body-top":{let B=ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(T):ue.insertBefore(T,ue.firstChild);break}case"body-bottom":ue.appendChild(T);break;case"footer-top":Ct.replaceWith(T);break;case"footer-bottom":I.replaceWith(T);break;default:break}};for(let[v,T]of Object.entries(a))if(T)try{let B=T({config:o,defaultContent:()=>g(v)});B&&y(v,B)}catch(B){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${v}":`,B)}})();let Hc=a=>{let y=a.target.closest('button[data-expand-header="true"]');if(!y)return;let v=y.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!v)return;let T=v.getAttribute("data-message-id");if(!T)return;let B=y.getAttribute("data-bubble-type");if(B==="reasoning")Cr.has(T)?Cr.delete(T):Cr.add(T),wf(T,v);else if(B==="tool")wr.has(T)?wr.delete(T):wr.add(T),Af(T,v,o);else if(B==="approval"){let q=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",X=$o.get(T)??q;$o.set(T,!X),Ef(T,v,o)}wo.delete(T)};Ae.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Hc(a))}),Ae.addEventListener("keydown",a=>{let g=a.target;(a.key==="Enter"||a.key===" ")&&g.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Hc(a))}),Ae.addEventListener("copy",a=>{let{clipboardData:g}=a;if(!g)return;let y=Ae.getRootNode(),v=typeof y.getSelection=="function"?y.getSelection():window.getSelection();if(!v||v.isCollapsed)return;let T=v.toString(),B=Yu(T);!B||B===T||(g.setData("text/plain",B),a.preventDefault())});let Ea=new Map,Bc=null,Dc="idle",hg={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},bg=(a,g)=>{let{icon:y,label:v}=hg[g];a.setAttribute("aria-label",v),a.title=v,a.setAttribute("aria-pressed",g==="idle"?"false":"true"),a.classList.toggle("persona-message-action-active",g!=="idle"),a.classList.toggle("persona-message-action-loading",g==="loading");let T=se(y,14,"currentColor",2);T&&(a.innerHTML="",a.appendChild(T))},Nc=()=>{Ae.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let v=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;bg(g,v&&v===Bc?Dc:"idle")})};Ae.addEventListener("click",a=>{let y=a.target.closest(".persona-message-action-btn[data-action]");if(!y)return;a.preventDefault(),a.stopPropagation();let v=y.closest("[data-actions-for]");if(!v)return;let T=v.getAttribute("data-actions-for");if(!T)return;let B=y.getAttribute("data-action");if(B==="copy"){let q=V.getMessages().find(X=>X.id===T);if(q&&ze.onCopy){let X=q.content||"";navigator.clipboard.writeText(X).then(()=>{y.classList.add("persona-message-action-success");let le=se("check",14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let me=se("copy",14,"currentColor",2);me&&(y.innerHTML="",y.appendChild(me))},2e3)}).catch(le=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",le)}),ze.onCopy(q)}}else if(B==="read-aloud")V.toggleReadAloud(T);else if(B==="upvote"||B==="downvote"){let q=(Ea.get(T)??null)===B,X=B==="upvote"?"thumbs-up":"thumbs-down";if(q){Ea.delete(T),y.classList.remove("persona-message-action-active");let le=se(X,14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le))}else{let le=B==="upvote"?"downvote":"upvote",me=v.querySelector(`[data-action="${le}"]`);if(me){me.classList.remove("persona-message-action-active");let at=se(le==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);at&&(me.innerHTML="",me.appendChild(at))}Ea.set(T,B),y.classList.add("persona-message-action-active");let ce=se(X,14,"currentColor",2);ce&&(ce.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(ce)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Ge=V.getMessages().find(yt=>yt.id===T);Ge&&ze.onFeedback&&ze.onFeedback({type:B,messageId:Ge.id,message:Ge})}}}),Ae.addEventListener("click",a=>{let y=a.target.closest("button[data-approval-action]");if(!y)return;a.preventDefault(),a.stopPropagation();let v=y.closest(".persona-approval-bubble");if(!v)return;let T=v.getAttribute("data-message-id");if(!T)return;let B=y.getAttribute("data-approval-action");if(!B)return;let Z=B==="approve"?"approved":"denied",X=V.getMessages().find(me=>me.id===T);if(!X?.approval)return;let le=v.querySelector("[data-approval-buttons]");le&&le.querySelectorAll("button").forEach(ce=>{ce.disabled=!0,ce.style.opacity="0.5",ce.style.cursor="not-allowed"}),X.approval.toolType==="webmcp"?V.resolveWebMcpApproval(T,Z):V.resolveApproval(X.approval,Z)});let Ze=null,Lr=null,Pr=()=>{},Ir="none",Fs=null,yn={artifacts:[],selectedId:null},Rn=!1,vn=!1,Rr=!1,qo=!1,Oc=()=>qo||yn.artifacts.some(a=>Wo(o.features?.artifacts,a.artifactType)==="panel"),_s=()=>yn.artifacts.length>0&&!Rn&&Oc(),ht={current:null},ka=(a,g)=>{let y=V.getArtifactById(g),v=y?.markdown,T=y?.title||"artifact",B=y?.file,Z=y?.artifactType??"markdown";if(!v){let le=a.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(le){let ce=V.getMessages().find(Se=>Se.id===le);if(ce?.rawContent)try{let Se=JSON.parse(ce.rawContent);v=Se?.props?.markdown,T=Se?.props?.title||T,Se?.props?.file&&typeof Se.props.file=="object"&&(B=Se.props.file),!y&&typeof Se?.props?.artifactType=="string"&&(Z=Se.props.artifactType)}catch{}}}return{markdown:v,title:T,file:B,artifactType:Z}};Ae.addEventListener("click",a=>{let y=a.target.closest("[data-download-artifact]");if(!y)return;a.preventDefault(),a.stopPropagation();let v=y.getAttribute("data-download-artifact");if(!v||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:v})===!0)return;let{markdown:B,title:Z,file:q}=ka(y,v);if(!B)return;let{filename:X,mime:le,content:me}=Wu({title:Z,markdown:B,file:q}),ce=new Blob([me],{type:le}),Se=URL.createObjectURL(ce),Ge=document.createElement("a");Ge.href=Se,Ge.download=X,Ge.click(),URL.revokeObjectURL(Se)}),Ae.addEventListener("click",a=>{let y=a.target.closest("[data-artifact-custom-action]");if(!y)return;a.preventDefault(),a.stopPropagation();let v=y.getAttribute("data-artifact-custom-action");if(!v)return;let T=y.closest("[data-artifact-inline]"),B=T?null:y.closest("[data-open-artifact]"),Z=T?T.getAttribute("data-artifact-inline"):B?.getAttribute("data-open-artifact")??null,X=(T?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(yt=>yt.id===v);if(!X)return;let{markdown:le,title:me,file:ce,artifactType:Se}=ka(y,Z??""),Ge={artifactId:Z,title:me,artifactType:Se,markdown:le,file:ce};try{Promise.resolve(X.onClick(Ge)).catch(()=>{})}catch{}}),Ae.addEventListener("click",a=>{let y=a.target.closest("[data-copy-artifact]");if(!y)return;a.preventDefault(),a.stopPropagation();let v=y.getAttribute("data-copy-artifact");if(!v)return;let T=V.getArtifactById(v),B="";if(T)B=Cs(T);else{let{markdown:Z,file:q,artifactType:X}=ka(y,v);X==="markdown"&&(B=Cs({id:v,artifactType:"markdown",status:"complete",markdown:Z??"",...q?{file:q}:{}}))}B&&navigator.clipboard.writeText(B).then(()=>{let Z=se("check",16,"currentColor",2);Z&&(y.replaceChildren(Z),setTimeout(()=>{let q=se("copy",16,"currentColor",2);q&&y.replaceChildren(q)},1500))}).catch(()=>{})}),Ae.addEventListener("click",a=>{let y=a.target.closest("[data-expand-artifact-inline]");if(!y)return;a.preventDefault(),a.stopPropagation();let v=y.getAttribute("data-expand-artifact-inline");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(Rn=!1,qo=!0,vn=!0,Rr=!0,V.selectArtifact(v),Wn())}),Ae.addEventListener("click",a=>{let g=a.target;if(g.closest("[data-download-artifact]")||g.closest("[data-artifact-custom-action]"))return;let y=g.closest("[data-open-artifact]");if(!y)return;let v=y.getAttribute("data-open-artifact");!v||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:v})===!0||(a.preventDefault(),a.stopPropagation(),Rn=!1,qo=!0,V.selectArtifact(v),Wn())}),Ae.addEventListener("keydown",a=>{if(a.key!=="Enter"&&a.key!==" ")return;let g=a.target;!g.hasAttribute("data-open-artifact")&&!g.hasAttribute("data-expand-artifact-inline")||(a.preventDefault(),g.click())});let Vo=He.composerOverlay,Ko=(a,g,y)=>{let v=g.trim();if(!v||!ht.current)return;let T=a.getAttribute("data-tool-call-id")??"",B=y.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:v,answers:y.structured,values:y.values??(y.source==="multi"?v.split(", "):[v]),isFreeText:B,source:y.source},bubbles:!0,composed:!0})),lr(Vo,T);let Z=ht.current.getMessages().find(q=>q.toolCall?.id===T);Z?.agentMetadata?.awaitingLocalTool?ht.current.resolveAskUserQuestion(Z,y.structured??v):ht.current.sendMessage(v)},vo=a=>{let g=ht.current;if(!g)return;let y=a.getAttribute("data-tool-call-id")??"",v=g.getMessages().find(T=>T.toolCall?.id===y);v&&g.persistAskUserQuestionProgress(v,{answers:hi(a,v),currentIndex:hn(a)})},Fc=a=>Object.entries(a).map(([g,y])=>`${g}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),La=a=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=hn(a),y=ar(a);if(g>=y-1)return;let v=ht.current?.getMessages().find(T=>T.toolCall?.id===a.getAttribute("data-tool-call-id"));v&&(yi(a,v,o,g+1),vo(a))};Vo.addEventListener("click",a=>{let y=a.target.closest("[data-ask-user-action]");if(!y)return;let v=y.closest("[data-persona-ask-sheet-for]");if(!v)return;let T=y.getAttribute("data-ask-user-action");if(a.preventDefault(),a.stopPropagation(),T==="dismiss"){let B=v.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:B},bubbles:!0,composed:!0})),lr(Vo,B);let Z=ht.current?.getMessages().find(q=>q.toolCall?.id===B);Z?.agentMetadata?.awaitingLocalTool&&(ht.current?.markAskUserQuestionResolved(Z),ht.current?.resolveAskUserQuestion(Z,"(dismissed)"));return}if(T==="pick"){let B=y.getAttribute("data-option-label");if(!B)return;let Z=v.getAttribute("data-multi-select")==="true",q=so(v);if(q&&Z){let X=Bo(v)[hn(v)],le=new Set(Array.isArray(X)?X:[]);le.has(B)?le.delete(B):le.add(B),io(v,Array.from(le)),vo(v);return}if(q){io(v,B),vo(v),La(v);return}if(Z){let X=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",X?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!X);let le=v.querySelector('[data-ask-user-action="submit-multi"]');le&&(le.disabled=ul(v).length===0);return}Ko(v,B,{source:"pick",values:[B]});return}if(T==="submit-multi"){let B=ul(v);if(B.length===0)return;Ko(v,B.join(", "),{source:"multi",values:B});return}if(T==="open-free-text"){let B=v.querySelector('[data-ask-free-text-row="true"]');B&&(B.classList.remove("persona-hidden"),B.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(T==="focus-free-text"){v.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(T==="submit-free-text"){let Z=v.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!Z.trim())return;if(so(v)){io(v,Z.trim()),vo(v),La(v);return}Ko(v,Z,{source:"free-text"});return}if(T==="next"||T==="back"){if(!ht.current)return;let B=v.getAttribute("data-tool-call-id")??"",Z=ht.current.getMessages().find(ce=>ce.toolCall?.id===B);if(!Z)return;let X=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(X){let ce=Bo(v)[hn(v)];(typeof ce!="string"||ce!==X)&&io(v,X)}let le=T==="next"?1:-1,me=hn(v)+le;yi(v,Z,o,me),vo(v);return}if(T==="submit-all"){if(!ht.current)return;let B=v.getAttribute("data-tool-call-id")??"",Z=ht.current.getMessages().find(ce=>ce.toolCall?.id===B);if(!Z)return;let X=v.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";X&&io(v,X);let le=hi(v,Z);ht.current.persistAskUserQuestionProgress(Z,{answers:le,currentIndex:hn(v)});let me=Fc(le);Ko(v,me||"(submitted)",{source:"submit-all",structured:le});return}if(T==="skip"){if(!ht.current)return;let B=v.getAttribute("data-tool-call-id")??"",Z=ht.current.getMessages().find(Se=>Se.toolCall?.id===B);if(!Z)return;let q=so(v),X=hn(v),le=ar(v),me=X>=le-1;if(!q){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:B},bubbles:!0,composed:!0})),lr(Vo,B),Z.agentMetadata?.awaitingLocalTool&&(ht.current.markAskUserQuestionResolved(Z),ht.current.resolveAskUserQuestion(Z,"(dismissed)"));return}io(v,"");let ce=v.querySelector('[data-ask-free-text-input="true"]');if(ce&&(ce.value=""),me){let Se=hi(v,Z),Ge=Fc(Se);Ko(v,Ge||"(skipped)",{source:"submit-all",structured:Se});return}yi(v,Z,o,X+1),vo(v);return}}),Vo.addEventListener("keydown",a=>{if(a.key!=="Enter")return;let y=a.target;if(!y.matches?.('[data-ask-free-text-input="true"]'))return;let v=y.closest("[data-persona-ask-sheet-for]");if(!v)return;a.preventDefault();let T=y.value;if(T.trim()){if(so(v)){io(v,T.trim()),vo(v),La(v);return}Ko(v,T,{source:"free-text"})}});let _c=a=>{if(!/^[1-9]$/.test(a.key)||a.metaKey||a.ctrlKey||a.altKey)return;let g=a.target;if(g?.tagName==="INPUT"||g?.tagName==="TEXTAREA"||g?.isContentEditable)return;let y=Vo.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let v=Number(a.key),B=y.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[v-1];B&&(a.preventDefault(),B.click())};document.addEventListener("keydown",_c);let Gn=null,wt=null,Wr=null,$s=null,Pa=()=>{},$c=!1,zs="",Us="";function Ia(){$s?.(),$s=null}let zc=()=>{if(!Gn||!wt)return;let a=t.classList.contains("persona-artifact-welded-split"),g=t.ownerDocument.defaultView??window,y=g.innerWidth<=640;if(!a||t.classList.contains("persona-artifact-narrow-host")||y){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 v=Gn.firstElementChild;if(!v||v===wt)return;let T=10;wt.style.position="absolute",wt.style.top="0",wt.style.bottom="0",wt.style.width=`${T}px`,wt.style.zIndex="5";let B=cc(Gn,g),Z=v.offsetWidth+B/2-T/2;wt.style.left=`${Math.max(0,Z)}px`},js=()=>{},yg=()=>{let a=t.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,y=o.launcher?.mobileBreakpoint??640;return!g||a.innerWidth>y?!1:A||zt(o)},qs=()=>!Zt(o)||!_s()||t.classList.contains("persona-artifact-narrow-host")||yg()||(t.ownerDocument.defaultView??window).innerWidth<fv?"none":lc(o)?"detached":"welded",Wn=()=>{if(!Ze||!Zt(o))return;Ws(t,o),Hs(t,o),js();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=we.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",g>0&&g<=a);let y=_s();Ze.setVisible(y),Ze.update(yn),Rn?(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),Ze.backdrop?.classList.add("persona-hidden"),vn=!1,Rr=!1):yn.artifacts.length>0&&Oc()?(Ze.element.classList.remove("persona-hidden"),Ze.setMobileOpen(!0)):(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),Ze.backdrop?.classList.add("persona-hidden"),vn=!1,Rr=!1);let v=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ze.setExpandToggleVisible(v),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),!v&&!Rr&&(vn=!1),vn!==$c){let B=Ze.element;vn?(zs=B.style.width,Us=B.style.maxWidth,B.style.removeProperty("width"),B.style.removeProperty("max-width")):(zs&&(B.style.width=zs),Us&&(B.style.maxWidth=Us),zs="",Us=""),$c=vn}t.classList.toggle("persona-artifact-expanded",vn),Ze.setExpanded(vn);let T=qs();T!==Ir&&(Ir=T,Pr()),Pa()};if(Zt(o)){we.style.position="relative";let a=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");a.appendChild(ye),Ze=Df(o,{onSelect:y=>ht.current?.selectArtifact(y),onDismiss:()=>{Rn=!0,Wn()},onToggleExpand:()=>{let y=!vn,v=yn.selectedId??yn.artifacts[yn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:v,expanded:y})!==!0&&(vn=y,y||(Rr=!1),Wn())}}),Ze.element.classList.add("persona-hidden"),Gn=g,g.appendChild(a),g.appendChild(Ze.element),Ze.backdrop&&we.appendChild(Ze.backdrop),we.appendChild(g),Pa=()=>{if(!Gn||!Ze)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Wr?.(),Wr=null,Ia(),wt&&(wt.remove(),wt=null),Ze.element.style.removeProperty("width"),Ze.element.style.removeProperty("maxWidth");return}if(!wt){let v=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");v.setAttribute("role","separator"),v.setAttribute("aria-orientation","vertical"),v.setAttribute("aria-label","Resize artifacts panel"),v.tabIndex=0;let T=t.ownerDocument,B=T.defaultView??window,Z=q=>{if(!Ze||q.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||B.innerWidth<=640)return;q.preventDefault(),Ia();let X=q.clientX,le=Ze.element.getBoundingClientRect().width,me=o.features?.artifacts?.layout,ce=Ge=>{let yt=Gn.getBoundingClientRect().width,at=t.classList.contains("persona-artifact-welded-split"),Gt=cc(Gn,B),Ot=at?0:v.getBoundingClientRect().width||6,F=le-(Ge.clientX-X),$e=_f(F,yt,Gt,Ot,me?.resizableMinWidth,me?.resizableMaxWidth);Ze.element.style.width=`${$e}px`,Ze.element.style.maxWidth="none",zc()},Se=()=>{T.removeEventListener("pointermove",ce),T.removeEventListener("pointerup",Se),T.removeEventListener("pointercancel",Se),$s=null;try{v.releasePointerCapture(q.pointerId)}catch{}};$s=Se,T.addEventListener("pointermove",ce),T.addEventListener("pointerup",Se),T.addEventListener("pointercancel",Se);try{v.setPointerCapture(q.pointerId)}catch{}};v.addEventListener("pointerdown",Z),wt=v,Gn.insertBefore(v,Ze.element),Wr=()=>{v.removeEventListener("pointerdown",Z)}}if(wt){let v=_s();wt.classList.toggle("persona-hidden",!v),zc()}},js=()=>{if(!A||!Ze||(o.launcher?.sidebarMode??!1)||zt(o)&&bn(o).reveal==="emerge")return;let v=t.ownerDocument.defaultView??window,T=o.launcher?.mobileFullscreen??!0,B=o.launcher?.mobileBreakpoint??640;if(T&&v.innerWidth<=B||!Ff(o,A))return;let Z=o.launcher?.width??o.launcherWidth??Un,q=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";_s()?(we.style.width=q,we.style.maxWidth=q):(we.style.width=Z,we.style.maxWidth=Z)},typeof ResizeObserver<"u"&&(Lr=new ResizeObserver(()=>{Wn()}),Lr.observe(we))}else we.appendChild(ye);L()&&ct&&(He.peekBanner&&ct.appendChild(He.peekBanner),ct.appendChild(G)),t.appendChild(Re),ct&&t.appendChild(ct);let Vs=()=>{if(L()){we.style.width="100%",we.style.maxWidth="100%";let Wt=o.launcher?.composerBar??{},tn=Re.dataset.state==="expanded",si=Wt.expandedSize??"anchored";if(!(tn&&si!=="fullscreen")){ye.style.background="",ye.style.border="",ye.style.borderRadius="",ye.style.overflow="",ye.style.boxShadow="";return}let Kr=o.theme?.components?.panel,ii=mr(o),tr=(Nn,Po)=>Nn==null||Nn===""?Po:Jt(ii,Nn)??Nn,Gr="1px solid var(--persona-border)",nl="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Lo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ye.style.background="var(--persona-surface, #ffffff)",ye.style.border=tr(Kr?.border,Gr),ye.style.borderRadius=tr(Kr?.borderRadius,Lo),ye.style.boxShadow=tr(Kr?.shadow,nl),ye.style.overflow="hidden";return}let a=zt(o),g=o.launcher?.sidebarMode??!1,y=a||g||(o.launcher?.fullHeight??!1),v=o.launcher?.enabled===!1,T=o.launcher?.detachedPanel===!0,B=o.theme?.components?.panel,Z=mr(o),q=(Wt,tn)=>Wt==null||Wt===""?tn:Jt(Z,Wt)??Wt,X=t.ownerDocument.defaultView??window,le=o.launcher?.mobileFullscreen??!0,me=o.launcher?.mobileBreakpoint??640,ce=X.innerWidth<=me,Se=le&&ce&&A,Ge=a&&le&&ce,yt=o.launcher?.position??"bottom-left",at=yt==="bottom-left"||yt==="top-left",Gt=o.launcher?.zIndex??Vt,Ot="var(--persona-panel-border, 1px solid var(--persona-border))",F="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",$e="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ke=T&&!Se&&!Ge;ke?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let Ue=ke?Ot:g||Se?"none":Ot,Et=ke?F:Se?"none":g?at?"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))":v?"none":F;a&&!Se&&!ke&&(Et="none",Ue="none");let ft=ke?$e:g||Se?"0":$e,St=q(B?.border,Ue),xt=q(B?.shadow,Et),jt=q(B?.borderRadius,ft),Eo=qs(),gt=Eo==="detached",be=Eo==="welded";t.classList.toggle("persona-artifact-detached-split",gt),t.classList.toggle("persona-artifact-welded-split",be);let Mt="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",st=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Zt(o)&&lc(o)&&v&&!a;t.classList.toggle("persona-artifact-chat-flush",st);let Ve=gt||st?"none":xt,et=gt?Ot:be?"none":St,Rt=gt?$e:jt;st&&(et="none",Rt="0");let Oe=B?.borderRadius!=null&&B.borderRadius!=="",tt=st&&!Oe?"0":jt,an=ue.scrollTop;t.style.cssText="",Re.style.cssText="",we.style.cssText="",ye.style.cssText="",ue.style.cssText="",G.style.cssText="",Ee&&(ue.style.display="none");let ko=()=>{if(an<=0)return;(ue.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(ue.scrollTop===an)return;let tn=ue.scrollHeight-ue.clientHeight;tn<=0||(ue.scrollTop=Math.min(an,tn))})};if(Se){Re.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"),Re.style.cssText=`
|
|
219
|
+
`,w.addEventListener("click",()=>{u=U,D.forEach((O,N)=>{let R=N<U;O.classList.toggle("selected",R),O.setAttribute("aria-checked",N===U-1?"true":"false")})}),D.push(w),I.appendChild(w)}b.appendChild(I);let T=null;if(p){let U=document.createElement("div");U.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=s,T.rows=3,T.setAttribute("aria-label","Additional comments"),U.appendChild(T),b.appendChild(U)}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){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}z.disabled=!0,z.textContent="Submitting...";try{let U=T?.value.trim()||void 0;await e(u,U),d.remove()}catch(U){z.disabled=!1,z.textContent=i,console.error("[CSAT Feedback] Failed to submit:",U)}}),A.appendChild(W),A.appendChild(z),b.appendChild(A),d.appendChild(b),d}function Yf(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 b=null,f=document.createElement("div");f.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 I=document.createElement("p");I.className="persona-feedback-subtitle",I.textContent=r,m.appendChild(I),f.appendChild(m);let D=document.createElement("div");D.className="persona-feedback-rating persona-feedback-rating-nps",D.setAttribute("role","radiogroup"),D.setAttribute("aria-label","Likelihood rating from 0 to 10");let T=document.createElement("div");T.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,T.appendChild(A),T.appendChild(W);let z=document.createElement("div");z.className="persona-feedback-numbers";let U=[];for(let L=0;L<=10;L++){let H=document.createElement("button");H.type="button",H.className="persona-feedback-rating-btn persona-feedback-number-btn",H.setAttribute("role","radio"),H.setAttribute("aria-checked","false"),H.setAttribute("aria-label",`Rating ${L} out of 10`),H.textContent=String(L),H.dataset.rating=String(L),L<=6?H.classList.add("persona-feedback-detractor"):L<=8?H.classList.add("persona-feedback-passive"):H.classList.add("persona-feedback-promoter"),H.addEventListener("click",()=>{b=L,U.forEach((ne,de)=>{ne.classList.toggle("selected",de===L),ne.setAttribute("aria-checked",de===L?"true":"false")})}),U.push(H),z.appendChild(H)}D.appendChild(T),D.appendChild(z),f.appendChild(D);let w=null;if(p){let L=document.createElement("div");L.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"),L.appendChild(w),f.appendChild(L)}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 R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=i,R.addEventListener("click",async()=>{if(b===null){z.classList.add("persona-feedback-shake"),setTimeout(()=>z.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let L=w?.value.trim()||void 0;await e(b,L),u.remove()}catch(L){R.disabled=!1,R.textContent=i,console.error("[NPS Feedback] Failed to submit:",L)}}),O.appendChild(N),O.appendChild(R),f.appendChild(O),u.appendChild(f),u}var Sr="persona-chat-history",hv=30*1e3,bv=641,yv={"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 vv(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=yv[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 Aa(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 xv(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 Cv(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var vc=t=>!t||typeof t!="object"?{}:{...t},Zf=t=>t.map(e=>({...e,streaming:!1})),eg=(t,e,n)=>{let o=t?.markdown?pi(t.markdown):null,r=ui(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=On()!==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?jd(i):i,u=o(d);c=r&&p?r(u):u}else c=oo(i);return c}};function tg(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 wv=(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},Av=t=>t.reduce((e,n)=>({blocks:[...e.blocks,...n.blocks],contentParts:[...e.contentParts,...n.contentParts],context:wv(e.context,n.context)}),{blocks:[],contentParts:[],context:{}}),ng=(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=qi(e),r=fc.getForInstance(o.plugins),{plugin:s,teardown:i}=Lf();o.components&&jn.registerAll(o.components);let l=qf(),c=o.persistState===!1?null:o.storageAdapter??Kf(),d={},u=null,b=!1,f=a=>{if(o.onStateLoaded)try{let g=o.onStateLoaded(a);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:x}=g;return x&&(b=!0),y}return g}catch(g){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return a};if(c?.load)try{let a=c.load();if(a&&typeof a.then=="function")u=a.then(g=>f(g??{messages:[],metadata:{}}));else{let y=f(a??{messages:[],metadata:{}});y.metadata&&(d=vc(y.metadata)),y.messages?.length&&(o={...o,initialMessages:y.messages}),y.artifacts?.length&&(o={...o,initialArtifacts:y.artifacts,initialSelectedArtifactId:y.selectedArtifactId??null})}}catch(a){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",a)}else if(o.onStateLoaded)try{let a=f({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})??{},$a()},I=o.actionParsers&&o.actionParsers.length?o.actionParsers:[mc],D=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Bs.message,Bs.messageAndClick],T=hc({parsers:I,handlers:D,getSessionMetadata:m,updateSessionMetadata:C,emit:l.emit,documentRef:typeof document<"u"?document:null});T.syncFromMetadata();let A=o.launcher?.enabled??!0,W=o.launcher?.autoExpand??!1,z=o.autoFocusInput??!1,U=W,w=A,O=o.layout?.header?.layout,N=!1,R=()=>Es(o),L=()=>A||R(),H=R()?!1:A?W:!0,ne=!1,de=null,me=()=>{ne=!0,de&&clearTimeout(de),de=setTimeout(()=>{ne&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ne=!1)},1e4)},ue=eg(o,T,me),ee=o.features?.showReasoning??!0,re=o.features?.showToolCalls??!0,G=o.features?.showEventStreamToggle??!1,ie=o.features?.scrollToBottom??{},te=o.features?.scrollBehavior??{},ve=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,fe=G?new Is(ve):null,Ee=o.features?.eventStream?.maxEvents??2e3,Te=G?new Ps(Ee,fe):null,Fe=G?new Rs:null,Le=null,Ge=!1,Ze=null,Be=0;fe?.open().then(()=>Te?.restore()).catch(a=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",a)});let Pe={onCopy:a=>{l.emit("message:copy",a),V?.isClientTokenMode()&&V.submitMessageFeedback(a.id,"copy").catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",g)}),o.messageActions?.onCopy?.(a)},onFeedback:a=>{l.emit("message:feedback",a),V?.isClientTokenMode()&&V.submitMessageFeedback(a.messageId,a.type).catch(g=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",g)}),o.messageActions?.onFeedback?.(a)}},et=o.statusIndicator??{},dn=a=>a==="idle"?et.idleText??Bt.idle:a==="connecting"?et.connectingText??Bt.connecting:a==="connected"?et.connectedText??Bt.connected:a==="error"?et.errorText??Bt.error:a==="paused"?et.pausedText??Bt.paused:a==="resuming"?et.resumingText??Bt.resuming:Bt[a];function Pt(a,g,y,x){if(x==="idle"&&y.idleLink){a.textContent="";let E=document.createElement("a");E.href=y.idleLink,E.target="_blank",E.rel="noopener noreferrer",E.textContent=g,E.style.color="inherit",E.style.textDecoration="none",a.appendChild(E)}else a.textContent=g}let xt=bf({config:o,showClose:L()}),{wrapper:De,panel:we,pillRoot:Je}=xt.shell,We=xt.panelElements,{container:xe,body:pe,messagesWrapper:Se,suggestions:Ct,textarea:Ae,sendButton:be,sendButtonWrapper:bn,composerForm:Z,statusText:k,introTitle:j,introSubtitle:v,closeButton:S,iconHolder:P,headerTitle:_,headerSubtitle:Q,header:$,footer:K,actionsRow:ae,rightActions:Qe}=We,Ie=We.leftActions,dt=We.setSendButtonMode,X=We.micButton,ze=We.micButtonWrapper,Re=We.attachmentButton,Ne=We.attachmentButtonWrapper,He=We.attachmentInput,tt=We.attachmentPreviewsContainer;xe.classList.add("persona-relative"),pe.classList.add("persona-relative");let mo=12,ho=()=>ie.label??"",Ma=()=>ie.iconName??"arrow-down",Ns=()=>ie.enabled!==!1,Zt=()=>te.mode??"anchor-top",qn=()=>Zt()==="follow"||Zt()==="anchor-top"&&Hr,Tc=()=>te.anchorTopOffset??16,mg=()=>te.restorePosition??"bottom",Ec=()=>te.pauseOnInteraction===!0,kc=()=>te.showActivityWhilePinned!==!1,Lc=()=>te.announce===!0,Wt=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");Wt.type="button",Wt.style.display="none",Wt.setAttribute("data-persona-scroll-to-bottom","true");let Tr=h("span","persona-flex persona-items-center"),Ta=h("span",""),bo=h("span","");bo.setAttribute("data-persona-scroll-to-bottom-count",""),bo.style.display="none",Wt.append(Tr,Ta,bo),xe.appendChild(Wt);let Vn=h("div","persona-stream-anchor-spacer");Vn.setAttribute("aria-hidden","true"),Vn.setAttribute("data-persona-anchor-spacer",""),Vn.style.flexShrink="0",Vn.style.pointerEvents="none",Vn.style.height="0px",pe.appendChild(Vn);let yo=h("div","persona-sr-only");yo.setAttribute("aria-live","polite"),yo.setAttribute("aria-atomic","true"),yo.setAttribute("role","status"),yo.setAttribute("data-persona-live-region",""),Object.assign(yo.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"}),xe.appendChild(yo);let Er=null,Os=null,Pc=a=>{!Lc()||!a||(Os=a,Er===null&&(Er=setTimeout(()=>{Er=null,Os&&Lc()&&(yo.textContent=Os),Os=null},400)))},Uo=()=>{let g=K.style.display==="none"?0:K.offsetHeight;Wt.style.bottom=`${g+mo}px`};Uo();let Ic=()=>{let a=!!ho();Wt.setAttribute("aria-label",ho()||"Jump to latest"),Wt.title=ho(),Wt.setAttribute("data-persona-scroll-to-bottom-has-label",a?"true":"false"),Tr.innerHTML="";let g=se(Ma(),"14px","currentColor",2);g?(Tr.appendChild(g),Tr.style.display=""):Tr.style.display="none",Ta.textContent=ho(),Ta.style.display=a?"":"none"};Ic();let kt=null,nn=null,Rc=null,Wc=r.find(a=>a.renderHeader);if(Wc?.renderHeader){let a=Wc.renderHeader({config:o,defaultRenderer:()=>{let g=Fo({config:o,showClose:L()});return ks(xe,g,o),g.header},onClose:()=>mt(!1,"user")});if(a){let g=xe.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(a),$=a,xt.header.element=a)}}let Ea=()=>{if(!Te)return;if(Ge=!0,!Le&&Te&&(Le=Hf({buffer:Te,getFullHistory:()=>Te.getAllFromStore(),onClose:()=>kr(),config:o,plugins:r,getThroughput:()=>Fe?.getMetric()??{status:"idle"}})),Le&&(pe.style.display="none",K.parentNode?.insertBefore(Le.element,K),Le.update()),lt){lt.style.boxShadow=`inset 0 0 0 1.5px ${Jt.actionIconColor}`;let g=o.features?.eventStream?.classNames?.toggleButtonActive;g&&g.split(/\s+/).forEach(y=>y&<.classList.add(y))}let a=()=>{if(!Ge)return;let g=Date.now();g-Be>=200&&(Le?.update(),Be=g),Ze=requestAnimationFrame(a)};Be=0,Ze=requestAnimationFrame(a),rn(),l.emit("eventStream:opened",{timestamp:Date.now()})},kr=()=>{if(Ge){if(Ge=!1,Le&&Le.element.remove(),pe.style.display="",lt){lt.style.boxShadow="";let a=o.features?.eventStream?.classNames?.toggleButtonActive;a&&a.split(/\s+/).forEach(g=>g&<.classList.remove(g))}Ze!==null&&(cancelAnimationFrame(Ze),Ze=null),rn(),l.emit("eventStream:closed",{timestamp:Date.now()})}},lt=null;if(G){let a=o.features?.eventStream?.classNames,g="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:"");lt=h("button",g),lt.style.width="28px",lt.style.height="28px",lt.style.color=Jt.actionIconColor,lt.type="button",lt.setAttribute("aria-label","Event Stream"),lt.title="Event Stream";let y=se("activity","18px","currentColor",1.5);y&<.appendChild(y);let x=We.clearChatButtonWrapper,E=We.closeButtonWrapper,B=x||E;B&&B.parentNode===$?$.insertBefore(lt,B):$.appendChild(lt),lt.addEventListener("click",()=>{Ge?kr():Ea()})}let hg=a=>{let g=o.attachments;if(!g?.enabled)return;let y=a.querySelector("[data-persona-composer-attachment-previews]")??a.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.setAttribute("data-persona-composer-attachment-previews",""),y.style.display="none";let E=a.querySelector("[data-persona-composer-form]");E?.parentNode?E.parentNode.insertBefore(y,E):a.insertBefore(y,a.firstChild)}if(!(a.querySelector("[data-persona-composer-attachment-input]")??a.querySelector('input[type="file"]'))){let E=h("input");E.type="file",E.setAttribute("data-persona-composer-attachment-input",""),E.accept=(g.allowedTypes??zn).join(","),E.multiple=(g.maxFiles??4)>1,E.style.display="none",E.setAttribute("aria-label",g.buttonTooltipText??"Attach files"),a.appendChild(E)}},Hc=r.find(a=>a.renderComposer);if(Hc?.renderComposer){let a=o.composer,g=Hc.renderComposer({config:o,defaultRenderer:()=>va({config:o}).footer,onSubmit:y=>{if(!V||V.isStreaming())return;let x=y.trim(),E=kt?.hasAttachments()??!1;if(!x&&!E)return;cd();let B;E&&(B=[],B.push(...kt.getContentParts()),x&&B.push(dr(x))),V.sendMessage(x,{contentParts:B}),E&&kt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{He?.click()},models:a?.models,selectedModelId:a?.selectedModelId,onModelChange:y=>{o.composer={...o.composer,selectedModelId:y},o.agent&&(o.agent={...o.agent,model:y})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Rc?.()}:void 0});g&&(xt.replaceComposer(g),K=xt.composer.footer)}let bg=a=>{let g=(...ge)=>{for(let ce of ge){let Me=a.querySelector(ce);if(Me)return Me}return null},y=a.querySelector("[data-persona-composer-form]"),x=a.querySelector("[data-persona-composer-input]"),E=a.querySelector("[data-persona-composer-submit]"),B=a.querySelector("[data-persona-composer-mic]"),Y=a.querySelector("[data-persona-composer-status]");y&&(Z=y),x&&(Ae=x),E&&(be=E),B&&(X=B,ze=B.parentElement),Y&&(k=Y);let q=g("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");q&&(Ct=q);let J=g("[data-persona-composer-attachment-button]",".persona-attachment-button");J&&(Re=J,Ne=J.parentElement),He=g("[data-persona-composer-attachment-input]",'input[type="file"]'),tt=g("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let le=g("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");le&&(ae=le),Ie=g(".persona-widget-composer__left-actions")};hg(K),bg(K);let Kn=o.layout?.contentMaxWidth??(R()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Kn&&(Se.style.maxWidth=Kn,Se.style.marginLeft="auto",Se.style.marginRight="auto",Se.style.width="100%"),Kn&&Z&&!R()&&(Z.style.maxWidth=Kn,Z.style.marginLeft="auto",Z.style.marginRight="auto"),Kn&&Ct&&!R()&&(Ct.style.maxWidth=Kn,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),Kn&&tt&&!R()&&(tt.style.maxWidth=Kn,tt.style.marginLeft="auto",tt.style.marginRight="auto"),o.attachments?.enabled&&He&&tt){kt=cs.fromConfig(o.attachments),kt.setPreviewsContainer(tt),He.addEventListener("change",y=>{let x=y.target;kt?.handleFileSelect(x.files),x.value=""});let a=o.attachments.dropOverlay,g=tg(a);xe.appendChild(g)}let yg=()=>nn?.prefetch();if(o.contextMentions?.enabled&&Ae&&(nn=Au({config:o,textarea:Ae,anchor:Z??Ae,getMessages:()=>V.getMessages(),liveRegionHost:xe}),nn)){let a=Ae;a.parentElement?.insertBefore(nn.contextRow,a);let g=nn.affordanceButtons;for(let y=g.length-1;y>=0;y--){let x=g[y];Ie?Ie.insertBefore(x,Ie.firstChild):Z?.appendChild(x)}}(()=>{let a=o.layout?.slots??{},g=x=>{switch(x){case"body-top":return xe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Se;case"footer-top":return Ct;case"composer":return Z;case"footer-bottom":return k;default:return null}},y=(x,E)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")$.insertBefore(E,$.firstChild);else if(x==="header-right")$.appendChild(E);else{let B=$.querySelector(".persona-flex-col");B?B.parentNode?.insertBefore(E,B.nextSibling):$.appendChild(E)}break;case"body-top":{let B=pe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(E):pe.insertBefore(E,pe.firstChild);break}case"body-bottom":pe.appendChild(E);break;case"footer-top":Ct.replaceWith(E);break;case"footer-bottom":k.replaceWith(E);break;default:break}};for(let[x,E]of Object.entries(a))if(E)try{let B=E({config:o,defaultContent:()=>g(x)});B&&y(x,B)}catch(B){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,B)}})();let Bc=a=>{let y=a.target.closest('button[data-expand-header="true"]');if(!y)return;let x=y.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let E=x.getAttribute("data-message-id");if(!E)return;let B=y.getAttribute("data-bubble-type");if(B==="reasoning")Cr.has(E)?Cr.delete(E):Cr.add(E),wf(E,x);else if(B==="tool")wr.has(E)?wr.delete(E):wr.add(E),Af(E,x,o);else if(B==="approval"){let q=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",J=_o.get(E)??q;_o.set(E,!J),Ef(E,x,o)}wo.delete(E)};Se.addEventListener("pointerdown",a=>{a.target.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Bc(a))}),Se.addEventListener("keydown",a=>{let g=a.target;(a.key==="Enter"||a.key===" ")&&g.closest('button[data-expand-header="true"]')&&(a.preventDefault(),Bc(a))}),Se.addEventListener("copy",a=>{let{clipboardData:g}=a;if(!g)return;let y=Se.getRootNode(),x=typeof y.getSelection=="function"?y.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let E=x.toString(),B=Yu(E);!B||B===E||(g.setData("text/plain",B),a.preventDefault())});let ka=new Map,Dc=null,Nc="idle",vg={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},xg=(a,g)=>{let{icon:y,label:x}=vg[g];a.setAttribute("aria-label",x),a.title=x,a.setAttribute("aria-pressed",g==="idle"?"false":"true"),a.classList.toggle("persona-message-action-active",g!=="idle"),a.classList.toggle("persona-message-action-loading",g==="loading");let E=se(y,14,"currentColor",2);E&&(a.innerHTML="",a.appendChild(E))},Oc=()=>{Se.querySelectorAll('[data-action="read-aloud"]').forEach(g=>{let x=g.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;xg(g,x&&x===Dc?Nc:"idle")})};Se.addEventListener("click",a=>{let y=a.target.closest(".persona-message-action-btn[data-action]");if(!y)return;a.preventDefault(),a.stopPropagation();let x=y.closest("[data-actions-for]");if(!x)return;let E=x.getAttribute("data-actions-for");if(!E)return;let B=y.getAttribute("data-action");if(B==="copy"){let q=V.getMessages().find(J=>J.id===E);if(q&&Pe.onCopy){let J=q.content||"";navigator.clipboard.writeText(J).then(()=>{y.classList.add("persona-message-action-success");let le=se("check",14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ge=se("copy",14,"currentColor",2);ge&&(y.innerHTML="",y.appendChild(ge))},2e3)}).catch(le=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",le)}),Pe.onCopy(q)}}else if(B==="read-aloud")V.toggleReadAloud(E);else if(B==="upvote"||B==="downvote"){let q=(ka.get(E)??null)===B,J=B==="upvote"?"thumbs-up":"thumbs-down";if(q){ka.delete(E),y.classList.remove("persona-message-action-active");let le=se(J,14,"currentColor",2);le&&(y.innerHTML="",y.appendChild(le))}else{let le=B==="upvote"?"downvote":"upvote",ge=x.querySelector(`[data-action="${le}"]`);if(ge){ge.classList.remove("persona-message-action-active");let ct=se(le==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ct&&(ge.innerHTML="",ge.appendChild(ct))}ka.set(E,B),y.classList.add("persona-message-action-active");let ce=se(J,14,"currentColor",2);ce&&(ce.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(ce)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Ke=V.getMessages().find(ht=>ht.id===E);Ke&&Pe.onFeedback&&Pe.onFeedback({type:B,messageId:Ke.id,message:Ke})}}}),Se.addEventListener("click",a=>{let y=a.target.closest("button[data-approval-action]");if(!y)return;a.preventDefault(),a.stopPropagation();let x=y.closest(".persona-approval-bubble");if(!x)return;let E=x.getAttribute("data-message-id");if(!E)return;let B=y.getAttribute("data-approval-action");if(!B)return;let Y=B==="approve"?"approved":"denied",J=V.getMessages().find(ge=>ge.id===E);if(!J?.approval)return;let le=x.querySelector("[data-approval-buttons]");le&&le.querySelectorAll("button").forEach(ce=>{ce.disabled=!0,ce.style.opacity="0.5",ce.style.cursor="not-allowed"}),J.approval.toolType==="webmcp"?V.resolveWebMcpApproval(E,Y):V.resolveApproval(J.approval,Y)});let nt=null,Lr=null,Pr=()=>{},Ir="none",Fs=null,yn={artifacts:[],selectedId:null},Rn=!1,vn=!1,Rr=!1,jo=!1,Fc=()=>jo||yn.artifacts.some(a=>Wo(o.features?.artifacts,a.artifactType)==="panel"),_s=()=>yn.artifacts.length>0&&!Rn&&Fc(),gt={current:null},La=(a,g)=>{let y=V.getArtifactById(g),x=y?.markdown,E=y?.title||"artifact",B=y?.file,Y=y?.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 ce=V.getMessages().find(Me=>Me.id===le);if(ce?.rawContent)try{let Me=JSON.parse(ce.rawContent);x=Me?.props?.markdown,E=Me?.props?.title||E,Me?.props?.file&&typeof Me.props.file=="object"&&(B=Me.props.file),!y&&typeof Me?.props?.artifactType=="string"&&(Y=Me.props.artifactType)}catch{}}}return{markdown:x,title:E,file:B,artifactType:Y}};Se.addEventListener("click",a=>{let y=a.target.closest("[data-download-artifact]");if(!y)return;a.preventDefault(),a.stopPropagation();let x=y.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:B,title:Y,file:q}=La(y,x);if(!B)return;let{filename:J,mime:le,content:ge}=Wu({title:Y,markdown:B,file:q}),ce=new Blob([ge],{type:le}),Me=URL.createObjectURL(ce),Ke=document.createElement("a");Ke.href=Me,Ke.download=J,Ke.click(),URL.revokeObjectURL(Me)}),Se.addEventListener("click",a=>{let y=a.target.closest("[data-artifact-custom-action]");if(!y)return;a.preventDefault(),a.stopPropagation();let x=y.getAttribute("data-artifact-custom-action");if(!x)return;let E=y.closest("[data-artifact-inline]"),B=E?null:y.closest("[data-open-artifact]"),Y=E?E.getAttribute("data-artifact-inline"):B?.getAttribute("data-open-artifact")??null,J=(E?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ht=>ht.id===x);if(!J)return;let{markdown:le,title:ge,file:ce,artifactType:Me}=La(y,Y??""),Ke={artifactId:Y,title:ge,artifactType:Me,markdown:le,file:ce};try{Promise.resolve(J.onClick(Ke)).catch(()=>{})}catch{}}),Se.addEventListener("click",a=>{let y=a.target.closest("[data-copy-artifact]");if(!y)return;a.preventDefault(),a.stopPropagation();let x=y.getAttribute("data-copy-artifact");if(!x)return;let E=V.getArtifactById(x),B="";if(E)B=Cs(E);else{let{markdown:Y,file:q,artifactType:J}=La(y,x);J==="markdown"&&(B=Cs({id:x,artifactType:"markdown",status:"complete",markdown:Y??"",...q?{file:q}:{}}))}B&&navigator.clipboard.writeText(B).then(()=>{let Y=se("check",16,"currentColor",2);Y&&(y.replaceChildren(Y),setTimeout(()=>{let q=se("copy",16,"currentColor",2);q&&y.replaceChildren(q)},1500))}).catch(()=>{})}),Se.addEventListener("click",a=>{let y=a.target.closest("[data-expand-artifact-inline]");if(!y)return;a.preventDefault(),a.stopPropagation();let x=y.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(Rn=!1,jo=!0,vn=!0,Rr=!0,V.selectArtifact(x),Wn())}),Se.addEventListener("click",a=>{let g=a.target;if(g.closest("[data-download-artifact]")||g.closest("[data-artifact-custom-action]"))return;let y=g.closest("[data-open-artifact]");if(!y)return;let x=y.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(a.preventDefault(),a.stopPropagation(),Rn=!1,jo=!0,V.selectArtifact(x),Wn())}),Se.addEventListener("keydown",a=>{if(a.key!=="Enter"&&a.key!==" ")return;let g=a.target;!g.hasAttribute("data-open-artifact")&&!g.hasAttribute("data-expand-artifact-inline")||(a.preventDefault(),g.click())});let qo=We.composerOverlay,Vo=(a,g,y)=>{let x=g.trim();if(!x||!gt.current)return;let E=a.getAttribute("data-tool-call-id")??"",B=y.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:E,answer:x,answers:y.structured,values:y.values??(y.source==="multi"?x.split(", "):[x]),isFreeText:B,source:y.source},bubbles:!0,composed:!0})),ar(qo,E);let Y=gt.current.getMessages().find(q=>q.toolCall?.id===E);Y?.agentMetadata?.awaitingLocalTool?gt.current.resolveAskUserQuestion(Y,y.structured??x):gt.current.sendMessage(x)},vo=a=>{let g=gt.current;if(!g)return;let y=a.getAttribute("data-tool-call-id")??"",x=g.getMessages().find(E=>E.toolCall?.id===y);x&&g.persistAskUserQuestionProgress(x,{answers:hi(a,x),currentIndex:mn(a)})},_c=a=>Object.entries(a).map(([g,y])=>`${g}: ${Array.isArray(y)?y.join(", "):y}`).join(" | "),Pa=a=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let g=mn(a),y=ir(a);if(g>=y-1)return;let x=gt.current?.getMessages().find(E=>E.toolCall?.id===a.getAttribute("data-tool-call-id"));x&&(yi(a,x,o,g+1),vo(a))};qo.addEventListener("click",a=>{let y=a.target.closest("[data-ask-user-action]");if(!y)return;let x=y.closest("[data-persona-ask-sheet-for]");if(!x)return;let E=y.getAttribute("data-ask-user-action");if(a.preventDefault(),a.stopPropagation(),E==="dismiss"){let B=x.getAttribute("data-tool-call-id")??"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:B},bubbles:!0,composed:!0})),ar(qo,B);let Y=gt.current?.getMessages().find(q=>q.toolCall?.id===B);Y?.agentMetadata?.awaitingLocalTool&&(gt.current?.markAskUserQuestionResolved(Y),gt.current?.resolveAskUserQuestion(Y,"(dismissed)"));return}if(E==="pick"){let B=y.getAttribute("data-option-label");if(!B)return;let Y=x.getAttribute("data-multi-select")==="true",q=so(x);if(q&&Y){let J=Bo(x)[mn(x)],le=new Set(Array.isArray(J)?J:[]);le.has(B)?le.delete(B):le.add(B),io(x,Array.from(le)),vo(x);return}if(q){io(x,B),vo(x),Pa(x);return}if(Y){let J=y.getAttribute("aria-pressed")==="true";y.setAttribute("aria-pressed",J?"false":"true"),y.classList.toggle("persona-ask-pill-selected",!J);let le=x.querySelector('[data-ask-user-action="submit-multi"]');le&&(le.disabled=fl(x).length===0);return}Vo(x,B,{source:"pick",values:[B]});return}if(E==="submit-multi"){let B=fl(x);if(B.length===0)return;Vo(x,B.join(", "),{source:"multi",values:B});return}if(E==="open-free-text"){let B=x.querySelector('[data-ask-free-text-row="true"]');B&&(B.classList.remove("persona-hidden"),B.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(E==="focus-free-text"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(E==="submit-free-text"){let Y=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!Y.trim())return;if(so(x)){io(x,Y.trim()),vo(x),Pa(x);return}Vo(x,Y,{source:"free-text"});return}if(E==="next"||E==="back"){if(!gt.current)return;let B=x.getAttribute("data-tool-call-id")??"",Y=gt.current.getMessages().find(ce=>ce.toolCall?.id===B);if(!Y)return;let J=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(J){let ce=Bo(x)[mn(x)];(typeof ce!="string"||ce!==J)&&io(x,J)}let le=E==="next"?1:-1,ge=mn(x)+le;yi(x,Y,o,ge),vo(x);return}if(E==="submit-all"){if(!gt.current)return;let B=x.getAttribute("data-tool-call-id")??"",Y=gt.current.getMessages().find(ce=>ce.toolCall?.id===B);if(!Y)return;let J=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";J&&io(x,J);let le=hi(x,Y);gt.current.persistAskUserQuestionProgress(Y,{answers:le,currentIndex:mn(x)});let ge=_c(le);Vo(x,ge||"(submitted)",{source:"submit-all",structured:le});return}if(E==="skip"){if(!gt.current)return;let B=x.getAttribute("data-tool-call-id")??"",Y=gt.current.getMessages().find(Me=>Me.toolCall?.id===B);if(!Y)return;let q=so(x),J=mn(x),le=ir(x),ge=J>=le-1;if(!q){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:B},bubbles:!0,composed:!0})),ar(qo,B),Y.agentMetadata?.awaitingLocalTool&&(gt.current.markAskUserQuestionResolved(Y),gt.current.resolveAskUserQuestion(Y,"(dismissed)"));return}io(x,"");let ce=x.querySelector('[data-ask-free-text-input="true"]');if(ce&&(ce.value=""),ge){let Me=hi(x,Y),Ke=_c(Me);Vo(x,Ke||"(skipped)",{source:"submit-all",structured:Me});return}yi(x,Y,o,J+1),vo(x);return}}),qo.addEventListener("keydown",a=>{if(a.key!=="Enter")return;let y=a.target;if(!y.matches?.('[data-ask-free-text-input="true"]'))return;let x=y.closest("[data-persona-ask-sheet-for]");if(!x)return;a.preventDefault();let E=y.value;if(E.trim()){if(so(x)){io(x,E.trim()),vo(x),Pa(x);return}Vo(x,E,{source:"free-text"})}});let $c=a=>{if(!/^[1-9]$/.test(a.key)||a.metaKey||a.ctrlKey||a.altKey)return;let g=a.target;if(g?.tagName==="INPUT"||g?.tagName==="TEXTAREA"||g?.isContentEditable)return;let y=qo.querySelector("[data-persona-ask-sheet-for]");if(!y||y.getAttribute("data-ask-layout")!=="rows"||y.getAttribute("data-multi-select")==="true")return;let x=Number(a.key),B=y.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];B&&(a.preventDefault(),B.click())};document.addEventListener("keydown",$c);let Gn=null,wt=null,Wr=null,$s=null,Ia=()=>{},zc=!1,zs="",Us="";function Ra(){$s?.(),$s=null}let Uc=()=>{if(!Gn||!wt)return;let a=t.classList.contains("persona-artifact-welded-split"),g=t.ownerDocument.defaultView??window,y=g.innerWidth<=640;if(!a||t.classList.contains("persona-artifact-narrow-host")||y){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=Gn.firstElementChild;if(!x||x===wt)return;let E=10;wt.style.position="absolute",wt.style.top="0",wt.style.bottom="0",wt.style.width=`${E}px`,wt.style.zIndex="5";let B=dc(Gn,g),Y=x.offsetWidth+B/2-E/2;wt.style.left=`${Math.max(0,Y)}px`},js=()=>{},Cg=()=>{let a=t.ownerDocument.defaultView??window,g=o.launcher?.mobileFullscreen??!0,y=o.launcher?.mobileBreakpoint??640;return!g||a.innerWidth>y?!1:A||$t(o)},qs=()=>!Yt(o)||!_s()||t.classList.contains("persona-artifact-narrow-host")||Cg()||(t.ownerDocument.defaultView??window).innerWidth<bv?"none":cc(o)?"detached":"welded",Wn=()=>{if(!nt||!Yt(o))return;Ws(t,o),Hs(t,o),js();let a=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,g=we.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",g>0&&g<=a);let y=_s();nt.setVisible(y),nt.update(yn),Rn?(nt.setMobileOpen(!1),nt.element.classList.add("persona-hidden"),nt.backdrop?.classList.add("persona-hidden"),vn=!1,Rr=!1):yn.artifacts.length>0&&Fc()?(nt.element.classList.remove("persona-hidden"),nt.setMobileOpen(!0)):(nt.setMobileOpen(!1),nt.element.classList.add("persona-hidden"),nt.backdrop?.classList.add("persona-hidden"),vn=!1,Rr=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(nt.setExpandToggleVisible(x),nt.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),nt.setCustomActions(o.features?.artifacts?.toolbarActions??[]),nt.setTabFade(o.features?.artifacts?.layout?.tabFade),nt.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!Rr&&(vn=!1),vn!==zc){let B=nt.element;vn?(zs=B.style.width,Us=B.style.maxWidth,B.style.removeProperty("width"),B.style.removeProperty("max-width")):(zs&&(B.style.width=zs),Us&&(B.style.maxWidth=Us),zs="",Us=""),zc=vn}t.classList.toggle("persona-artifact-expanded",vn),nt.setExpanded(vn);let E=qs();E!==Ir&&(Ir=E,Pr()),Ia()};if(Yt(o)){we.style.position="relative";let a=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");a.appendChild(xe),nt=Df(o,{onSelect:y=>gt.current?.selectArtifact(y),onDismiss:()=>{Rn=!0,Wn()},onToggleExpand:()=>{let y=!vn,x=yn.selectedId??yn.artifacts[yn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:y})!==!0&&(vn=y,y||(Rr=!1),Wn())}}),nt.element.classList.add("persona-hidden"),Gn=g,g.appendChild(a),g.appendChild(nt.element),nt.backdrop&&we.appendChild(nt.backdrop),we.appendChild(g),Ia=()=>{if(!Gn||!nt)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Wr?.(),Wr=null,Ra(),wt&&(wt.remove(),wt=null),nt.element.style.removeProperty("width"),nt.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 E=t.ownerDocument,B=E.defaultView??window,Y=q=>{if(!nt||q.button!==0||t.classList.contains("persona-artifact-narrow-host")||t.classList.contains("persona-artifact-expanded")||B.innerWidth<=640)return;q.preventDefault(),Ra();let J=q.clientX,le=nt.element.getBoundingClientRect().width,ge=o.features?.artifacts?.layout,ce=Ke=>{let ht=Gn.getBoundingClientRect().width,ct=t.classList.contains("persona-artifact-welded-split"),Gt=dc(Gn,B),Nt=ct?0:x.getBoundingClientRect().width||6,F=le-(Ke.clientX-J),_e=_f(F,ht,Gt,Nt,ge?.resizableMinWidth,ge?.resizableMaxWidth);nt.element.style.width=`${_e}px`,nt.element.style.maxWidth="none",Uc()},Me=()=>{E.removeEventListener("pointermove",ce),E.removeEventListener("pointerup",Me),E.removeEventListener("pointercancel",Me),$s=null;try{x.releasePointerCapture(q.pointerId)}catch{}};$s=Me,E.addEventListener("pointermove",ce),E.addEventListener("pointerup",Me),E.addEventListener("pointercancel",Me);try{x.setPointerCapture(q.pointerId)}catch{}};x.addEventListener("pointerdown",Y),wt=x,Gn.insertBefore(x,nt.element),Wr=()=>{x.removeEventListener("pointerdown",Y)}}if(wt){let x=_s();wt.classList.toggle("persona-hidden",!x),Uc()}},js=()=>{if(!A||!nt||(o.launcher?.sidebarMode??!1)||$t(o)&&hn(o).reveal==="emerge")return;let x=t.ownerDocument.defaultView??window,E=o.launcher?.mobileFullscreen??!0,B=o.launcher?.mobileBreakpoint??640;if(E&&x.innerWidth<=B||!Ff(o,A))return;let Y=o.launcher?.width??o.launcherWidth??Un,q=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";_s()?(we.style.width=q,we.style.maxWidth=q):(we.style.width=Y,we.style.maxWidth=Y)},typeof ResizeObserver<"u"&&(Lr=new ResizeObserver(()=>{Wn()}),Lr.observe(we))}else we.appendChild(xe);R()&&Je&&(We.peekBanner&&Je.appendChild(We.peekBanner),Je.appendChild(K)),t.appendChild(De),Je&&t.appendChild(Je);let Vs=()=>{if(R()){we.style.width="100%",we.style.maxWidth="100%";let Rt=o.launcher?.composerBar??{},en=De.dataset.state==="expanded",si=Rt.expandedSize??"anchored";if(!(en&&si!=="fullscreen")){xe.style.background="",xe.style.border="",xe.style.borderRadius="",xe.style.overflow="",xe.style.boxShadow="";return}let Kr=o.theme?.components?.panel,ii=mr(o),er=(Nn,Po)=>Nn==null||Nn===""?Po:Xt(ii,Nn)??Nn,Gr="1px solid var(--persona-border)",ol="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Lo="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";xe.style.background="var(--persona-surface, #ffffff)",xe.style.border=er(Kr?.border,Gr),xe.style.borderRadius=er(Kr?.borderRadius,Lo),xe.style.boxShadow=er(Kr?.shadow,ol),xe.style.overflow="hidden";return}let a=$t(o),g=o.launcher?.sidebarMode??!1,y=a||g||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,E=o.launcher?.detachedPanel===!0,B=o.theme?.components?.panel,Y=mr(o),q=(Rt,en)=>Rt==null||Rt===""?en:Xt(Y,Rt)??Rt,J=t.ownerDocument.defaultView??window,le=o.launcher?.mobileFullscreen??!0,ge=o.launcher?.mobileBreakpoint??640,ce=J.innerWidth<=ge,Me=le&&ce&&A,Ke=a&&le&&ce,ht=o.launcher?.position??"bottom-left",ct=ht==="bottom-left"||ht==="top-left",Gt=o.launcher?.zIndex??Vt,Nt="var(--persona-panel-border, 1px solid var(--persona-border))",F="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",_e="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ke=E&&!Me&&!Ke;ke?t.setAttribute("data-persona-panel-detached","true"):t.removeAttribute("data-persona-panel-detached");let $e=ke?Nt:g||Me?"none":Nt,Tt=ke?F:Me?"none":g?ct?"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":F;a&&!Me&&!ke&&(Tt="none",$e="none");let ut=ke?_e:g||Me?"0":_e,St=q(B?.border,$e),vt=q(B?.shadow,Tt),jt=q(B?.borderRadius,ut),Eo=qs(),ft=Eo==="detached",he=Eo==="welded";t.classList.toggle("persona-artifact-detached-split",ft),t.classList.toggle("persona-artifact-welded-split",he);let Mt="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",it=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Yt(o)&&cc(o)&&x&&!a;t.classList.toggle("persona-artifact-chat-flush",it);let je=ft||it?"none":vt,ot=ft?Nt:he?"none":St,It=ft?_e:jt;it&&(ot="none",It="0");let Oe=B?.borderRadius!=null&&B.borderRadius!=="",rt=it&&!Oe?"0":jt,sn=pe.scrollTop;t.style.cssText="",De.style.cssText="",we.style.cssText="",xe.style.cssText="",pe.style.cssText="",K.style.cssText="",Ge&&(pe.style.display="none");let ko=()=>{if(sn<=0)return;(pe.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(pe.scrollTop===sn)return;let en=pe.scrollHeight-pe.clientHeight;en<=0||(pe.scrollTop=Math.min(sn,en))})};if(Me){De.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"),De.style.cssText=`
|
|
220
220
|
position: fixed !important;
|
|
221
221
|
inset: 0 !important;
|
|
222
222
|
width: 100% !important;
|
|
@@ -241,7 +241,7 @@ _Details: ${n.message}_`:o}var ls=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
241
241
|
padding: 0 !important;
|
|
242
242
|
box-shadow: none !important;
|
|
243
243
|
border-radius: 0 !important;
|
|
244
|
-
`,
|
|
244
|
+
`,xe.style.cssText=`
|
|
245
245
|
display: flex !important;
|
|
246
246
|
flex-direction: column !important;
|
|
247
247
|
flex: 1 1 0% !important;
|
|
@@ -252,11 +252,11 @@ _Details: ${n.message}_`:o}var ls=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
|
-
`,
|
|
255
|
+
`,pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.overflowY="auto",K.style.flexShrink="0",N=!0,ko();return}let ri=o?.launcher?.width??o?.launcherWidth??Un;if(!g&&!a)x&&y?(we.style.width="100%",we.style.maxWidth="100%"):(we.style.width=ri,we.style.maxWidth=ri);else if(a)if(hn(o).reveal==="emerge"&&!E){let en=hn(o).width;we.style.width=en,we.style.maxWidth=en}else we.style.width="100%",we.style.maxWidth="100%";if(js(),we.style.boxShadow=je,we.style.borderRadius=rt,ft?we.style.border="none":he&&(we.style.border=St),xe.style.border=ot,xe.style.borderRadius=It,xe.style.boxShadow=ft&&!it?Mt:"",it&&(xe.style.background="transparent",pe.style.background="transparent",K.style.background="transparent",K.style.borderTop="none"),he){let Rt=o.features?.artifacts?.layout;Fs=Rt?.unifiedSplitOuterRadius?.trim()||Rt?.paneBorderRadius?.trim()||jt}else Fs=null;if(a&&!Me&&!ke&&!ft&&!he&&B?.border===void 0&&(xe.style.border="none",hn(o).side==="right"?xe.style.borderLeft="1px solid var(--persona-border)":xe.style.borderRight="1px solid var(--persona-border)"),a&&!Me&&he&&B?.border===void 0&&(hn(o).side==="right"?we.style.borderLeft="1px solid var(--persona-border)":we.style.borderRight="1px solid var(--persona-border)"),y&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",x&&(t.style.width="100%"),De.style.display="flex",De.style.flexDirection="column",De.style.flex="1 1 0%",De.style.minHeight="0",De.style.maxHeight="100%",De.style.height="100%",x&&(De.style.overflow="hidden"),we.style.display="flex",we.style.flexDirection="column",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.maxHeight="100%",we.style.height="100%",ft||(we.style.overflow="hidden"),xe.style.display="flex",xe.style.flexDirection="column",xe.style.flex="1 1 0%",xe.style.minHeight="0",xe.style.maxHeight="100%",xe.style.overflow="hidden",pe.style.flex="1 1 0%",pe.style.minHeight="0",pe.style.overflowY="auto",K.style.flexShrink="0"),x&&(ke||ft||it)&&!a&&(it||(De.style.padding="var(--persona-panel-inset)"),De.style.background="var(--persona-panel-canvas-bg)"),De.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"),!g&&!x&&!a&&(Mn[ht]??Mn["bottom-right"]).split(" ").forEach(en=>De.classList.add(en)),g){let Rt=o.launcher?.sidebarWidth??"420px";E?De.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: ${
|
|
259
|
+
width: ${Rt} !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;
|
|
@@ -264,12 +264,12 @@ _Details: ${n.message}_`:o}var ls=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
264
264
|
display: flex !important;
|
|
265
265
|
flex-direction: column !important;
|
|
266
266
|
z-index: ${Gt} !important;
|
|
267
|
-
${
|
|
268
|
-
`:
|
|
267
|
+
${ct?"left: var(--persona-panel-inset) !important; right: auto !important;":"left: auto !important; right: var(--persona-panel-inset) !important;"}
|
|
268
|
+
`:De.style.cssText=`
|
|
269
269
|
position: fixed !important;
|
|
270
270
|
top: 0 !important;
|
|
271
271
|
bottom: 0 !important;
|
|
272
|
-
width: ${
|
|
272
|
+
width: ${Rt} !important;
|
|
273
273
|
height: 100vh !important;
|
|
274
274
|
max-height: 100vh !important;
|
|
275
275
|
margin: 0 !important;
|
|
@@ -277,7 +277,7 @@ _Details: ${n.message}_`:o}var ls=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
277
277
|
display: flex !important;
|
|
278
278
|
flex-direction: column !important;
|
|
279
279
|
z-index: ${Gt} !important;
|
|
280
|
-
${
|
|
280
|
+
${ct?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
281
281
|
`,we.style.cssText=`
|
|
282
282
|
position: relative !important;
|
|
283
283
|
display: flex !important;
|
|
@@ -289,10 +289,10 @@ _Details: ${n.message}_`:o}var ls=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: ${
|
|
293
|
-
border-radius: ${
|
|
294
|
-
${
|
|
295
|
-
`,we.style.setProperty("width","100%","important"),we.style.setProperty("max-width","100%","important"),
|
|
292
|
+
box-shadow: ${je} !important;
|
|
293
|
+
border-radius: ${rt} !important;
|
|
294
|
+
${ft?"border: none !important;":he?`border: ${St} !important;`:""}
|
|
295
|
+
`,we.style.setProperty("width","100%","important"),we.style.setProperty("max-width","100%","important"),xe.style.cssText=`
|
|
296
296
|
display: flex !important;
|
|
297
297
|
flex-direction: column !important;
|
|
298
298
|
flex: 1 1 0% !important;
|
|
@@ -301,16 +301,16 @@ _Details: ${n.message}_`:o}var ls=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: ${
|
|
305
|
-
border: ${
|
|
306
|
-
${
|
|
307
|
-
${
|
|
308
|
-
`,
|
|
304
|
+
border-radius: ${It} !important;
|
|
305
|
+
border: ${ot} !important;
|
|
306
|
+
${ft&&!it?`box-shadow: ${Mt} !important;`:""}
|
|
307
|
+
${it?"background: transparent !important;":""}
|
|
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
|
-
${
|
|
313
|
-
`}if(!v&&!a){let Wt="max-height: -moz-available !important; max-height: stretch !important;",tn=g?"":"padding-top: 1.25em !important;",si=g?"":`z-index: ${o.launcher?.zIndex??Vt} !important;`;Re.style.cssText+=Wt+tn+si}ko()};Vs(),bs(t,o),Ws(t,o),Hs(t,o),Pr=()=>{Vs(),bs(t,o),Ws(t,o),Hs(t,o),Fs?t.style.setProperty("--persona-artifact-welded-outer-radius",Fs):t.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ke=[];Ke.push(()=>{document.removeEventListener("keydown",_c)}),Ke.push(()=>{Er!==null&&clearTimeout(Er)});let Tn=null,En=null;Ke.push(()=>{Tn?.(),Tn=null,En?.(),En=null}),Lr&&Ke.push(()=>{Lr?.disconnect(),Lr=null}),Ke.push(()=>{Wr?.(),Wr=null,Ia(),wt&&(wt.remove(),wt=null),Ze?.element.style.removeProperty("width"),Ze?.element.style.removeProperty("maxWidth")}),K&&Ke.push(()=>{Ne!==null&&(cancelAnimationFrame(Ne),Ne=null),Pe?.destroy(),Pe=null,Me?.destroy(),Me=null,ge=null});let xo=null,Uc=()=>{xo&&(xo(),xo=null),o.colorScheme==="auto"&&(xo=Ki(()=>{bs(t,o)}))};Uc(),Ke.push(()=>{xo&&(xo(),xo=null)}),Ke.push(i);let Ks=o.features?.streamAnimation;if(Ks?.type&&Ks.type!=="none"){let a=xr(Ks.type,Ks.plugins);a&&(la(a,t),Ke.push(()=>pf(t)))}let Gs=Pf(Ct),Co=null,V,Ra=a=>{if(!V)return;let g=a??V.getMessages(),y=o.features?.suggestReplies?.enabled!==!1?dp(g):null;y?Gs.render(y,V,j,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(v=>v.role==="user")?Gs.render([],V,j,g):Gs.render(o.suggestionChips,V,j,g,o.suggestionChipsConfig)},xn=!1,wo=tf(),Go=new Map,Ao=new Map,Qn=new Map,Wa=0,vg=On()!==null,rn=na(),un=0,Xn=null,fn=!1,Qs=!1,Jn=0,Cn=null,So=null,Ha=!1,Xs=!1,Ba=null,Hr=!0,Da=!1,Na=null,xg=4,Js=24,Cg=80,Oa=new Map,Xe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},jc=o.voiceRecognition?.autoResume??!1,Hn=a=>{l.emit("voice:state",{active:Xe.active,source:a,timestamp:Date.now()})},wn=()=>{C(a=>({...a,voiceState:{active:Xe.active,timestamp:Date.now(),manuallyDeactivated:Xe.manuallyDeactivated}}))},wg=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=yc(d.voiceState),g=!!a.active,y=Number(a.timestamp??0);Xe.manuallyDeactivated=!!a.manuallyDeactivated,g&&Date.now()-y<uv&&setTimeout(()=>{Xe.active||(Xe.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?V.toggleVoice().then(()=>{Xe.active=V.isVoiceActive(),Hn("restore"),V.isVoiceActive()&&Zo()}):ei("restore"))},1e3)},Ag=()=>V?Xf(V.getMessages()).filter(a=>!a.__skipPersist):[],Ys=null,qc=(a,g)=>{typeof console<"u"&&console.error(a,g)},Fa=(a,g)=>{let y=()=>{try{let Z=a();return!Z||typeof Z.then!="function"?null:Promise.resolve(Z).catch(q=>{qc(g,q)})}catch(Z){return qc(g,Z),null}},v=Ys,T=v?v.then(()=>y()??void 0):y();if(!T)return;let B=T.finally(()=>{Ys===B&&(Ys=null)});Ys=B};function _a(a){if(!c?.save)return;let y={messages:a?Xf(a):V?Ag():[],metadata:d,artifacts:yn.artifacts,selectedArtifactId:yn.selectedId};Fa(()=>c.save(y),"[AgentWidget] Failed to persist state:")}let Qo=null,Vc=()=>Re.querySelector("#persona-scroll-container")||ue,Br=()=>{Qo!==null&&(cancelAnimationFrame(Qo),Qo=null),fn=!1},Kc=()=>{Xn!==null&&(cancelAnimationFrame(Xn),Xn=null),Qs=!1,Br()},Sg=()=>xn&&za()&&(en()!=="anchor-top"||Ec()),$a=()=>{let a=ho()||"Jump to latest",g=Sg();Ht.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),Jn>0?(bo.textContent=String(Jn),bo.style.display="",Ht.setAttribute("aria-label",`${a} (${Jn} new)`)):(bo.textContent="",bo.style.display="none",Ht.setAttribute("aria-label",g?`${a} (response streaming below)`:a))},Gc=()=>{Jn!==0&&(Jn=0,$a())},za=()=>qn()?!rn.isFollowing():!fo(ue,Js),sn=()=>{if(!Ns()||Ee){Ht.parentNode&&Ht.remove(),Ht.style.display="none";return}Ht.parentNode!==ye&&ye.appendChild(Ht),jo();let g=In(ue)>0&&za();g?$a():Gc(),Ht.style.display=g?"":"none"},Dr=()=>{rn.pause()&&(Kc(),sn())},Yn=()=>{rn.resume(),Gc(),sn()},Zn=(a=!1)=>{qn()&&rn.isFollowing()&&(!a&&!xn||(Xn!==null&&(cancelAnimationFrame(Xn),Xn=null),Qs=!0,Xn=requestAnimationFrame(()=>{Xn=null,Qs=!1,rn.isFollowing()&&Mg(Vc(),a?220:140)})))},Qc=(a,g,y,v=()=>!0)=>{let T=a.scrollTop,B=g(),Z=B-T;if(Br(),Math.abs(Z)<1){fn=!0,a.scrollTop=B,un=a.scrollTop,fn=!1;return}let q=performance.now();fn=!0;let X=me=>1-Math.pow(1-me,3),le=me=>{if(!v()){Br();return}let ce=g();ce!==B&&(B=ce,Z=B-T);let Se=me-q,Ge=Math.min(Se/y,1),yt=X(Ge),at=T+Z*yt;a.scrollTop=at,un=a.scrollTop,Ge<1?Qo=requestAnimationFrame(le):(a.scrollTop=B,un=a.scrollTop,Qo=null,fn=!1)};Qo=requestAnimationFrame(le)},Mg=(a,g=500)=>{let y=In(a)-a.scrollTop;if(Math.abs(y)<1){un=a.scrollTop;return}if(Math.abs(y)>=Cg){Br(),fn=!0,a.scrollTop=In(a),un=a.scrollTop,fn=!1;return}Qc(a,()=>In(a),g,()=>rn.isFollowing())},Xc=()=>{let a=Vc();fn=!0,a.scrollTop=In(a),un=a.scrollTop,fn=!1,sn()},Jc=a=>{let g=0,y=a;for(;y&&y!==ue;)g+=y.offsetTop,y=y.offsetParent;return g},Yc=()=>{if(ug()!=="last-user-turn")return!1;let a=V?.getMessages()??[];if(a.length<2)return!1;let g=[...a].reverse().find(B=>B.role==="user");if(!g)return!1;let y=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(g.id):g.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),v=ue.querySelector(`[data-message-id="${y}"]`);if(!v)return!1;let T=Math.min(Math.max(0,Jc(v)-Mc()),In(ue));return fn=!0,ue.scrollTop=T,un=ue.scrollTop,fn=!1,en()==="follow"&&!fo(ue,Js)&&rn.pause(),sn(),!0},Zc=a=>{Vn.style.height=`${Math.max(0,Math.round(a))}px`,Cn&&(Cn.spacerHeight=Math.max(0,a))},Nr=()=>{So!==null&&(cancelAnimationFrame(So),So=null),Br(),Cn=null,Vn.style.height="0px"},Tg=a=>{So!==null&&cancelAnimationFrame(So),So=requestAnimationFrame(()=>{So=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=ue.querySelector(`[data-message-id="${g}"]`);if(!y)return;let v=Jc(y),T=Cn?.spacerHeight??0,B=ue.scrollHeight-T,{targetScrollTop:Z,spacerHeight:q}=af({anchorOffsetTop:v,topOffset:Mc(),viewportHeight:ue.clientHeight,contentHeight:B});Cn={initialSpacerHeight:q,contentHeightAtAnchor:B,spacerHeight:q},Zc(q),Qc(ue,()=>Z,220)})},Eg=()=>{if(qn()){if(!rn.isFollowing()||fo(ue,1))return;Zn(!xn);return}if(Cn&&Cn.initialSpacerHeight>0){let a=ue.scrollHeight-Cn.spacerHeight,g=lf({initialSpacerHeight:Cn.initialSpacerHeight,contentHeightAtAnchor:Cn.contentHeightAtAnchor,currentContentHeight:a});g!==Cn.spacerHeight&&Zc(g)}sn()},kg=a=>{let g=en();g==="follow"?(Yn(),Zn(!0)):g==="anchor-top"&&(Hr=!1,Da=!0,Tg(a))},Lg=()=>{if(en()==="anchor-top"){if(Da){Hr=!1;return}Hr=!0,Nr(),Yn(),Zn(!0)}},Pg=a=>{let g=new Map;a.forEach(y=>{let v=Oa.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!v&&y.role==="assistant"&&(l.emit("assistant:message",y),!Xs&&(en()!=="anchor-top"||Ec())&&za()&&(Jn+=1,$a(),sn(),Lc(Jn===1?"1 new message below.":`${Jn} new messages below.`))),y.role==="assistant"&&v?.streaming&&y.streaming===!1&&l.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(v?y.approval.status!=="pending"&&l.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):l.emit("approval:requested",{approval:y.approval,message:y}))}),Oa.clear(),g.forEach((y,v)=>{Oa.set(v,y)})},Ig=(a,g,y)=>{let v=document.createElement("div"),B=(()=>{let F=r.find($e=>$e.renderLoadingIndicator);if(F?.renderLoadingIndicator)return F.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),Z=(F,$e)=>$e==null?!1:typeof $e=="string"?(F.textContent=$e,!0):(F.appendChild($e),!0),q=new Set,X=new Set,le=r.some(F=>F.renderAskUserQuestion),me=[],ce=[],Se=o.enableComponentStreaming!==!1,Ge=o.approval!==!1,yt=[];if(g.forEach(F=>{q.add(F.id);let $e=le&&Ho(F),ke=Ge&&F.variant==="approval"&&!!F.approval,Ue=!$e&&F.role==="assistant"&&!F.variant&&Se&&bc(F);!ke&&Qn.has(F.id)&&(a.querySelector(`#wrapper-${F.id}`)?.removeAttribute("data-preserve-runtime"),Qn.delete(F.id)),!Ue&&Ao.has(F.id)&&(a.querySelector(`#wrapper-${F.id}`)?.removeAttribute("data-preserve-runtime"),Ao.delete(F.id));let Et=Ho(F)?`:${F.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${F.agentMetadata?.askUserQuestionAnswers?Object.keys(F.agentMetadata.askUserQuestionAnswers).length:0}`:"",ft=ef(F,Wa)+Et,St=$e||ke||Ue?null:nf(wo,F.id,ft);if(St){v.appendChild(St.cloneNode(!0)),Ho(F)&&F.toolCall?.id&&F.agentMetadata?.awaitingLocalTool===!0&&!F.agentMetadata?.askUserQuestionAnswered&&(X.add(F.toolCall.id),bi(F,o,He.composerOverlay));return}let xt=null,jt=r.find(be=>!!(F.variant==="reasoning"&&be.renderReasoning||F.variant==="tool"&&be.renderToolCall||!F.variant&&be.renderMessage)),Eo=o.layout?.messages;if(Ho(F)&&F.agentMetadata?.askUserQuestionAnswered===!0){Go.delete(F.id),a.querySelector(`#wrapper-${F.id}`)?.removeAttribute("data-preserve-runtime");return}if(gl(F)&&o.features?.suggestReplies?.enabled!==!1)return;if(Ho(F)&&o.features?.askUserQuestion?.enabled!==!1){let be=r.find(Mt=>typeof Mt.renderAskUserQuestion=="function");if(be&&ht.current){let Mt=Go.get(F.id),Qt=Mt!==ft,Ft=null;if(Qt){let{payload:et,complete:Rt}=ir(F),Oe=F.id,tt=()=>ht.current?.getMessages().find(an=>an.id===Oe);Ft=be.renderAskUserQuestion({message:F,payload:et,complete:Rt,resolve:an=>{let ko=tt();ko&&ht.current?.resolveAskUserQuestion(ko,an)},dismiss:()=>{let an=tt();an?.agentMetadata?.awaitingLocalTool&&(ht.current?.markAskUserQuestionResolved(an),ht.current?.resolveAskUserQuestion(an,"(dismissed)"))},config:o})}let st=Mt!=null;if(Qt&&Ft===null&&!st){F.agentMetadata?.awaitingLocalTool===!0&&!F.agentMetadata?.askUserQuestionAnswered&&(X.add(F.toolCall.id),bi(F,o,He.composerOverlay));return}let Ve=document.createElement("div");Ve.className="persona-flex",Ve.id=`wrapper-${F.id}`,Ve.setAttribute("data-wrapper-id",F.id),Ve.setAttribute("data-ask-plugin-stub","true"),Ve.setAttribute("data-preserve-runtime","true"),v.appendChild(Ve),me.push({messageId:F.id,fingerprint:ft,bubble:Ft});return}else{F.agentMetadata?.awaitingLocalTool===!0&&!F.agentMetadata?.askUserQuestionAnswered&&(X.add(F.toolCall.id),bi(F,o,He.composerOverlay));return}}else if(ke){let be=r.find(st=>typeof st.renderApproval=="function")??s,Qt=Qn.get(F.id)!==ft,Ft=null;if(Qt&&be?.renderApproval){let st=F.id,Ve=(et,Rt)=>{let Oe=ht.current?.getMessages().find(tt=>tt.id===st);Oe?.approval&&(Oe.approval.toolType==="webmcp"?ht.current?.resolveWebMcpApproval(Oe.id,et):ht.current?.resolveApproval(Oe.approval,et,Rt))};Ft=be.renderApproval({message:F,defaultRenderer:()=>xa(F,o),config:o,approve:et=>Ve("approved",et),deny:et=>Ve("denied",et)})}if(Qt&&Ft===null)a.querySelector(`#wrapper-${F.id}`)?.removeAttribute("data-preserve-runtime"),Qn.delete(F.id),xt=xa(F,o);else{let st=document.createElement("div");st.className="persona-flex",st.id=`wrapper-${F.id}`,st.setAttribute("data-wrapper-id",F.id),st.setAttribute("data-approval-plugin-stub","true"),st.setAttribute("data-preserve-runtime","true"),v.appendChild(st),yt.push({messageId:F.id,fingerprint:ft,bubble:Ft});return}}else if(jt)if(F.variant==="reasoning"&&F.reasoning&&jt.renderReasoning){if(!ee)return;xt=jt.renderReasoning({message:F,defaultRenderer:()=>tc(F,o),config:o})}else if(F.variant==="tool"&&F.toolCall&&jt.renderToolCall){if(!oe)return;xt=jt.renderToolCall({message:F,defaultRenderer:()=>oc(F,o),config:o})}else jt.renderMessage&&(xt=jt.renderMessage({message:F,defaultRenderer:()=>{let be=ec(F,y,Eo,o.messageActions,ze,{loadingIndicatorRenderer:B,widgetConfig:o});return F.role!=="user"&&dc(be,F,o,V),be},config:o}));if(!xt&&Ue){let be=Kf(F);if(be){let Mt=Ao.get(F.id),Qt=Mt!==ft,Ft=o.wrapComponentDirectiveInBubble!==!1&&jn.getOptions(be.component)?.bubbleChrome!==!1,st=null;if(Qt){let Ve=qf(be,{config:o,message:F,transform:y});if(Ve&&be.component==="PersonaArtifactInline"){let et=Ve.hasAttribute("data-artifact-inline")?Ve:Ve.querySelector("[data-artifact-inline]"),Rt=et?.getAttribute("data-artifact-inline")??"",Oe=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Rt):Rt,tt=Rt?a.querySelector(`#wrapper-${F.id}`)?.querySelector(`[data-artifact-inline="${Oe}"]`)??null:null;et&&tt&&tt!==et&&Gu(tt)&&(et===Ve?Ve=tt:et.replaceWith(tt))}if(Ve)if(Ft){let et=document.createElement("div");if(et.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),et.id=`bubble-${F.id}`,et.setAttribute("data-message-id",F.id),F.content&&F.content.trim()){let Rt=document.createElement("div");Rt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Rt.innerHTML=y({text:F.content,message:F,streaming:!!F.streaming,raw:F.rawContent}),et.appendChild(Rt)}et.appendChild(Ve),st=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 Rt=document.createElement("div");Rt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Rt.innerHTML=y({text:F.content,message:F,streaming:!!F.streaming,raw:F.rawContent}),et.appendChild(Rt)}et.appendChild(Ve),st=et}}if(st||Mt!=null){let Ve=document.createElement("div");Ve.className="persona-flex",Ve.id=`wrapper-${F.id}`,Ve.setAttribute("data-wrapper-id",F.id),Ve.setAttribute("data-component-directive-stub","true"),Ve.setAttribute("data-preserve-runtime","true"),Ft||Ve.classList.add("persona-w-full"),v.appendChild(Ve),ce.push({messageId:F.id,fingerprint:ft,bubble:st});return}}}if(!xt)if(F.variant==="reasoning"&&F.reasoning){if(!ee)return;xt=tc(F,o)}else if(F.variant==="tool"&&F.toolCall){if(!oe)return;xt=oc(F,o)}else if(F.variant==="approval"&&F.approval){if(o.approval===!1)return;xt=xa(F,o)}else{let be=o.layout?.messages;be?.renderUserMessage&&F.role==="user"?xt=be.renderUserMessage({message:F,config:o,streaming:!!F.streaming}):be?.renderAssistantMessage&&F.role==="assistant"?xt=be.renderAssistantMessage({message:F,config:o,streaming:!!F.streaming}):xt=ec(F,y,be,o.messageActions,ze,{loadingIndicatorRenderer:B,widgetConfig:o}),F.role!=="user"&&xt&&dc(xt,F,o,V)}let gt=document.createElement("div");gt.className="persona-flex",gt.id=`wrapper-${F.id}`,gt.setAttribute("data-wrapper-id",F.id),F.role==="user"&>.classList.add("persona-justify-end"),xt?.getAttribute("data-persona-component-directive")==="true"&>.classList.add("persona-w-full"),gt.appendChild(xt),of(wo,F.id,ft,gt),v.appendChild(gt)}),He.composerOverlay&&He.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach($e=>{let ke=$e.getAttribute("data-persona-ask-sheet-for");ke&&!X.has(ke)&&lr(He.composerOverlay,ke)}),o.features?.toolCallDisplay?.grouped){let F=[],$e=[];g.forEach(ke=>{if(ke.variant==="tool"&&ke.toolCall&&oe){$e.push(ke);return}ke.variant==="reasoning"&&!ee||($e.length>1&&F.push($e),$e=[])}),$e.length>1&&F.push($e),F.forEach((ke,Ue)=>{let Et=ke.map(Mt=>Array.from(v.children).find(Qt=>Qt instanceof HTMLElement&&Qt.getAttribute("data-wrapper-id")===Mt.id)).filter(Mt=>!!Mt);if(Et.length<2)return;let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-tool-group-${Ue}-${ke[0].id}`,ft.setAttribute("data-wrapper-id",`tool-group-${Ue}-${ke[0].id}`);let St=document.createElement("div");St.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",St.setAttribute("data-persona-tool-group","true");let xt=document.createElement("div");xt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let jt=`Called ${ke.length} tools`,Eo=o.toolCall?.renderGroupedSummary?.({messages:ke,toolCalls:ke.map(Mt=>Mt.toolCall).filter(Mt=>!!Mt),defaultSummary:jt,config:o});Z(xt,Eo)||(xt.textContent=jt);let gt=document.createElement("div");gt.className="persona-tool-group-stack persona-flex persona-flex-col";let be=o.features?.toolCallDisplay?.groupedMode==="summary";St.appendChild(xt),be||St.appendChild(gt),ft.appendChild(St),Et[0].before(ft),Et.forEach((Mt,Qt)=>{if(be){Mt.remove();return}let Ft=document.createElement("div");Ft.className="persona-tool-group-item persona-relative",Ft.setAttribute("data-persona-tool-group-item","true"),Qt<Et.length-1&&Ft.setAttribute("data-persona-tool-group-connector","true"),Ft.appendChild(Mt),gt.appendChild(Ft)})})}rf(wo,q);let at=g.some(F=>F.role==="assistant"&&F.streaming),Gt=g[g.length-1],Ot=Gt?.role==="assistant"&&!Gt.streaming&&Gt.variant!=="approval";if(xn&&g.some(F=>F.role==="user")&&!at&&!Ot){let F={config:o,streaming:!0,location:"standalone",defaultRenderer:Ls},$e=r.find(Ue=>Ue.renderLoadingIndicator),ke=null;if($e?.renderLoadingIndicator&&(ke=$e.renderLoadingIndicator(F)),ke===null&&o.loadingIndicator?.render&&(ke=o.loadingIndicator.render(F)),ke===null&&(ke=Ls()),ke){let Ue=document.createElement("div"),Et=o.loadingIndicator?.showBubble!==!1;Ue.className=Et?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ue.setAttribute("data-typing-indicator","true"),Ue.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ue.appendChild(ke);let ft=document.createElement("div");ft.className="persona-flex",ft.id="wrapper-typing-indicator",ft.setAttribute("data-wrapper-id","typing-indicator"),ft.appendChild(Ue),v.appendChild(ft)}}if(!xn&&g.length>0){let F=g[g.length-1],$e={config:o,lastMessage:F,messageCount:g.length},ke=r.find(Et=>Et.renderIdleIndicator),Ue=null;if(ke?.renderIdleIndicator&&(Ue=ke.renderIdleIndicator($e)),Ue===null&&o.loadingIndicator?.renderIdle&&(Ue=o.loadingIndicator.renderIdle($e)),Ue){let Et=document.createElement("div"),ft=o.loadingIndicator?.showBubble!==!1;Et.className=ft?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Et.setAttribute("data-idle-indicator","true"),Et.appendChild(Ue);let St=document.createElement("div");St.className="persona-flex",St.id="wrapper-idle-indicator",St.setAttribute("data-wrapper-id","idle-indicator"),St.appendChild(Et),v.appendChild(St)}}if(ta(a,v),me.length>0)for(let{messageId:F,fingerprint:$e,bubble:ke}of me){let Ue=a.querySelector(`#wrapper-${F}`);Ue&&ke!==null&&(Ue.replaceChildren(ke),Ue.setAttribute("data-bubble-fp",$e),Go.set(F,$e))}if(Go.size>0)for(let F of Go.keys())q.has(F)||Go.delete(F);if(ce.length>0)for(let{messageId:F,fingerprint:$e,bubble:ke}of ce){let Ue=a.querySelector(`#wrapper-${F}`);Ue&&ke!==null&&(Ue.replaceChildren(ke),Ue.setAttribute("data-bubble-fp",$e),Ao.set(F,$e))}if(Ao.size>0)for(let F of Ao.keys())q.has(F)||Ao.delete(F);if(yt.length>0)for(let{messageId:F,fingerprint:$e,bubble:ke}of yt){let Ue=a.querySelector(`#wrapper-${F}`);Ue&&ke!==null&&(Ue.replaceChildren(ke),Ue.setAttribute("data-bubble-fp",$e),Qn.set(F,$e))}if(Qn.size>0)for(let F of Qn.keys())q.has(F)||Qn.delete(F)},Or=(a,g,y)=>{Ig(a,g,y),Nc()},Fr=null,Rg=()=>{if(Fr)return;let a=y=>{let v=y.composedPath();v.includes(Re)||ct&&v.includes(ct)||bt(!1,"user")};Fr=a,(t.ownerDocument??document).addEventListener("pointerdown",a,!0)},ed=()=>{if(!Fr)return;(t.ownerDocument??document).removeEventListener("pointerdown",Fr,!0),Fr=null};Ke.push(()=>ed());let _r=null,Wg=()=>{if(_r)return;let a=y=>{y.key==="Escape"&&(y.isComposing||bt(!1,"user"))};_r=a,(t.ownerDocument??document).addEventListener("keydown",a,!0)},td=()=>{if(!_r)return;(t.ownerDocument??document).removeEventListener("keydown",_r,!0),_r=null};Ke.push(()=>td());let $r=!1,nd=new Set,Hg=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},Xo=()=>{if(!L())return;let a=He.peekBanner,g=He.peekTextNode;if(!a||!g)return;if(H){a.classList.remove("persona-pill-peek--visible");return}let y=V?.getMessages()??[],v;for(let Ot=y.length-1;Ot>=0;Ot--){let F=y[Ot];if(F.role==="assistant"&&F.content){v=F;break}}if(!v){a.classList.remove("persona-pill-peek--visible");return}let T=v.content,B=!!v.streaming,Z=Hg(),q=sa(Z),X=q.type!=="none"?xr(q.type,Z?.plugins):null,le=X?.isAnimating?.(v)===!0,me=X!==null&&(B||le);me&&X&&!nd.has(X.name)&&(la(X,t),nd.add(X.name));let ce=me&&X?.containerClass?X.containerClass:null,Se=g.dataset.personaPeekStreamClass??null;Se&&Se!==ce&&(g.classList.remove(Se),delete g.dataset.personaPeekStreamClass),ce&&Se!==ce&&(g.classList.add(ce),g.dataset.personaPeekStreamClass=ce),me?(g.style.setProperty("--persona-stream-step",`${q.speed}ms`),g.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ge=me?ia(T,q.buffer,X,v,B):T;if(me&&q.placeholder==="skeleton"&&B&&(!Ge||!Ge.trim())){let Ot=document.createElement("div"),F=Ss();F.classList.add("persona-pill-peek__skeleton"),Ot.appendChild(F),ta(g,Ot)}else{let Ot=Math.max(0,Ge.length-100),F=Ge.length>100?Ge.slice(-100):Ge,$e=oo(F);if(!me||!X){let ke=Ge.length>100?`\u2026${F}`:F;g.textContent!==ke&&(g.textContent=ke)}else{let ke=$e;(X.wrap==="char"||X.wrap==="word")&&(ke=As($e,X.wrap,`peek-${v.id}`,{skipTags:X.skipTags,startIndex:Ot}));let Ue=document.createElement("div");if(Ue.innerHTML=ke,X.useCaret&&F.length>0){let Et=aa(),ft=Ue.querySelectorAll(".persona-stream-char, .persona-stream-word"),St=ft[ft.length-1];St?.parentNode?St.parentNode.insertBefore(Et,St.nextSibling):Ue.appendChild(Et)}ta(g,Ue),X.onAfterRender?.({container:g,bubble:a,messageId:v.id,message:v,speed:q.speed,duration:q.duration})}}let Gt=xn||$r;a.classList.toggle("persona-pill-peek--visible",Gt)};if(L()){let a=He.peekBanner;if(a){let v=T=>{T.preventDefault(),T.stopPropagation(),bt(!0,"user")};a.addEventListener("pointerdown",v),Ke.push(()=>{a.removeEventListener("pointerdown",v)})}let g=()=>{$r||($r=!0,Xo())},y=()=>{$r&&($r=!1,Xo())};we.addEventListener("pointerenter",g),we.addEventListener("pointerleave",y),Ke.push(()=>{we.removeEventListener("pointerenter",g),we.removeEventListener("pointerleave",y)}),ct&&(ct.addEventListener("pointerenter",g),ct.addEventListener("pointerleave",y),Ke.push(()=>{ct.removeEventListener("pointerenter",g),ct.removeEventListener("pointerleave",y)}))}let Bg=a=>{let g=o.launcher?.composerBar??{},y=g.expandedSize??"anchored",v=g.bottomOffset??"16px",T=g.collapsedMaxWidth,B=g.expandedMaxWidth??"880px",Z=g.expandedTopOffset??"5vh",q=g.modalMaxWidth??"880px",X=g.modalMaxHeight??"min(90vh, 800px)",le="calc(100vw - 32px)",me="var(--persona-pill-area-height, 80px)",ce=Re.style;if(ce.left="",ce.right="",ce.top="",ce.bottom="",ce.transform="",ce.width="",ce.maxWidth="",ce.height="",ce.maxHeight="",ct){let Se=ct.style;Se.bottom=v,Se.width=T??""}if(a&&y!=="fullscreen"){if(y==="modal"){ce.top="50%",ce.left="50%",ce.transform="translate(-50%, -50%)",ce.bottom="auto",ce.right="auto",ce.width=q,ce.maxWidth=le,ce.maxHeight=X,ce.height=X;return}ce.left="50%",ce.transform="translateX(-50%)",ce.bottom=`calc(${v} + ${me})`,ce.top=Z,ce.width=B,ce.maxWidth=le}},zr=()=>{if(!P())return;if(L()){let le=(o.launcher?.composerBar??{}).expandedSize??"anchored",me=H?"expanded":"collapsed";Re.dataset.state=me,Re.dataset.expandedSize=le,ct&&(ct.dataset.state=me,ct.dataset.expandedSize=le),Re.style.removeProperty("display"),Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Bg(H),ye.style.display=H?"flex":"none",Vs(),H?(Rg(),Wg()):(ed(),td()),Xo();return}let a=zt(o),g=t.ownerDocument.defaultView??window,y=o.launcher?.mobileBreakpoint??640,v=o.launcher?.mobileFullscreen??!0,T=g.innerWidth<=y,B=v&&T&&A,Z=bn(o).reveal;H?(Re.style.removeProperty("display"),Re.style.display=a?"flex":"",Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0"),we.classList.add("persona-scale-100","persona-opacity-100"),Ut?Ut.element.style.display="none":Kt&&(Kt.style.display="none")):(a?a&&(Z==="overlay"||Z==="push")&&!B?(Re.style.removeProperty("display"),Re.style.display="flex",Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Re.style.setProperty("display","none","important"),Re.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Re.style.display="",Re.classList.add("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100"),we.classList.add("persona-scale-95","persona-opacity-0")),Ut?Ut.element.style.display=a?"none":"":Kt&&(Kt.style.display=a?"none":""))},bt=(a,g="user")=>{if(!P()||H===a)return;let y=H;H=a,zr();let v=(()=>{let B=o.launcher?.sidebarMode??!1,Z=t.ownerDocument.defaultView??window,q=o.launcher?.mobileFullscreen??!0,X=o.launcher?.mobileBreakpoint??640,le=Z.innerWidth<=X,me=zt(o)&&q&&le,ce=L()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return B||q&&le&&A||me||ce})();if(H&&v){if(!Tn){let B=t.getRootNode(),Z=B instanceof ShadowRoot?B.host:t.closest(".persona-host");Z&&(Tn=Gl(Z,o.launcher?.zIndex??Vt))}En||(En=Ql(t.ownerDocument))}else H||(Tn?.(),Tn=null,En?.(),En=null);H&&(qr(),Yc()||(en()==="follow"?Zn(!0):Xc()));let T={open:H,source:g,timestamp:Date.now()};H&&!y?l.emit("widget:opened",T):!H&&y&&l.emit("widget:closed",T),l.emit("widget:state",{open:H,launcherEnabled:A,voiceActive:Xe.active,streaming:V.isStreaming()})},Ua=a=>{dt(a?"stop":"send"),Q&&(Q.disabled=a),Gs.buttons.forEach(g=>{g.disabled=a}),G.dataset.personaComposerStreaming=a?"true":"false",G.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=a)})},ja=()=>{Xe.active||j&&j.focus()};l.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>ja(),200)});let od=()=>{Y.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",x.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",j.placeholder=o.copy?.inputPlaceholder??"How can I help...";let a=ue.querySelector("[data-persona-intro-card]");if(a){let y=o.copy?.showWelcomeCard!==!1;a.style.display=y?"":"none",y?(ue.classList.remove("persona-gap-3"),ue.classList.add("persona-gap-6")):(ue.classList.remove("persona-gap-6"),ue.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!V?.isStreaming()&&(ie.textContent=o.copy?.sendButtonLabel??"Send"),j.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',j.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(g=>({...g,sessionId:a}))}});let Mo=null,Dg=()=>{Mo==null&&(Mo=setInterval(()=>{let a=Ae.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(Mo),Mo=null;return}let g=Date.now();a.forEach(y=>{let v=Number(y.getAttribute("data-tool-elapsed"));v&&(y.textContent=xi(g-v))})},100))},qa=(a,g)=>{if(Object.is(a,g))return!0;if(a===null||g===null||typeof a!="object"||typeof g!="object")return!1;if(Array.isArray(a)||Array.isArray(g))return!Array.isArray(a)||!Array.isArray(g)||a.length!==g.length?!1:a.every((Z,q)=>qa(Z,g[q]));let y=a,v=g,T=Object.keys(y),B=Object.keys(v);return T.length===B.length&&T.every(Z=>Object.prototype.hasOwnProperty.call(v,Z)&&qa(y[Z],v[Z]))},rd=a=>{let{content:g,rawContent:y,llmContent:v,...T}=a;return T},Va=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!bc(a),Ng=(a,g,y)=>{if(a.length!==g.length)return!1;let v=a[y.index],T=g[y.index];return!v||!T||v.id!==y.id||T.id!==y.id?!1:(!Object.is(v.content,T.content)||!Object.is(v.rawContent,T.rawContent)||!Object.is(v.llmContent,T.llmContent))&&Va(v)&&Va(T)&&qa(rd(v),rd(T))},sd=null,Jo=null,To=null,Bn=null,Zs=a=>{sd=a;let g,y;Jo=null;for(let T=a.length-1;T>=0;T-=1){let B=a[T];if(!g&&B.role==="user"&&(g=B),!y&&B.role==="assistant"&&(y=B),!Jo&&Va(B)&&(Jo={index:T,id:B.id}),g&&y&&Jo)break}Or(Ae,a,fe),zl(Ae,yn.artifacts,{suppressTransition:xn}),Dg(),Ra(a),Zn(!xn),Pg(a),a.length===0&&(Nr(),Hr=!0,Da=!1),!Ha||Xs?(Ha=!0,Ba=g?.id??null,Na=y?.id??null):g&&g.id!==Ba?(Ba=g.id,kg(g.id)):y&&y.id!==Na&&Lg(),y&&(Na=y.id);let v=Xe.lastUserMessageId;g&&g.id!==v&&(Xe.lastUserMessageId=g.id,l.emit("user:message",g)),Xe.lastUserMessageWasVoice=!!g?.viaVoice,_a(a),Xo()},Ka=()=>{Bn!==null&&(cancelAnimationFrame(Bn),Bn=null);let a=To;To=null,a&&Zs(a)},id=()=>{Bn!==null&&cancelAnimationFrame(Bn),Bn=null,To=null},Og=a=>{let g=To??sd;if(xn&&g&&Jo&&Ng(g,a,Jo)){To=a,Bn===null&&(Bn=requestAnimationFrame(()=>{Bn=null;let y=To;To=null,y&&Zs(y)}));return}if(a.length===0){id(),Zs(a);return}Ka(),Zs(a)};V=new Pi(o,{onMessagesChanged(a){Og(a)},onStatusChanged(a){let g=o.statusIndicator??{};It(I,(v=>v==="idle"?g.idleText??Dt.idle:v==="connecting"?g.connectingText??Dt.connecting:v==="connected"?g.connectedText??Dt.connected:v==="error"?g.errorText??Dt.error:v==="paused"?g.pausedText??Dt.paused:v==="resuming"?g.resumingText??Dt.resuming:Dt[v])(a),g,a)},onStreamingChanged(a){a||(V?.getMessages().length===0?id():Ka()),xn=a,Ua(a),V&&Or(Ae,V.getMessages(),fe),a||Zn(!0),sn(),Lc(a?"Responding\u2026":"Response complete."),Xo()},onVoiceStatusChanged(a){if(l.emit("voice:status",{status:a,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(a){case"listening":Dn(),Zo();break;case"processing":Dn(),Qg();break;case"speaking":Dn(),Xg();break;default:a==="idle"&&V.isBargeInActive()?(Dn(),Zo(),Q?.setAttribute("aria-label","End voice session")):(Xe.active=!1,Dn(),Hn("system"),wn());break}},onArtifactsState(a){yn=a,a.artifacts.length===0&&(qo=!1),zl(Ae,a.artifacts,{suppressTransition:xn}),Wn(),_a()},onReconnect(a){let{executionId:g,lastEventId:y}=a.handle;a.phase==="paused"?l.emit("stream:paused",{executionId:g,after:y}):a.phase==="resuming"?l.emit("stream:resuming",{executionId:g,after:y,attempt:a.attempt??1}):l.emit("stream:resumed",{executionId:g,after:y})}}),ht.current=V,Ke.push(()=>V.cancel());let Ga=null;if(V.onReadAloudChange((a,g)=>{Bc=a,Dc=g,Nc();let y=a??Ga;a&&(Ga=a);let v=y?V.getMessages().find(T=>T.id===y)??null:null;l.emit("message:read-aloud",{messageId:y,message:v,state:g,timestamp:Date.now()}),g==="idle"&&(Ga=null)}),Ha=!0,o.voiceRecognition?.provider?.type==="runtype")try{V.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}o.clientToken&&V.initClientSession().catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)}),(Me||o.onSSEEvent)&&V.setSSEEventCallback((a,g)=>{o.onSSEEvent?.(a,g),Fe?.processEvent(a,g),Me?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(g)})});let ad=()=>{o.resume&&typeof o.reconnectStream=="function"&&V.resumeFromHandle(o.resume)};u?u.then(a=>{if(a){if(a.metadata&&(d=yc(a.metadata),M.syncFromMetadata()),a.messages?.length){Xs=!0;try{V.hydrateMessages(a.messages)}finally{Xs=!1}}a.artifacts?.length&&V.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>ad()):ad();let ld=()=>{!L()||H||!(o.launcher?.composerBar?.expandOnSubmit??!0)||bt(!0,"auto")},Fg=(a,g)=>a?g?{refs:[...a.refs,...g.refs],finalize:async()=>{let[y,v]=await Promise.allSettled([a.finalize(),g.finalize()]),T=[];return y.status==="fulfilled"?T.push(y.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",y.reason),v.status==="fulfilled"?T.push(v.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",v.reason),vv(T)}}:a:g,_g=()=>{let g=j.getInlineMessageFields?.();return g&&g.contentSegments.some(v=>v.kind==="mention")?g.contentSegments:void 0},Ur=!1,$g=async a=>{let g=j.value.trim(),y=Lt?.hasAttachments()??!1,v=g?await(on?.takeInlineCommand(g)??Promise.resolve(null)):null;if(v?.kind==="action"){j.value="",j.style.height="auto",jr(),on?.clear();return}let T=on?.collectForSubmit()??null,B=v?.kind==="server"?v.mentions:null,Z=Fg(T,B),q=v?.kind==="prompt"?v.sendText:g,X=!!T&&T.refs.length>0;if(!q&&!y&&!X&&!B)return;ld();let le;y&&(le=[],le.push(...Lt.getContentParts()),q&&le.push(pr(q)));let me=v?.kind==="prompt"?void 0:_g();j.value="",j.style.height="auto",jr(),V.sendMessage(q,{contentParts:le,mentions:Z??void 0,contentSegments:me,viaVoice:a?.viaVoice}),y&&Lt.clearAttachments(),T&&on?.clear()},Qa=async a=>{if(!Ur){Ur=!0;try{await $g(a)}finally{Ur=!1}}},cd=a=>{if(a.preventDefault(),V.isStreaming()){V.cancel(),Fe?.reset(),Pe?.update();return}Ur||Qa()},zg=()=>o.features?.composerHistory!==!1,Xa={...ql},Ja=!1,jr=()=>{Xa={...ql}},Ug=()=>V.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),jg=a=>{if(!j)return;Ja=!0,j.value=a,j.dispatchEvent(new Event("input",{bubbles:!0})),Ja=!1;let g=j.value.length;j.setSelectionRange(g,g)},qg=a=>{Ja||(a.isComposing||on?.handleInput(a.inputType??void 0),jr())},Vg=a=>{if(j&&!(!a.isComposing&&on?.handleKeydown(a))){if(zg()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let g=j.selectionStart===0&&j.selectionEnd===0,y=Zu({direction:a.key==="ArrowUp"?"up":"down",history:Ug(),currentValue:j.value,atStart:g,state:Xa});if(Xa=y.state,y.handled){a.preventDefault(),y.value!==void 0&&jg(y.value);return}}if(a.key==="Enter"&&!a.shiftKey){if(V.isStreaming()){a.preventDefault();return}if(Ur){a.preventDefault();return}jr(),a.preventDefault(),ie.click()}}},dd=a=>{a.key!=="Escape"||a.isComposing||V.isStreaming()&&a.composedPath().includes(ye)&&(V.cancel(),Fe?.reset(),Pe?.update(),jr(),a.preventDefault(),a.stopImmediatePropagation())},Kg=async a=>{if(o.attachments?.enabled!==!0||!Lt)return;let g=mv(a.clipboardData);g.length!==0&&(a.preventDefault(),await Lt.handleFiles(g))},gn=null,kn=!1,Yo=null,At=null,pd=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ei=(a="user")=>{if(kn||V.isStreaming())return;let g=pd();if(!g)return;gn=new g;let v=(o.voiceRecognition??{}).pauseDuration??2e3;gn.continuous=!0,gn.interimResults=!0,gn.lang="en-US";let T=j.value;gn.onresult=B=>{let Z="",q="";for(let le=0;le<B.results.length;le++){let me=B.results[le],ce=me[0].transcript;me.isFinal?Z+=ce+" ":q=ce}let X=T+Z+q;j.value=X,Yo&&clearTimeout(Yo),(Z||q)&&(Yo=window.setTimeout(()=>{j.value.trim()&&gn&&kn&&(eo(),Qa({viaVoice:!0}))},v))},gn.onerror=B=>{B.error!=="no-speech"&&eo()},gn.onend=()=>{if(kn){let B=j.value.trim();B&&B!==T.trim()&&Qa({viaVoice:!0}),eo()}};try{if(gn.start(),kn=!0,Xe.active=!0,a!=="system"&&(Xe.manuallyDeactivated=!1),Hn(a),wn(),Q){let B=o.voiceRecognition??{};At={backgroundColor:Q.style.backgroundColor,color:Q.style.color,borderColor:Q.style.borderColor,iconName:B.iconName??"mic",iconSize:parseFloat(B.iconSize??o.sendButton?.size??"40")||24};let Z=B.recordingBackgroundColor,q=B.recordingIconColor,X=B.recordingBorderColor;if(Q.classList.add("persona-voice-recording"),Q.style.backgroundColor=Z??"var(--persona-voice-recording-bg, #ef4444)",Q.style.color=q??"var(--persona-voice-recording-indicator, #ffffff)",q){let le=Q.querySelector("svg");le&&le.setAttribute("stroke",q)}X&&(Q.style.borderColor=X),Q.setAttribute("aria-label","Stop voice recognition")}}catch{eo("system")}},eo=(a="user")=>{if(kn){if(kn=!1,Yo&&(clearTimeout(Yo),Yo=null),gn){try{gn.stop()}catch{}gn=null}if(Xe.active=!1,Hn(a),wn(),Q){if(Q.classList.remove("persona-voice-recording"),At){Q.style.backgroundColor=At.backgroundColor,Q.style.color=At.color,Q.style.borderColor=At.borderColor;let g=Q.querySelector("svg");g&&g.setAttribute("stroke",At.color||"currentColor"),At=null}Q.setAttribute("aria-label","Start voice recognition")}}},Gg=(a,g)=>{let y=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),v=a?.provider?.type==="runtype",T=a?.provider?.type==="custom";if(!(y||v||T))return null;let Z=h("div","persona-send-button-wrapper"),q=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");q.type="button",q.setAttribute("aria-label","Start voice recognition");let X=a?.iconName??"mic",le=g?.size??"40px",me=a?.iconSize??le,ce=parseFloat(me)||24,Se=a?.backgroundColor??g?.backgroundColor,Ge=a?.iconColor??g?.textColor;q.style.width=me,q.style.height=me,q.style.minWidth=me,q.style.minHeight=me,q.style.fontSize="18px",q.style.lineHeight="1",Ge?q.style.color=Ge:q.style.color="var(--persona-text, #111827)";let at=se(X,ce,Ge||"currentColor",1.5);at?q.appendChild(at):q.textContent="\u{1F3A4}",Se?q.style.backgroundColor=Se:q.style.backgroundColor="",a?.borderWidth&&(q.style.borderWidth=a.borderWidth,q.style.borderStyle="solid"),a?.borderColor&&(q.style.borderColor=a.borderColor),a?.paddingX&&(q.style.paddingLeft=a.paddingX,q.style.paddingRight=a.paddingX),a?.paddingY&&(q.style.paddingTop=a.paddingY,q.style.paddingBottom=a.paddingY),Z.appendChild(q);let Gt=a?.tooltipText??"Start voice recognition";if((a?.showTooltip??!1)&&Gt){let F=h("div","persona-send-button-tooltip");F.textContent=Gt,Z.appendChild(F)}return{micButton:q,micButtonWrapper:Z}},Ya=()=>{if(!Q||At)return;let a=o.voiceRecognition??{};At={backgroundColor:Q.style.backgroundColor,color:Q.style.color,borderColor:Q.style.borderColor,iconName:a.iconName??"mic",iconSize:parseFloat(a.iconSize??o.sendButton?.size??"40")||24}},Za=(a,g)=>{if(!Q)return;let y=Q.querySelector("svg");y&&y.remove();let v=At?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),T=se(a,v,g,1.5);T&&Q.appendChild(T)},ti=()=>{Q&&Q.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Zo=()=>{if(!Q)return;Ya();let a=o.voiceRecognition??{},g=a.recordingBackgroundColor,y=a.recordingIconColor,v=a.recordingBorderColor;if(ti(),Q.classList.add("persona-voice-recording"),Q.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",Q.style.color=y??"var(--persona-voice-recording-indicator, #ffffff)",y){let T=Q.querySelector("svg");T&&T.setAttribute("stroke",y)}v&&(Q.style.borderColor=v),Q.setAttribute("aria-label","Stop voice recognition")},Qg=()=>{if(!Q)return;Ya();let a=o.voiceRecognition??{},g=V.getVoiceInterruptionMode(),y=a.processingIconName??"loader",v=a.processingIconColor??At?.color??"",T=a.processingBackgroundColor??At?.backgroundColor??"",B=a.processingBorderColor??At?.borderColor??"";ti(),Q.classList.add("persona-voice-processing"),Q.style.backgroundColor=T,Q.style.borderColor=B;let Z=v||"currentColor";Q.style.color=Z,Za(y,Z),Q.setAttribute("aria-label","Processing voice input"),g==="none"&&(Q.style.cursor="default")},Xg=()=>{if(!Q)return;Ya();let a=o.voiceRecognition??{},g=V.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",v=a.speakingIconName??y,T=a.speakingIconColor??(g==="barge-in"?a.recordingIconColor??At?.color??"":At?.color??""),B=a.speakingBackgroundColor??(g==="barge-in"?a.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":At?.backgroundColor??""),Z=a.speakingBorderColor??(g==="barge-in"?a.recordingBorderColor??"":At?.borderColor??"");ti(),Q.classList.add("persona-voice-speaking"),Q.style.backgroundColor=B,Q.style.borderColor=Z;let q=T||"currentColor";Q.style.color=q,Za(v,q);let X=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";Q.setAttribute("aria-label",X),g==="none"&&(Q.style.cursor="default"),g==="barge-in"&&Q.classList.add("persona-voice-recording")},Dn=()=>{Q&&(ti(),At&&(Q.style.backgroundColor=At.backgroundColor??"",Q.style.color=At.color??"",Q.style.borderColor=At.borderColor??"",Za(At.iconName,At.color||"currentColor"),At=null),Q.style.cursor="",Q.setAttribute("aria-label","Start voice recognition"))},ni=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let a=V.getVoiceStatus(),g=V.getVoiceInterruptionMode();if(g==="none"&&(a==="processing"||a==="speaking"))return;if(g==="cancel"&&(a==="processing"||a==="speaking")){V.stopVoicePlayback();return}if(V.isBargeInActive()){V.stopVoicePlayback(),V.deactivateBargeIn().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,wn(),Hn("user"),Dn()});return}V.toggleVoice().then(()=>{Xe.active=V.isVoiceActive(),Xe.manuallyDeactivated=!V.isVoiceActive(),wn(),Hn("user"),V.isVoiceActive()?Zo():Dn()});return}if(kn){let a=j.value.trim();Xe.manuallyDeactivated=!0,wn(),eo("user"),a&&(j.value="",j.style.height="auto",V.sendMessage(a))}else Xe.manuallyDeactivated=!1,wn(),ei("user")};Ic=ni,Q&&(Q.addEventListener("click",ni),Ke.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(V.isVoiceActive()&&V.toggleVoice(),Dn()):eo("system"),Q&&Q.removeEventListener("click",ni)}));let Jg=l.on("assistant:complete",()=>{jc&&(Xe.active||Xe.manuallyDeactivated||jc==="assistant"&&!Xe.lastUserMessageWasVoice||setTimeout(()=>{!Xe.active&&!Xe.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?V.toggleVoice().then(()=>{Xe.active=V.isVoiceActive(),Hn("auto"),V.isVoiceActive()&&Zo()}):ei("auto"))},600))});Ke.push(Jg);let Yg=l.on("action:resubmit",()=>{setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)});Ke.push(Yg);let ud=()=>{bt(!H,"user")},Ut=null,Kt=null;if(A&&!L()){let{instance:a,element:g}=Jl({config:o,plugins:r,onToggle:ud});Ut=a,a||(Kt=g)}Ut?t.appendChild(Ut.element):Kt&&t.appendChild(Kt),zr(),Ra(),od(),Ua(V.isStreaming()),Yc()||(en()==="follow"?Zn(!0):Xc()),wg(),z&&(!A||L()?setTimeout(()=>ja(),0):H&&setTimeout(()=>ja(),200));let qr=()=>{if(L()){jo(),zr();return}let a=zt(o),g=o.launcher?.sidebarMode??!1,y=a||g||(o.launcher?.fullHeight??!1),v=t.ownerDocument.defaultView??window,T=o.launcher?.mobileFullscreen??!0,B=o.launcher?.mobileBreakpoint??640,Z=v.innerWidth<=B,q=T&&Z&&A;try{if(q){Pr(),Ir=qs();return}let X=!1;N&&(N=!1,Pr(),X=!0);let le=qs();if(!X&&le!==Ir&&(Pr(),X=!0),Ir=le,X&&Pa(),!A&&!a){we.style.height="",we.style.width="";return}if(!g&&!a){let ce=o?.launcher?.width??o?.launcherWidth??Un;we.style.width=ce,we.style.maxWidth=ce}if(js(),!y){let me=v.innerHeight,ce=64,Se=o.launcher?.heightOffset??0,Ge=Math.max(200,me-ce),yt=Math.min(640,Ge),at=Math.max(200,yt-Se);we.style.height=`${at}px`}}finally{if(jo(),zr(),H&&A){let le=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),me=o.launcher?.sidebarMode??!1,ce=o.launcher?.mobileFullscreen??!0,Se=zt(o)&&ce&&le,Ge=me||ce&&le&&A||Se;if(Ge&&!En){let yt=t.getRootNode(),at=yt instanceof ShadowRoot?yt.host:t.closest(".persona-host");at&&!Tn&&(Tn=Gl(at,o.launcher?.zIndex??Vt)),En=Ql(t.ownerDocument)}else Ge||(Tn?.(),Tn=null,En?.(),En=null)}}};qr();let fd=t.ownerDocument.defaultView??window;if(fd.addEventListener("resize",qr),Ke.push(()=>fd.removeEventListener("resize",qr)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{jo()});a.observe(G),Ke.push(()=>a.disconnect())}un=ue.scrollTop;let gd=In(ue),Zg=()=>{let a=ue.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??ue.ownerDocument.getSelection()},el=()=>sf(Zg(),ue),md=()=>{let a=ue.scrollTop,g=In(ue),y=g<gd;if(gd=g,!qn()){un=a,sn();return}let{action:v,nextLastScrollTop:T}=oa({following:rn.isFollowing(),currentScrollTop:a,lastScrollTop:un,nearBottom:fo(ue,Js),userScrollThreshold:xg,isAutoScrolling:fn||Qs||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(un=T,v==="resume"){el()||Yn();return}v==="pause"&&Dr()};if(ue.addEventListener("scroll",md,{passive:!0}),Ke.push(()=>ue.removeEventListener("scroll",md)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{Eg()});a.observe(Ae),a.observe(ue),Ke.push(()=>a.disconnect())}let hd=()=>{qn()&&rn.isFollowing()&&el()&&Dr()},bd=ue.ownerDocument;bd.addEventListener("selectionchange",hd),Ke.push(()=>{bd.removeEventListener("selectionchange",hd)});let em=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),yd=a=>{Tc()&&qn()&&rn.isFollowing()&&em.has(a.key)&&Dr()},vd=a=>{if(!Tc()||!qn()||!rn.isFollowing())return;let g=a.target;g&&g.closest("a, button, [tabindex], input, textarea, select")&&Dr()};ue.addEventListener("keydown",yd),ue.addEventListener("focusin",vd),Ke.push(()=>{ue.removeEventListener("keydown",yd),ue.removeEventListener("focusin",vd)});let xd=a=>{if(!qn())return;let g=ra({following:rn.isFollowing(),deltaY:a.deltaY,nearBottom:fo(ue,Js),resumeWhenNearBottom:!0});g==="pause"?Dr():g==="resume"&&!el()&&Yn()};ue.addEventListener("wheel",xd,{passive:!0}),Ke.push(()=>ue.removeEventListener("wheel",xd)),Ht.addEventListener("click",()=>{Nr(),ue.scrollTop=ue.scrollHeight,un=ue.scrollTop,Yn(),Zn(!0),sn()}),Ke.push(()=>Ht.remove()),Ke.push(()=>{Kc(),Nr()});let Cd=()=>{E&&(Co&&(E.removeEventListener("click",Co),Co=null),P()?(E.style.display="",Co=()=>{bt(!1,"user")},E.addEventListener("click",Co)):E.style.display="none")};Cd(),(()=>{let{clearChatButton:a}=He;a&&a.addEventListener("click",()=>{V.clearMessages(),wo.clear(),Yn(),lr(He.composerOverlay);try{localStorage.removeItem(Sr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Sr}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Sr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(g),c?.clear&&Fa(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),d={},M.syncFromMetadata(),Me?.clear(),Fe?.reset(),Pe?.update()})})(),Le&&Le.addEventListener("submit",cd);let wd=[["keydown",Vg],["input",qg],["paste",Kg],["focus",mg]],Ad=a=>{if(a)for(let[g,y]of wd)a.addEventListener(g,y)},Sd=a=>{if(a)for(let[g,y]of wd)a.removeEventListener(g,y)};Ad(j),on?.onComposerSwap((a,g)=>{Sd(g),j=a,Ad(a)});let Md=t.ownerDocument??document;Md.addEventListener("keydown",dd,!0);let Td="persona-attachment-drop-active",Vr=0,tl=()=>{Vr=0,ye.classList.remove(Td)},er=()=>o.attachments?.enabled===!0&&Lt!==null,Ed=a=>{!wa(a.dataTransfer)||!er()||(Vr++,Vr===1&&ye.classList.add(Td))},kd=a=>{!wa(a.dataTransfer)||!er()||(Vr--,Vr<=0&&tl())},Ld=a=>{!wa(a.dataTransfer)||!er()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},Pd=a=>{if(!wa(a.dataTransfer)||!er())return;a.preventDefault(),a.stopPropagation(),tl();let g=Array.from(a.dataTransfer.files??[]);g.length!==0&&Lt.handleFiles(g)},to=!0;ye.addEventListener("dragenter",Ed,to),ye.addEventListener("dragleave",kd,to),t.addEventListener("dragover",Ld,to),t.addEventListener("drop",Pd,to);let oi=t.ownerDocument,Id=a=>{er()&&a.preventDefault()},Rd=a=>{er()&&a.preventDefault()};oi.addEventListener("dragover",Id),oi.addEventListener("drop",Rd),Ke.push(()=>{Le&&Le.removeEventListener("submit",cd),Sd(j),Md.removeEventListener("keydown",dd,!0),on?.destroy()}),Ke.push(()=>{ye.removeEventListener("dragenter",Ed,to),ye.removeEventListener("dragleave",kd,to),t.removeEventListener("dragover",Ld,to),t.removeEventListener("drop",Pd,to),oi.removeEventListener("dragover",Id),oi.removeEventListener("drop",Rd),tl()}),Ke.push(()=>{V.cancel()}),Ut?Ke.push(()=>{Ut?.destroy()}):Kt&&Ke.push(()=>{Kt?.remove()});let Bt={update(a){let g=o.toolCall,y=o.messageActions,v=o.layout?.messages,T=o.colorScheme,B=o.loadingIndicator,Z=o.iterationDisplay,q=o.features?.showReasoning,X=o.features?.showToolCalls,le=o.features?.toolCallDisplay,me=o.features?.reasoningDisplay,ce=o.features?.streamAnimation?.type;o={...o,...a},Vs(),bs(t,o),Ws(t,o),Hs(t,o),Wn(),o.colorScheme!==T&&Uc();let Se=uc.getForInstance(o.plugins);r.length=0,r.push(...Se),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 Ge=en();te=o.features?.scrollBehavior??{},Ge!==en()&&(Nr(),Yn()),Pc(),sn();let yt=K;if(K=o.features?.showEventStreamToggle??!1,K&&!yt){if(Me||(ge=new Is(xe),Me=new Ps(Te,ge),Fe=Fe??new Rs,ge.open().then(()=>Me?.restore()).catch(()=>{}),V.setSSEEventCallback((re,rt)=>{o.onSSEEvent?.(re,rt),Fe?.processEvent(re,rt),Me.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:re,timestamp:Date.now(),payload:JSON.stringify(rt)})})),!it&&$){let re=o.features?.eventStream?.classNames,rt="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:"");it=h("button",rt),it.style.width="28px",it.style.height="28px",it.style.color=Yt.actionIconColor,it.type="button",it.setAttribute("aria-label","Event Stream"),it.title="Event Stream";let Tt=se("activity","18px","currentColor",1.5);Tt&&it.appendChild(Tt);let Qe=He.clearChatButtonWrapper,pt=He.closeButtonWrapper,qt=Qe||pt;qt&&qt.parentNode===$?$.insertBefore(it,qt):$.appendChild(it),it.addEventListener("click",()=>{Ee?kr():Ta()})}}else!K&&yt&&(kr(),it&&(it.remove(),it=null),Me?.clear(),ge?.destroy(),Me=null,ge=null,Fe?.reset(),Fe=null);if(o.launcher?.enabled===!1&&Ut&&(Ut.destroy(),Ut=null),o.launcher?.enabled===!1&&Kt&&(Kt.remove(),Kt=null),o.launcher?.enabled!==!1&&!Ut&&!Kt){let{instance:re,element:rt}=Jl({config:o,plugins:r,onToggle:ud});Ut=re,re||(Kt=rt),t.appendChild(rt)}Ut&&Ut.update(o),_&&o.launcher?.title!==void 0&&(_.textContent=o.launcher.title),J&&o.launcher?.subtitle!==void 0&&(J.textContent=o.launcher.subtitle);let at=o.layout?.header;if(at?.layout!==O&&$){let re=at?pa(o,at,{showClose:P(),onClose:()=>bt(!1,"user")}):_o({config:o,showClose:P(),onClose:()=>bt(!1,"user")});mt.replaceHeader(re),$=mt.header.element,R=mt.header.iconHolder,_=mt.header.headerTitle,J=mt.header.headerSubtitle,E=mt.header.closeButton,O=at?.layout}else if(at&&(R&&(R.style.display=at.showIcon===!1?"none":""),_&&(_.style.display=at.showTitle===!1?"none":""),J&&(J.style.display=at.showSubtitle===!1?"none":""),E&&(E.style.display=at.showCloseButton===!1?"none":""),He.clearChatButtonWrapper)){let re=at.showClearChat;if(re!==void 0){He.clearChatButtonWrapper.style.display=re?"":"none";let{closeButtonWrapper:rt}=He;rt&&!rt.classList.contains("persona-absolute")&&(re?rt.classList.remove("persona-ml-auto"):rt.classList.add("persona-ml-auto"))}}let Ot=o.layout?.showHeader!==!1;$&&($.style.display=Ot?"":"none");let F=o.layout?.showFooter!==!1;G&&(G.style.display=F?"":"none"),jo(),sn(),A!==w?A?bt(W,"auto"):(H=!0,zr()):W!==U&&bt(W,"auto"),U=W,w=A,qr(),Cd();let Ue=JSON.stringify(a.toolCall)!==JSON.stringify(g),Et=JSON.stringify(o.messageActions)!==JSON.stringify(y),ft=JSON.stringify(o.layout?.messages)!==JSON.stringify(v),St=o.loadingIndicator?.render!==B?.render||o.loadingIndicator?.renderIdle!==B?.renderIdle||o.loadingIndicator?.showBubble!==B?.showBubble,xt=o.iterationDisplay!==Z,jt=(o.features?.showReasoning??!0)!==(q??!0)||(o.features?.showToolCalls??!0)!==(X??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(le)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(me);(Ue||Et||ft||St||xt||jt)&&V&&(Wa++,Or(Ae,V.getMessages(),fe));let gt=o.features?.streamAnimation?.type;if(gt!==ce&>&>!=="none"){let re=xr(gt,o.features?.streamAnimation?.plugins);re&&la(re,t)}let be=o.launcher??{},Mt=be.headerIconHidden??!1,Qt=o.layout?.header?.showIcon,Ft=Mt||Qt===!1,st=be.headerIconName,Ve=be.headerIconSize??"48px";if(R){let re=ye.querySelector(".persona-border-b-persona-divider"),rt=re?.querySelector(".persona-flex-col");if(Ft)R.style.display="none",re&&rt&&!re.contains(rt)&&re.insertBefore(rt,re.firstChild);else{if(R.style.display="",R.style.height=Ve,R.style.width=Ve,re&&rt&&(re.contains(R)?R.nextSibling!==rt&&(R.remove(),re.insertBefore(R,rt)):re.insertBefore(R,rt)),st){let Qe=parseFloat(Ve)||24,pt=se(st,Qe*.6,"currentColor",1);pt?R.replaceChildren(pt):R.textContent=be.agentIconText??"\u{1F4AC}"}else if(be.iconUrl){let Qe=R.querySelector("img");if(Qe)Qe.src=be.iconUrl,Qe.style.height=Ve,Qe.style.width=Ve;else{let pt=document.createElement("img");pt.src=be.iconUrl,pt.alt="",pt.className="persona-rounded-xl persona-object-cover",pt.style.height=Ve,pt.style.width=Ve,R.replaceChildren(pt)}}else{let Qe=R.querySelector("svg"),pt=R.querySelector("img");(Qe||pt)&&R.replaceChildren(),R.textContent=be.agentIconText??"\u{1F4AC}"}let Tt=R.querySelector("img");Tt&&(Tt.style.height=Ve,Tt.style.width=Ve)}}let et=o.layout?.header?.showTitle,Rt=o.layout?.header?.showSubtitle;if(_&&(_.style.display=et===!1?"none":""),J&&(J.style.display=Rt===!1?"none":""),E){o.layout?.header?.showCloseButton===!1?E.style.display="none":E.style.display="";let rt=be.closeButtonSize??"32px",Tt=be.closeButtonPlacement??"inline";E.style.height=rt,E.style.width=rt;let{closeButtonWrapper:Qe}=He,pt=Tt==="top-right",qt=Qe?.classList.contains("persona-absolute");if(Qe&&pt!==qt)if(Qe.remove(),pt)Qe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ye.style.position="relative",ye.appendChild(Qe);else{let qe=be.clearChat?.placement??"inline",$t=be.clearChat?.enabled??!0;Qe.className=$t&&qe==="inline"?"":"persona-ml-auto";let nn=ye.querySelector(".persona-border-b-persona-divider");nn&&nn.appendChild(Qe)}if(E.style.color=be.closeButtonColor||Yt.actionIconColor,be.closeButtonBackgroundColor?(E.style.backgroundColor=be.closeButtonBackgroundColor,E.classList.remove("hover:persona-bg-gray-100")):(E.style.backgroundColor="",E.classList.add("hover:persona-bg-gray-100")),be.closeButtonBorderWidth||be.closeButtonBorderColor){let qe=be.closeButtonBorderWidth||"0px",$t=be.closeButtonBorderColor||"transparent";E.style.border=`${qe} solid ${$t}`,E.classList.remove("persona-border-none")}else E.style.border="",E.classList.add("persona-border-none");be.closeButtonBorderRadius?(E.style.borderRadius=be.closeButtonBorderRadius,E.classList.remove("persona-rounded-full")):(E.style.borderRadius="",E.classList.add("persona-rounded-full")),be.closeButtonPaddingX?(E.style.paddingLeft=be.closeButtonPaddingX,E.style.paddingRight=be.closeButtonPaddingX):(E.style.paddingLeft="",E.style.paddingRight=""),be.closeButtonPaddingY?(E.style.paddingTop=be.closeButtonPaddingY,E.style.paddingBottom=be.closeButtonPaddingY):(E.style.paddingTop="",E.style.paddingBottom="");let ln=be.closeButtonIconName??"x",An=be.closeButtonIconText??"\xD7";E.innerHTML="";let Xt=se(ln,"28px","currentColor",1);Xt?E.appendChild(Xt):E.textContent=An;let Pt=be.closeButtonTooltipText??"Close chat",cn=be.closeButtonShowTooltip??!0;if(E.setAttribute("aria-label",Pt),Qe&&(Qe._cleanupTooltip&&(Qe._cleanupTooltip(),delete Qe._cleanupTooltip),cn&&Pt)){let qe=null,$t=()=>{if(qe||!E)return;let Io=E.ownerDocument,Xr=Io.body;if(!Xr)return;qe=Ln(Io,"div","persona-clear-chat-tooltip"),qe.textContent=Pt;let Jr=Ln(Io,"div");Jr.className="persona-clear-chat-tooltip-arrow",qe.appendChild(Jr);let Ro=E.getBoundingClientRect();qe.style.position="fixed",qe.style.zIndex=String(po),qe.style.left=`${Ro.left+Ro.width/2}px`,qe.style.top=`${Ro.top-8}px`,qe.style.transform="translate(-50%, -100%)",Xr.appendChild(qe)},nn=()=>{qe&&qe.parentNode&&(qe.parentNode.removeChild(qe),qe=null)};Qe.addEventListener("mouseenter",$t),Qe.addEventListener("mouseleave",nn),E.addEventListener("focus",$t),E.addEventListener("blur",nn),Qe._cleanupTooltip=()=>{nn(),Qe&&(Qe.removeEventListener("mouseenter",$t),Qe.removeEventListener("mouseleave",nn)),E&&(E.removeEventListener("focus",$t),E.removeEventListener("blur",nn))}}}let{clearChatButton:Oe,clearChatButtonWrapper:tt}=He;if(Oe){let re=be.clearChat??{},rt=re.enabled??!0,Tt=o.layout?.header?.showClearChat,Qe=Tt!==void 0?Tt:rt,pt=re.placement??"inline";if(tt){tt.style.display=Qe?"":"none";let{closeButtonWrapper:qt}=He;!L()&&qt&&!qt.classList.contains("persona-absolute")&&(Qe?qt.classList.remove("persona-ml-auto"):qt.classList.add("persona-ml-auto"));let ln=pt==="top-right",An=tt.classList.contains("persona-absolute");if(!L()&&ln!==An&&Qe){if(tt.remove(),ln)tt.className="persona-absolute persona-top-4 persona-z-50",tt.style.right="48px",ye.style.position="relative",ye.appendChild(tt);else{tt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",tt.style.right="";let Pt=ye.querySelector(".persona-border-b-persona-divider"),cn=He.closeButtonWrapper;Pt&&cn&&cn.parentElement===Pt?Pt.insertBefore(tt,cn):Pt&&Pt.appendChild(tt)}let Xt=He.closeButtonWrapper;Xt&&!Xt.classList.contains("persona-absolute")&&(ln?Xt.classList.add("persona-ml-auto"):Xt.classList.remove("persona-ml-auto"))}}if(Qe){if(!L()){let qe=re.size??"32px";Oe.style.height=qe,Oe.style.width=qe}let qt=re.iconName??"refresh-cw",ln=re.iconColor??"";Oe.style.color=ln||Yt.actionIconColor,Oe.innerHTML="";let An=L()?"14px":"20px",Xt=se(qt,An,"currentColor",2);if(Xt&&Oe.appendChild(Xt),re.backgroundColor?(Oe.style.backgroundColor=re.backgroundColor,Oe.classList.remove("hover:persona-bg-gray-100")):(Oe.style.backgroundColor="",Oe.classList.add("hover:persona-bg-gray-100")),re.borderWidth||re.borderColor){let qe=re.borderWidth||"0px",$t=re.borderColor||"transparent";Oe.style.border=`${qe} solid ${$t}`,Oe.classList.remove("persona-border-none")}else Oe.style.border="",Oe.classList.add("persona-border-none");re.borderRadius?(Oe.style.borderRadius=re.borderRadius,Oe.classList.remove("persona-rounded-full")):(Oe.style.borderRadius="",Oe.classList.add("persona-rounded-full")),re.paddingX?(Oe.style.paddingLeft=re.paddingX,Oe.style.paddingRight=re.paddingX):(Oe.style.paddingLeft="",Oe.style.paddingRight=""),re.paddingY?(Oe.style.paddingTop=re.paddingY,Oe.style.paddingBottom=re.paddingY):(Oe.style.paddingTop="",Oe.style.paddingBottom="");let Pt=re.tooltipText??"Clear chat",cn=re.showTooltip??!0;if(Oe.setAttribute("aria-label",Pt),tt&&(tt._cleanupTooltip&&(tt._cleanupTooltip(),delete tt._cleanupTooltip),cn&&Pt)){let qe=null,$t=()=>{if(qe||!Oe)return;let Io=Oe.ownerDocument,Xr=Io.body;if(!Xr)return;qe=Ln(Io,"div","persona-clear-chat-tooltip"),qe.textContent=Pt;let Jr=Ln(Io,"div");Jr.className="persona-clear-chat-tooltip-arrow",qe.appendChild(Jr);let Ro=Oe.getBoundingClientRect();qe.style.position="fixed",qe.style.zIndex=String(po),qe.style.left=`${Ro.left+Ro.width/2}px`,qe.style.top=`${Ro.top-8}px`,qe.style.transform="translate(-50%, -100%)",Xr.appendChild(qe)},nn=()=>{qe&&qe.parentNode&&(qe.parentNode.removeChild(qe),qe=null)};tt.addEventListener("mouseenter",$t),tt.addEventListener("mouseleave",nn),Oe.addEventListener("focus",$t),Oe.addEventListener("blur",nn),tt._cleanupTooltip=()=>{nn(),tt&&(tt.removeEventListener("mouseenter",$t),tt.removeEventListener("mouseleave",nn)),Oe&&(Oe.removeEventListener("focus",$t),Oe.removeEventListener("blur",nn))}}}}let an=o.actionParsers&&o.actionParsers.length?o.actionParsers:[gc],ko=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Bs.message,Bs.messageAndClick];M=mc({parsers:an,handlers:ko,getSessionMetadata:m,updateSessionMetadata:C,emit:l.emit,documentRef:typeof document<"u"?document:null}),fe=Jf(o,M,he),V.updateConfig(o),Or(Ae,V.getMessages(),fe),Ra(),od(),Ua(V.isStreaming());let Wd=o.voiceRecognition?.enabled===!0,ri=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Wt=o.voiceRecognition?.provider?.type==="runtype";if(Wd&&(ri||Wt))if(!Q||!je){let re=Gg(o.voiceRecognition,o.sendButton);re&&(Q=re.micButton,je=re.micButtonWrapper,ot.insertBefore(je,_e),Q.addEventListener("click",ni),Q.disabled=V.isStreaming())}else{let re=o.voiceRecognition??{},rt=o.sendButton??{},Tt=re.iconName??"mic",Qe=rt.size??"40px",pt=re.iconSize??Qe,qt=parseFloat(pt)||24;Q.style.width=pt,Q.style.height=pt,Q.style.minWidth=pt,Q.style.minHeight=pt;let ln=re.iconColor??rt.textColor??"currentColor";Q.innerHTML="";let An=se(Tt,qt,ln,2);An?Q.appendChild(An):Q.textContent="\u{1F3A4}";let Xt=re.backgroundColor??rt.backgroundColor;Xt?Q.style.backgroundColor=Xt:Q.style.backgroundColor="",ln?Q.style.color=ln:Q.style.color="var(--persona-text, #111827)",re.borderWidth?(Q.style.borderWidth=re.borderWidth,Q.style.borderStyle="solid"):(Q.style.borderWidth="",Q.style.borderStyle=""),re.borderColor?Q.style.borderColor=re.borderColor:Q.style.borderColor="",re.paddingX?(Q.style.paddingLeft=re.paddingX,Q.style.paddingRight=re.paddingX):(Q.style.paddingLeft="",Q.style.paddingRight=""),re.paddingY?(Q.style.paddingTop=re.paddingY,Q.style.paddingBottom=re.paddingY):(Q.style.paddingTop="",Q.style.paddingBottom="");let Pt=je?.querySelector(".persona-send-button-tooltip"),cn=re.tooltipText??"Start voice recognition";if((re.showTooltip??!1)&&cn)if(Pt)Pt.textContent=cn,Pt.style.display="";else{let $t=document.createElement("div");$t.className="persona-send-button-tooltip",$t.textContent=cn,je?.insertBefore($t,Q)}else Pt&&(Pt.style.display="none");je.style.display="",Q.disabled=V.isStreaming()}else Q&&je&&(je.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?V.isVoiceActive()&&V.toggleVoice():kn&&eo());if(o.attachments?.enabled===!0)if(!De||!Be){let re=o.attachments??{},Tt=(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",Le.insertBefore(Ye,j)),We||(We=document.createElement("input"),We.type="file",We.accept=(re.allowedTypes??zn).join(","),We.multiple=(re.maxFiles??4)>1,We.style.display="none",We.setAttribute("aria-label","Attach files"),Le.insertBefore(We,j)),De=h("div","persona-send-button-wrapper"),Be=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Be.type="button",Be.setAttribute("aria-label",re.buttonTooltipText??"Attach file");let Qe=re.buttonIconName??"paperclip",pt=Tt,qt=parseFloat(pt)||40,ln=Math.round(qt*.6);Be.style.width=pt,Be.style.height=pt,Be.style.minWidth=pt,Be.style.minHeight=pt,Be.style.fontSize="18px",Be.style.lineHeight="1";let An=se(Qe,ln,"currentColor",1.5);An?Be.appendChild(An):Be.textContent="\u{1F4CE}",Be.addEventListener("click",cn=>{cn.preventDefault(),We?.click()}),De.appendChild(Be);let Xt=re.buttonTooltipText??"Attach file",Pt=h("div","persona-send-button-tooltip");Pt.textContent=Xt,De.appendChild(Pt),Ie?Ie.append(De):Le.appendChild(De),!Lt&&We&&Ye&&(Lt=cs.fromConfig(re),Lt.setPreviewsContainer(Ye),We.addEventListener("change",async()=>{Lt&&We?.files&&(await Lt.handleFileSelect(We.files),We.value="")})),ye.querySelector(".persona-attachment-drop-overlay")||ye.appendChild(Yf(re.dropOverlay))}else{De.style.display="";let re=o.attachments??{};We&&(We.accept=(re.allowedTypes??zn).join(","),We.multiple=(re.maxFiles??4)>1),Lt&&Lt.updateConfig({allowedTypes:re.allowedTypes,maxFileSize:re.maxFileSize,maxFiles:re.maxFiles})}else De&&(De.style.display="none"),Lt&&Lt.clearAttachments(),ye.querySelector(".persona-attachment-drop-overlay")?.remove();let _t=o.sendButton??{},Kr=_t.useIcon??!1,ii=_t.iconText??"\u2191",tr=_t.iconName,Gr=_t.tooltipText??"Send message",nl=_t.showTooltip??!1,Lo=_t.size??"40px",Nn=_t.backgroundColor,Po=_t.textColor;if(Kr){if(ie.style.width=Lo,ie.style.height=Lo,ie.style.minWidth=Lo,ie.style.minHeight=Lo,ie.style.fontSize="18px",ie.style.lineHeight="1",ie.innerHTML="",Po?ie.style.color=Po:ie.style.color="var(--persona-button-primary-fg, #ffffff)",tr){let re=parseFloat(Lo)||24,rt=Po?.trim()||"currentColor",Tt=se(tr,re,rt,2);Tt?ie.appendChild(Tt):ie.textContent=ii}else ie.textContent=ii;ie.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Nn?(ie.style.backgroundColor=Nn,ie.classList.remove("persona-bg-persona-primary")):(ie.style.backgroundColor="",ie.classList.add("persona-bg-persona-primary"))}else ie.textContent=o.copy?.sendButtonLabel??"Send",ie.style.width="",ie.style.height="",ie.style.minWidth="",ie.style.minHeight="",ie.style.fontSize="",ie.style.lineHeight="",ie.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",Nn?(ie.style.backgroundColor=Nn,ie.classList.remove("persona-bg-persona-accent")):ie.classList.add("persona-bg-persona-accent"),Po?ie.style.color=Po:ie.classList.add("persona-text-white");_t.borderWidth?(ie.style.borderWidth=_t.borderWidth,ie.style.borderStyle="solid"):(ie.style.borderWidth="",ie.style.borderStyle=""),_t.borderColor?ie.style.borderColor=_t.borderColor:ie.style.borderColor="",_t.paddingX?(ie.style.paddingLeft=_t.paddingX,ie.style.paddingRight=_t.paddingX):(ie.style.paddingLeft="",ie.style.paddingRight=""),_t.paddingY?(ie.style.paddingTop=_t.paddingY,ie.style.paddingBottom=_t.paddingY):(ie.style.paddingTop="",ie.style.paddingBottom="");let Qr=_e?.querySelector(".persona-send-button-tooltip");if(nl&&Gr)if(Qr)Qr.textContent=Gr,Qr.style.display="";else{let re=document.createElement("div");re.className="persona-send-button-tooltip",re.textContent=Gr,_e?.insertBefore(re,ie)}else Qr&&(Qr.style.display="none");let ai=o.layout?.contentMaxWidth??(L()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);ai?(Ae.style.maxWidth=ai,Ae.style.marginLeft="auto",Ae.style.marginRight="auto",Ae.style.width="100%",Le&&(Le.style.maxWidth=ai,Le.style.marginLeft="auto",Le.style.marginRight="auto"),Ct&&(Ct.style.maxWidth=ai,Ct.style.marginLeft="auto",Ct.style.marginRight="auto")):(Ae.style.maxWidth="",Ae.style.marginLeft="",Ae.style.marginRight="",Ae.style.width="",Le&&(Le.style.maxWidth="",Le.style.marginLeft="",Le.style.marginRight=""),Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""));let no=o.statusIndicator??{},tm=no.visible??!0;if(I.style.display=tm?"":"none",V){let re=V.getStatus();It(I,(Tt=>Tt==="idle"?no.idleText??Dt.idle:Tt==="connecting"?no.connectingText??Dt.connecting:Tt==="connected"?no.connectedText??Dt.connected:Tt==="error"?no.errorText??Dt.error:Dt[Tt])(re),no,re)}I.classList.remove("persona-text-left","persona-text-center","persona-text-right");let nm=no.align==="left"?"persona-text-left":no.align==="center"?"persona-text-center":"persona-text-right";I.classList.add(nm)},open(){P()&&bt(!0,"api")},close(){P()&&bt(!1,"api")},toggle(){P()&&bt(!H,"api")},reconnect(){V.reconnectNow()},clearChat(){Rn=!1,V.clearMessages(),wo.clear(),Yn();try{localStorage.removeItem(Sr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Sr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Sr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),c?.clear&&Fa(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),d={},M.syncFromMetadata(),Me?.clear(),Fe?.reset(),Pe?.update()},setMessage(a){return!j||V.isStreaming()?!1:(!H&&P()&&bt(!0,"system"),j.value=a,j.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(V.isStreaming())return!1;let g=a?.trim()||j.value.trim();return g?(!H&&P()&&bt(!0,"system"),j.value="",j.style.height="auto",V.sendMessage(g),!0):!1},startVoiceRecognition(){return V.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(V.isVoiceActive()||(!H&&P()&&bt(!0,"system"),Xe.manuallyDeactivated=!1,wn(),V.toggleVoice().then(()=>{Xe.active=V.isVoiceActive(),Hn("user"),V.isVoiceActive()&&Zo()})),!0):kn?!0:pd()?(!H&&P()&&bt(!0,"system"),Xe.manuallyDeactivated=!1,wn(),ei("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?V.isVoiceActive()?(V.toggleVoice().then(()=>{Xe.active=!1,Xe.manuallyDeactivated=!0,wn(),Hn("user"),Dn()}),!0):!1:kn?(Xe.manuallyDeactivated=!0,wn(),eo("user"),!0):!1},injectMessage(a){return!H&&P()&&bt(!0,"system"),V.injectMessage(a)},injectAssistantMessage(a){!H&&P()&&bt(!0,"system");let g=V.injectAssistantMessage(a);return ne&&(ne=!1,pe&&(clearTimeout(pe),pe=null),setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)),g},injectUserMessage(a){return!H&&P()&&bt(!0,"system"),V.injectUserMessage(a)},injectSystemMessage(a){return!H&&P()&&bt(!0,"system"),V.injectSystemMessage(a)},injectMessageBatch(a){return!H&&P()&&bt(!0,"system"),V.injectMessageBatch(a)},injectComponentDirective(a){return!H&&P()&&bt(!0,"system"),V.injectComponentDirective(a)},injectTestMessage(a){!H&&P()&&bt(!0,"system"),V.injectTestEvent(a)},async connectStream(a,g){return V.connectStream(a,g)},__pushEventStreamEvent(a){Me&&(Fe?.processEvent(a.type,a.payload),Me.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a.type,timestamp:Date.now(),payload:JSON.stringify(a.payload)}))},showEventStream(){!K||!Me||Ta()},hideEventStream(){Ee&&kr()},isEventStreamVisible(){return Ee},showArtifacts(){Zt(o)&&(Rn=!1,qo=!0,Wn(),Ze?.setMobileOpen(!0))},hideArtifacts(){Zt(o)&&(Rn=!0,Wn())},upsertArtifact(a){return Zt(o)?(Wo(o.features?.artifacts,a.artifactType)==="panel"&&(Rn=!1,qo=!0),V.upsertArtifact(a)):null},selectArtifact(a){Zt(o)&&V.selectArtifact(a)},clearArtifacts(){Zt(o)&&V.clearArtifacts()},getArtifacts(){return V?.getArtifacts()??[]},getSelectedArtifactId(){return V?.getSelectedArtifactId()??null},focusInput(){return A&&!H&&!L()||!j?!1:(j.focus(),!0)},async resolveApproval(a,g,y){let T=V.getMessages().find(B=>B.variant==="approval"&&B.approval?.id===a);if(!T?.approval)throw new Error(`Approval not found: ${a}`);if(T.approval.toolType==="webmcp"){V.resolveWebMcpApproval(T.id,g);return}return V.resolveApproval(T.approval,g,y)},getMessages(){return V.getMessages()},getStatus(){return V.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(a){C(a)},on(a,g){return l.on(a,g)},off(a,g){l.off(a,g)},isOpen(){return P()&&H},isVoiceActive(){return Xe.active},toggleReadAloud(a){V.toggleReadAloud(a)},stopReadAloud(){V.stopSpeaking()},getReadAloudState(a){return V.getReadAloudState(a)},onReadAloudChange(a){return V.onReadAloudChange(a)},getState(){return{open:P()&&H,launcherEnabled:A,voiceActive:Xe.active,streaming:V.isStreaming()}},showCSATFeedback(a){!H&&P()&&bt(!0,"system");let g=Ae.querySelector(".persona-feedback-container");g&&g.remove();let y=Gf({onSubmit:async(v,T)=>{V.isClientTokenMode()&&await V.submitCSATFeedback(v,T),a?.onSubmit?.(v,T)},onDismiss:a?.onDismiss,...a});Ae.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!H&&P()&&bt(!0,"system");let g=Ae.querySelector(".persona-feedback-container");g&&g.remove();let y=Qf({onSubmit:async(v,T)=>{V.isClientTokenMode()&&await V.submitNPSFeedback(v,T),a?.onSubmit?.(v,T)},onDismiss:a?.onDismiss,...a});Ae.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,g){return V.submitCSATFeedback(a,g)},async submitNPSFeedback(a,g){return V.submitNPSFeedback(a,g)},destroy(){Ka(),Mo!=null&&(clearInterval(Mo),Mo=null),Ke.forEach(a=>a()),Re.remove(),ct?.remove(),Ut?.destroy(),Kt?.remove(),Co&&E.removeEventListener("click",Co)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,g={controller:Bt,getMessages:Bt.getMessages,getStatus:Bt.getStatus,getMetadata:Bt.getPersistentMetadata,updateMetadata:Bt.updatePersistentMetadata,clearHistory:()=>Bt.clearChat(),setVoiceActive:y=>y?Bt.startVoiceRecognition():Bt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Ke.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=a)})}if(typeof window<"u"){let a=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),g=q=>{let X=q.detail;(!X?.instanceId||X.instanceId===a)&&Bt.focusInput()};if(window.addEventListener("persona:focusInput",g),Ke.push(()=>{window.removeEventListener("persona:focusInput",g)}),K){let q=le=>{let me=le.detail;(!me?.instanceId||me.instanceId===a)&&Bt.showEventStream()},X=le=>{let me=le.detail;(!me?.instanceId||me.instanceId===a)&&Bt.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",X),Ke.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",X)})}let y=q=>{let X=q.detail;(!X?.instanceId||X.instanceId===a)&&Bt.showArtifacts()},v=q=>{let X=q.detail;(!X?.instanceId||X.instanceId===a)&&Bt.hideArtifacts()},T=q=>{let X=q.detail;X?.instanceId&&X.instanceId!==a||X?.artifact&&Bt.upsertArtifact(X.artifact)},B=q=>{let X=q.detail;X?.instanceId&&X.instanceId!==a||typeof X?.id=="string"&&Bt.selectArtifact(X.id)},Z=q=>{let X=q.detail;(!X?.instanceId||X.instanceId===a)&&Bt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",v),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",B),window.addEventListener("persona:clearArtifacts",Z),Ke.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",v),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",B),window.removeEventListener("persona:clearArtifacts",Z)})}let mn=hv(o.persistState);if(mn&&P()){let a=bv(mn.storage),g=`${mn.keyPrefix}widget-open`,y=`${mn.keyPrefix}widget-voice`,v=`${mn.keyPrefix}widget-voice-mode`;if(a){let T=mn.persist?.openState&&a.getItem(g)==="true",B=mn.persist?.voiceState&&a.getItem(y)==="true",Z=mn.persist?.voiceState&&a.getItem(v)==="true";if(T&&setTimeout(()=>{Bt.open(),setTimeout(()=>{if(B||Z)Bt.startVoiceRecognition();else if(mn.persist?.focusInput){let q=t.querySelector("textarea");q&&q.focus()}},100)},0),mn.persist?.openState&&(l.on("widget:opened",()=>{a.setItem(g,"true")}),l.on("widget:closed",()=>{a.setItem(g,"false")})),mn.persist?.voiceState&&(l.on("voice:state",q=>{a.setItem(y,q.active?"true":"false")}),l.on("user:message",q=>{a.setItem(v,q.viaVoice?"true":"false")})),mn.clearOnChatClear){let q=()=>{a.removeItem(g),a.removeItem(y),a.removeItem(v)},X=()=>q();window.addEventListener("persona:clear-chat",X),Ke.push(()=>{window.removeEventListener("persona:clear-chat",X)})}}}if(b&&P()&&setTimeout(()=>{Bt.open()},0),Xo(),!vg){let a=di(()=>{V&&(Wa++,wo.clear(),Or(Ae,V.getMessages(),fe))});Ke.push(a)}return Bt};var eg=(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},xv=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},Cv=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},wv=(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.")},tg=(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"},wc=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=""},ng=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",wc(t)},vc=t=>{t.style.transition=""},xc=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=""},Cc=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Aa=(t,e)=>{t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},Av=(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))},Sv=(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)},Mv=t=>{let e=mr(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:Jt(e,r)??r;return{inset:o(n?.inset,qi),canvasBackground:o(n?.canvasBackground,Vi)}},og=(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},Tv=(t,e,n,o,r,s,i,l)=>{let p=bn(s),c=p.reveal==="push",d=l!=null,u=l?.inset??"",b=l?.canvasBackground??"";Av(t,e,n,o,c),Sv(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.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=t.ownerDocument.defaultView,m=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,k=f!=null?f.innerWidth<=C:!1;if(m&&k&&i){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),xc(e),vc(o),ng(o),Cc(n),Aa(r,o),og(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"),ng(o),xv(o,p.maxHeight),og(o,d&&i,u,b),p.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",xc(e),vc(o),Cc(n),Aa(r,o);let M=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=M,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",vc(o),wc(o),Aa(r,o);let M=eg(p.width,t.clientWidth),A=Math.max(0,t.clientWidth),W=p.animate?"margin-left 180ms ease":"none",z=p.side==="right"?i?-M:0:i?0:-M;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+M}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="",xc(e),wc(o),Cc(n),Aa(r,o);let M=p.reveal==="emerge";M?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",Cv(o,p.maxHeight),o.style.overflow=M||z?"hidden":"visible",o.style.transition=W,M){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let U=d?`calc(${eg(p.width,t.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=U,r.style.minWidth=U,r.style.maxWidth=U,r.style.boxSizing="border-box"}}},Ev=(t,e)=>{let n=t.ownerDocument.createElement("div");return tg(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){tg(n,o)},destroy(){n.remove()}}},kv=(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 b=null,f=()=>{b?.disconnect(),b=null},m=null,C=()=>{m=e?.launcher?.detachedPanel===!0?Mv(e):null};C();let k=()=>{Tv(i,l,p,c,d,e,u,m)},D=null,M=()=>{D?.(),D=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(D=Ki(()=>{C(),k()}))},A=()=>{f(),bn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(b=new ResizeObserver(()=>{k()}),b.observe(i)))},W=!1,z=()=>{k(),A(),u&&!W&&i.dataset.personaDockMobileFullscreen!=="true"&&(W=!0,wv(i,bn(e)))},U=i.ownerDocument.defaultView,w=()=>{z()};return U?.addEventListener("resize",w),bn(e).reveal==="push"?(l.appendChild(p),l.appendChild(c),i.appendChild(l)):(i.appendChild(p),i.appendChild(c)),z(),M(),{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(),M()},destroy(){U?.removeEventListener("resize",w),D?.(),D=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),i.remove()}}},rg=(t,e)=>zt(e)?kv(t,e):Ev(t,e);var Ds={desktop:{w:1280,h:800},mobile:{w:390,h:844}},sg=.15,ig=1.5,Ac="persona-preview-shell-theme",Lv={load:()=>null,save:()=>{},clear:()=>{}},Pv=["How do I get started?","Pricing & plans","Talk to support"];function Sc(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Iv(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 ag(t){let e=Iv(t);return`* { box-sizing: border-box; }
|
|
312
|
+
${it?"background: transparent !important;":""}
|
|
313
|
+
`}if(!x&&!a){let Rt="max-height: -moz-available !important; max-height: stretch !important;",en=g?"":"padding-top: 1.25em !important;",si=g?"":`z-index: ${o.launcher?.zIndex??Vt} !important;`;De.style.cssText+=Rt+en+si}ko()};Vs(),bs(t,o),Ws(t,o),Hs(t,o),Pr=()=>{Vs(),bs(t,o),Ws(t,o),Hs(t,o),Fs?t.style.setProperty("--persona-artifact-welded-outer-radius",Fs):t.style.removeProperty("--persona-artifact-welded-outer-radius")};let Ve=[];Ve.push(()=>{document.removeEventListener("keydown",$c)}),Ve.push(()=>{Er!==null&&clearTimeout(Er)});let Tn=null,En=null;Ve.push(()=>{Tn?.(),Tn=null,En?.(),En=null}),Lr&&Ve.push(()=>{Lr?.disconnect(),Lr=null}),Ve.push(()=>{Wr?.(),Wr=null,Ra(),wt&&(wt.remove(),wt=null),nt?.element.style.removeProperty("width"),nt?.element.style.removeProperty("maxWidth")}),G&&Ve.push(()=>{Ze!==null&&(cancelAnimationFrame(Ze),Ze=null),Le?.destroy(),Le=null,Te?.destroy(),Te=null,fe=null});let xo=null,jc=()=>{xo&&(xo(),xo=null),o.colorScheme==="auto"&&(xo=Gi(()=>{bs(t,o)}))};jc(),Ve.push(()=>{xo&&(xo(),xo=null)}),Ve.push(i);let Ks=o.features?.streamAnimation;if(Ks?.type&&Ks.type!=="none"){let a=xr(Ks.type,Ks.plugins);a&&(ca(a,t),Ve.push(()=>pf(t)))}let Gs=Pf(Ct),Co=null,V,Wa=a=>{if(!V)return;let g=a??V.getMessages(),y=o.features?.suggestReplies?.enabled!==!1?pp(g):null;y?Gs.render(y,V,Ae,g,o.suggestionChipsConfig,{agentPushed:!0}):g.some(x=>x.role==="user")?Gs.render([],V,Ae,g):Gs.render(o.suggestionChips,V,Ae,g,o.suggestionChipsConfig)},xn=!1,wo=tf(),Ko=new Map,Ao=new Map,Qn=new Map,Ha=0,wg=On()!==null,on=oa(),pn=0,Xn=null,un=!1,Qs=!1,Jn=0,Cn=null,So=null,Ba=!1,Xs=!1,Da=null,Hr=!0,Na=!1,Oa=null,Ag=4,Js=24,Sg=80,Fa=new Map,Ye={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},qc=o.voiceRecognition?.autoResume??!1,Hn=a=>{l.emit("voice:state",{active:Ye.active,source:a,timestamp:Date.now()})},wn=()=>{C(a=>({...a,voiceState:{active:Ye.active,timestamp:Date.now(),manuallyDeactivated:Ye.manuallyDeactivated}}))},Mg=()=>{if(o.voiceRecognition?.enabled===!1)return;let a=vc(d.voiceState),g=!!a.active,y=Number(a.timestamp??0);Ye.manuallyDeactivated=!!a.manuallyDeactivated,g&&Date.now()-y<hv&&setTimeout(()=>{Ye.active||(Ye.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?V.toggleVoice().then(()=>{Ye.active=V.isVoiceActive(),Hn("restore"),V.isVoiceActive()&&Yo()}):ei("restore"))},1e3)},Tg=()=>V?Zf(V.getMessages()).filter(a=>!a.__skipPersist):[],Ys=null,Vc=(a,g)=>{typeof console<"u"&&console.error(a,g)},_a=(a,g)=>{let y=()=>{try{let Y=a();return!Y||typeof Y.then!="function"?null:Promise.resolve(Y).catch(q=>{Vc(g,q)})}catch(Y){return Vc(g,Y),null}},x=Ys,E=x?x.then(()=>y()??void 0):y();if(!E)return;let B=E.finally(()=>{Ys===B&&(Ys=null)});Ys=B};function $a(a){if(!c?.save)return;let y={messages:a?Zf(a):V?Tg():[],metadata:d,artifacts:yn.artifacts,selectedArtifactId:yn.selectedId};_a(()=>c.save(y),"[AgentWidget] Failed to persist state:")}let Go=null,Kc=()=>De.querySelector("#persona-scroll-container")||pe,Br=()=>{Go!==null&&(cancelAnimationFrame(Go),Go=null),un=!1},Gc=()=>{Xn!==null&&(cancelAnimationFrame(Xn),Xn=null),Qs=!1,Br()},Eg=()=>xn&&Ua()&&(Zt()!=="anchor-top"||kc()),za=()=>{let a=ho()||"Jump to latest",g=Eg();Wt.toggleAttribute("data-persona-scroll-to-bottom-streaming",g),Jn>0?(bo.textContent=String(Jn),bo.style.display="",Wt.setAttribute("aria-label",`${a} (${Jn} new)`)):(bo.textContent="",bo.style.display="none",Wt.setAttribute("aria-label",g?`${a} (response streaming below)`:a))},Qc=()=>{Jn!==0&&(Jn=0,za())},Ua=()=>qn()?!on.isFollowing():!fo(pe,Js),rn=()=>{if(!Ns()||Ge){Wt.parentNode&&Wt.remove(),Wt.style.display="none";return}Wt.parentNode!==xe&&xe.appendChild(Wt),Uo();let g=In(pe)>0&&Ua();g?za():Qc(),Wt.style.display=g?"":"none"},Dr=()=>{on.pause()&&(Gc(),rn())},Yn=()=>{on.resume(),Qc(),rn()},Zn=(a=!1)=>{qn()&&on.isFollowing()&&(!a&&!xn||(Xn!==null&&(cancelAnimationFrame(Xn),Xn=null),Qs=!0,Xn=requestAnimationFrame(()=>{Xn=null,Qs=!1,on.isFollowing()&&kg(Kc(),a?220:140)})))},Xc=(a,g,y,x=()=>!0)=>{let E=a.scrollTop,B=g(),Y=B-E;if(Br(),Math.abs(Y)<1){un=!0,a.scrollTop=B,pn=a.scrollTop,un=!1;return}let q=performance.now();un=!0;let J=ge=>1-Math.pow(1-ge,3),le=ge=>{if(!x()){Br();return}let ce=g();ce!==B&&(B=ce,Y=B-E);let Me=ge-q,Ke=Math.min(Me/y,1),ht=J(Ke),ct=E+Y*ht;a.scrollTop=ct,pn=a.scrollTop,Ke<1?Go=requestAnimationFrame(le):(a.scrollTop=B,pn=a.scrollTop,Go=null,un=!1)};Go=requestAnimationFrame(le)},kg=(a,g=500)=>{let y=In(a)-a.scrollTop;if(Math.abs(y)<1){pn=a.scrollTop;return}if(Math.abs(y)>=Sg){Br(),un=!0,a.scrollTop=In(a),pn=a.scrollTop,un=!1;return}Xc(a,()=>In(a),g,()=>on.isFollowing())},Jc=()=>{let a=Kc();un=!0,a.scrollTop=In(a),pn=a.scrollTop,un=!1,rn()},Yc=a=>{let g=0,y=a;for(;y&&y!==pe;)g+=y.offsetTop,y=y.offsetParent;return g},Zc=()=>{if(mg()!=="last-user-turn")return!1;let a=V?.getMessages()??[];if(a.length<2)return!1;let g=[...a].reverse().find(B=>B.role==="user");if(!g)return!1;let y=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(g.id):g.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=pe.querySelector(`[data-message-id="${y}"]`);if(!x)return!1;let E=Math.min(Math.max(0,Yc(x)-Tc()),In(pe));return un=!0,pe.scrollTop=E,pn=pe.scrollTop,un=!1,Zt()==="follow"&&!fo(pe,Js)&&on.pause(),rn(),!0},ed=a=>{Vn.style.height=`${Math.max(0,Math.round(a))}px`,Cn&&(Cn.spacerHeight=Math.max(0,a))},Nr=()=>{So!==null&&(cancelAnimationFrame(So),So=null),Br(),Cn=null,Vn.style.height="0px"},Lg=a=>{So!==null&&cancelAnimationFrame(So),So=requestAnimationFrame(()=>{So=null;let g=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(a):a.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),y=pe.querySelector(`[data-message-id="${g}"]`);if(!y)return;let x=Yc(y),E=Cn?.spacerHeight??0,B=pe.scrollHeight-E,{targetScrollTop:Y,spacerHeight:q}=af({anchorOffsetTop:x,topOffset:Tc(),viewportHeight:pe.clientHeight,contentHeight:B});Cn={initialSpacerHeight:q,contentHeightAtAnchor:B,spacerHeight:q},ed(q),Xc(pe,()=>Y,220)})},Pg=()=>{if(qn()){if(!on.isFollowing()||fo(pe,1))return;Zn(!xn);return}if(Cn&&Cn.initialSpacerHeight>0){let a=pe.scrollHeight-Cn.spacerHeight,g=lf({initialSpacerHeight:Cn.initialSpacerHeight,contentHeightAtAnchor:Cn.contentHeightAtAnchor,currentContentHeight:a});g!==Cn.spacerHeight&&ed(g)}rn()},Ig=a=>{let g=Zt();g==="follow"?(Yn(),Zn(!0)):g==="anchor-top"&&(Hr=!1,Na=!0,Lg(a))},Rg=()=>{if(Zt()==="anchor-top"){if(Na){Hr=!1;return}Hr=!0,Nr(),Yn(),Zn(!0)}},Wg=a=>{let g=new Map;a.forEach(y=>{let x=Fa.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!x&&y.role==="assistant"&&(l.emit("assistant:message",y),!Xs&&(Zt()!=="anchor-top"||kc())&&Ua()&&(Jn+=1,za(),rn(),Pc(Jn===1?"1 new message below.":`${Jn} new messages below.`))),y.role==="assistant"&&x?.streaming&&y.streaming===!1&&l.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(x?y.approval.status!=="pending"&&l.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):l.emit("approval:requested",{approval:y.approval,message:y}))}),Fa.clear(),g.forEach((y,x)=>{Fa.set(x,y)})},Hg=(a,g,y)=>{let x=document.createElement("div"),B=(()=>{let F=r.find(_e=>_e.renderLoadingIndicator);if(F?.renderLoadingIndicator)return F.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),Y=(F,_e)=>_e==null?!1:typeof _e=="string"?(F.textContent=_e,!0):(F.appendChild(_e),!0),q=new Set,J=new Set,le=r.some(F=>F.renderAskUserQuestion),ge=[],ce=[],Me=o.enableComponentStreaming!==!1,Ke=o.approval!==!1,ht=[];if(g.forEach(F=>{q.add(F.id);let _e=le&&Ho(F),ke=Ke&&F.variant==="approval"&&!!F.approval,$e=!_e&&F.role==="assistant"&&!F.variant&&Me&&yc(F);!ke&&Qn.has(F.id)&&(a.querySelector(`#wrapper-${F.id}`)?.removeAttribute("data-preserve-runtime"),Qn.delete(F.id)),!$e&&Ao.has(F.id)&&(a.querySelector(`#wrapper-${F.id}`)?.removeAttribute("data-preserve-runtime"),Ao.delete(F.id));let Tt=Ho(F)?`:${F.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${F.agentMetadata?.askUserQuestionAnswers?Object.keys(F.agentMetadata.askUserQuestionAnswers).length:0}`:"",ut=ef(F,Ha)+Tt,St=_e||ke||$e?null:nf(wo,F.id,ut);if(St){x.appendChild(St.cloneNode(!0)),Ho(F)&&F.toolCall?.id&&F.agentMetadata?.awaitingLocalTool===!0&&!F.agentMetadata?.askUserQuestionAnswered&&(J.add(F.toolCall.id),bi(F,o,We.composerOverlay));return}let vt=null,jt=r.find(he=>!!(F.variant==="reasoning"&&he.renderReasoning||F.variant==="tool"&&he.renderToolCall||!F.variant&&he.renderMessage)),Eo=o.layout?.messages;if(Ho(F)&&F.agentMetadata?.askUserQuestionAnswered===!0){Ko.delete(F.id),a.querySelector(`#wrapper-${F.id}`)?.removeAttribute("data-preserve-runtime");return}if(ml(F)&&o.features?.suggestReplies?.enabled!==!1)return;if(Ho(F)&&o.features?.askUserQuestion?.enabled!==!1){let he=r.find(Mt=>typeof Mt.renderAskUserQuestion=="function");if(he&>.current){let Mt=Ko.get(F.id),Qt=Mt!==ut,Ot=null;if(Qt){let{payload:ot,complete:It}=sr(F),Oe=F.id,rt=()=>gt.current?.getMessages().find(sn=>sn.id===Oe);Ot=he.renderAskUserQuestion({message:F,payload:ot,complete:It,resolve:sn=>{let ko=rt();ko&>.current?.resolveAskUserQuestion(ko,sn)},dismiss:()=>{let sn=rt();sn?.agentMetadata?.awaitingLocalTool&&(gt.current?.markAskUserQuestionResolved(sn),gt.current?.resolveAskUserQuestion(sn,"(dismissed)"))},config:o})}let it=Mt!=null;if(Qt&&Ot===null&&!it){F.agentMetadata?.awaitingLocalTool===!0&&!F.agentMetadata?.askUserQuestionAnswered&&(J.add(F.toolCall.id),bi(F,o,We.composerOverlay));return}let je=document.createElement("div");je.className="persona-flex",je.id=`wrapper-${F.id}`,je.setAttribute("data-wrapper-id",F.id),je.setAttribute("data-ask-plugin-stub","true"),je.setAttribute("data-preserve-runtime","true"),x.appendChild(je),ge.push({messageId:F.id,fingerprint:ut,bubble:Ot});return}else{F.agentMetadata?.awaitingLocalTool===!0&&!F.agentMetadata?.askUserQuestionAnswered&&(J.add(F.toolCall.id),bi(F,o,We.composerOverlay));return}}else if(ke){let he=r.find(it=>typeof it.renderApproval=="function")??s,Qt=Qn.get(F.id)!==ut,Ot=null;if(Qt&&he?.renderApproval){let it=F.id,je=(ot,It)=>{let Oe=gt.current?.getMessages().find(rt=>rt.id===it);Oe?.approval&&(Oe.approval.toolType==="webmcp"?gt.current?.resolveWebMcpApproval(Oe.id,ot):gt.current?.resolveApproval(Oe.approval,ot,It))};Ot=he.renderApproval({message:F,defaultRenderer:()=>Ca(F,o),config:o,approve:ot=>je("approved",ot),deny:ot=>je("denied",ot)})}if(Qt&&Ot===null)a.querySelector(`#wrapper-${F.id}`)?.removeAttribute("data-preserve-runtime"),Qn.delete(F.id),vt=Ca(F,o);else{let it=document.createElement("div");it.className="persona-flex",it.id=`wrapper-${F.id}`,it.setAttribute("data-wrapper-id",F.id),it.setAttribute("data-approval-plugin-stub","true"),it.setAttribute("data-preserve-runtime","true"),x.appendChild(it),ht.push({messageId:F.id,fingerprint:ut,bubble:Ot});return}}else if(jt)if(F.variant==="reasoning"&&F.reasoning&&jt.renderReasoning){if(!ee)return;vt=jt.renderReasoning({message:F,defaultRenderer:()=>nc(F,o),config:o})}else if(F.variant==="tool"&&F.toolCall&&jt.renderToolCall){if(!re)return;vt=jt.renderToolCall({message:F,defaultRenderer:()=>rc(F,o),config:o})}else jt.renderMessage&&(vt=jt.renderMessage({message:F,defaultRenderer:()=>{let he=tc(F,y,Eo,o.messageActions,Pe,{loadingIndicatorRenderer:B,widgetConfig:o});return F.role!=="user"&&pc(he,F,o,V),he},config:o}));if(!vt&&$e){let he=Xf(F);if(he){let Mt=Ao.get(F.id),Qt=Mt!==ut,Ot=o.wrapComponentDirectiveInBubble!==!1&&jn.getOptions(he.component)?.bubbleChrome!==!1,it=null;if(Qt){let je=Gf(he,{config:o,message:F,transform:y});if(je&&he.component==="PersonaArtifactInline"){let ot=je.hasAttribute("data-artifact-inline")?je:je.querySelector("[data-artifact-inline]"),It=ot?.getAttribute("data-artifact-inline")??"",Oe=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(It):It,rt=It?a.querySelector(`#wrapper-${F.id}`)?.querySelector(`[data-artifact-inline="${Oe}"]`)??null:null;ot&&rt&&rt!==ot&&Gu(rt)&&(ot===je?je=rt:ot.replaceWith(rt))}if(je)if(Ot){let ot=document.createElement("div");if(ot.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),ot.id=`bubble-${F.id}`,ot.setAttribute("data-message-id",F.id),F.content&&F.content.trim()){let It=document.createElement("div");It.className="persona-mb-3 persona-text-sm persona-leading-relaxed",It.innerHTML=y({text:F.content,message:F,streaming:!!F.streaming,raw:F.rawContent}),ot.appendChild(It)}ot.appendChild(je),it=ot}else{let ot=document.createElement("div");if(ot.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",ot.id=`bubble-${F.id}`,ot.setAttribute("data-message-id",F.id),ot.setAttribute("data-persona-component-directive","true"),F.content&&F.content.trim()){let It=document.createElement("div");It.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",It.innerHTML=y({text:F.content,message:F,streaming:!!F.streaming,raw:F.rawContent}),ot.appendChild(It)}ot.appendChild(je),it=ot}}if(it||Mt!=null){let je=document.createElement("div");je.className="persona-flex",je.id=`wrapper-${F.id}`,je.setAttribute("data-wrapper-id",F.id),je.setAttribute("data-component-directive-stub","true"),je.setAttribute("data-preserve-runtime","true"),Ot||je.classList.add("persona-w-full"),x.appendChild(je),ce.push({messageId:F.id,fingerprint:ut,bubble:it});return}}}if(!vt)if(F.variant==="reasoning"&&F.reasoning){if(!ee)return;vt=nc(F,o)}else if(F.variant==="tool"&&F.toolCall){if(!re)return;vt=rc(F,o)}else if(F.variant==="approval"&&F.approval){if(o.approval===!1)return;vt=Ca(F,o)}else{let he=o.layout?.messages;he?.renderUserMessage&&F.role==="user"?vt=he.renderUserMessage({message:F,config:o,streaming:!!F.streaming}):he?.renderAssistantMessage&&F.role==="assistant"?vt=he.renderAssistantMessage({message:F,config:o,streaming:!!F.streaming}):vt=tc(F,y,he,o.messageActions,Pe,{loadingIndicatorRenderer:B,widgetConfig:o}),F.role!=="user"&&vt&&pc(vt,F,o,V)}let ft=document.createElement("div");ft.className="persona-flex",ft.id=`wrapper-${F.id}`,ft.setAttribute("data-wrapper-id",F.id),F.role==="user"&&ft.classList.add("persona-justify-end"),vt?.getAttribute("data-persona-component-directive")==="true"&&ft.classList.add("persona-w-full"),ft.appendChild(vt),of(wo,F.id,ut,ft),x.appendChild(ft)}),We.composerOverlay&&We.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(_e=>{let ke=_e.getAttribute("data-persona-ask-sheet-for");ke&&!J.has(ke)&&ar(We.composerOverlay,ke)}),o.features?.toolCallDisplay?.grouped){let F=[],_e=[];g.forEach(ke=>{if(ke.variant==="tool"&&ke.toolCall&&re){_e.push(ke);return}ke.variant==="reasoning"&&!ee||(_e.length>1&&F.push(_e),_e=[])}),_e.length>1&&F.push(_e),F.forEach((ke,$e)=>{let Tt=ke.map(Mt=>Array.from(x.children).find(Qt=>Qt instanceof HTMLElement&&Qt.getAttribute("data-wrapper-id")===Mt.id)).filter(Mt=>!!Mt);if(Tt.length<2)return;let ut=document.createElement("div");ut.className="persona-flex",ut.id=`wrapper-tool-group-${$e}-${ke[0].id}`,ut.setAttribute("data-wrapper-id",`tool-group-${$e}-${ke[0].id}`);let St=document.createElement("div");St.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",St.setAttribute("data-persona-tool-group","true");let vt=document.createElement("div");vt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let jt=`Called ${ke.length} tools`,Eo=o.toolCall?.renderGroupedSummary?.({messages:ke,toolCalls:ke.map(Mt=>Mt.toolCall).filter(Mt=>!!Mt),defaultSummary:jt,config:o});Y(vt,Eo)||(vt.textContent=jt);let ft=document.createElement("div");ft.className="persona-tool-group-stack persona-flex persona-flex-col";let he=o.features?.toolCallDisplay?.groupedMode==="summary";St.appendChild(vt),he||St.appendChild(ft),ut.appendChild(St),Tt[0].before(ut),Tt.forEach((Mt,Qt)=>{if(he){Mt.remove();return}let Ot=document.createElement("div");Ot.className="persona-tool-group-item persona-relative",Ot.setAttribute("data-persona-tool-group-item","true"),Qt<Tt.length-1&&Ot.setAttribute("data-persona-tool-group-connector","true"),Ot.appendChild(Mt),ft.appendChild(Ot)})})}rf(wo,q);let ct=g.some(F=>F.role==="assistant"&&F.streaming),Gt=g[g.length-1],Nt=Gt?.role==="assistant"&&!Gt.streaming&&Gt.variant!=="approval";if(xn&&g.some(F=>F.role==="user")&&!ct&&!Nt){let F={config:o,streaming:!0,location:"standalone",defaultRenderer:Ls},_e=r.find($e=>$e.renderLoadingIndicator),ke=null;if(_e?.renderLoadingIndicator&&(ke=_e.renderLoadingIndicator(F)),ke===null&&o.loadingIndicator?.render&&(ke=o.loadingIndicator.render(F)),ke===null&&(ke=Ls()),ke){let $e=document.createElement("div"),Tt=o.loadingIndicator?.showBubble!==!1;$e.className=Tt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),$e.setAttribute("data-typing-indicator","true"),$e.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",$e.appendChild(ke);let ut=document.createElement("div");ut.className="persona-flex",ut.id="wrapper-typing-indicator",ut.setAttribute("data-wrapper-id","typing-indicator"),ut.appendChild($e),x.appendChild(ut)}}if(!xn&&g.length>0){let F=g[g.length-1],_e={config:o,lastMessage:F,messageCount:g.length},ke=r.find(Tt=>Tt.renderIdleIndicator),$e=null;if(ke?.renderIdleIndicator&&($e=ke.renderIdleIndicator(_e)),$e===null&&o.loadingIndicator?.renderIdle&&($e=o.loadingIndicator.renderIdle(_e)),$e){let Tt=document.createElement("div"),ut=o.loadingIndicator?.showBubble!==!1;Tt.className=ut?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Tt.setAttribute("data-idle-indicator","true"),Tt.appendChild($e);let St=document.createElement("div");St.className="persona-flex",St.id="wrapper-idle-indicator",St.setAttribute("data-wrapper-id","idle-indicator"),St.appendChild(Tt),x.appendChild(St)}}if(na(a,x),ge.length>0)for(let{messageId:F,fingerprint:_e,bubble:ke}of ge){let $e=a.querySelector(`#wrapper-${F}`);$e&&ke!==null&&($e.replaceChildren(ke),$e.setAttribute("data-bubble-fp",_e),Ko.set(F,_e))}if(Ko.size>0)for(let F of Ko.keys())q.has(F)||Ko.delete(F);if(ce.length>0)for(let{messageId:F,fingerprint:_e,bubble:ke}of ce){let $e=a.querySelector(`#wrapper-${F}`);$e&&ke!==null&&($e.replaceChildren(ke),$e.setAttribute("data-bubble-fp",_e),Ao.set(F,_e))}if(Ao.size>0)for(let F of Ao.keys())q.has(F)||Ao.delete(F);if(ht.length>0)for(let{messageId:F,fingerprint:_e,bubble:ke}of ht){let $e=a.querySelector(`#wrapper-${F}`);$e&&ke!==null&&($e.replaceChildren(ke),$e.setAttribute("data-bubble-fp",_e),Qn.set(F,_e))}if(Qn.size>0)for(let F of Qn.keys())q.has(F)||Qn.delete(F)},Or=(a,g,y)=>{Hg(a,g,y),Oc()},Fr=null,Bg=()=>{if(Fr)return;let a=y=>{let x=y.composedPath();x.includes(De)||Je&&x.includes(Je)||mt(!1,"user")};Fr=a,(t.ownerDocument??document).addEventListener("pointerdown",a,!0)},td=()=>{if(!Fr)return;(t.ownerDocument??document).removeEventListener("pointerdown",Fr,!0),Fr=null};Ve.push(()=>td());let _r=null,Dg=()=>{if(_r)return;let a=y=>{y.key==="Escape"&&(y.isComposing||mt(!1,"user"))};_r=a,(t.ownerDocument??document).addEventListener("keydown",a,!0)},nd=()=>{if(!_r)return;(t.ownerDocument??document).removeEventListener("keydown",_r,!0),_r=null};Ve.push(()=>nd());let $r=!1,od=new Set,Ng=()=>{let a=o.launcher?.composerBar?.peek?.streamAnimation;return a||o.features?.streamAnimation},Qo=()=>{if(!R())return;let a=We.peekBanner,g=We.peekTextNode;if(!a||!g)return;if(H){a.classList.remove("persona-pill-peek--visible");return}let y=V?.getMessages()??[],x;for(let Nt=y.length-1;Nt>=0;Nt--){let F=y[Nt];if(F.role==="assistant"&&F.content){x=F;break}}if(!x){a.classList.remove("persona-pill-peek--visible");return}let E=x.content,B=!!x.streaming,Y=Ng(),q=ia(Y),J=q.type!=="none"?xr(q.type,Y?.plugins):null,le=J?.isAnimating?.(x)===!0,ge=J!==null&&(B||le);ge&&J&&!od.has(J.name)&&(ca(J,t),od.add(J.name));let ce=ge&&J?.containerClass?J.containerClass:null,Me=g.dataset.personaPeekStreamClass??null;Me&&Me!==ce&&(g.classList.remove(Me),delete g.dataset.personaPeekStreamClass),ce&&Me!==ce&&(g.classList.add(ce),g.dataset.personaPeekStreamClass=ce),ge?(g.style.setProperty("--persona-stream-step",`${q.speed}ms`),g.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(g.style.removeProperty("--persona-stream-step"),g.style.removeProperty("--persona-stream-duration"));let Ke=ge?aa(E,q.buffer,J,x,B):E;if(ge&&q.placeholder==="skeleton"&&B&&(!Ke||!Ke.trim())){let Nt=document.createElement("div"),F=Ss();F.classList.add("persona-pill-peek__skeleton"),Nt.appendChild(F),na(g,Nt)}else{let Nt=Math.max(0,Ke.length-100),F=Ke.length>100?Ke.slice(-100):Ke,_e=oo(F);if(!ge||!J){let ke=Ke.length>100?`\u2026${F}`:F;g.textContent!==ke&&(g.textContent=ke)}else{let ke=_e;(J.wrap==="char"||J.wrap==="word")&&(ke=As(_e,J.wrap,`peek-${x.id}`,{skipTags:J.skipTags,startIndex:Nt}));let $e=document.createElement("div");if($e.innerHTML=ke,J.useCaret&&F.length>0){let Tt=la(),ut=$e.querySelectorAll(".persona-stream-char, .persona-stream-word"),St=ut[ut.length-1];St?.parentNode?St.parentNode.insertBefore(Tt,St.nextSibling):$e.appendChild(Tt)}na(g,$e),J.onAfterRender?.({container:g,bubble:a,messageId:x.id,message:x,speed:q.speed,duration:q.duration})}}let Gt=xn||$r;a.classList.toggle("persona-pill-peek--visible",Gt)};if(R()){let a=We.peekBanner;if(a){let x=E=>{E.preventDefault(),E.stopPropagation(),mt(!0,"user")};a.addEventListener("pointerdown",x),Ve.push(()=>{a.removeEventListener("pointerdown",x)})}let g=()=>{$r||($r=!0,Qo())},y=()=>{$r&&($r=!1,Qo())};we.addEventListener("pointerenter",g),we.addEventListener("pointerleave",y),Ve.push(()=>{we.removeEventListener("pointerenter",g),we.removeEventListener("pointerleave",y)}),Je&&(Je.addEventListener("pointerenter",g),Je.addEventListener("pointerleave",y),Ve.push(()=>{Je.removeEventListener("pointerenter",g),Je.removeEventListener("pointerleave",y)}))}let Og=a=>{let g=o.launcher?.composerBar??{},y=g.expandedSize??"anchored",x=g.bottomOffset??"16px",E=g.collapsedMaxWidth,B=g.expandedMaxWidth??"880px",Y=g.expandedTopOffset??"5vh",q=g.modalMaxWidth??"880px",J=g.modalMaxHeight??"min(90vh, 800px)",le="calc(100vw - 32px)",ge="var(--persona-pill-area-height, 80px)",ce=De.style;if(ce.left="",ce.right="",ce.top="",ce.bottom="",ce.transform="",ce.width="",ce.maxWidth="",ce.height="",ce.maxHeight="",Je){let Me=Je.style;Me.bottom=x,Me.width=E??""}if(a&&y!=="fullscreen"){if(y==="modal"){ce.top="50%",ce.left="50%",ce.transform="translate(-50%, -50%)",ce.bottom="auto",ce.right="auto",ce.width=q,ce.maxWidth=le,ce.maxHeight=J,ce.height=J;return}ce.left="50%",ce.transform="translateX(-50%)",ce.bottom=`calc(${x} + ${ge})`,ce.top=Y,ce.width=B,ce.maxWidth=le}},zr=()=>{if(!L())return;if(R()){let le=(o.launcher?.composerBar??{}).expandedSize??"anchored",ge=H?"expanded":"collapsed";De.dataset.state=ge,De.dataset.expandedSize=le,Je&&(Je.dataset.state=ge,Je.dataset.expandedSize=le),De.style.removeProperty("display"),De.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Og(H),xe.style.display=H?"flex":"none",Vs(),H?(Bg(),Dg()):(td(),nd()),Qo();return}let a=$t(o),g=t.ownerDocument.defaultView??window,y=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,E=g.innerWidth<=y,B=x&&E&&A,Y=hn(o).reveal;H?(De.style.removeProperty("display"),De.style.display=a?"flex":"",De.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-95","persona-opacity-0"),we.classList.add("persona-scale-100","persona-opacity-100"),zt?zt.element.style.display="none":Kt&&(Kt.style.display="none")):(a?a&&(Y==="overlay"||Y==="push")&&!B?(De.style.removeProperty("display"),De.style.display="flex",De.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(De.style.setProperty("display","none","important"),De.classList.remove("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(De.style.display="",De.classList.add("persona-pointer-events-none","persona-opacity-0"),we.classList.remove("persona-scale-100","persona-opacity-100"),we.classList.add("persona-scale-95","persona-opacity-0")),zt?zt.element.style.display=a?"none":"":Kt&&(Kt.style.display=a?"none":""))},mt=(a,g="user")=>{if(!L()||H===a)return;let y=H;H=a,zr();let x=(()=>{let B=o.launcher?.sidebarMode??!1,Y=t.ownerDocument.defaultView??window,q=o.launcher?.mobileFullscreen??!0,J=o.launcher?.mobileBreakpoint??640,le=Y.innerWidth<=J,ge=$t(o)&&q&&le,ce=R()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return B||q&&le&&A||ge||ce})();if(H&&x){if(!Tn){let B=t.getRootNode(),Y=B instanceof ShadowRoot?B.host:t.closest(".persona-host");Y&&(Tn=Ql(Y,o.launcher?.zIndex??Vt))}En||(En=Xl(t.ownerDocument))}else H||(Tn?.(),Tn=null,En?.(),En=null);H&&(qr(),Zc()||(Zt()==="follow"?Zn(!0):Jc()));let E={open:H,source:g,timestamp:Date.now()};H&&!y?l.emit("widget:opened",E):!H&&y&&l.emit("widget:closed",E),l.emit("widget:state",{open:H,launcherEnabled:A,voiceActive:Ye.active,streaming:V.isStreaming()})},ja=a=>{dt(a?"stop":"send"),X&&(X.disabled=a),Gs.buttons.forEach(g=>{g.disabled=a}),K.dataset.personaComposerStreaming=a?"true":"false",K.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=a)})},qa=()=>{Ye.active||Ae&&Ae.focus()};l.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>qa(),200)});let rd=()=>{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=pe.querySelector("[data-persona-intro-card]");if(a){let y=o.copy?.showWelcomeCard!==!1;a.style.display=y?"":"none",y?(pe.classList.remove("persona-gap-3"),pe.classList.add("persona-gap-6")):(pe.classList.remove("persona-gap-6"),pe.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!V?.isStreaming()&&(be.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(g=>({...g,sessionId:a}))}});let Mo=null,Fg=()=>{Mo==null&&(Mo=setInterval(()=>{let a=Se.querySelectorAll("[data-tool-elapsed]");if(a.length===0){clearInterval(Mo),Mo=null;return}let g=Date.now();a.forEach(y=>{let x=Number(y.getAttribute("data-tool-elapsed"));x&&(y.textContent=xi(g-x))})},100))},Va=(a,g)=>{if(Object.is(a,g))return!0;if(a===null||g===null||typeof a!="object"||typeof g!="object")return!1;if(Array.isArray(a)||Array.isArray(g))return!Array.isArray(a)||!Array.isArray(g)||a.length!==g.length?!1:a.every((Y,q)=>Va(Y,g[q]));let y=a,x=g,E=Object.keys(y),B=Object.keys(x);return E.length===B.length&&E.every(Y=>Object.prototype.hasOwnProperty.call(x,Y)&&Va(y[Y],x[Y]))},sd=a=>{let{content:g,rawContent:y,llmContent:x,...E}=a;return E},Ka=a=>a.role==="assistant"&&a.streaming===!0&&!a.variant&&!a.toolCall&&!a.tools&&!a.approval&&!a.reasoning&&!a.contentParts&&!a.stopReason&&!yc(a),_g=(a,g,y)=>{if(a.length!==g.length)return!1;let x=a[y.index],E=g[y.index];return!x||!E||x.id!==y.id||E.id!==y.id?!1:(!Object.is(x.content,E.content)||!Object.is(x.rawContent,E.rawContent)||!Object.is(x.llmContent,E.llmContent))&&Ka(x)&&Ka(E)&&Va(sd(x),sd(E))},id=null,Xo=null,To=null,Bn=null,Zs=a=>{id=a;let g,y;Xo=null;for(let E=a.length-1;E>=0;E-=1){let B=a[E];if(!g&&B.role==="user"&&(g=B),!y&&B.role==="assistant"&&(y=B),!Xo&&Ka(B)&&(Xo={index:E,id:B.id}),g&&y&&Xo)break}Or(Se,a,ue),Ul(Se,yn.artifacts,{suppressTransition:xn}),Fg(),Wa(a),Zn(!xn),Wg(a),a.length===0&&(Nr(),Hr=!0,Na=!1),!Ba||Xs?(Ba=!0,Da=g?.id??null,Oa=y?.id??null):g&&g.id!==Da?(Da=g.id,Ig(g.id)):y&&y.id!==Oa&&Rg(),y&&(Oa=y.id);let x=Ye.lastUserMessageId;g&&g.id!==x&&(Ye.lastUserMessageId=g.id,l.emit("user:message",g)),Ye.lastUserMessageWasVoice=!!g?.viaVoice,$a(a),Qo()},Ga=()=>{Bn!==null&&(cancelAnimationFrame(Bn),Bn=null);let a=To;To=null,a&&Zs(a)},ad=()=>{Bn!==null&&cancelAnimationFrame(Bn),Bn=null,To=null},$g=a=>{let g=To??id;if(xn&&g&&Xo&&_g(g,a,Xo)){To=a,Bn===null&&(Bn=requestAnimationFrame(()=>{Bn=null;let y=To;To=null,y&&Zs(y)}));return}if(a.length===0){ad(),Zs(a);return}Ga(),Zs(a)};V=new Pi(o,{onMessagesChanged(a){$g(a)},onStatusChanged(a){let g=o.statusIndicator??{};Pt(k,(x=>x==="idle"?g.idleText??Bt.idle:x==="connecting"?g.connectingText??Bt.connecting:x==="connected"?g.connectedText??Bt.connected:x==="error"?g.errorText??Bt.error:x==="paused"?g.pausedText??Bt.paused:x==="resuming"?g.resumingText??Bt.resuming:Bt[x])(a),g,a)},onStreamingChanged(a){a||(V?.getMessages().length===0?ad():Ga()),xn=a,ja(a),V&&Or(Se,V.getMessages(),ue),a||Zn(!0),rn(),Pc(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":Dn(),Yo();break;case"processing":Dn(),Yg();break;case"speaking":Dn(),Zg();break;default:a==="idle"&&V.isBargeInActive()?(Dn(),Yo(),X?.setAttribute("aria-label","End voice session")):(Ye.active=!1,Dn(),Hn("system"),wn());break}},onArtifactsState(a){yn=a,a.artifacts.length===0&&(jo=!1),Ul(Se,a.artifacts,{suppressTransition:xn}),Wn(),$a()},onReconnect(a){let{executionId:g,lastEventId:y}=a.handle;a.phase==="paused"?l.emit("stream:paused",{executionId:g,after:y}):a.phase==="resuming"?l.emit("stream:resuming",{executionId:g,after:y,attempt:a.attempt??1}):l.emit("stream:resumed",{executionId:g,after:y})}}),gt.current=V,Ve.push(()=>V.cancel());let Qa=null;if(V.onReadAloudChange((a,g)=>{Dc=a,Nc=g,Oc();let y=a??Qa;a&&(Qa=a);let x=y?V.getMessages().find(E=>E.id===y)??null:null;l.emit("message:read-aloud",{messageId:y,message:x,state:g,timestamp:Date.now()}),g==="idle"&&(Qa=null)}),Ba=!0,o.voiceRecognition?.provider?.type==="runtype")try{V.setupVoice()}catch(a){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",a)}o.clientToken&&V.initClientSession().catch(a=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",a)}),(Te||o.onSSEEvent)&&V.setSSEEventCallback((a,g)=>{o.onSSEEvent?.(a,g),Fe?.processEvent(a,g),Te?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a,timestamp:Date.now(),payload:JSON.stringify(g)})});let ld=()=>{o.resume&&typeof o.reconnectStream=="function"&&V.resumeFromHandle(o.resume)};u?u.then(a=>{if(a){if(a.metadata&&(d=vc(a.metadata),T.syncFromMetadata()),a.messages?.length){Xs=!0;try{V.hydrateMessages(a.messages)}finally{Xs=!1}}a.artifacts?.length&&V.hydrateArtifacts(a.artifacts,a.selectedArtifactId??null)}}).catch(a=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",a)}).finally(()=>ld()):ld();let cd=()=>{!R()||H||!(o.launcher?.composerBar?.expandOnSubmit??!0)||mt(!0,"auto")},zg=(a,g)=>a?g?{refs:[...a.refs,...g.refs],finalize:async()=>{let[y,x]=await Promise.allSettled([a.finalize(),g.finalize()]),E=[];return y.status==="fulfilled"?E.push(y.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",y.reason),x.status==="fulfilled"?E.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),Av(E)}}:a:g,Ug=()=>{let g=Ae.getInlineMessageFields?.();return g&&g.contentSegments.some(x=>x.kind==="mention")?g.contentSegments:void 0},Ur=!1,jg=async a=>{let g=Ae.value.trim(),y=kt?.hasAttachments()??!1,x=g?await(nn?.takeInlineCommand(g)??Promise.resolve(null)):null;if(x?.kind==="action"){Ae.value="",Ae.style.height="auto",jr(),nn?.clear();return}let E=nn?.collectForSubmit()??null,B=x?.kind==="server"?x.mentions:null,Y=zg(E,B),q=x?.kind==="prompt"?x.sendText:g,J=!!E&&E.refs.length>0;if(!q&&!y&&!J&&!B)return;cd();let le;y&&(le=[],le.push(...kt.getContentParts()),q&&le.push(dr(q)));let ge=x?.kind==="prompt"?void 0:Ug();Ae.value="",Ae.style.height="auto",jr(),V.sendMessage(q,{contentParts:le,mentions:Y??void 0,contentSegments:ge,viaVoice:a?.viaVoice}),y&&kt.clearAttachments(),E&&nn?.clear()},Xa=async a=>{if(!Ur){Ur=!0;try{await jg(a)}finally{Ur=!1}}},dd=a=>{if(a.preventDefault(),V.isStreaming()){V.cancel(),Fe?.reset(),Le?.update();return}Ur||Xa()},qg=()=>o.features?.composerHistory!==!1,Ja={...Vl},Ya=!1,jr=()=>{Ja={...Vl}},Vg=()=>V.getMessages().filter(a=>a.role==="user").map(a=>a.content??"").filter(a=>a.length>0),Kg=a=>{if(!Ae)return;Ya=!0,Ae.value=a,Ae.dispatchEvent(new Event("input",{bubbles:!0})),Ya=!1;let g=Ae.value.length;Ae.setSelectionRange(g,g)},Gg=a=>{Ya||(a.isComposing||nn?.handleInput(a.inputType??void 0),jr())},Qg=a=>{if(Ae&&!(!a.isComposing&&nn?.handleKeydown(a))){if(qg()&&(a.key==="ArrowUp"||a.key==="ArrowDown")&&!a.shiftKey&&!a.metaKey&&!a.ctrlKey&&!a.altKey&&!a.isComposing){let g=Ae.selectionStart===0&&Ae.selectionEnd===0,y=Zu({direction:a.key==="ArrowUp"?"up":"down",history:Vg(),currentValue:Ae.value,atStart:g,state:Ja});if(Ja=y.state,y.handled){a.preventDefault(),y.value!==void 0&&Kg(y.value);return}}if(a.key==="Enter"&&!a.shiftKey){if(V.isStreaming()){a.preventDefault();return}if(Ur){a.preventDefault();return}jr(),a.preventDefault(),be.click()}}},pd=a=>{a.key!=="Escape"||a.isComposing||V.isStreaming()&&a.composedPath().includes(xe)&&(V.cancel(),Fe?.reset(),Le?.update(),jr(),a.preventDefault(),a.stopImmediatePropagation())},Xg=async a=>{if(o.attachments?.enabled!==!0||!kt)return;let g=vv(a.clipboardData);g.length!==0&&(a.preventDefault(),await kt.handleFiles(g))},fn=null,kn=!1,Jo=null,At=null,ud=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ei=(a="user")=>{if(kn||V.isStreaming())return;let g=ud();if(!g)return;fn=new g;let x=(o.voiceRecognition??{}).pauseDuration??2e3;fn.continuous=!0,fn.interimResults=!0,fn.lang="en-US";let E=Ae.value;fn.onresult=B=>{let Y="",q="";for(let le=0;le<B.results.length;le++){let ge=B.results[le],ce=ge[0].transcript;ge.isFinal?Y+=ce+" ":q=ce}let J=E+Y+q;Ae.value=J,Jo&&clearTimeout(Jo),(Y||q)&&(Jo=window.setTimeout(()=>{Ae.value.trim()&&fn&&kn&&(eo(),Xa({viaVoice:!0}))},x))},fn.onerror=B=>{B.error!=="no-speech"&&eo()},fn.onend=()=>{if(kn){let B=Ae.value.trim();B&&B!==E.trim()&&Xa({viaVoice:!0}),eo()}};try{if(fn.start(),kn=!0,Ye.active=!0,a!=="system"&&(Ye.manuallyDeactivated=!1),Hn(a),wn(),X){let B=o.voiceRecognition??{};At={backgroundColor:X.style.backgroundColor,color:X.style.color,borderColor:X.style.borderColor,iconName:B.iconName??"mic",iconSize:parseFloat(B.iconSize??o.sendButton?.size??"40")||24};let Y=B.recordingBackgroundColor,q=B.recordingIconColor,J=B.recordingBorderColor;if(X.classList.add("persona-voice-recording"),X.style.backgroundColor=Y??"var(--persona-voice-recording-bg, #ef4444)",X.style.color=q??"var(--persona-voice-recording-indicator, #ffffff)",q){let le=X.querySelector("svg");le&&le.setAttribute("stroke",q)}J&&(X.style.borderColor=J),X.setAttribute("aria-label","Stop voice recognition")}}catch{eo("system")}},eo=(a="user")=>{if(kn){if(kn=!1,Jo&&(clearTimeout(Jo),Jo=null),fn){try{fn.stop()}catch{}fn=null}if(Ye.active=!1,Hn(a),wn(),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 g=X.querySelector("svg");g&&g.setAttribute("stroke",At.color||"currentColor"),At=null}X.setAttribute("aria-label","Start voice recognition")}}},Jg=(a,g)=>{let y=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=a?.provider?.type==="runtype",E=a?.provider?.type==="custom";if(!(y||x||E))return null;let Y=h("div","persona-send-button-wrapper"),q=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");q.type="button",q.setAttribute("aria-label","Start voice recognition");let J=a?.iconName??"mic",le=g?.size??"40px",ge=a?.iconSize??le,ce=parseFloat(ge)||24,Me=a?.backgroundColor??g?.backgroundColor,Ke=a?.iconColor??g?.textColor;q.style.width=ge,q.style.height=ge,q.style.minWidth=ge,q.style.minHeight=ge,q.style.fontSize="18px",q.style.lineHeight="1",Ke?q.style.color=Ke:q.style.color="var(--persona-text, #111827)";let ct=se(J,ce,Ke||"currentColor",1.5);ct?q.appendChild(ct):q.textContent="\u{1F3A4}",Me?q.style.backgroundColor=Me:q.style.backgroundColor="",a?.borderWidth&&(q.style.borderWidth=a.borderWidth,q.style.borderStyle="solid"),a?.borderColor&&(q.style.borderColor=a.borderColor),a?.paddingX&&(q.style.paddingLeft=a.paddingX,q.style.paddingRight=a.paddingX),a?.paddingY&&(q.style.paddingTop=a.paddingY,q.style.paddingBottom=a.paddingY),Y.appendChild(q);let Gt=a?.tooltipText??"Start voice recognition";if((a?.showTooltip??!1)&&Gt){let F=h("div","persona-send-button-tooltip");F.textContent=Gt,Y.appendChild(F)}return{micButton:q,micButtonWrapper:Y}},Za=()=>{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}},el=(a,g)=>{if(!X)return;let y=X.querySelector("svg");y&&y.remove();let x=At?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),E=se(a,x,g,1.5);E&&X.appendChild(E)},ti=()=>{X&&X.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Yo=()=>{if(!X)return;Za();let a=o.voiceRecognition??{},g=a.recordingBackgroundColor,y=a.recordingIconColor,x=a.recordingBorderColor;if(ti(),X.classList.add("persona-voice-recording"),X.style.backgroundColor=g??"var(--persona-voice-recording-bg, #ef4444)",X.style.color=y??"var(--persona-voice-recording-indicator, #ffffff)",y){let E=X.querySelector("svg");E&&E.setAttribute("stroke",y)}x&&(X.style.borderColor=x),X.setAttribute("aria-label","Stop voice recognition")},Yg=()=>{if(!X)return;Za();let a=o.voiceRecognition??{},g=V.getVoiceInterruptionMode(),y=a.processingIconName??"loader",x=a.processingIconColor??At?.color??"",E=a.processingBackgroundColor??At?.backgroundColor??"",B=a.processingBorderColor??At?.borderColor??"";ti(),X.classList.add("persona-voice-processing"),X.style.backgroundColor=E,X.style.borderColor=B;let Y=x||"currentColor";X.style.color=Y,el(y,Y),X.setAttribute("aria-label","Processing voice input"),g==="none"&&(X.style.cursor="default")},Zg=()=>{if(!X)return;Za();let a=o.voiceRecognition??{},g=V.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",x=a.speakingIconName??y,E=a.speakingIconColor??(g==="barge-in"?a.recordingIconColor??At?.color??"":At?.color??""),B=a.speakingBackgroundColor??(g==="barge-in"?a.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":At?.backgroundColor??""),Y=a.speakingBorderColor??(g==="barge-in"?a.recordingBorderColor??"":At?.borderColor??"");ti(),X.classList.add("persona-voice-speaking"),X.style.backgroundColor=B,X.style.borderColor=Y;let q=E||"currentColor";X.style.color=q,el(x,q);let J=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";X.setAttribute("aria-label",J),g==="none"&&(X.style.cursor="default"),g==="barge-in"&&X.classList.add("persona-voice-recording")},Dn=()=>{X&&(ti(),At&&(X.style.backgroundColor=At.backgroundColor??"",X.style.color=At.color??"",X.style.borderColor=At.borderColor??"",el(At.iconName,At.color||"currentColor"),At=null),X.style.cursor="",X.setAttribute("aria-label","Start voice recognition"))},ni=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let a=V.getVoiceStatus(),g=V.getVoiceInterruptionMode();if(g==="none"&&(a==="processing"||a==="speaking"))return;if(g==="cancel"&&(a==="processing"||a==="speaking")){V.stopVoicePlayback();return}if(V.isBargeInActive()){V.stopVoicePlayback(),V.deactivateBargeIn().then(()=>{Ye.active=!1,Ye.manuallyDeactivated=!0,wn(),Hn("user"),Dn()});return}V.toggleVoice().then(()=>{Ye.active=V.isVoiceActive(),Ye.manuallyDeactivated=!V.isVoiceActive(),wn(),Hn("user"),V.isVoiceActive()?Yo():Dn()});return}if(kn){let a=Ae.value.trim();Ye.manuallyDeactivated=!0,wn(),eo("user"),a&&(Ae.value="",Ae.style.height="auto",V.sendMessage(a))}else Ye.manuallyDeactivated=!1,wn(),ei("user")};Rc=ni,X&&(X.addEventListener("click",ni),Ve.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(V.isVoiceActive()&&V.toggleVoice(),Dn()):eo("system"),X&&X.removeEventListener("click",ni)}));let em=l.on("assistant:complete",()=>{qc&&(Ye.active||Ye.manuallyDeactivated||qc==="assistant"&&!Ye.lastUserMessageWasVoice||setTimeout(()=>{!Ye.active&&!Ye.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?V.toggleVoice().then(()=>{Ye.active=V.isVoiceActive(),Hn("auto"),V.isVoiceActive()&&Yo()}):ei("auto"))},600))});Ve.push(em);let tm=l.on("action:resubmit",()=>{setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)});Ve.push(tm);let fd=()=>{mt(!H,"user")},zt=null,Kt=null;if(A&&!R()){let{instance:a,element:g}=Yl({config:o,plugins:r,onToggle:fd});zt=a,a||(Kt=g)}zt?t.appendChild(zt.element):Kt&&t.appendChild(Kt),zr(),Wa(),rd(),ja(V.isStreaming()),Zc()||(Zt()==="follow"?Zn(!0):Jc()),Mg(),z&&(!A||R()?setTimeout(()=>qa(),0):H&&setTimeout(()=>qa(),200));let qr=()=>{if(R()){Uo(),zr();return}let a=$t(o),g=o.launcher?.sidebarMode??!1,y=a||g||(o.launcher?.fullHeight??!1),x=t.ownerDocument.defaultView??window,E=o.launcher?.mobileFullscreen??!0,B=o.launcher?.mobileBreakpoint??640,Y=x.innerWidth<=B,q=E&&Y&&A;try{if(q){Pr(),Ir=qs();return}let J=!1;N&&(N=!1,Pr(),J=!0);let le=qs();if(!J&&le!==Ir&&(Pr(),J=!0),Ir=le,J&&Ia(),!A&&!a){we.style.height="",we.style.width="";return}if(!g&&!a){let ce=o?.launcher?.width??o?.launcherWidth??Un;we.style.width=ce,we.style.maxWidth=ce}if(js(),!y){let ge=x.innerHeight,ce=64,Me=o.launcher?.heightOffset??0,Ke=Math.max(200,ge-ce),ht=Math.min(640,Ke),ct=Math.max(200,ht-Me);we.style.height=`${ct}px`}}finally{if(Uo(),zr(),H&&A){let le=(t.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ge=o.launcher?.sidebarMode??!1,ce=o.launcher?.mobileFullscreen??!0,Me=$t(o)&&ce&&le,Ke=ge||ce&&le&&A||Me;if(Ke&&!En){let ht=t.getRootNode(),ct=ht instanceof ShadowRoot?ht.host:t.closest(".persona-host");ct&&!Tn&&(Tn=Ql(ct,o.launcher?.zIndex??Vt)),En=Xl(t.ownerDocument)}else Ke||(Tn?.(),Tn=null,En?.(),En=null)}}};qr();let gd=t.ownerDocument.defaultView??window;if(gd.addEventListener("resize",qr),Ve.push(()=>gd.removeEventListener("resize",qr)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{Uo()});a.observe(K),Ve.push(()=>a.disconnect())}pn=pe.scrollTop;let md=In(pe),nm=()=>{let a=pe.getRootNode();return(typeof a.getSelection=="function"?a.getSelection():null)??pe.ownerDocument.getSelection()},tl=()=>sf(nm(),pe),hd=()=>{let a=pe.scrollTop,g=In(pe),y=g<md;if(md=g,!qn()){pn=a,rn();return}let{action:x,nextLastScrollTop:E}=ra({following:on.isFollowing(),currentScrollTop:a,lastScrollTop:pn,nearBottom:fo(pe,Js),userScrollThreshold:Ag,isAutoScrolling:un||Qs||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(pn=E,x==="resume"){tl()||Yn();return}x==="pause"&&Dr()};if(pe.addEventListener("scroll",hd,{passive:!0}),Ve.push(()=>pe.removeEventListener("scroll",hd)),typeof ResizeObserver<"u"){let a=new ResizeObserver(()=>{Pg()});a.observe(Se),a.observe(pe),Ve.push(()=>a.disconnect())}let bd=()=>{qn()&&on.isFollowing()&&tl()&&Dr()},yd=pe.ownerDocument;yd.addEventListener("selectionchange",bd),Ve.push(()=>{yd.removeEventListener("selectionchange",bd)});let om=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),vd=a=>{Ec()&&qn()&&on.isFollowing()&&om.has(a.key)&&Dr()},xd=a=>{if(!Ec()||!qn()||!on.isFollowing())return;let g=a.target;g&&g.closest("a, button, [tabindex], input, textarea, select")&&Dr()};pe.addEventListener("keydown",vd),pe.addEventListener("focusin",xd),Ve.push(()=>{pe.removeEventListener("keydown",vd),pe.removeEventListener("focusin",xd)});let Cd=a=>{if(!qn())return;let g=sa({following:on.isFollowing(),deltaY:a.deltaY,nearBottom:fo(pe,Js),resumeWhenNearBottom:!0});g==="pause"?Dr():g==="resume"&&!tl()&&Yn()};pe.addEventListener("wheel",Cd,{passive:!0}),Ve.push(()=>pe.removeEventListener("wheel",Cd)),Wt.addEventListener("click",()=>{Nr(),pe.scrollTop=pe.scrollHeight,pn=pe.scrollTop,Yn(),Zn(!0),rn()}),Ve.push(()=>Wt.remove()),Ve.push(()=>{Gc(),Nr()});let wd=()=>{S&&(Co&&(S.removeEventListener("click",Co),Co=null),L()?(S.style.display="",Co=()=>{mt(!1,"user")},S.addEventListener("click",Co)):S.style.display="none")};wd(),(()=>{let{clearChatButton:a}=We;a&&a.addEventListener("click",()=>{V.clearMessages(),wo.clear(),Yn(),ar(We.composerOverlay);try{localStorage.removeItem(Sr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Sr}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Sr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(g),c?.clear&&_a(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),d={},T.syncFromMetadata(),Te?.clear(),Fe?.reset(),Le?.update()})})(),Z&&Z.addEventListener("submit",dd);let Ad=[["keydown",Qg],["input",Gg],["paste",Xg],["focus",yg]],Sd=a=>{if(a)for(let[g,y]of Ad)a.addEventListener(g,y)},Md=a=>{if(a)for(let[g,y]of Ad)a.removeEventListener(g,y)};Sd(Ae),nn?.onComposerSwap((a,g)=>{Md(g),Ae=a,Sd(a)});let Td=t.ownerDocument??document;Td.addEventListener("keydown",pd,!0);let Ed="persona-attachment-drop-active",Vr=0,nl=()=>{Vr=0,xe.classList.remove(Ed)},Zo=()=>o.attachments?.enabled===!0&&kt!==null,kd=a=>{!Aa(a.dataTransfer)||!Zo()||(Vr++,Vr===1&&xe.classList.add(Ed))},Ld=a=>{!Aa(a.dataTransfer)||!Zo()||(Vr--,Vr<=0&&nl())},Pd=a=>{!Aa(a.dataTransfer)||!Zo()||(a.preventDefault(),a.dataTransfer.dropEffect="copy")},Id=a=>{if(!Aa(a.dataTransfer)||!Zo())return;a.preventDefault(),a.stopPropagation(),nl();let g=Array.from(a.dataTransfer.files??[]);g.length!==0&&kt.handleFiles(g)},to=!0;xe.addEventListener("dragenter",kd,to),xe.addEventListener("dragleave",Ld,to),t.addEventListener("dragover",Pd,to),t.addEventListener("drop",Id,to);let oi=t.ownerDocument,Rd=a=>{Zo()&&a.preventDefault()},Wd=a=>{Zo()&&a.preventDefault()};oi.addEventListener("dragover",Rd),oi.addEventListener("drop",Wd),Ve.push(()=>{Z&&Z.removeEventListener("submit",dd),Md(Ae),Td.removeEventListener("keydown",pd,!0),nn?.destroy()}),Ve.push(()=>{xe.removeEventListener("dragenter",kd,to),xe.removeEventListener("dragleave",Ld,to),t.removeEventListener("dragover",Pd,to),t.removeEventListener("drop",Id,to),oi.removeEventListener("dragover",Rd),oi.removeEventListener("drop",Wd),nl()}),Ve.push(()=>{V.cancel()}),zt?Ve.push(()=>{zt?.destroy()}):Kt&&Ve.push(()=>{Kt?.remove()});let Ht={update(a){let g=o.toolCall,y=o.messageActions,x=o.layout?.messages,E=o.colorScheme,B=o.loadingIndicator,Y=o.iterationDisplay,q=o.features?.showReasoning,J=o.features?.showToolCalls,le=o.features?.toolCallDisplay,ge=o.features?.reasoningDisplay,ce=o.features?.streamAnimation?.type;o=jf(o,a),Vs(),bs(t,o),Ws(t,o),Hs(t,o),Wn(),o.colorScheme!==E&&jc();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,re=o.features?.showToolCalls??!0,ie=o.features?.scrollToBottom??{};let Ke=Zt();te=o.features?.scrollBehavior??{},Ke!==Zt()&&(Nr(),Yn()),Ic(),rn();let ht=G;if(G=o.features?.showEventStreamToggle??!1,G&&!ht){if(Te||(fe=new Is(ve),Te=new Ps(Ee,fe),Fe=Fe??new Rs,fe.open().then(()=>Te?.restore()).catch(()=>{}),V.setSSEEventCallback((oe,Xe)=>{o.onSSEEvent?.(oe,Xe),Fe?.processEvent(oe,Xe),Te.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:oe,timestamp:Date.now(),payload:JSON.stringify(Xe)})})),!lt&&$){let oe=o.features?.eventStream?.classNames,Xe="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"+(oe?.toggleButton?" "+oe.toggleButton:"");lt=h("button",Xe),lt.style.width="28px",lt.style.height="28px",lt.style.color=Jt.actionIconColor,lt.type="button",lt.setAttribute("aria-label","Event Stream"),lt.title="Event Stream";let bt=se("activity","18px","currentColor",1.5);bt&<.appendChild(bt);let qe=We.clearChatButtonWrapper,at=We.closeButtonWrapper,qt=qe||at;qt&&qt.parentNode===$?$.insertBefore(lt,qt):$.appendChild(lt),lt.addEventListener("click",()=>{Ge?kr():Ea()})}}else!G&&ht&&(kr(),lt&&(lt.remove(),lt=null),Te?.clear(),fe?.destroy(),Te=null,fe=null,Fe?.reset(),Fe=null);if(o.launcher?.enabled===!1&&zt&&(zt.destroy(),zt=null),o.launcher?.enabled===!1&&Kt&&(Kt.remove(),Kt=null),o.launcher?.enabled!==!1&&!zt&&!Kt){let{instance:oe,element:Xe}=Yl({config:o,plugins:r,onToggle:fd});zt=oe,oe||(Kt=Xe),t.appendChild(Xe)}zt&&zt.update(o),_&&o.launcher?.title!==void 0&&(_.textContent=o.launcher.title),Q&&o.launcher?.subtitle!==void 0&&(Q.textContent=o.launcher.subtitle);let ct=o.layout?.header;if(ct?.layout!==O&&$){let oe=ct?ua(o,ct,{showClose:L(),onClose:()=>mt(!1,"user")}):Fo({config:o,showClose:L(),onClose:()=>mt(!1,"user")});xt.replaceHeader(oe),$=xt.header.element,P=xt.header.iconHolder,_=xt.header.headerTitle,Q=xt.header.headerSubtitle,S=xt.header.closeButton,O=ct?.layout}else if(ct){if(P&&(P.style.display=ct.showIcon===!1?"none":""),_&&(_.style.display=ct.showTitle===!1?"none":""),Q&&(Q.style.display=ct.showSubtitle===!1?"none":""),S){let oe=L()&&ct.showCloseButton!==!1;S.style.display=oe?"":"none"}if(We.clearChatButtonWrapper){let oe=ct.showClearChat;if(oe!==void 0){We.clearChatButtonWrapper.style.display=oe?"":"none";let{closeButtonWrapper:Xe}=We;Xe&&!Xe.classList.contains("persona-absolute")&&(oe?Xe.classList.remove("persona-ml-auto"):Xe.classList.add("persona-ml-auto"))}}}let Nt=o.layout?.showHeader!==!1;$&&($.style.display=Nt?"":"none");let F=o.layout?.showFooter!==!1;K&&(K.style.display=F?"":"none"),Uo(),rn(),A!==w?A?mt(W,"auto"):(H=!0,zr()):W!==U&&mt(W,"auto"),U=W,w=A,qr(),wd();let $e=JSON.stringify(o.toolCall)!==JSON.stringify(g),Tt=JSON.stringify(o.messageActions)!==JSON.stringify(y),ut=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),St=o.loadingIndicator?.render!==B?.render||o.loadingIndicator?.renderIdle!==B?.renderIdle||o.loadingIndicator?.showBubble!==B?.showBubble,vt=o.iterationDisplay!==Y,jt=(o.features?.showReasoning??!0)!==(q??!0)||(o.features?.showToolCalls??!0)!==(J??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(le)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ge);($e||Tt||ut||St||vt||jt)&&V&&(Ha++,Or(Se,V.getMessages(),ue));let ft=o.features?.streamAnimation?.type;if(ft!==ce&&ft&&ft!=="none"){let oe=xr(ft,o.features?.streamAnimation?.plugins);oe&&ca(oe,t)}let he=o.launcher??{},Mt=he.headerIconHidden??!1,Qt=o.layout?.header?.showIcon,Ot=Mt||Qt===!1,it=he.headerIconName,je=he.headerIconSize??"48px";if(P){let oe=xe.querySelector(".persona-border-b-persona-divider"),Xe=oe?.querySelector(".persona-flex-col");if(Ot)P.style.display="none",oe&&Xe&&!oe.contains(Xe)&&oe.insertBefore(Xe,oe.firstChild);else{if(P.style.display="",P.style.height=je,P.style.width=je,oe&&Xe&&(oe.contains(P)?P.nextSibling!==Xe&&(P.remove(),oe.insertBefore(P,Xe)):oe.insertBefore(P,Xe)),it){let qe=parseFloat(je)||24,at=se(it,qe*.6,"currentColor",1);at?P.replaceChildren(at):P.textContent=he.agentIconText??"\u{1F4AC}"}else if(he.iconUrl){let qe=P.querySelector("img");if(qe)qe.src=he.iconUrl,qe.style.height=je,qe.style.width=je;else{let at=document.createElement("img");at.src=he.iconUrl,at.alt="",at.className="persona-rounded-xl persona-object-cover",at.style.height=je,at.style.width=je,P.replaceChildren(at)}}else{let qe=P.querySelector("svg"),at=P.querySelector("img");(qe||at)&&P.replaceChildren(),P.textContent=he.agentIconText??"\u{1F4AC}"}let bt=P.querySelector("img");bt&&(bt.style.height=je,bt.style.width=je)}}let ot=o.layout?.header?.showTitle,It=o.layout?.header?.showSubtitle;if(_&&(_.style.display=ot===!1?"none":""),Q&&(Q.style.display=It===!1?"none":""),S){let oe=L()&&o.layout?.header?.showCloseButton!==!1;S.style.display=oe?"":"none";let Xe=he.closeButtonSize??"32px",bt=he.closeButtonPlacement??"inline";S.style.height=Xe,S.style.width=Xe;let{closeButtonWrapper:qe}=We,at=bt==="top-right",qt=qe?.classList.contains("persona-absolute");if(qe&&at!==qt)if(qe.remove(),at)qe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",xe.style.position="relative",xe.appendChild(qe);else{let Ue=he.clearChat?.placement??"inline",_t=he.clearChat?.enabled??!0;qe.className=_t&&Ue==="inline"?"":"persona-ml-auto";let tn=xe.querySelector(".persona-border-b-persona-divider");tn&&tn.appendChild(qe)}if(S.style.color=he.closeButtonColor||Jt.actionIconColor,he.closeButtonBackgroundColor?(S.style.backgroundColor=he.closeButtonBackgroundColor,S.classList.remove("hover:persona-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:persona-bg-gray-100")),he.closeButtonBorderWidth||he.closeButtonBorderColor){let Ue=he.closeButtonBorderWidth||"0px",_t=he.closeButtonBorderColor||"transparent";S.style.border=`${Ue} solid ${_t}`,S.classList.remove("persona-border-none")}else S.style.border="",S.classList.add("persona-border-none");he.closeButtonBorderRadius?(S.style.borderRadius=he.closeButtonBorderRadius,S.classList.remove("persona-rounded-full")):(S.style.borderRadius="",S.classList.add("persona-rounded-full")),he.closeButtonPaddingX?(S.style.paddingLeft=he.closeButtonPaddingX,S.style.paddingRight=he.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),he.closeButtonPaddingY?(S.style.paddingTop=he.closeButtonPaddingY,S.style.paddingBottom=he.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom="");let an=he.closeButtonIconName??"x",An=he.closeButtonIconText??"\xD7";S.innerHTML="";let Ut=se(an,"28px","currentColor",1);Ut?(Ut.style.display="block",S.appendChild(Ut)):S.textContent=An;let Lt=he.closeButtonTooltipText??"Close chat",ln=he.closeButtonShowTooltip??!0;if(S.setAttribute("aria-label",Lt),qe&&(qe._cleanupTooltip&&(qe._cleanupTooltip(),delete qe._cleanupTooltip),ln&&Lt)){let Ue=null,_t=()=>{if(Ue||!S)return;let Io=S.ownerDocument,Xr=Io.body;if(!Xr)return;Ue=Ln(Io,"div","persona-clear-chat-tooltip"),Ue.textContent=Lt;let Jr=Ln(Io,"div");Jr.className="persona-clear-chat-tooltip-arrow",Ue.appendChild(Jr);let Ro=S.getBoundingClientRect();Ue.style.position="fixed",Ue.style.zIndex=String(po),Ue.style.left=`${Ro.left+Ro.width/2}px`,Ue.style.top=`${Ro.top-8}px`,Ue.style.transform="translate(-50%, -100%)",Xr.appendChild(Ue)},tn=()=>{Ue&&Ue.parentNode&&(Ue.parentNode.removeChild(Ue),Ue=null)};qe.addEventListener("mouseenter",_t),qe.addEventListener("mouseleave",tn),S.addEventListener("focus",_t),S.addEventListener("blur",tn),qe._cleanupTooltip=()=>{tn(),qe&&(qe.removeEventListener("mouseenter",_t),qe.removeEventListener("mouseleave",tn)),S&&(S.removeEventListener("focus",_t),S.removeEventListener("blur",tn))}}}let{clearChatButton:Oe,clearChatButtonWrapper:rt}=We;if(Oe){let oe=he.clearChat??{},Xe=oe.enabled??!0,bt=o.layout?.header?.showClearChat,qe=bt!==void 0?bt:Xe,at=oe.placement??"inline";if(rt){rt.style.display=qe?"":"none";let{closeButtonWrapper:qt}=We;!R()&&qt&&!qt.classList.contains("persona-absolute")&&(qe?qt.classList.remove("persona-ml-auto"):qt.classList.add("persona-ml-auto"));let an=at==="top-right",An=rt.classList.contains("persona-absolute");if(!R()&&an!==An&&qe){if(rt.remove(),an)rt.className="persona-absolute persona-top-4 persona-z-50",rt.style.right="48px",xe.style.position="relative",xe.appendChild(rt);else{rt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",rt.style.right="";let Lt=xe.querySelector(".persona-border-b-persona-divider"),ln=We.closeButtonWrapper;Lt&&ln&&ln.parentElement===Lt?Lt.insertBefore(rt,ln):Lt&&Lt.appendChild(rt)}let Ut=We.closeButtonWrapper;Ut&&!Ut.classList.contains("persona-absolute")&&(an?Ut.classList.add("persona-ml-auto"):Ut.classList.remove("persona-ml-auto"))}}if(qe){if(!R()){let Ue=oe.size??"32px";Oe.style.height=Ue,Oe.style.width=Ue}let qt=oe.iconName??"refresh-cw",an=oe.iconColor??"";Oe.style.color=an||Jt.actionIconColor,Oe.innerHTML="";let An=R()?"14px":"20px",Ut=se(qt,An,"currentColor",1);if(Ut&&(Ut.style.display="block",Oe.appendChild(Ut)),oe.backgroundColor?(Oe.style.backgroundColor=oe.backgroundColor,Oe.classList.remove("hover:persona-bg-gray-100")):(Oe.style.backgroundColor="",Oe.classList.add("hover:persona-bg-gray-100")),oe.borderWidth||oe.borderColor){let Ue=oe.borderWidth||"0px",_t=oe.borderColor||"transparent";Oe.style.border=`${Ue} solid ${_t}`,Oe.classList.remove("persona-border-none")}else Oe.style.border="",Oe.classList.add("persona-border-none");oe.borderRadius?(Oe.style.borderRadius=oe.borderRadius,Oe.classList.remove("persona-rounded-full")):(Oe.style.borderRadius="",Oe.classList.add("persona-rounded-full")),oe.paddingX?(Oe.style.paddingLeft=oe.paddingX,Oe.style.paddingRight=oe.paddingX):(Oe.style.paddingLeft="",Oe.style.paddingRight=""),oe.paddingY?(Oe.style.paddingTop=oe.paddingY,Oe.style.paddingBottom=oe.paddingY):(Oe.style.paddingTop="",Oe.style.paddingBottom="");let Lt=oe.tooltipText??"Clear chat",ln=oe.showTooltip??!0;if(Oe.setAttribute("aria-label",Lt),rt&&(rt._cleanupTooltip&&(rt._cleanupTooltip(),delete rt._cleanupTooltip),ln&&Lt)){let Ue=null,_t=()=>{if(Ue||!Oe)return;let Io=Oe.ownerDocument,Xr=Io.body;if(!Xr)return;Ue=Ln(Io,"div","persona-clear-chat-tooltip"),Ue.textContent=Lt;let Jr=Ln(Io,"div");Jr.className="persona-clear-chat-tooltip-arrow",Ue.appendChild(Jr);let Ro=Oe.getBoundingClientRect();Ue.style.position="fixed",Ue.style.zIndex=String(po),Ue.style.left=`${Ro.left+Ro.width/2}px`,Ue.style.top=`${Ro.top-8}px`,Ue.style.transform="translate(-50%, -100%)",Xr.appendChild(Ue)},tn=()=>{Ue&&Ue.parentNode&&(Ue.parentNode.removeChild(Ue),Ue=null)};rt.addEventListener("mouseenter",_t),rt.addEventListener("mouseleave",tn),Oe.addEventListener("focus",_t),Oe.addEventListener("blur",tn),rt._cleanupTooltip=()=>{tn(),rt&&(rt.removeEventListener("mouseenter",_t),rt.removeEventListener("mouseleave",tn)),Oe&&(Oe.removeEventListener("focus",_t),Oe.removeEventListener("blur",tn))}}}}let sn=o.actionParsers&&o.actionParsers.length?o.actionParsers:[mc],ko=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Bs.message,Bs.messageAndClick];T=hc({parsers:sn,handlers:ko,getSessionMetadata:m,updateSessionMetadata:C,emit:l.emit,documentRef:typeof document<"u"?document:null}),ue=eg(o,T,me),V.updateConfig(o),Or(Se,V.getMessages(),ue),Wa(),rd(),ja(V.isStreaming());let Hd=o.voiceRecognition?.enabled===!0,ri=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Rt=o.voiceRecognition?.provider?.type==="runtype";if(Hd&&(ri||Rt))if(!X||!ze){let oe=Jg(o.voiceRecognition,o.sendButton);oe&&(X=oe.micButton,ze=oe.micButtonWrapper,Qe.insertBefore(ze,bn),X.addEventListener("click",ni),X.disabled=V.isStreaming())}else{let oe=o.voiceRecognition??{},Xe=o.sendButton??{},bt=oe.iconName??"mic",qe=Xe.size??"40px",at=oe.iconSize??qe,qt=parseFloat(at)||24;X.style.width=at,X.style.height=at,X.style.minWidth=at,X.style.minHeight=at;let an=oe.iconColor??Xe.textColor;X.innerHTML="";let An=se(bt,qt,an||"currentColor",1.5);An?X.appendChild(An):X.textContent="\u{1F3A4}";let Ut=oe.backgroundColor??Xe.backgroundColor;Ut?X.style.backgroundColor=Ut:X.style.backgroundColor="",an?X.style.color=an:X.style.color="var(--persona-text, #111827)",oe.borderWidth?(X.style.borderWidth=oe.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),oe.borderColor?X.style.borderColor=oe.borderColor:X.style.borderColor="",oe.paddingX?(X.style.paddingLeft=oe.paddingX,X.style.paddingRight=oe.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),oe.paddingY?(X.style.paddingTop=oe.paddingY,X.style.paddingBottom=oe.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let Lt=ze?.querySelector(".persona-send-button-tooltip"),ln=oe.tooltipText??"Start voice recognition";if((oe.showTooltip??!1)&&ln)if(Lt)Lt.textContent=ln,Lt.style.display="";else{let _t=document.createElement("div");_t.className="persona-send-button-tooltip",_t.textContent=ln,ze?.insertBefore(_t,X)}else Lt&&(Lt.style.display="none");ze.style.display="",X.disabled=V.isStreaming()}else X&&ze&&(ze.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?V.isVoiceActive()&&V.toggleVoice():kn&&eo());if(o.attachments?.enabled===!0){if(!Ne||!Re){let oe=o.attachments??{},bt=(o.sendButton??{}).size??"40px";tt||(tt=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),tt.style.display="none",Z.insertBefore(tt,Ae)),He||(He=document.createElement("input"),He.type="file",He.accept=(oe.allowedTypes??zn).join(","),He.multiple=(oe.maxFiles??4)>1,He.style.display="none",He.setAttribute("aria-label","Attach files"),Z.insertBefore(He,Ae)),Ne=h("div","persona-send-button-wrapper"),Re=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Re.type="button",Re.setAttribute("aria-label",oe.buttonTooltipText??"Attach file");let qe=oe.buttonIconName??"paperclip",at=bt,qt=parseFloat(at)||40,an=Math.round(qt*.6);Re.style.width=at,Re.style.height=at,Re.style.minWidth=at,Re.style.minHeight=at,Re.style.fontSize="18px",Re.style.lineHeight="1";let An=se(qe,an,"currentColor",1.5);An?Re.appendChild(An):Re.textContent="\u{1F4CE}",Re.addEventListener("click",ln=>{ln.preventDefault(),He?.click()}),Ne.appendChild(Re);let Ut=oe.buttonTooltipText??"Attach file",Lt=h("div","persona-send-button-tooltip");Lt.textContent=Ut,Ne.appendChild(Lt),Ie?Ie.append(Ne):Z.appendChild(Ne),!kt&&He&&tt&&(kt=cs.fromConfig(oe),kt.setPreviewsContainer(tt),He.addEventListener("change",async()=>{kt&&He?.files&&(await kt.handleFileSelect(He.files),He.value="")}))}else{Ne.style.display="";let oe=o.attachments??{};He&&(He.accept=(oe.allowedTypes??zn).join(","),He.multiple=(oe.maxFiles??4)>1),kt&&kt.updateConfig({allowedTypes:oe.allowedTypes,maxFileSize:oe.maxFileSize,maxFiles:oe.maxFiles})}if(xe.querySelector(".persona-attachment-drop-overlay")?.remove(),xe.appendChild(tg(o.attachments?.dropOverlay)),Re){let oe=o.attachments??{},Xe=oe.buttonTooltipText??"Attach file";Re.setAttribute("aria-label",Xe),Re.textContent="";let bt=parseFloat(o.sendButton?.size??"40px")||40,qe=se(oe.buttonIconName??"paperclip",Math.round(bt*.6),"currentColor",1.5);qe?Re.appendChild(qe):Re.textContent="\u{1F4CE}";let at=Ne?.querySelector(".persona-send-button-tooltip");at&&(at.textContent=Xe)}}else Ne&&(Ne.style.display="none"),kt&&kt.clearAttachments(),xe.querySelector(".persona-attachment-drop-overlay")?.remove();let Ft=o.sendButton??{},Kr=Ft.useIcon??!1,ii=Ft.iconText??"\u2191",er=Ft.iconName,Gr=Ft.tooltipText??"Send message",ol=Ft.showTooltip??!1,Lo=Ft.size??"40px",Nn=Ft.backgroundColor,Po=Ft.textColor;if(Kr){if(be.style.width=Lo,be.style.height=Lo,be.style.minWidth=Lo,be.style.minHeight=Lo,be.style.fontSize="18px",be.style.lineHeight="1",Po?be.style.color=Po:be.style.color="var(--persona-button-primary-fg, #ffffff)",!V.isStreaming())if(be.innerHTML="",er){let oe=parseFloat(Lo)||24,Xe=Po?.trim()||"currentColor",bt=se(er,oe,Xe,2);bt?be.appendChild(bt):be.textContent=ii}else be.textContent=ii;be.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Nn?(be.style.backgroundColor=Nn,be.classList.remove("persona-bg-persona-primary")):(be.style.backgroundColor="",be.classList.add("persona-bg-persona-primary"))}else be.textContent=o.copy?.sendButtonLabel??"Send",be.style.width="",be.style.height="",be.style.minWidth="",be.style.minHeight="",be.style.fontSize="",be.style.lineHeight="",be.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",Nn?(be.style.backgroundColor=Nn,be.classList.remove("persona-bg-persona-accent")):be.classList.add("persona-bg-persona-accent"),Po?be.style.color=Po:be.classList.add("persona-text-white");Ft.borderWidth?(be.style.borderWidth=Ft.borderWidth,be.style.borderStyle="solid"):(be.style.borderWidth="",be.style.borderStyle=""),Ft.borderColor?be.style.borderColor=Ft.borderColor:be.style.borderColor="",Ft.paddingX?(be.style.paddingLeft=Ft.paddingX,be.style.paddingRight=Ft.paddingX):(be.style.paddingLeft="",be.style.paddingRight=""),Ft.paddingY?(be.style.paddingTop=Ft.paddingY,be.style.paddingBottom=Ft.paddingY):(be.style.paddingTop="",be.style.paddingBottom="");let Qr=bn?.querySelector(".persona-send-button-tooltip");if(ol&&Gr)if(Qr)Qr.textContent=Gr,Qr.style.display="";else{let oe=document.createElement("div");oe.className="persona-send-button-tooltip",oe.textContent=Gr,bn?.insertBefore(oe,be)}else Qr&&(Qr.style.display="none");let ai=o.layout?.contentMaxWidth??(R()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);ai?(Se.style.maxWidth=ai,Se.style.marginLeft="auto",Se.style.marginRight="auto",Se.style.width="100%",Z&&(Z.style.maxWidth=ai,Z.style.marginLeft="auto",Z.style.marginRight="auto"),Ct&&(Ct.style.maxWidth=ai,Ct.style.marginLeft="auto",Ct.style.marginRight="auto")):(Se.style.maxWidth="",Se.style.marginLeft="",Se.style.marginRight="",Se.style.width="",Z&&(Z.style.maxWidth="",Z.style.marginLeft="",Z.style.marginRight=""),Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""));let no=o.statusIndicator??{},rm=no.visible??!0;if(k.style.display=rm?"":"none",V){let oe=V.getStatus();Pt(k,(bt=>bt==="idle"?no.idleText??Bt.idle:bt==="connecting"?no.connectingText??Bt.connecting:bt==="connected"?no.connectedText??Bt.connected:bt==="error"?no.errorText??Bt.error:Bt[bt])(oe),no,oe)}k.classList.remove("persona-text-left","persona-text-center","persona-text-right");let sm=no.align==="left"?"persona-text-left":no.align==="center"?"persona-text-center":"persona-text-right";k.classList.add(sm)},open(){L()&&mt(!0,"api")},close(){L()&&mt(!1,"api")},toggle(){L()&&mt(!H,"api")},reconnect(){V.reconnectNow()},clearChat(){Rn=!1,V.clearMessages(),wo.clear(),Yn();try{localStorage.removeItem(Sr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Sr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Sr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let a=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(a),c?.clear&&_a(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),d={},T.syncFromMetadata(),Te?.clear(),Fe?.reset(),Le?.update()},setMessage(a){return!Ae||V.isStreaming()?!1:(!H&&L()&&mt(!0,"system"),Ae.value=a,Ae.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(a){if(V.isStreaming())return!1;let g=a?.trim()||Ae.value.trim();return g?(!H&&L()&&mt(!0,"system"),Ae.value="",Ae.style.height="auto",V.sendMessage(g),!0):!1},startVoiceRecognition(){return V.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(V.isVoiceActive()||(!H&&L()&&mt(!0,"system"),Ye.manuallyDeactivated=!1,wn(),V.toggleVoice().then(()=>{Ye.active=V.isVoiceActive(),Hn("user"),V.isVoiceActive()&&Yo()})),!0):kn?!0:ud()?(!H&&L()&&mt(!0,"system"),Ye.manuallyDeactivated=!1,wn(),ei("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?V.isVoiceActive()?(V.toggleVoice().then(()=>{Ye.active=!1,Ye.manuallyDeactivated=!0,wn(),Hn("user"),Dn()}),!0):!1:kn?(Ye.manuallyDeactivated=!0,wn(),eo("user"),!0):!1},injectMessage(a){return!H&&L()&&mt(!0,"system"),V.injectMessage(a)},injectAssistantMessage(a){!H&&L()&&mt(!0,"system");let g=V.injectAssistantMessage(a);return ne&&(ne=!1,de&&(clearTimeout(de),de=null),setTimeout(()=>{V&&!V.isStreaming()&&V.continueConversation()},100)),g},injectUserMessage(a){return!H&&L()&&mt(!0,"system"),V.injectUserMessage(a)},injectSystemMessage(a){return!H&&L()&&mt(!0,"system"),V.injectSystemMessage(a)},injectMessageBatch(a){return!H&&L()&&mt(!0,"system"),V.injectMessageBatch(a)},injectComponentDirective(a){return!H&&L()&&mt(!0,"system"),V.injectComponentDirective(a)},injectTestMessage(a){!H&&L()&&mt(!0,"system"),V.injectTestEvent(a)},async connectStream(a,g){return V.connectStream(a,g)},__pushEventStreamEvent(a){Te&&(Fe?.processEvent(a.type,a.payload),Te.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:a.type,timestamp:Date.now(),payload:JSON.stringify(a.payload)}))},showEventStream(){!G||!Te||Ea()},hideEventStream(){Ge&&kr()},isEventStreamVisible(){return Ge},showArtifacts(){Yt(o)&&(Rn=!1,jo=!0,Wn(),nt?.setMobileOpen(!0))},hideArtifacts(){Yt(o)&&(Rn=!0,Wn())},upsertArtifact(a){return Yt(o)?(Wo(o.features?.artifacts,a.artifactType)==="panel"&&(Rn=!1,jo=!0),V.upsertArtifact(a)):null},selectArtifact(a){Yt(o)&&V.selectArtifact(a)},clearArtifacts(){Yt(o)&&V.clearArtifacts()},getArtifacts(){return V?.getArtifacts()??[]},getSelectedArtifactId(){return V?.getSelectedArtifactId()??null},focusInput(){return A&&!H&&!R()||!Ae?!1:(Ae.focus(),!0)},async resolveApproval(a,g,y){let E=V.getMessages().find(B=>B.variant==="approval"&&B.approval?.id===a);if(!E?.approval)throw new Error(`Approval not found: ${a}`);if(E.approval.toolType==="webmcp"){V.resolveWebMcpApproval(E.id,g);return}return V.resolveApproval(E.approval,g,y)},getMessages(){return V.getMessages()},getStatus(){return V.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(a){C(a)},on(a,g){return l.on(a,g)},off(a,g){l.off(a,g)},isOpen(){return L()&&H},isVoiceActive(){return Ye.active},toggleReadAloud(a){V.toggleReadAloud(a)},stopReadAloud(){V.stopSpeaking()},getReadAloudState(a){return V.getReadAloudState(a)},onReadAloudChange(a){return V.onReadAloudChange(a)},getState(){return{open:L()&&H,launcherEnabled:A,voiceActive:Ye.active,streaming:V.isStreaming()}},showCSATFeedback(a){!H&&L()&&mt(!0,"system");let g=Se.querySelector(".persona-feedback-container");g&&g.remove();let y=Jf({onSubmit:async(x,E)=>{V.isClientTokenMode()&&await V.submitCSATFeedback(x,E),a?.onSubmit?.(x,E)},onDismiss:a?.onDismiss,...a});Se.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(a){!H&&L()&&mt(!0,"system");let g=Se.querySelector(".persona-feedback-container");g&&g.remove();let y=Yf({onSubmit:async(x,E)=>{V.isClientTokenMode()&&await V.submitNPSFeedback(x,E),a?.onSubmit?.(x,E)},onDismiss:a?.onDismiss,...a});Se.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(a,g){return V.submitCSATFeedback(a,g)},async submitNPSFeedback(a,g){return V.submitNPSFeedback(a,g)},destroy(){Ga(),Mo!=null&&(clearInterval(Mo),Mo=null),Ve.forEach(a=>a()),De.remove(),Je?.remove(),zt?.destroy(),Kt?.remove(),Co&&S.removeEventListener("click",Co)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let a=window.AgentWidgetBrowser,g={controller:Ht,getMessages:Ht.getMessages,getStatus:Ht.getStatus,getMetadata:Ht.getPersistentMetadata,updateMetadata:Ht.updatePersistentMetadata,clearHistory:()=>Ht.clearChat(),setVoiceActive:y=>y?Ht.startVoiceRecognition():Ht.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Ve.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=a)})}if(typeof window<"u"){let a=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),g=q=>{let J=q.detail;(!J?.instanceId||J.instanceId===a)&&Ht.focusInput()};if(window.addEventListener("persona:focusInput",g),Ve.push(()=>{window.removeEventListener("persona:focusInput",g)}),G){let q=le=>{let ge=le.detail;(!ge?.instanceId||ge.instanceId===a)&&Ht.showEventStream()},J=le=>{let ge=le.detail;(!ge?.instanceId||ge.instanceId===a)&&Ht.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",J),Ve.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",J)})}let y=q=>{let J=q.detail;(!J?.instanceId||J.instanceId===a)&&Ht.showArtifacts()},x=q=>{let J=q.detail;(!J?.instanceId||J.instanceId===a)&&Ht.hideArtifacts()},E=q=>{let J=q.detail;J?.instanceId&&J.instanceId!==a||J?.artifact&&Ht.upsertArtifact(J.artifact)},B=q=>{let J=q.detail;J?.instanceId&&J.instanceId!==a||typeof J?.id=="string"&&Ht.selectArtifact(J.id)},Y=q=>{let J=q.detail;(!J?.instanceId||J.instanceId===a)&&Ht.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",E),window.addEventListener("persona:selectArtifact",B),window.addEventListener("persona:clearArtifacts",Y),Ve.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",E),window.removeEventListener("persona:selectArtifact",B),window.removeEventListener("persona:clearArtifacts",Y)})}let gn=xv(o.persistState);if(gn&&L()){let a=Cv(gn.storage),g=`${gn.keyPrefix}widget-open`,y=`${gn.keyPrefix}widget-voice`,x=`${gn.keyPrefix}widget-voice-mode`;if(a){let E=gn.persist?.openState&&a.getItem(g)==="true",B=gn.persist?.voiceState&&a.getItem(y)==="true",Y=gn.persist?.voiceState&&a.getItem(x)==="true";if(E&&setTimeout(()=>{Ht.open(),setTimeout(()=>{if(B||Y)Ht.startVoiceRecognition();else if(gn.persist?.focusInput){let q=t.querySelector("textarea");q&&q.focus()}},100)},0),gn.persist?.openState&&(l.on("widget:opened",()=>{a.setItem(g,"true")}),l.on("widget:closed",()=>{a.setItem(g,"false")})),gn.persist?.voiceState&&(l.on("voice:state",q=>{a.setItem(y,q.active?"true":"false")}),l.on("user:message",q=>{a.setItem(x,q.viaVoice?"true":"false")})),gn.clearOnChatClear){let q=()=>{a.removeItem(g),a.removeItem(y),a.removeItem(x)},J=()=>q();window.addEventListener("persona:clear-chat",J),Ve.push(()=>{window.removeEventListener("persona:clear-chat",J)})}}}if(b&&L()&&setTimeout(()=>{Ht.open()},0),Qo(),!wg){let a=di(()=>{V&&(Ha++,wo.clear(),Or(Se,V.getMessages(),ue))});Ve.push(a)}return Ht};var og=(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},Sv=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},Mv=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},Tv=(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.")},rg=(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"},Ac=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=""},sg=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",Ac(t)},xc=t=>{t.style.transition=""},Cc=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=""},wc=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},Sa=(t,e)=>{t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},Ev=(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))},kv=(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)},Lv=t=>{let e=mr(t),n=e.components?.panel,o=(r,s)=>r==null||r===""?s:Xt(e,r)??r;return{inset:o(n?.inset,Vi),canvasBackground:o(n?.canvasBackground,Ki)}},ig=(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},Pv=(t,e,n,o,r,s,i,l)=>{let p=hn(s),c=p.reveal==="push",d=l!=null,u=l?.inset??"",b=l?.canvasBackground??"";Ev(t,e,n,o,c),kv(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.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let f=t.ownerDocument.defaultView,m=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,I=f!=null?f.innerWidth<=C:!1;if(m&&I&&i){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),Cc(e),xc(o),sg(o),wc(n),Sa(r,o),ig(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"),sg(o),Sv(o,p.maxHeight),ig(o,d&&i,u,b),p.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",Cc(e),xc(o),wc(n),Sa(r,o);let T=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=T,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",xc(o),Ac(o),Sa(r,o);let T=og(p.width,t.clientWidth),A=Math.max(0,t.clientWidth),W=p.animate?"margin-left 180ms ease":"none",z=p.side==="right"?i?-T:0:i?0:-T;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+T}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="",Cc(e),Ac(o),wc(n),Sa(r,o);let T=p.reveal==="emerge";T?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",Mv(o,p.maxHeight),o.style.overflow=T||z?"hidden":"visible",o.style.transition=W,T){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let U=d?`calc(${og(p.width,t.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=U,r.style.minWidth=U,r.style.maxWidth=U,r.style.boxSizing="border-box"}}},Iv=(t,e)=>{let n=t.ownerDocument.createElement("div");return rg(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){rg(n,o)},destroy(){n.remove()}}},Rv=(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 b=null,f=()=>{b?.disconnect(),b=null},m=null,C=()=>{m=e?.launcher?.detachedPanel===!0?Lv(e):null};C();let I=()=>{Pv(i,l,p,c,d,e,u,m)},D=null,T=()=>{D?.(),D=null,!(e?.launcher?.detachedPanel!==!0||e?.colorScheme!=="auto")&&(D=Gi(()=>{C(),I()}))},A=()=>{f(),hn(e).reveal==="push"&&(typeof ResizeObserver>"u"||(b=new ResizeObserver(()=>{I()}),b.observe(i)))},W=!1,z=()=>{I(),A(),u&&!W&&i.dataset.personaDockMobileFullscreen!=="true"&&(W=!0,Tv(i,hn(e)))},U=i.ownerDocument.defaultView,w=()=>{z()};return U?.addEventListener("resize",w),hn(e).reveal==="push"?(l.appendChild(p),l.appendChild(c),i.appendChild(l)):(i.appendChild(p),i.appendChild(c)),z(),T(),{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(),T()},destroy(){U?.removeEventListener("resize",w),D?.(),D=null,f(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(t,s):o.appendChild(t)),i.remove()}}},ag=(t,e)=>$t(e)?Rv(t,e):Iv(t,e);var Ds={desktop:{w:1280,h:800},mobile:{w:390,h:844}},lg=.15,cg=1.5,Sc="persona-preview-shell-theme",Wv={load:()=>null,save:()=>{},clear:()=>{}},Hv=["How do I get started?","Pricing & plans","Talk to support"];function Mc(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Bv(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 dg(t){let e=Bv(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}; }
|
|
@@ -334,7 +334,7 @@ _Details: ${n.message}_`:o}var ls=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
334
334
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
335
335
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
336
336
|
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
|
|
337
|
-
.preview-workspace-card.short { height: 96px; }`}function
|
|
337
|
+
.preview-workspace-card.short { height: 96px; }`}function pg(t,e){let n=t.contentDocument;if(!n?.documentElement)return;let o=n.getElementById(Sc);o||(o=n.createElement("style"),o.id=Sc,n.head.appendChild(o)),o.textContent=dg(e)}var Dv=`
|
|
338
338
|
<div class="preview-iframe-mock" aria-hidden="true">
|
|
339
339
|
<div class="preview-iframe-chrome">
|
|
340
340
|
<span class="preview-iframe-dot"></span>
|
|
@@ -353,7 +353,7 @@ _Details: ${n.message}_`:o}var ls=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
353
353
|
<div class="preview-iframe-line body"></div>
|
|
354
354
|
<div class="preview-iframe-line body"></div>
|
|
355
355
|
</div>
|
|
356
|
-
</div>`,
|
|
356
|
+
</div>`,Nv=`
|
|
357
357
|
<div class="preview-workspace-content-shell" aria-hidden="true">
|
|
358
358
|
<div class="preview-iframe-line hero"></div>
|
|
359
359
|
<div class="preview-iframe-line body"></div>
|
|
@@ -366,8 +366,8 @@ _Details: ${n.message}_`:o}var ls=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
366
366
|
<div class="preview-workspace-card short"></div>
|
|
367
367
|
<div class="preview-workspace-card short"></div>
|
|
368
368
|
</div>
|
|
369
|
-
</div>`;function
|
|
370
|
-
${
|
|
369
|
+
</div>`;function ug(t,e,n,o){let r=`
|
|
370
|
+
${Dv}
|
|
371
371
|
<div style="position:fixed;inset:0;z-index:9999;"><div id="${t}" data-mount-id="${t}"></div></div>`,s=`
|
|
372
372
|
<div class="preview-workspace-shell">
|
|
373
373
|
<div class="preview-workspace-topbar">
|
|
@@ -379,7 +379,7 @@ _Details: ${n.message}_`:o}var ls=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
379
379
|
</div>
|
|
380
380
|
<div class="preview-workspace-body">
|
|
381
381
|
<div id="preview-content-${t}" class="preview-workspace-content" data-mount-id="${t}">
|
|
382
|
-
${
|
|
382
|
+
${Nv}
|
|
383
383
|
</div>
|
|
384
384
|
</div>
|
|
385
385
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -387,16 +387,16 @@ _Details: ${n.message}_`:o}var ls=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
387
387
|
<head>
|
|
388
388
|
<meta charset="UTF-8">
|
|
389
389
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
390
|
-
<link rel="stylesheet" href="${
|
|
391
|
-
<style id="${
|
|
390
|
+
<link rel="stylesheet" href="${Mc(o)}">
|
|
391
|
+
<style id="${Sc}">${dg(e)}</style>
|
|
392
392
|
</head>
|
|
393
393
|
<body>
|
|
394
394
|
${n?s:r}
|
|
395
395
|
</body>
|
|
396
|
-
</html>`}var
|
|
397
|
-
${z?`<div class="preview-frame-meta"><span class="preview-frame-label">${
|
|
398
|
-
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${
|
|
399
|
-
</div>`,
|
|
396
|
+
</html>`}var Ov=()=>[{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()}],Fv=t=>!!(t?.features?.toolCallDisplay?.activePreview||t?.features?.toolCallDisplay?.grouped||t?.features?.toolCallDisplay?.collapsedMode&&t.features.toolCallDisplay.collapsedMode!=="tool-call"||t?.features?.reasoningDisplay?.activePreview);function _v(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"&&Fv(e)?[...Ov(),...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 $v(t,e,n=[]){let o={...t.launcher,enabled:!0,autoExpand:e!=="minimized"},r={...t,launcher:o,suggestionChips:e==="home"?t.suggestionChips?.length?t.suggestionChips:Hv:t.suggestionChips,initialMessages:_v(e,t,n),storageAdapter:Wv};return e==="artifact"&&(r.features={...r.features,artifacts:{...r.features?.artifacts,enabled:!0}}),r}function zv(t,e){let n=t.theme?gr(t.theme,{validate:!1}):gr();return{...pt,...t.config,theme:n,darkTheme:t.darkTheme,colorScheme:e??t.config?.colorScheme??"light"}}function Mr(t,e){let n=t.scene??"conversation";return $v(zv(t,e),n,t.appendedMessages??[])}function fg(t){let e=t.compareMode??"off",n=t.shellMode??"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:Mr(t,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Mr(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:Mr(o,n),shellMode:n},{mountId:"preview-current",label:"Current",config:Mr(t,n),shellMode:n}]}return[{mountId:"preview-current",label:"Current",config:Mr(t,n),shellMode:n}]}function gg(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 b(){let T=getComputedStyle(t),A=parseFloat(T.paddingLeft)+parseFloat(T.paddingRight),W=parseFloat(T.paddingTop)+parseFloat(T.paddingBottom),z=40,U=(n.compareMode??"off")!=="off",w=(t.clientWidth-A-z)/(U?2:1),O=t.clientHeight-W-z;if(w<=0||O<=0)return 1;let N=Ds[d()]??Ds.desktop;return Math.min(w/N.w,O/N.h,1)}function f(){l=b();let T=Math.max(lg,Math.min(cg,u()));p=T;let A=Array.from(t.querySelectorAll(".preview-iframe-wrapper"));for(let W of A){let z=W.dataset.device??"desktop",U=Ds[z]??Ds.desktop;W.style.width=`${U.w*T}px`,W.style.height=`${U.h*T}px`,z==="mobile"&&(W.style.borderRadius=`${32*T}px`);let w=W.querySelector("iframe");w&&(w.style.width=`${U.w}px`,w.style.height=`${U.h}px`,w.style.transformOrigin="top left",w.style.transition="none",w.style.transform=`scale(${T})`)}n.onScaleChange?.(T)}function m(){n.onBeforeDestroy?.();for(let T of o)T.destroy();for(let T of r)T();o=[],r=[]}function C(){return Array.from(t.querySelectorAll("iframe[data-mount-id]"))}function I(){if(i)return;m();let T=++c,A=fg(n),W=d(),z=(n.compareMode??"off")!=="off",U=(n.scene??"conversation")==="minimized",w=n.widgetCssPath??"/widget-dist/widget.css",O=n.buildSrcdoc??ug,N=W==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",R=ue=>`<div class="${N}" data-mount-id="${ue.mountId}" data-device="${W}" data-shell-mode="${ue.shellMode}">
|
|
397
|
+
${z?`<div class="preview-frame-meta"><span class="preview-frame-label">${Mc(ue.label)}</span></div>`:""}
|
|
398
|
+
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${ue.mountId}"></iframe>
|
|
399
|
+
</div>`,L=z?`<div class="preview-compare-grid">${A.map(ue=>`<div class="preview-compare-cell">${R(ue)}</div>`).join("")}</div>`:`<div class="preview-single">${R(A[0])}</div>`;n.morphContainer?n.morphContainer(t,L):t.innerHTML=L,f();let H=C(),ne=0,de=H.length,me=()=>{if(i||T!==c)return;for(let ee of H){let re=ee.dataset.mountId;if(!re||!ee.contentDocument)continue;let G=A.find(fe=>fe.mountId===re);if(!G)continue;let ie=()=>{},te=$t(G.config),ye=te?(()=>{let fe=ee.contentDocument?.getElementById(`preview-content-${re}`);if(!fe)return null;let Ee=ag(fe,G.config),Te=ee.contentDocument.createElement("div");Te.id=re,Te.style.height="100%",Te.style.display="flex",Te.style.flexDirection="column",Te.style.flex="1",Te.style.minHeight="0",Ee.host.appendChild(Te);let Fe=()=>Ee.syncWidgetState(ve.getState()),Le=ie;return ie=()=>{Ee.destroy(),Le()},Te.__syncDock=Fe,Te.__hostLayout=Ee,Te})():ee.contentDocument.getElementById(re);if(!ye)continue;let ve=ng(ye,G.config);if(o.push(ve),te&&ye.__syncDock){let fe=ye.__syncDock,Ee=ve.on("widget:opened",fe),Te=ve.on("widget:closed",fe),Fe=ie;ie=()=>{Ee(),Te(),Fe()},fe()}r.push(ie),U&&ve.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:H,controllers:[...o]})};for(let
|
|
407
|
+
- Resizable panes`,transcript:!1});n.onAfterMount?.({iframes:H,controllers:[...o]})};for(let ue of H){let ee=ue.dataset.mountId;if(!ee)continue;let re=A.find(G=>G.mountId===ee);re&&(ue.addEventListener("load",()=>{ne++,ne>=de&&me()},{once:!0}),ue.srcdoc=O(ee,re.shellMode,$t(re.config),w))}de===0&&me()}function D(){if(i)return;let T=fg(n);if(o.length!==T.length){I();return}if(T.some(W=>{let z=t.querySelector(`.preview-iframe-wrapper[data-mount-id="${W.mountId}"]`);return!z||z.dataset.shellMode!==W.shellMode})){I();return}o.forEach((W,z)=>{W.update(T[z].config),(n.scene??"conversation")==="minimized"&&W.close()});for(let W of T){let z=t.querySelector(`iframe[data-mount-id="${W.mountId}"]`);z&&pg(z,W.shellMode)}n.onAfterUpdate?.({iframes:C(),controllers:[...o]})}return typeof ResizeObserver<"u"&&(s=new ResizeObserver(()=>{i||f()}),s.observe(t)),I(),{update(T){if(i)return;let A=T.device!==void 0&&T.device!==n.device||T.scene!==void 0&&T.scene!==n.scene||T.compareMode!==void 0&&T.compareMode!==n.compareMode||T.widgetCssPath!==void 0&&T.widgetCssPath!==n.widgetCssPath;n={...n,...T},A?I():D()},destroy(){i||(i=!0,m(),s?.disconnect(),t.innerHTML="")},getControllers(){return[...o]},fitToContainer(){i||(n={...n,zoom:void 0},f())},getIframes(){return C()},getScale(){return p},setZoom(T){i||(n={...n,zoom:T},f())}}}0&&(module.exports={createThemePreview});
|