@runtypelabs/persona 4.11.1 → 4.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,36 +1,36 @@
1
- var em=Object.defineProperty;var ir=(e,t)=>()=>(e&&(t=e(e=0)),t);var Zi=(e,t)=>{for(var n in t)em(e,n,{get:t[n],enumerable:!0})};var Bd={};Zi(Bd,{DOMPurify:()=>nm,Marked:()=>tm});import{Marked as tm}from"marked";import nm from"dompurify";var Od=ir(()=>{"use strict"});var gr,vl=ir(()=>{"use strict";gr=class{constructor(t=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=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*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 t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let r=new Uint8Array(this.remainder.length+t.length);r.set(this.remainder),r.set(t,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 t of this.activeSources)try{t.stop(),t.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(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}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 t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}r.onended=()=>{let a=this.activeSources.indexOf(r);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function Ah(e){return e.replace(/\/+$/,"")}async function Sh(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Ma,Op=ir(()=>{"use strict";vl();Ma=class{constructor(t){this.opts=t;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 gr(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(t=>this.player=t))}speak(t,n){let o=++this.generation;this.run(o,t,n)}async run(t,n,o){try{let r=await this.ensurePlayer();if(t!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.generation&&o.onStart?.()}),r.onFinished(()=>{t===this.generation&&o.onEnd?.()});let s=`${Ah(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!a.ok||!a.body)throw new Error(await Sh(a));let i=a.body.getReader();for(;;){let{done:p,value:d}=await i.read();if(t!==this.generation){await i.cancel().catch(()=>{});return}if(p)break;d&&d.byteLength>0&&r.enqueue(d)}r.markStreamEnd()}catch(r){if(t!==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 ka,Dp=ir(()=>{"use strict";ka=class{constructor(t,n,o={}){this.primary=t;this.fallback=n;this.options=o;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let o=!1;this.primary.speak(t,{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(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var Np={};Zi(Np,{FallbackSpeechEngine:()=>ka,RuntypeSpeechEngine:()=>Ma});var Fp=ir(()=>{"use strict";Op();Dp()});var $p={};Zi($p,{createReconnectController:()=>Eh});function Eh(e){let t=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let y=n;n=null,y()}},a=()=>{let y=e.getStatus();y!=="resuming"&&y!=="paused"||s()},i=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},p=()=>{a()},d=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",i),typeof window<"u"&&window.addEventListener("online",p),r=!0)},c=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",i),typeof window<"u"&&window.removeEventListener("online",p),r=!1)},u=y=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},y)}),b=()=>{let y=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,c(),e.setAbortController(null);let C=!1;for(let L of e.getMessages())L.streaming&&(L.streaming=!1,C=!0);let M=e.buildErrorContent("Connection lost and the response could not be resumed.");M?e.appendMessage({id:`reconnect-failed-${y?.executionId??e.nextSequence()}`,role:"assistant",content:M,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):C&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},g=async()=>{let y=e.config.reconnect?.backoffMs??Th,C=e.config.reconnect?.maxAttempts??y.length,M=e.config.reconnectStream;if(!M){e.setReconnecting(!1);return}for(;e.getResumable()&&t<C;){t+=1,e.setStatus("resuming");let L=e.getResumable(),I=L.lastEventId,S=new AbortController;e.setAbortController(S),e.emitReconnect({phase:"resuming",handle:L,attempt:t});let R=null;try{let $=await M({executionId:L.executionId,after:L.lastEventId,signal:S.signal});$&&$.ok&&$.body&&(R=$.body)}catch{R=null}if(S.signal.aborted)return;if(R){let $=e.getMessages().find(w=>w.id===L.assistantMessageId)?.content,z=typeof $=="string"?$:"";try{await e.resumeConnect(R,L.assistantMessageId,z)}catch{}if(S.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:L});return}e.getResumable().lastEventId!==I&&(t=0)}if(e.getResumable()&&t<C&&(e.setStatus("paused"),await u(y[Math.min(t-1,y.length-1)]??1e3),S.signal.aborted))return}e.getResumable()&&b()};return{begin(){t=0,d(),g()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,c()},wake:s}}var Th,jp=ir(()=>{"use strict";Th=[1e3,2e3,4e3,8e3,8e3]});import{Marked as sm}from"marked";import am from"dompurify";var lr=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:c=>{o=c,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(u=>(r=u,u)).catch(u=>{throw s=null,u}),s),provide:c=>{r=c},getSync:()=>r}};var{setLoader:Dw,load:om,provide:rm,getSync:el}=lr({fallbackImport:()=>Promise.resolve().then(()=>(Od(),Bd))}),da=new Set,Dd=()=>{let e=[...da];da.clear();for(let t of e)try{t()}catch{}};var Nd=()=>{let e=el();return e?Promise.resolve(e):om().then(t=>(Dd(),t))},Yr=e=>el()?()=>{}:(da.add(e),Nd().catch(()=>{}),()=>{da.delete(e)}),Fd=e=>{rm(e),Dd()},Fn=el;Fd({Marked:sm,DOMPurify:am});var im=e=>{if(e)return e},pa=e=>{let t=null;return n=>{let o=Fn();if(!o)return _n(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=im(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},cr=e=>e?pa({markedOptions:e.options,renderer:e.renderer}):pa(),lm=pa(),$d=e=>lm(e),_n=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),jd=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),_d=e=>`%%FORM_PLACEHOLDER_${e}%%`,Ud=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=_d(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=_d(t.length);return t.push({token:s,type:r}),s}),n},cm=e=>{let t=cr(e);return n=>{let o=[],r=Ud(n,o),s=t(r);return o.forEach(({token:a,type:i})=>{let p=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${jd(i)}"></div>`;s=s.replace(p,c)}),s}},dm=e=>{let t=[],n=Ud(e,t),o=$d(n);return t.forEach(({token:r,type:s})=>{let a=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${jd(s)}"></div>`;o=o.replace(a,p)}),o};var pm={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"]},um=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,zd=()=>{let e=null;return t=>{let n=Fn();if(!n)return _n(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!um.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,pm)}},Zr=e=>e===!1?null:typeof e=="function"?e:zd();var qd=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Vd=e=>e.includes("|"),Kd=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},gm=e=>`| ${e.join(" | ")} |`,fm=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,mm=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Gd=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
- `),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!Vd(r)||qd.test(r)||!qd.test(s))continue;let a=Kd(r).length;if(a<1)continue;let i=fm(a);t[o+1]!==i&&(t[o+1]=i,n=!0);let p=o+2;for(;p<t.length;p++){let d=t[p];if(d.trim()===""||!Vd(d))break;let c=gm(mm(Kd(d),a));t[p]!==c&&(t[p]=c,n=!0)}o=p-1}return n?t.join(`
3
- `):e};var Jd="var(--persona-md-table-scroll-fade, 24px)",Xd=new WeakSet;function Yd(e){e.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function Qd(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":Jd),e.style.setProperty("--persona-fade-r",r<=1?"0px":Jd)}function tl(e){Xd.has(e)||(Xd.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&Qd(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Qd)}var En="webmcp:",nl=new Map,Zd=e=>{nl.clear();for(let t of e){let n=t.title?.trim();n&&nl.set(t.name,n)}},ts=e=>nl.get(ol(e)),ua={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},ep=null;function np(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${hm(t.join(""))}`}function tp(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.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 hm(e){let t=tp(e,0).toString(36),n=tp(e,2654435761).toString(36);return`${t}.${n}`}var es=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return ua.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}Zd(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=bm(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return xn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let y=typeof document<"u"&&!!document.modelContext;return xn(y?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=ol(t),a;try{a=await r.getTools()}catch(y){let C=y instanceof Error?y.message:String(y);return xn(`Failed to read WebMCP registry: ${C}`)}Zd(a);let i=a.find(y=>y.name===s);if(!i)return xn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return xn(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return xn("Aborted by cancel()");let p=ts(s),d={toolName:s,args:n,description:i.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return xn("User declined the tool call.");if(o?.aborted)return xn("Aborted by cancel()");let c=new AbortController,u=!1,b=setTimeout(()=>{u=!0,c.abort()},this.timeoutMs),g=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",g,{once:!0}));try{let y=await r.executeTool(i,wm(n),{signal:c.signal});return vm(y)}catch(y){if(u)return xn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return xn("Aborted by cancel()");let C=y instanceof Error?y.message:String(y);return xn(C)}finally{clearTimeout(b),o&&o.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(ep?await ep():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){ua.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ua.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):t}async requestConfirm(t){let n=this.confirmHandler??xm;try{return await n(t)}catch(o){return ua.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>ym(t,o))}},ol=e=>e.startsWith(En)?e.slice(En.length):e,Ho=e=>e.startsWith(En),ym=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},bm=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},vm=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Am(t)}]}},xn=e=>({isError:!0,content:[{type:"text",text:e}]}),xm=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=Cm(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ var tm=Object.defineProperty;var ir=(e,t)=>()=>(e&&(t=e(e=0)),t);var Zi=(e,t)=>{for(var n in t)tm(e,n,{get:t[n],enumerable:!0})};var Od={};Zi(Od,{DOMPurify:()=>om,Marked:()=>nm});import{Marked as nm}from"marked";import om from"dompurify";var Dd=ir(()=>{"use strict"});var gr,vl=ir(()=>{"use strict";gr=class{constructor(t=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=t;let o=Math.max(0,n.prebufferMs??0);this.waterlineSamples=Math.round(t*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 t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let r=new Uint8Array(this.remainder.length+t.length);r.set(this.remainder),r.set(t,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 t of this.activeSources)try{t.stop(),t.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(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}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 t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),o=n.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let r=n.createBufferSource();r.buffer=o,r.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),r.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(r),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}r.onended=()=>{let a=this.activeSources.indexOf(r);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),o=new Float32Array(n),r=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=r.getInt16(s*2,!0);o[s]=a/32768}return o}}});function Sh(e){return e.replace(/\/+$/,"")}async function Th(e){try{let t=await e.json();return t.detail?`${t.error??`Runtype TTS ${e.status}`}: ${t.detail}`:t.error??`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Ma,Dp=ir(()=>{"use strict";vl();Ma=class{constructor(t){this.opts=t;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 gr(24e3,{prebufferMs:this.opts.prebufferMs??200})).then(t=>this.player=t))}speak(t,n){let o=++this.generation;this.run(o,t,n)}async run(t,n,o){try{let r=await this.ensurePlayer();if(t!==this.generation)return;r.flush(),r.resume(),r.onStarted(()=>{t===this.generation&&o.onStart?.()}),r.onFinished(()=>{t===this.generation&&o.onEnd?.()});let s=`${Sh(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:n.voice??this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!a.ok||!a.body)throw new Error(await Th(a));let i=a.body.getReader();for(;;){let{done:p,value:d}=await i.read();if(t!==this.generation){await i.cancel().catch(()=>{});return}if(p)break;d&&d.byteLength>0&&r.enqueue(d)}r.markStreamEnd()}catch(r){if(t!==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 ka,Np=ir(()=>{"use strict";ka=class{constructor(t,n,o={}){this.primary=t;this.fallback=n;this.options=o;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let o=!1;this.primary.speak(t,{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(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){this.primary.destroy?.(),this.fallback.destroy?.()}}});var Fp={};Zi(Fp,{FallbackSpeechEngine:()=>ka,RuntypeSpeechEngine:()=>Ma});var _p=ir(()=>{"use strict";Dp();Np()});var jp={};Zi(jp,{createReconnectController:()=>Mh});function Mh(e){let t=0,n=null,o=null,r=!1,s=()=>{if(o&&(clearTimeout(o),o=null),n){let y=n;n=null,y()}},a=()=>{let y=e.getStatus();y!=="resuming"&&y!=="paused"||s()},i=()=>{typeof document<"u"&&document.visibilityState==="hidden"||a()},p=()=>{a()},d=()=>{r||(typeof document<"u"&&document.addEventListener("visibilitychange",i),typeof window<"u"&&window.addEventListener("online",p),r=!0)},c=()=>{r&&(typeof document<"u"&&document.removeEventListener("visibilitychange",i),typeof window<"u"&&window.removeEventListener("online",p),r=!1)},u=y=>new Promise(C=>{n=C,o=setTimeout(()=>{o=null,n=null,C()},y)}),b=()=>{let y=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,c(),e.setAbortController(null);let C=!1;for(let L of e.getMessages())L.streaming&&(L.streaming=!1,C=!0);let M=e.buildErrorContent("Connection lost and the response could not be resumed.");M?e.appendMessage({id:`reconnect-failed-${y?.executionId??e.nextSequence()}`,role:"assistant",content:M,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):C&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},g=async()=>{let y=e.config.reconnect?.backoffMs??Eh,C=e.config.reconnect?.maxAttempts??y.length,M=e.config.reconnectStream;if(!M){e.setReconnecting(!1);return}for(;e.getResumable()&&t<C;){t+=1,e.setStatus("resuming");let L=e.getResumable(),I=L.lastEventId,S=new AbortController;e.setAbortController(S),e.emitReconnect({phase:"resuming",handle:L,attempt:t});let R=null;try{let $=await M({executionId:L.executionId,after:L.lastEventId,signal:S.signal});$&&$.ok&&$.body&&(R=$.body)}catch{R=null}if(S.signal.aborted)return;if(R){let $=e.getMessages().find(w=>w.id===L.assistantMessageId)?.content,z=typeof $=="string"?$:"";try{await e.resumeConnect(R,L.assistantMessageId,z)}catch{}if(S.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,c(),e.emitReconnect({phase:"resumed",handle:L});return}e.getResumable().lastEventId!==I&&(t=0)}if(e.getResumable()&&t<C&&(e.setStatus("paused"),await u(y[Math.min(t-1,y.length-1)]??1e3),S.signal.aborted))return}e.getResumable()&&b()};return{begin(){t=0,d(),g()},teardown(){o&&(clearTimeout(o),o=null),n=null,t=0,c()},wake:s}}var Eh,Up=ir(()=>{"use strict";Eh=[1e3,2e3,4e3,8e3,8e3]});import{Marked as am}from"marked";import im from"dompurify";var lr=e=>{let{fallbackImport:t,resetOnSetLoader:n=!1}=e,o=null,r=null,s=null;return{setLoader:c=>{o=c,n&&(r=null,s=null)},load:()=>r?Promise.resolve(r):s||(s=(o??t)().then(u=>(r=u,u)).catch(u=>{throw s=null,u}),s),provide:c=>{r=c},getSync:()=>r}};var{setLoader:Nw,load:rm,provide:sm,getSync:el}=lr({fallbackImport:()=>Promise.resolve().then(()=>(Dd(),Od))}),da=new Set,Nd=()=>{let e=[...da];da.clear();for(let t of e)try{t()}catch{}};var Fd=()=>{let e=el();return e?Promise.resolve(e):rm().then(t=>(Nd(),t))},Yr=e=>el()?()=>{}:(da.add(e),Fd().catch(()=>{}),()=>{da.delete(e)}),_d=e=>{sm(e),Nd()},Nn=el;_d({Marked:am,DOMPurify:im});var lm=e=>{if(e)return e},pa=e=>{let t=null;return n=>{let o=Nn();if(!o)return Fn(n);if(!t){let{Marked:r}=o,s=e?.markedOptions;t=new r({gfm:s?.gfm??!0,breaks:s?.breaks??!0,pedantic:s?.pedantic,silent:s?.silent});let a=lm(e?.renderer);a&&t.use({renderer:a})}return t.parse(n)}},cr=e=>e?pa({markedOptions:e.options,renderer:e.renderer}):pa(),cm=pa(),jd=e=>cm(e),Fn=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Ud=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),$d=e=>`%%FORM_PLACEHOLDER_${e}%%`,zd=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(o,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=$d(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return o}return o}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(o,r)=>{let s=$d(t.length);return t.push({token:s,type:r}),s}),n},dm=e=>{let t=cr(e);return n=>{let o=[],r=zd(n,o),s=t(r);return o.forEach(({token:a,type:i})=>{let p=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),c=`<div class="persona-form-directive" data-tv-form="${Ud(i)}"></div>`;s=s.replace(p,c)}),s}},pm=e=>{let t=[],n=zd(e,t),o=jd(n);return t.forEach(({token:r,type:s})=>{let a=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Ud(s)}"></div>`;o=o.replace(a,p)}),o};var um={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"]},gm=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,qd=()=>{let e=null;return t=>{let n=Nn();if(!n)return Fn(t);if(!e){let{DOMPurify:o}=n;e=o(typeof window<"u"?window:void 0),e.addHook("uponSanitizeAttribute",(r,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!gm.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,um)}},Zr=e=>e===!1?null:typeof e=="function"?e:qd();var Vd=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Kd=e=>e.includes("|"),Gd=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},fm=e=>`| ${e.join(" | ")} |`,mm=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,hm=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Jd=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
+ `),n=!1;for(let o=0;o<t.length-1;o++){let r=t[o],s=t[o+1];if(!Kd(r)||Vd.test(r)||!Vd.test(s))continue;let a=Gd(r).length;if(a<1)continue;let i=mm(a);t[o+1]!==i&&(t[o+1]=i,n=!0);let p=o+2;for(;p<t.length;p++){let d=t[p];if(d.trim()===""||!Kd(d))break;let c=fm(hm(Gd(d),a));t[p]!==c&&(t[p]=c,n=!0)}o=p-1}return n?t.join(`
3
+ `):e};var Xd="var(--persona-md-table-scroll-fade, 24px)",Qd=new WeakSet;function Zd(e){e.querySelectorAll("table").forEach(n=>{if(n.parentElement?.classList.contains("persona-table-scroll"))return;let r=document.createElement("div");r.className="persona-table-scroll",n.replaceWith(r),r.appendChild(n)})}function Yd(e){let t=e.scrollWidth-e.clientWidth;if(t<=1){e.removeAttribute("data-persona-scroll-x");return}e.setAttribute("data-persona-scroll-x","");let o=getComputedStyle(e).direction==="rtl"?t+e.scrollLeft:e.scrollLeft,r=t-o;e.style.setProperty("--persona-fade-l",o<=1?"0px":Xd),e.style.setProperty("--persona-fade-r",r<=1?"0px":Xd)}function tl(e){Qd.has(e)||(Qd.add(e),e.addEventListener("scroll",t=>{let n=t.target;n?.classList?.contains("persona-table-scroll")&&Yd(n)},!0)),e.querySelectorAll(".persona-table-scroll").forEach(Yd)}var Tn="webmcp:",nl=new Map,ep=e=>{nl.clear();for(let t of e){let n=t.title?.trim();n&&nl.set(t.name,n)}},ts=e=>nl.get(ol(e)),ua={warn(e,...t){typeof console<"u"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},tp=null;function op(e){if(e.length===0)return"0:empty";let t=e.map(n=>[n.name,n.description??"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",n.origin??"",n.annotations?JSON.stringify(n.annotations):""].join("")).sort();return`${e.length}:${ym(t.join(""))}`}function np(e,t){let n=3735928559^t,o=1103547991^t;for(let r=0;r<e.length;r++){let s=e.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 ym(e){let t=np(e,0).toString(36),n=np(e,2654435761).toString(36);return`${t}.${n}`}var es=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;this.confirmHandler=t.onConfirm??null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(r){return ua.warn("getTools() threw: shipping an empty WebMCP snapshot.",r),[]}ep(n);let o=typeof location<"u"?location.origin:"";return n.filter(r=>this.passesClientAllowlist(r.name)).map(r=>{let s={name:r.name,description:r.description,origin:"webmcp",...o?{pageOrigin:o}:{}},a=vm(r.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,o){if(await this.ensureReady(),this.config.enabled!==!0)return xn("WebMCP is not enabled on this widget.");let r=this.getModelContext();if(!r){let y=typeof document<"u"&&!!document.modelContext;return xn(y?"WebMCP is not operational: document.modelContext is present but does not expose the strict getTools()/executeTool() surface (likely a different or older WebMCP polyfill).":"WebMCP bridge is not operational on this page (document.modelContext not available).")}let s=ol(t),a;try{a=await r.getTools()}catch(y){let C=y instanceof Error?y.message:String(y);return xn(`Failed to read WebMCP registry: ${C}`)}ep(a);let i=a.find(y=>y.name===s);if(!i)return xn(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return xn(`WebMCP tool not allowed by client allowlist: ${s}`);if(o?.aborted)return xn("Aborted by cancel()");let p=ts(s),d={toolName:s,args:n,description:i.description,...p?{title:p}:{},reason:"gate"};if(!await this.requestConfirm(d))return xn("User declined the tool call.");if(o?.aborted)return xn("Aborted by cancel()");let c=new AbortController,u=!1,b=setTimeout(()=>{u=!0,c.abort()},this.timeoutMs),g=()=>c.abort();o&&(o.aborted?c.abort():o.addEventListener("abort",g,{once:!0}));try{let y=await r.executeTool(i,Am(n),{signal:c.signal});return xm(y)}catch(y){if(u)return xn(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(o?.aborted)return xn("Aborted by cancel()");let C=y instanceof Error?y.message:String(y);return xn(C)}finally{clearTimeout(b),o&&o.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(tp?await tp():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){ua.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document>"u")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,ua.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):t}async requestConfirm(t){let n=this.confirmHandler??Cm;try{return await n(t)}catch(o){return ua.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(o=>bm(t,o))}},ol=e=>e.startsWith(Tn)?e.slice(Tn.length):e,Ho=e=>e.startsWith(Tn),bm=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},vm=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},xm=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:Sm(t)}]}},xn=e=>({isError:!0,content:[{type:"text",text:e}]}),Cm=async e=>{if(typeof window>"u"||typeof window.confirm!="function")return!1;let t=wm(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
4
4
 
5
5
  Arguments:
6
6
  ${t}`:"")+(e.description?`
7
7
 
8
- ${e.description}`:"");return window.confirm(n)},Cm=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},wm=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Am=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function Bo(e,t){let n=e?.display;return n?typeof n=="string"?n:n.byType?.[t]??n.default??"panel":"panel"}function ga(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var Sm="agent_",Tm="flow_";function op(e){return e.startsWith(Sm)?{kind:"agentId",agentId:e}:e.startsWith(Tm)?{kind:"flowId",flowId:e}:null}function rp(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),i=n.slice(o+1);if(a==="runtype"){let d=op(i);if(d)return d;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[a];if(!p)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(i).payload}}let r=op(n);if(r)return r;let s=t?.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.`)}import{parse as Em,ARR as Mm,OBJ as km,STR as Lm}from"partial-json";var m=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var sp=()=>document.createDocumentFragment(),Fe=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))o.setAttribute(s,a);if(t.style){let s=o.style,a=t.style;for(let i of Object.keys(a)){let p=a[i];p!=null&&(s[i]=p)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},$n=(...e)=>e.filter(Boolean).join(" ");var fa="ask_user_question",ns=8,dr="data-persona-ask-sheet-for",Pm="Other",Rm="Other\u2026",ip="Type your own answer here",lp="Send",Im="Next",Wm="Back",Hm="Submit all",Bm="Skip",Om=3,rl="data-ask-current-index",sl="data-ask-question-count",cp="data-ask-answers",al="data-ask-grouped",dp="data-ask-layout",Dm=e=>e.layout==="pills"?"pills":"rows",Nm=e=>e.getAttribute(dp)==="pills"?"pills":"rows",ap=!1,pp=e=>e.replace(/["\\]/g,"\\$&"),oo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===fa,ma=e=>e?.features?.askUserQuestion??{},ro=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=Em(r,Lm|km|Mm);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},os=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>ns&&!ap&&(ap=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ns}.`)),t.slice(0,ns)},Fm=e=>os(e)[0]??null,_m=(e,t)=>os(e)[t]??null,up=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},gp=(e,t,n)=>{if(e!=="rows")return null;let o=m("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=m("span","persona-ask-row-check");o.appendChild(r)}else{let r=m("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},$m=(e,t,n,o)=>{let s=m("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(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=m("span","persona-ask-row-content"),i=m("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let d=m("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let p=gp(n,o,t);p&&s.appendChild(p)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},jm=e=>{let n=m("span",e==="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=(e,t,n,o)=>{let s=m("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<Om;c++)s.appendChild(jm(o));return s}if(p.forEach((c,u)=>{s.appendChild($m(c,u,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?Pm:Rm;if(o==="rows"){let u=m("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=m("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=t.freeTextPlaceholder??ip,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",t.freeTextLabel??c),b.appendChild(g),u.appendChild(b);let y=gp(o,a,p.length);y&&u.appendChild(y),s.appendChild(u)}else{let u=m("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=t.freeTextLabel??c,s.appendChild(u)}}return s},fp=(e,t)=>{let o=m("div",t==="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=e.freeTextPlaceholder??ip,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=m("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??lp,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},zm=e=>{let t=m("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=m("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??lp,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},qm=(e,t,n)=>{let o=m("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=m("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Wm,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=m("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=m("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Bm,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=m("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let p=e===t-1;return i.textContent=p?n.submitAllLabel??Hm:n.nextLabel??Im,i.setAttribute("data-ask-user-action",p?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Oo=e=>{let t=e.getAttribute(cp);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},mp=(e,t)=>{e.setAttribute(cp,JSON.stringify(t))},pn=e=>{let t=Number(e.getAttribute(rl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Vm=(e,t)=>{e.setAttribute(rl,String(Math.max(0,Math.floor(t))))},pr=e=>{let t=Number(e.getAttribute(sl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},so=e=>e.getAttribute(al)==="true",Km=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let i=n[a];(typeof i=="string"||Array.isArray(i))&&(o[s]=i)}}),o},Gm=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},ha=(e,t)=>{let{payload:n}=ro(t),o=os(n),r=Oo(e),s={},a=new Set;return o.forEach((i,p)=>{let d=typeof i?.question=="string"?i.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(s[d]=r[p]))}),s},hp=e=>{let t=Oo(e),n=pn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),i=e.querySelector('[data-ask-free-text-input="true"]');i&&(typeof o=="string"&&o.length>0&&!a.has(o)?(i.value=o,i.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):i.value="")},yp=e=>{if(!so(e))return;let t=Oo(e),n=pn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},il=(e,t,n)=>{let o=ma(n),r=Nm(e),{payload:s,complete:a}=ro(t),i=so(e),p=pn(e),d=pr(e),c=i?_m(s,p):Fm(s),u=!!c?.multiSelect,b=e.querySelector('[data-ask-step-inline="true"]');b&&(b.textContent=i?`${p+1}/${d}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let y=e.querySelector('[data-ask-question="true"]');if(y){let I=typeof c?.question=="string"?c.question:"";y.textContent=I,y.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let I=Um(c,o,a,r);C.replaceWith(I)}if(r!=="rows"){let I=e.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(fp(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!M?e.appendChild(zm(o)):(!u||i)&&M&&M.remove(),e.setAttribute("data-multi-select",u?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(i){let I=qm(p,d,o);L?L.replaceWith(I):e.appendChild(I)}else L&&L.remove();hp(e),yp(e)},Jm=(e,t,n)=>{let o=ma(t),r=Dm(o),s=e.toolCall.id,a=os(n),i=Math.max(1,a.length),p=i>1,d=Km(e,a),c=p?Gm(e,i):0,u=m("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(dr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(sl,String(i)),u.setAttribute(rl,String(c)),u.setAttribute(al,p?"true":"false"),u.setAttribute(dp,r),mp(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),up(u,o);let b=m("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=m("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",b.appendChild(g);let y=m("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",b.appendChild(y),u.appendChild(b);let M=m("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),u.appendChild(M),r!=="rows"&&u.appendChild(fp(o,r)),il(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Xm=(e,t,n)=>{let{payload:o}=ro(t),r=Math.max(1,os(o).length);r>pr(e)&&(e.setAttribute(sl,String(r)),r>1&&!so(e)&&e.setAttribute(al,"true")),il(e,t,n)},Qm=(e,t)=>{let n=m("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=ma(t);up(n,o);let r=m("span","persona-ask-stub-label"),{complete:s}=ro(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},rs=(e,t,n)=>{if(!n||!oo(e)||ma(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${dr}]`).forEach(d=>{d.getAttribute(dr)!==r&&d.remove()});let a=n.querySelector(`[${dr}="${pp(r)}"]`);if(a){Xm(a,e,t);return}let{payload:i}=ro(e),p=Jm(e,t,i);n.appendChild(p)},Do=(e,t)=>{if(!e)return;let n=t?`[${dr}="${pp(t)}"]`:`[${dr}]`;e.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)})},ll=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),ao=(e,t)=>{let n=Oo(e),o=pn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,mp(e,n),hp(e),yp(e)},ya=(e,t,n,o)=>{let r=pr(e),s=Math.max(0,Math.min(r-1,o));Vm(e,s),il(e,t,n)};var Mn="suggest_replies";var bp={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},cl={name:Mn,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:bp,origin:"sdk",annotations:{readOnlyHint:!0}},dl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ba=e=>e.variant==="tool"&&e.toolCall?.name===Mn,vp=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.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},pl=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!ba(n))continue;let o=vp(n.toolCall?.args);return o.length>0?o:null}return null},xp=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var Cp={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ns,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},wp={name:fa,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:Cp,origin:"sdk",annotations:{readOnlyHint:!0}},ss=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(wp),xp(e)&&t.push(cl),t};import{parse as Ap,STR as Sp,OBJ as Tp}from"partial-json";var va=e=>e.replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),io=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Ym=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Ep=e=>e.status==="complete"?Ym(e):e.status==="pending"?"Waiting":"",Zm=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.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=e=>e.status==="complete"?Zm(e):"Using tool...",xa=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},is=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return xa(t)},Ca=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return xa(t)},ul=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=is(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},wa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&as(o,n.slice(s,a.index),[]),a[1]!==void 0?as(o,a[1],["bold"]):a[2]!==void 0?as(o,a[2],["italic"]):a[3]!==void 0&&as(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&as(o,n.slice(s),[]),o},as=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},eh=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
+ ${e.description}`:"");return window.confirm(n)},wm=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Am=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Sm=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};function Bo(e,t){let n=e?.display;return n?typeof n=="string"?n:n.byType?.[t]??n.default??"panel":"panel"}function ga(e,t){return JSON.stringify({component:e==="inline"?"PersonaArtifactInline":"PersonaArtifactCard",props:{artifactId:t.artifactId,title:t.title,artifactType:t.artifactType,status:t.status,...t.file?{file:t.file}:{},...e==="inline"&&t.component?{component:t.component}:{},...e==="inline"&&t.componentProps?{componentProps:t.componentProps}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}})}var Tm="agent_",Em="flow_";function rp(e){return e.startsWith(Tm)?{kind:"agentId",agentId:e}:e.startsWith(Em)?{kind:"flowId",flowId:e}:null}function sp(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let o=n.indexOf(":");if(o>0){let a=n.slice(0,o),i=n.slice(o+1);if(a==="runtype"){let d=rp(i);if(d)return d;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let p=t?.[a];if(!p)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:p(i).payload}}let r=rp(n);if(r)return r;let s=t?.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.`)}import{parse as Mm,ARR as km,OBJ as Lm,STR as Pm}from"partial-json";var m=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n};var ap=()=>document.createDocumentFragment(),Fe=(e,t={},...n)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))o.setAttribute(s,a);if(t.style){let s=o.style,a=t.style;for(let i of Object.keys(a)){let p=a[i];p!=null&&(s[i]=p)}}let r=n.filter(s=>s!=null);return r.length>0&&o.append(...r),o},_n=(...e)=>e.filter(Boolean).join(" ");var fa="ask_user_question",ns=8,dr="data-persona-ask-sheet-for",Rm="Other",Im="Other\u2026",lp="Type your own answer here",cp="Send",Wm="Next",Hm="Back",Bm="Submit all",Om="Skip",Dm=3,rl="data-ask-current-index",sl="data-ask-question-count",dp="data-ask-answers",al="data-ask-grouped",pp="data-ask-layout",Nm=e=>e.layout==="pills"?"pills":"rows",Fm=e=>e.getAttribute(pp)==="pills"?"pills":"rows",ip=!1,up=e=>e.replace(/["\\]/g,"\\$&"),no=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===fa,ma=e=>e?.features?.askUserQuestion??{},oo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:n};try{let r=o.join(""),s=Mm(r,Pm|Lm|km);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},os=e=>{let t=Array.isArray(e?.questions)?e.questions:[];return t.length>ns&&!ip&&(ip=!0,typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ns}.`)),t.slice(0,ns)},_m=e=>os(e)[0]??null,$m=(e,t)=>os(e)[t]??null,gp=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},fp=(e,t,n)=>{if(e!=="rows")return null;let o=m("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let r=m("span","persona-ask-row-check");o.appendChild(r)}else{let r=m("span","persona-ask-row-badge");r.textContent=String(n+1),o.appendChild(r)}return o},jm=(e,t,n,o)=>{let s=m("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(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=m("span","persona-ask-row-content"),i=m("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let d=m("span","persona-ask-row-description");d.textContent=e.description,a.appendChild(d)}s.appendChild(a);let p=fp(n,o,t);p&&s.appendChild(p)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Um=e=>{let n=m("span",e==="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},zm=(e,t,n,o)=>{let s=m("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!e?.multiSelect,p=(Array.isArray(e?.options)?e.options:[]).filter(c=>c&&typeof c.label=="string"&&c.label.length>0);if(p.length===0&&!n){for(let c=0;c<Dm;c++)s.appendChild(Um(o));return s}if(p.forEach((c,u)=>{s.appendChild(jm(c,u,o,a))}),e?.allowFreeText!==!1){let c=o==="rows"?Rm:Im;if(o==="rows"){let u=m("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=m("span","persona-ask-row-content"),g=document.createElement("input");g.type="text",g.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",g.placeholder=t.freeTextPlaceholder??lp,g.setAttribute("data-ask-free-text-input","true"),g.setAttribute("aria-label",t.freeTextLabel??c),b.appendChild(g),u.appendChild(b);let y=fp(o,a,p.length);y&&u.appendChild(y),s.appendChild(u)}else{let u=m("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=t.freeTextLabel??c,s.appendChild(u)}}return s},mp=(e,t)=>{let o=m("div",t==="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=e.freeTextPlaceholder??lp,r.setAttribute("data-ask-free-text-input","true"),o.appendChild(r),t!=="rows"){let s=m("button","persona-ask-free-text-submit persona-pointer-events-auto");s.type="button",s.textContent=e.submitLabel??cp,s.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(s)}return o},qm=e=>{let t=m("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=m("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=e.submitLabel??cp,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Vm=(e,t,n)=>{let o=m("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=m("button","persona-ask-nav-back persona-pointer-events-auto");r.type="button",r.textContent=n.backLabel??Hm,r.setAttribute("data-ask-user-action","back"),r.disabled=e===0,o.appendChild(r);let s=m("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=m("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=n.skipLabel??Om,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=m("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let p=e===t-1;return i.textContent=p?n.submitAllLabel??Bm:n.nextLabel??Wm,i.setAttribute("data-ask-user-action",p?"submit-all":"next"),i.disabled=!0,s.appendChild(i),o.appendChild(s),o},Oo=e=>{let t=e.getAttribute(dp);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},hp=(e,t)=>{e.setAttribute(dp,JSON.stringify(t))},pn=e=>{let t=Number(e.getAttribute(rl)??"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Km=(e,t)=>{e.setAttribute(rl,String(Math.max(0,Math.floor(t))))},pr=e=>{let t=Number(e.getAttribute(sl)??"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},ro=e=>e.getAttribute(al)==="true",Gm=(e,t)=>{let n=e.agentMetadata?.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let o={};return t.forEach((r,s)=>{let a=typeof r?.question=="string"?r.question:"";if(a&&Object.prototype.hasOwnProperty.call(n,a)){let i=n[a];(typeof i=="string"||Array.isArray(i))&&(o[s]=i)}}),o},Jm=(e,t)=>{let n=e.agentMetadata?.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},ha=(e,t)=>{let{payload:n}=oo(t),o=os(n),r=Oo(e),s={},a=new Set;return o.forEach((i,p)=>{let d=typeof i?.question=="string"?i.question:"";d&&(a.has(d)&&typeof console<"u"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),a.add(d),Object.prototype.hasOwnProperty.call(r,p)&&(s[d]=r[p]))}),s},yp=e=>{let t=Oo(e),n=pn(e),o=t[n],r=new Set;typeof o=="string"?r.add(o):Array.isArray(o)&&o.forEach(p=>r.add(p));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(p=>{let d=p.getAttribute("data-option-label")??"",c=r.has(d);p.setAttribute("aria-pressed",c?"true":"false"),p.classList.toggle("persona-ask-pill-selected",c)});let a=new Set(Array.from(s).map(p=>p.getAttribute("data-option-label")??"")),i=e.querySelector('[data-ask-free-text-input="true"]');i&&(typeof o=="string"&&o.length>0&&!a.has(o)?(i.value=o,i.closest('[data-ask-free-text-row="true"]')?.classList.remove("persona-hidden")):i.value="")},bp=e=>{if(!ro(e))return;let t=Oo(e),n=pn(e),o=t[n],r=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!r);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},il=(e,t,n)=>{let o=ma(n),r=Fm(e),{payload:s,complete:a}=oo(t),i=ro(e),p=pn(e),d=pr(e),c=i?$m(s,p):_m(s),u=!!c?.multiSelect,b=e.querySelector('[data-ask-step-inline="true"]');b&&(b.textContent=i?`${p+1}/${d}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let y=e.querySelector('[data-ask-question="true"]');if(y){let I=typeof c?.question=="string"?c.question:"";y.textContent=I,y.classList.toggle("persona-ask-question-skeleton",!I&&!a)}let C=e.querySelector('[data-ask-pill-list="true"]');if(C){let I=zm(c,o,a,r);C.replaceWith(I)}if(r!=="rows"){let I=e.querySelector('[data-ask-free-text-row="true"]');I&&I.replaceWith(mp(o,r))}let M=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!M?e.appendChild(qm(o)):(!u||i)&&M&&M.remove(),e.setAttribute("data-multi-select",u?"true":"false");let L=e.querySelector('[data-ask-nav-row="true"]');if(i){let I=Vm(p,d,o);L?L.replaceWith(I):e.appendChild(I)}else L&&L.remove();yp(e),bp(e)},Xm=(e,t,n)=>{let o=ma(t),r=Nm(o),s=e.toolCall.id,a=os(n),i=Math.max(1,a.length),p=i>1,d=Gm(e,a),c=p?Jm(e,i):0,u=m("div",["persona-ask-sheet",`persona-ask-sheet--${r}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(dr,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(sl,String(i)),u.setAttribute(rl,String(c)),u.setAttribute(al,p?"true":"false"),u.setAttribute(pp,r),hp(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),gp(u,o);let b=m("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=m("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",b.appendChild(g);let y=m("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",b.appendChild(y),u.appendChild(b);let M=m("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return M.setAttribute("data-ask-pill-list","true"),M.setAttribute("role","group"),u.appendChild(M),r!=="rows"&&u.appendChild(mp(o,r)),il(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Qm=(e,t,n)=>{let{payload:o}=oo(t),r=Math.max(1,os(o).length);r>pr(e)&&(e.setAttribute(sl,String(r)),r>1&&!ro(e)&&e.setAttribute(al,"true")),il(e,t,n)},Ym=(e,t)=>{let n=m("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let o=ma(t);gp(n,o);let r=m("span","persona-ask-stub-label"),{complete:s}=oo(e);return r.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(r),n},rs=(e,t,n)=>{if(!n||!no(e)||ma(t).enabled===!1)return;let r=e.toolCall.id;n.querySelectorAll(`[${dr}]`).forEach(d=>{d.getAttribute(dr)!==r&&d.remove()});let a=n.querySelector(`[${dr}="${up(r)}"]`);if(a){Qm(a,e,t);return}let{payload:i}=oo(e),p=Xm(e,t,i);n.appendChild(p)},Do=(e,t)=>{if(!e)return;let n=t?`[${dr}="${up(t)}"]`:`[${dr}]`;e.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)})},ll=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),so=(e,t)=>{let n=Oo(e),o=pn(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[o]:n[o]=t,hp(e,n),yp(e),bp(e)},ya=(e,t,n,o)=>{let r=pr(e),s=Math.max(0,Math.min(r-1,o));Km(e,s),il(e,t,n)};var En="suggest_replies";var vp={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},cl={name:En,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:vp,origin:"sdk",annotations:{readOnlyHint:!0}},dl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ba=e=>e.variant==="tool"&&e.toolCall?.name===En,xp=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t?.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},pl=e=>{for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="user")return null;if(!ba(n))continue;let o=xp(n.toolCall?.args);return o.length>0?o:null}return null},Cp=e=>{let t=e?.features?.suggestReplies;return t?.expose===!0&&t.enabled!==!1};var wp={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ns,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},Ap={name:fa,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:wp,origin:"sdk",annotations:{readOnlyHint:!0}},ss=e=>{let t=[],n=e?.features?.askUserQuestion;return n?.expose===!0&&n.enabled!==!1&&t.push(Ap),Cp(e)&&t.push(cl),t};import{parse as Sp,STR as Tp,OBJ as Ep}from"partial-json";var va=e=>e.replace(/\\n/g,`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ao=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Zm=e=>{let t=e.completedAt??Date.now(),n=e.startedAt??t,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},Mp=e=>e.status==="complete"?Zm(e):e.status==="pending"?"Waiting":"",eh=e=>{let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.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 kp=e=>e.status==="complete"?eh(e):"Using tool...",xa=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},is=e=>{let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return xa(t)},Ca=e=>{let t=e.durationMs!==void 0?e.durationMs:Math.max(0,(e.completedAt??Date.now())-(e.startedAt??e.completedAt??Date.now()));return xa(t)},ul=(e,t,n)=>{if(!t)return n;let o=e.name?.trim()||"tool",r=is(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,r)},wa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),o=[],r=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=r.exec(n))!==null;)a.index>s&&as(o,n.slice(s,a.index),[]),a[1]!==void 0?as(o,a[1],["bold"]):a[2]!==void 0?as(o,a[2],["italic"]):a[3]!==void 0&&as(o,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&as(o,n.slice(s),[]),o},as=(e,t,n)=>{let o=t.split("{duration}");for(let r=0;r<o.length;r++)o[r]&&e.push({text:o[r],styles:n}),r<o.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},th=()=>{let e=null,t=0,n=o=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=o.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
10
10
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
11
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ls=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},gl=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},fl=()=>{let e=eh();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},ml=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=Ap(n,Sp|Tp);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?va(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=va(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},th=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?va(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?va(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=Ap(s,Sp|Tp),p=r(i);p!==null&&(t=p)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},hl=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var kp="4.11.1";var Cn=kp;var oh="https://api.runtype.com/v1/dispatch",Aa="https://api.runtype.com";function rh(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var yl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function sh(e){switch(e){case"json":return ml;case"regex-json":return fl;case"xml":return hl;default:return gl}}var Lp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function ah(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Lp(n);if(!Lp(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=ls(e);return ls(t)!==null&&a===null?t:e}var ur=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??oh,this.headers={"Content-Type":"application/json","X-Persona-Version":Cn,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??sh(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new es(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=rp(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(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Aa}/v1/client/${t}`}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 t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Cn},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):s.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.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$/,"")||Aa}/v1/client/feedback`}async sendFeedback(t){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(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Cn},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,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:t,comment:n})}async submitNPSFeedback(t,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:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,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 d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(yl).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.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:i,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Cn},body:JSON.stringify(c),signal:t.signal})});if(!i.ok){let d=await i.json().catch(()=>({error:"Chat request failed"}));if(i.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(i.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!i.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,t.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(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Aa}/v1/agents/${t.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:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?np(n):void 0,i=this.clientToolsFingerprintSessionId===t,p=s&&i&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let b=0;;b++){if(u=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&b===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Aa}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...ss(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,d,b=>{let g={...p,...b};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:i,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(s,{method:"POST",headers:i,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,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(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(yl).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...ss(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(yl).sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[i,p]of Object.entries(o.targetPayload))i!=="messages"&&(r[i]=p);let s=[...ss(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let p=i;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let p=c=>{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(),...c!==void 0&&{partId:c}};return o.current=u,r(u),u},d=c=>o.current?o.current:p(c);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(i.partId)),i.partId!==void 0&&(a.current=i.partId);let c=d(i.partId);i.partId!==void 0&&!c.partId&&(c.partId=i.partId),c.content+=i.text,r(c)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,i="",p=Date.now(),d=0,c=()=>p+d++,u=E=>{let F=E.reasoning?{...E.reasoning,chunks:[...E.reasoning.chunks]}:void 0,v=E.toolCall?{...E.toolCall,chunks:E.toolCall.chunks?[...E.toolCall.chunks]:void 0}:void 0,T=E.tools?E.tools.map(k=>({...k,chunks:k.chunks?[...k.chunks]:void 0})):void 0;return{...E,reasoning:F,toolCall:v,tools:T}},b=E=>{if(E.role!=="assistant"||E.variant)return!0;let F=Array.isArray(E.contentParts)&&E.contentParts.length>0,v=typeof E.rawContent=="string"&&E.rawContent.trim()!=="";return typeof E.content=="string"&&E.content.trim()!==""||F||v||!!E.stopReason},g=E=>{b(E)&&n({type:"message",message:u(E)})},y=null,C=null,M={current:null},L={current:null},I=null,S="",R=new Map,$=new Map,z=new Map,w=new Map,U=new Map,q={lastId:null,byStep:new Map},Q={lastId:null,byCall:new Map},O=E=>{if(E==null)return null;try{return String(E)}catch{return null}},D=E=>O(E.stepId??E.step_id??E.step??E.parentId??E.flowStepId??E.flow_step_id),ie=E=>O(E.callId??E.call_id??E.requestId??E.request_id??E.toolCallId??E.tool_call_id??E.stepId??E.step_id),me=o,we=!1,Ee=()=>{if(y)return y;let E,F="",v=I;return!we&&me?(E=me,we=!0,F=r??""):me&&v?E=`${me}_${v}`:E=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:E,role:"assistant",content:F,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(y),y},se=(E,F)=>{q.lastId=F,E&&q.byStep.set(E,F)},fe=(E,F)=>{let v=E.reasoningId??E.id,T=D(E);if(v){let H=String(v);return se(T,H),H}if(T){let H=q.byStep.get(T);if(H)return q.lastId=H,H}if(q.lastId&&!F)return q.lastId;if(!F)return null;let k=`reason-${c()}`;return se(T,k),k},Y=E=>{let F=w.get(E);if(F)return F;let v={id:`reason-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:E,status:"streaming",chunks:[]}};return w.set(E,v),g(v),v},ce=(E,F)=>{Q.lastId=F,E&&Q.byCall.set(E,F)},Z=new Set,be=new Map,he=new Set,de=new Map,Me=E=>{if(!E)return!1;let F=E.replace(/_+/g,"_").replace(/^_|_$/g,"");return F==="emit_artifact_markdown"||F==="emit_artifact_component"},De=(E,F)=>{let v=E.toolId??E.id,T=ie(E);if(v){let H=String(v);return ce(T,H),H}if(T){let H=Q.byCall.get(T);if(H)return Q.lastId=H,H}if(Q.lastId&&!F)return Q.lastId;if(!F)return null;let k=`tool-${c()}`;return ce(T,k),k},_e=E=>{let F=U.get(E);if(F)return F;let v={id:`tool-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:E,status:"pending"}};return U.set(E,v),g(v),v},He=E=>{if(typeof E=="number"&&Number.isFinite(E))return E;if(typeof E=="string"){let F=Number(E);if(!Number.isNaN(F)&&Number.isFinite(F))return F;let v=Date.parse(E);if(!Number.isNaN(v))return v}return Date.now()},Ue=E=>{if(typeof E=="string")return E;if(E==null)return"";try{return JSON.stringify(E)}catch{return String(E)}},Ve=new Map,ke=new Map,ne=new Map,Be=(E,F,v)=>{let T=ne.get(E);T||(T=[],ne.set(E,T));let k=0,H=T.length;for(;k<H;){let B=k+H>>>1;T[B].seq<F?k=B+1:H=B}T[k]?.seq===F?T[k]={seq:F,text:v}:T.splice(k,0,{seq:F,text:v});let V="";for(let B=0;B<T.length;B++)V+=T[B].text;return V},vt=(E,F)=>{let v=Ue(F),T=ke.get(E.id),k=ah(T,v);E.rawContent=k;let H=Ve.get(E.id),V=Te=>{let rt=E.content??"";Te.trim()!==""&&(rt.trim().length===0||Te.startsWith(rt)||Te.trimStart().startsWith(rt.trim()))&&(E.content=Te)},B=()=>{if(H){let Te=H.close?.();Te instanceof Promise&&Te.catch(()=>{})}Ve.delete(E.id),ke.delete(E.id),E.streaming=!1,g(E)};if(!H){V(v),B();return}let j=ls(k);if(j!==null&&j.trim()!==""){V(j),B();return}let ae=Te=>{let rt=typeof Te=="string"?Te:Te?.text??null;if(rt!==null&&rt.trim()!=="")return rt;let K=H.getExtractedText();return K!==null&&K.trim()!==""?K:v},Ge;try{Ge=H.processChunk(k)}catch{V(v),B();return}if(Ge instanceof Promise){Ge.then(Te=>{V(ae(Te)),B()}).catch(()=>{V(v),B()});return}V(ae(Ge)),B()},mt=null,at=(E,F,v,T)=>{E.rawContent=F,Ve.has(E.id)||Ve.set(E.id,this.createStreamParser());let k=Ve.get(E.id),H=F.trim().startsWith("{")||F.trim().startsWith("[");if(H&&ke.set(E.id,F),k.__isPlainTextParser===!0){E.content=T!==void 0?F:E.content+v,ke.delete(E.id),Ve.delete(E.id),E.rawContent=void 0,g(E);return}let B=k.processChunk(F);if(B instanceof Promise)B.then(j=>{let ae=typeof j=="string"?j:j?.text??null;ae!==null&&ae.trim()!==""?(E.content=ae,g(E)):!H&&!F.trim().startsWith("<")&&(E.content=T!==void 0?F:E.content+v,ke.delete(E.id),Ve.delete(E.id),E.rawContent=void 0,g(E))}).catch(()=>{E.content=T!==void 0?F:E.content+v,ke.delete(E.id),Ve.delete(E.id),E.rawContent=void 0,g(E)});else{let j=typeof B=="string"?B:B?.text??null;j!==null&&j.trim()!==""?(E.content=j,g(E)):!H&&!F.trim().startsWith("<")&&(E.content=T!==void 0?F:E.content+v,ke.delete(E.id),Ve.delete(E.id),E.rawContent=void 0,g(E))}},Oe=(E,F)=>{let v=F??E.content;if(v==null||v===""){E.streaming=!1,g(E);return}let k=ke.get(E.id)??Ue(v);E.rawContent=k;let H=Ve.get(E.id),V=null,B=!1;if(H&&(V=H.getExtractedText(),V===null&&(V=ls(k)),V===null)){let j=H.processChunk(k);j instanceof Promise?(B=!0,j.then(ae=>{let Ge=typeof ae=="string"?ae:ae?.text??null;Ge!==null&&(E.content=Ge,E.streaming=!1,Ve.delete(E.id),ke.delete(E.id),g(E))}).catch(()=>{})):V=typeof j=="string"?j:j?.text??null}if(!B){V!==null&&V.trim()!==""?E.content=V:ke.has(E.id)||(E.content=Ue(v));let j=Ve.get(E.id);if(j){let ae=j.close?.();ae instanceof Promise&&ae.catch(()=>{}),Ve.delete(E.id)}ke.delete(E.id),E.streaming=!1,g(E)}},ye=(E,F,v)=>{let T=$.get(E);if(T)return T;let k={id:`nested-${F}-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:E,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:F}};return $.set(E,k),g(k),k},Xe=[],Le,ue=new Map,le=0,ve="agent",xt=!1,xe=null,pe=null,gn=new Map,X=this.config.iterationDisplay??"separate";for(Le=()=>{for(let E=0;E<Xe.length;E++){let F=Xe[E].payloadType,v=Xe[E].payload;if(!xt&&ve!=="flow"&&typeof v.stepType=="string"&&(ve="flow"),F==="reasoning_start"){let T=typeof v.id=="string"?v.id:null,k=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(T&&k){R.set(T,k),ye(T,k,"reasoning");continue}let H=fe(v,!0)??`reason-${c()}`,V=Y(H);V.reasoning=V.reasoning??{id:H,status:"streaming",chunks:[]},V.reasoning.startedAt=V.reasoning.startedAt??He(v.startedAt??v.timestamp),V.reasoning.completedAt=void 0,V.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(V.reasoning.scope=v.scope),V.streaming=!0,V.reasoning.status="streaming",g(V)}else if(F==="reasoning_delta"){let T=typeof v.id=="string"?v.id:null;if(T&&R.has(T)&&$.has(T)){let B=$.get(T),j=v.reasoningText??v.text??v.delta??"";j&&v.hidden!==!0&&B.reasoning&&(B.reasoning.chunks.push(String(j)),g(B));continue}let k=fe(v,!1)??fe(v,!0)??`reason-${c()}`,H=Y(k);H.reasoning=H.reasoning??{id:k,status:"streaming",chunks:[]},H.reasoning.startedAt=H.reasoning.startedAt??He(v.startedAt??v.timestamp);let V=v.reasoningText??v.text??v.delta??"";if(V&&v.hidden!==!0){let B=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if(B!==void 0){let j=Be(k,B,String(V));H.reasoning.chunks=[j]}else H.reasoning.chunks.push(String(V))}if(H.reasoning.status=v.done?"complete":"streaming",v.done){H.reasoning.completedAt=He(v.completedAt??v.timestamp);let B=H.reasoning.startedAt??Date.now();H.reasoning.durationMs=Math.max(0,(H.reasoning.completedAt??Date.now())-B)}H.streaming=H.reasoning.status!=="complete",g(H)}else if(F==="reasoning_complete"){let T=typeof v.id=="string"?v.id:null;if(T&&R.has(T)&&$.has(T)){let j=$.get(T);if(j.reasoning){let ae=typeof v.text=="string"?v.text:"";ae&&j.reasoning.chunks.length===0&&j.reasoning.chunks.push(ae),j.reasoning.status="complete",j.streaming=!1,g(j)}R.delete(T),$.delete(T);continue}let k=fe(v,!1)??fe(v,!0)??`reason-${c()}`,H=typeof v.text=="string"?v.text:"";!w.get(k)&&(H||v.scope==="loop")&&Y(k);let V=w.get(k);if(V?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(V.reasoning.scope=v.scope),H&&V.reasoning.chunks.length===0&&V.reasoning.chunks.push(H),V.reasoning.status="complete",V.reasoning.completedAt=He(v.completedAt??v.timestamp);let j=V.reasoning.startedAt??Date.now();V.reasoning.durationMs=Math.max(0,(V.reasoning.completedAt??Date.now())-j),V.streaming=!1,g(V)}let B=D(v);B&&q.byStep.delete(B)}else if(F==="tool_start"){y&&(y.streaming=!1,g(y),y=null),typeof v.iteration=="number"&&(le=v.iteration);let T=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??De(v,!0)??`tool-${c()}`,k=v.toolName??v.name;if(Me(k)){Z.add(T);continue}ce(ie(v),T);let H=_e(T),V=H.toolCall??{id:T,status:"pending"};V.name=k??V.name,V.status="running",v.parameters!==void 0?V.args=v.parameters:v.args!==void 0&&(V.args=v.args),V.startedAt=V.startedAt??He(v.startedAt??v.timestamp),V.completedAt=void 0,V.durationMs=void 0,H.toolCall=V,H.streaming=!0,v.executionId&&(H.agentMetadata={executionId:v.executionId,iteration:v.iteration}),g(H)}else if(F==="tool_output_delta"){let T=De(v,!1)??De(v,!0)??`tool-${c()}`;if(Z.has(T))continue;let k=_e(T),H=k.toolCall??{id:T,status:"running"};H.startedAt=H.startedAt??He(v.startedAt??v.timestamp);let V=v.text??v.delta??v.message??"";V&&(H.chunks=H.chunks??[],H.chunks.push(String(V))),H.status="running",k.toolCall=H,k.streaming=!0;let B=v.agentContext;(B||v.executionId)&&(k.agentMetadata=k.agentMetadata??{executionId:B?.executionId??v.executionId,iteration:B?.iteration??v.iteration}),g(k)}else if(F==="tool_complete"){let T=De(v,!1)??De(v,!0)??`tool-${c()}`;if(Z.has(T)){Z.delete(T);continue}let k=_e(T),H=k.toolCall??{id:T,status:"running"};H.status="complete",v.result!==void 0&&(H.result=v.result),typeof v.duration=="number"&&(H.duration=v.duration),H.completedAt=He(v.completedAt??v.timestamp);let V=v.duration??v.executionTime;if(typeof V=="number")H.durationMs=V;else{let ae=H.startedAt??Date.now();H.durationMs=Math.max(0,(H.completedAt??Date.now())-ae)}k.toolCall=H,k.streaming=!1;let B=v.agentContext;(B||v.executionId)&&(k.agentMetadata=k.agentMetadata??{executionId:B?.executionId??v.executionId,iteration:B?.iteration??v.iteration}),g(k);let j=ie(v);j&&Q.byCall.delete(j)}else if(F==="await"&&v.toolName){let T=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,k=T??v.toolId??`local-${c()}`,H=_e(k),V=v.toolName,B=v.origin==="webmcp"&&!Ho(V)?`webmcp:${V}`:V,j=Ho(B),ae=H.toolCall??{id:k,status:"pending"};ae.name=B,ae.args=v.parameters,ae.status=j?"running":"complete",ae.chunks=ae.chunks??[],ae.startedAt=ae.startedAt??He(v.startedAt??v.timestamp??v.awaitedAt),j?(ae.completedAt=void 0,ae.duration=void 0,ae.durationMs=void 0):ae.completedAt=ae.completedAt??ae.startedAt,H.toolCall=ae,H.streaming=!1,H.agentMetadata={...H.agentMetadata,executionId:v.executionId??H.agentMetadata?.executionId,awaitingLocalTool:!0,...T?{webMcpToolCallId:T}:{}},g(H)}else if(F==="text_start"){let T=typeof v.id=="string"?v.id:null,k=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(T&&k){R.set(T,k);continue}let H=y;H&&(ve==="flow"?(Oe(H),mt=H):(H.streaming=!1,g(H)),y=null),I=typeof v.id=="string"?v.id:I,S=""}else if(F==="text_delta"){let T=typeof v.id=="string"?v.id:null,k=T?R.get(T):void 0;if(T&&k){let V=typeof v.delta=="string"?v.delta:"",B=(z.get(T)??"")+V;if(z.set(T,B),B.trim()==="")continue;let j=ye(T,k);j.agentMetadata={...j.agentMetadata,executionId:v.executionId,parentToolId:k},at(j,B,V,void 0);continue}if(I=typeof v.id=="string"?v.id:I,ve==="flow"){let V=typeof v.delta=="string"?v.delta:"";if(S+=V,S.trim()==="")continue;let B=Ee();B.agentMetadata={executionId:v.executionId,iteration:v.iteration},at(B,S,V,void 0),C=B;continue}let H=Ee();H.content+=v.delta??"",H.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:xe??void 0,agentName:pe?.agentName},C=H,g(H)}else if(F==="text_complete"){let T=typeof v.id=="string"?v.id:null;if(T&&R.has(T)){let H=$.get(T);H&&Oe(H),R.delete(T),z.delete(T),$.delete(T);continue}let k=y;k&&(ve==="flow"?(Oe(k),mt=k):((k.content??"")===""&&typeof v.text=="string"&&(k.content=v.text),k.streaming=!1,g(k)),y=null),I=null,S=""}else if(F==="step_complete"){let T=v.stepType,k=v.executionType;if(T==="tool"||k==="context")continue;if(v.success===!1){let H=v.error,V=typeof H=="string"&&H!==""?H:H!=null&&typeof H=="object"&&Reflect.has(H,"message")?String(H.message??"Step failed"):"Step failed";n({type:"error",error:new Error(V)});let B=y;B&&B.streaming&&(B.streaming=!1,g(B)),n({type:"status",status:"idle"});continue}{let H=mt;mt=null;let V=v.stopReason,B=v.result?.response;if(H)V&&(H.stopReason=V),B!=null?vt(H,B):H.streaming!==!1&&(Ve.delete(H.id),ke.delete(H.id),H.streaming=!1,g(H));else{let j=B!=null&&B!=="";if(j||V){let ae=Ee();V&&(ae.stopReason=V),j?Oe(ae,B):(ae.streaming=!1,g(ae))}}continue}}else if(F==="execution_start")ve=v.kind==="flow"?"flow":"agent",xt=!0,ve==="agent"&&(pe={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:He(v.startedAt)});else if(F==="turn_start"){let T=typeof v.iteration=="number"?v.iteration:le;if(T!==le){if(pe&&(pe.currentIteration=T),X==="separate"&&T>1){let k=y;k&&(k.streaming=!1,g(k),gn.set(T-1,k),y=null)}le=T}xe=typeof v.id=="string"?v.id:null,C=null}else if(F==="tool_input_delta"){let T=v.toolCallId??Q.lastId;if(T){let k=U.get(T);k?.toolCall&&(k.toolCall.chunks=k.toolCall.chunks??[],k.toolCall.chunks.push(v.delta??""),g(k))}}else{if(F==="tool_input_complete")continue;if(F==="turn_complete"){let T=v.stopReason,k=y??C;if(T&&k!==null){let H=v.id;(!H||k.agentMetadata?.turnId===H)&&(k.stopReason=T,g(k))}xe===v.id&&(xe=null)}else if(F==="media_start"){let T=String(v.id);ue.set(T,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(F==="media_delta"){let T=ue.get(String(v.id));T&&typeof v.delta=="string"&&T.parts.push(v.delta)}else if(F==="media_complete"){let T=String(v.id),k=ue.get(T);ue.delete(T);let H=(typeof v.mediaType=="string"?v.mediaType:void 0)??k?.mediaType??"application/octet-stream",V=typeof v.data=="string"?v.data:void 0,B=typeof v.url=="string"?v.url:k&&k.parts.length>0?k.parts.join(""):void 0,j=null;if(V)j={type:"media",data:V,mediaType:H};else if(B){let rt=H.toLowerCase();j={type:rt==="image"||rt.startsWith("image/")?"image-url":"file-url",url:B,mediaType:H}}let ae=v.toolCallId??k?.toolCallId,Ge=j?[j]:[],Te=[];for(let rt of Ge){if(!rt||typeof rt!="object")continue;let K=rt,ze=typeof K.type=="string"?K.type:void 0,Ae=typeof K.mediaType=="string"?K.mediaType.toLowerCase():"",We=null,Pe="";if(ze==="media"){let Ye=typeof K.data=="string"?K.data:void 0;if(!Ye)continue;Pe=Ae.length>0?Ae:"application/octet-stream",We=`data:${Pe};base64,${Ye}`}else if(ze==="image-url"){let Ye=typeof K.url=="string"?K.url:void 0;if(!Ye)continue;Pe=Ae,We=Ye}else if(ze==="file-url"){let Ye=typeof K.url=="string"?K.url:void 0;if(!Ye)continue;Pe=Ae,We=Ye}else continue;if(We)if(ze==="image-url"||Pe.startsWith("image/"))Te.push({type:"image",image:We,...Pe.includes("/")?{mimeType:Pe}:{}});else if(Pe.startsWith("audio/"))Te.push({type:"audio",audio:We,mimeType:Pe});else if(Pe.startsWith("video/"))Te.push({type:"video",video:We,mimeType:Pe});else{let Ye=Pe||"application/octet-stream";Te.push({type:"file",data:We,mimeType:Ye,filename:rh(Ye)})}}if(Te.length>0){let rt=c(),K=ae,Ae={id:`agent-media-${typeof K=="string"&&K.length>0?`${K}-${rt}`:String(rt)}`,role:"assistant",content:"",contentParts:Te,createdAt:new Date().toISOString(),streaming:!1,sequence:rt,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:le}};g(Ae);let We=y;We&&(We.streaming=!1,g(We)),y=null,M.current=null}}else if(F==="execution_complete"){let T=v.kind??ve;T==="agent"&&pe&&(pe.status=v.success?"complete":"error",pe.completedAt=He(v.completedAt),pe.stopReason=v.stopReason);let k=y;k&&(T==="flow"&&k.streaming!==!1?Oe(k):(k.streaming=!1,g(k)),y=null),I=null,S="",mt=null,n({type:"status",status:"idle",terminal:!0})}else if(F==="execution_error"){let T=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(T)})}else if(F!=="ping"){if(F==="approval_start"){let T=v.approvalId??`approval-${c()}`,k={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:pe?.agentId??"virtual",executionId:v.executionId??pe?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};g(k)}else if(F==="step_await"&&v.awaitReason==="approval_required"){let T=v.approvalId??`approval-${c()}`,k={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:pe?.agentId??"virtual",executionId:v.executionId??pe?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};g(k)}else if(F==="approval_complete"){let T=v.approvalId;if(T){let H={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:v.decision??"approved",agentId:pe?.agentId??"virtual",executionId:v.executionId??pe?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};g(H)}}else if(F==="artifact_start"||F==="artifact_delta"||F==="artifact_update"||F==="artifact_complete"){if(F==="artifact_start"){let T=v.artifactType,k=String(v.id),H=typeof v.title=="string"?v.title:void 0,V=v.file,B;V&&typeof V=="object"&&!Array.isArray(V)&&typeof V.path=="string"&&typeof V.mimeType=="string"&&(B={path:V.path,mimeType:V.mimeType,...typeof V.language=="string"?{language:V.language}:{}}),n({type:"artifact_start",id:k,artifactType:T,title:H,component:typeof v.component=="string"?v.component:void 0,...B?{file:B}:{}});let j=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(de.set(k,{markdown:"",title:H,file:B,...j?{props:j}:{}}),!he.has(k)){he.add(k);let ae=Bo(this.config.features?.artifacts,T),Ge=typeof v.component=="string"?v.component:void 0,Te={id:`artifact-ref-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:ga(ae,{artifactId:k,title:H,artifactType:T,status:"streaming",...B?{file:B}:{},...Ge?{component:Ge}:{}})};be.set(k,Te),g(Te)}}else if(F==="artifact_delta"){let T=String(v.id),k=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:T,artDelta:k});let H=de.get(T);H&&(H.markdown+=k)}else if(F==="artifact_update"){let T=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:T,component:typeof v.component=="string"?v.component:void 0});let k=de.get(String(v.id));k&&(k.props={...k.props??{},...T})}else if(F==="artifact_complete"){let T=String(v.id);n({type:"artifact_complete",id:T});let k=be.get(T);if(k){k.streaming=!1;try{let H=JSON.parse(k.rawContent??"{}");if(H.props){H.props.status="complete";let V=de.get(T);V?.markdown&&(H.props.markdown=V.markdown),V?.file&&(H.props.file=V.file),H.component==="PersonaArtifactInline"&&V?.props&&Object.keys(V.props).length>0&&(H.props.componentProps=V.props)}k.rawContent=JSON.stringify(H)}catch{}de.delete(T),g(k),be.delete(T)}}}else if(F==="transcript_insert"){let T=v.message;if(!T||typeof T!="object")continue;let k=String(T.id??`msg-${c()}`),H=T.role,B={id:k,role:H==="user"?"user":H==="system"?"system":"assistant",content:typeof T.content=="string"?T.content:"",rawContent:typeof T.rawContent=="string"?T.rawContent:void 0,createdAt:typeof T.createdAt=="string"?T.createdAt:new Date().toISOString(),streaming:T.streaming===!0,...typeof T.variant=="string"?{variant:T.variant}:{},sequence:c()};if(g(B),B.rawContent)try{let ae=JSON.parse(B.rawContent)?.props?.artifactId;typeof ae=="string"&&he.add(ae)}catch{}y=null,M.current=null,Ve.delete(k),ke.delete(k)}else if(F==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let T=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(T)});let k=y;k&&k.streaming&&(k.streaming=!1,g(k)),n({type:"status",status:"idle"})}}else if(F==="step_error"||F==="dispatch_error"||F==="flow_error"){let T=null;if(v.error instanceof Error)T=v.error;else if(F==="dispatch_error"){let k=v.message??v.error;k!=null&&k!==""&&(T=new Error(String(k)))}else{let k=v.error;typeof k=="string"&&k!==""?T=new Error(k):k!=null&&typeof k=="object"&&Reflect.has(k,"message")&&(T=new Error(String(k.message??k)))}if(T){n({type:"error",error:T});let k=y;k&&k.streaming&&(k.streaming=!1,g(k)),n({type:"status",status:"idle"})}}}}}Xe.length=0};;){let{done:E,value:F}=await s.read();if(E)break;i+=a.decode(F,{stream:!0});let v=i.split(`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let r=o.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=n(o);return s!==null&&(e=s),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ls=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},gl=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},fl=()=>{let e=th();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:e.close?.bind(e)}},ml=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let r=Sp(n,Tp|Ep);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?va(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=va(r.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},nh=e=>{let t=null,n=0,r=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?va(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?va(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=Sp(s,Tp|Ep),p=r(i);p!==null&&(t=p)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},hl=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Lp="4.12.0";var io=Lp;var rh="https://api.runtype.com/v1/dispatch",Aa="https://api.runtype.com";function sh(e){let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let r=t.indexOf("/");if(r>0){let s=t.slice(r+1).split(";")[0]?.trim()??"";if(s&&s!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(s))return`attachment.${s}`}return"attachment"}var yl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function ah(e){switch(e){case"json":return ml;case"regex-json":return fl;case"xml":return hl;default:return gl}}var Pp=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function ih(e,t){if(!e)return t;let n=e.trim(),o=t.trim();if(n.length===0)return t;if(o.length===0)return e;let r=Pp(n);if(!Pp(o))return e;if(!r||o===n||o.startsWith(n))return t;let a=ls(e);return ls(t)!==null&&a===null?t:e}var ur=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=t.apiUrl??rh,this.headers={"Content-Type":"application/json","X-Persona-Version":io,...t.headers},this.debug=!!t.debug,this.createStreamParser=t.streamParser??ah(t.parserType),this.contextProviders=t.contextProviders??[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=t.webmcp?.enabled===!0?new es(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){this.webMcpBridge?.setConfirmHandler(t)}isWebMcpOperational(){return this.webMcpBridge?.isOperational()===!0}executeWebMcpToolCall(t,n,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:o,targetProviders:r}=this.config;if(!o)return{agentId:t,flowId:n};let s=sp(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(t){return`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Aa}/v1/client/${t}`}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 t=await this.sessionInitPromise;return this.clientSession=t,this.resetClientToolsFingerprint(),this.config.onSessionInit?.(t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){let t=this.config.getStoredSessionId?.()||null,n=this.routing(),o=n.agentId??n.flowId,r={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":io},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):s.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.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$/,"")||Aa}/v1/client/feedback`}async sendFeedback(t){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(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let r={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":io},body:JSON.stringify(r)});if(!s.ok){let a=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,this.config.onSessionExpired?.(),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,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:t,comment:n})}async submitNPSFeedback(t,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:t,comment:n})}async dispatch(t,n){return t.signal?.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,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 d=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:d}),d}let r=await this.buildPayload(t.messages),s=r.metadata?Object.fromEntries(Object.entries(r.metadata).filter(([d])=>d!=="sessionId"&&d!=="session_id")):void 0,a={sessionId:o.sessionId,messages:t.messages.filter(yl).map(d=>({id:d.id,role:d.role,content:d.contentParts??d.llmContent??d.rawContent??d.content})),...t.assistantMessageId&&{assistantMessageId:t.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:i,commit:p}=await this.sendWithClientToolsDiff(o.sessionId,r.clientTools,d=>{let c={...a,...d};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",c),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":io},body:JSON.stringify(c),signal:t.signal})});if(!i.ok){let d=await i.json().catch(()=>({error:"Chat request failed"}));if(i.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(i.status===429){let u=new Error(d.hint||"Message limit reached for this session.");throw n({type:"error",error:u}),u}let c=new Error(d.error||"Failed to send message");throw n({type:"error",error:c}),c}if(!i.body){let d=new Error("No response body received");throw n({type:"error",error:d}),d}p(),n({type:"status",status:"connected"});try{await this.streamResponse(i.body,n,t.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(t,n){n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let r={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();r={...r,...a}}catch(a){typeof console<"u"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal},o)}catch(a){let i=a instanceof Error?a:new Error(String(a));throw n({type:"error",error:i}),i}else s=await fetch(this.apiUrl,{method:"POST",headers:r,body:JSON.stringify(o),signal:t.signal});if(!s.ok||!s.body){let a=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw n({type:"error",error:a}),a}n({type:"status",status:"connected"});try{await this.streamResponse(s.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,o,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,o,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){let r=`${this.config.apiUrl?.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,"")||Aa}/v1/agents/${t.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:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,o,r){let s=!!(n&&n.length>0),a=s?op(n):void 0,i=this.clientToolsFingerprintSessionId===t,p=s&&i&&this.lastSentClientToolsFingerprint===a,d=!s&&r?.emptyMeansReplace===!0&&this.sentNonEmptyClientToolsSessionId===t,c=!1,u;for(let b=0;;b++){if(u=await o({...s&&(c||!p)&&n?{clientTools:n}:{},...d?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&b===0&&s&&(await u.clone().json().catch(()=>null))?.error==="client_tools_resend_required"){c=!0,this.lastSentClientToolsFingerprint=null;continue}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a??null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:d&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,o){let r=this.isClientTokenMode(),s=r?this.getClientApiUrl("resume"):`${this.config.apiUrl?.replace(/\/+$/,"")||Aa}/resume`,a;r&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let p={executionId:t,toolOutputs:n,streamResponse:o?.streamResponse??!0};if(a&&(p.sessionId=a),r&&a){let d=[...ss(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]],{response:c,commit:u}=await this.sendWithClientToolsDiff(a,d,b=>{let g={...p,...b};return this.debug&&console.debug("[AgentWidgetClient] client token resume",g),fetch(s,{method:"POST",headers:i,body:JSON.stringify(g),signal:o?.signal})},{emptyMeansReplace:!0});return c.ok&&u(),c}return fetch(s,{method:"POST",headers:i,body:JSON.stringify(p),signal:o?.signal})}latestMentionContext(t){for(let n=t.length-1;n>=0;n--){let o=t[n];if(o.role==="user")return o.mentionContext&&Object.keys(o.mentionContext).length>0?{mentions:o.mentionContext}:null}return null}async buildContextAggregate(t){let n={};this.contextProviders.length&&await Promise.all(this.contextProviders.map(async r=>{try{let s=await r({messages:t,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(t);return o&&Object.assign(n,o),Object.keys(n).length?n:null}async buildAgentPayload(t){let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(yl).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),r={agent:this.config.agent??{agentId:n},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...ss(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);return a&&(r.context=a),r}async buildPayload(t){let n=t.slice().filter(yl).sort((i,p)=>{let d=new Date(i.createdAt).getTime(),c=new Date(p.createdAt).getTime();return d-c}).map(i=>({role:i.role,content:i.contentParts??i.llmContent??i.rawContent??i.content,createdAt:i.createdAt})),o=this.routing(),r={messages:n,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[i,p]of Object.entries(o.targetPayload))i!=="messages"&&(r[i]=p);let s=[...ss(this.config),...await this.webMcpBridge?.snapshotForDispatch()??[]];s.length>0&&(r.clientTools=s);let a=await this.buildContextAggregate(t);if(a&&(r.context=a),this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let p=i;return r.clientTools!==void 0&&!("clientTools"in p)&&(p.clientTools=r.clientTools),p}}catch(i){typeof console<"u"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,o,r,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let p=c=>{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(),...c!==void 0&&{partId:c}};return o.current=u,r(u),u},d=c=>o.current?o.current:p(c);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(o.current&&(o.current.streaming=!1,r(o.current)),p(i.partId)),i.partId!==void 0&&(a.current=i.partId);let c=d(i.partId);i.partId!==void 0&&!c.partId&&(c.partId=i.partId),c.content+=i.text,r(c)}return i.done&&(o.current&&(o.current.streaming=!1,r(o.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console<"u"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,o,r){let s=t.getReader(),a=new TextDecoder,i="",p=Date.now(),d=0,c=()=>p+d++,u=E=>{let F=E.reasoning?{...E.reasoning,chunks:[...E.reasoning.chunks]}:void 0,v=E.toolCall?{...E.toolCall,chunks:E.toolCall.chunks?[...E.toolCall.chunks]:void 0}:void 0,T=E.tools?E.tools.map(k=>({...k,chunks:k.chunks?[...k.chunks]:void 0})):void 0;return{...E,reasoning:F,toolCall:v,tools:T}},b=E=>{if(E.role!=="assistant"||E.variant)return!0;let F=Array.isArray(E.contentParts)&&E.contentParts.length>0,v=typeof E.rawContent=="string"&&E.rawContent.trim()!=="";return typeof E.content=="string"&&E.content.trim()!==""||F||v||!!E.stopReason},g=E=>{b(E)&&n({type:"message",message:u(E)})},y=null,C=null,M={current:null},L={current:null},I=null,S="",R=new Map,$=new Map,z=new Map,w=new Map,U=new Map,q={lastId:null,byStep:new Map},Q={lastId:null,byCall:new Map},O=E=>{if(E==null)return null;try{return String(E)}catch{return null}},D=E=>O(E.stepId??E.step_id??E.step??E.parentId??E.flowStepId??E.flow_step_id),ie=E=>O(E.callId??E.call_id??E.requestId??E.request_id??E.toolCallId??E.tool_call_id??E.stepId??E.step_id),me=o,we=!1,Ee=()=>{if(y)return y;let E,F="",v=I;return!we&&me?(E=me,we=!0,F=r??""):me&&v?E=`${me}_${v}`:E=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:E,role:"assistant",content:F,createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(y),y},se=(E,F)=>{q.lastId=F,E&&q.byStep.set(E,F)},fe=(E,F)=>{let v=E.reasoningId??E.id,T=D(E);if(v){let H=String(v);return se(T,H),H}if(T){let H=q.byStep.get(T);if(H)return q.lastId=H,H}if(q.lastId&&!F)return q.lastId;if(!F)return null;let k=`reason-${c()}`;return se(T,k),k},Y=E=>{let F=w.get(E);if(F)return F;let v={id:`reason-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:E,status:"streaming",chunks:[]}};return w.set(E,v),g(v),v},ce=(E,F)=>{Q.lastId=F,E&&Q.byCall.set(E,F)},Z=new Set,be=new Map,he=new Set,de=new Map,Me=E=>{if(!E)return!1;let F=E.replace(/_+/g,"_").replace(/^_|_$/g,"");return F==="emit_artifact_markdown"||F==="emit_artifact_component"},De=(E,F)=>{let v=E.toolId??E.id,T=ie(E);if(v){let H=String(v);return ce(T,H),H}if(T){let H=Q.byCall.get(T);if(H)return Q.lastId=H,H}if(Q.lastId&&!F)return Q.lastId;if(!F)return null;let k=`tool-${c()}`;return ce(T,k),k},_e=E=>{let F=U.get(E);if(F)return F;let v={id:`tool-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:E,status:"pending"}};return U.set(E,v),g(v),v},He=E=>{if(typeof E=="number"&&Number.isFinite(E))return E;if(typeof E=="string"){let F=Number(E);if(!Number.isNaN(F)&&Number.isFinite(F))return F;let v=Date.parse(E);if(!Number.isNaN(v))return v}return Date.now()},Ue=E=>{if(typeof E=="string")return E;if(E==null)return"";try{return JSON.stringify(E)}catch{return String(E)}},Ve=new Map,ke=new Map,ne=new Map,Be=(E,F,v)=>{let T=ne.get(E);T||(T=[],ne.set(E,T));let k=0,H=T.length;for(;k<H;){let B=k+H>>>1;T[B].seq<F?k=B+1:H=B}T[k]?.seq===F?T[k]={seq:F,text:v}:T.splice(k,0,{seq:F,text:v});let V="";for(let B=0;B<T.length;B++)V+=T[B].text;return V},vt=(E,F)=>{let v=Ue(F),T=ke.get(E.id),k=ih(T,v);E.rawContent=k;let H=Ve.get(E.id),V=Te=>{let rt=E.content??"";Te.trim()!==""&&(rt.trim().length===0||Te.startsWith(rt)||Te.trimStart().startsWith(rt.trim()))&&(E.content=Te)},B=()=>{if(H){let Te=H.close?.();Te instanceof Promise&&Te.catch(()=>{})}Ve.delete(E.id),ke.delete(E.id),E.streaming=!1,g(E)};if(!H){V(v),B();return}let j=ls(k);if(j!==null&&j.trim()!==""){V(j),B();return}let ae=Te=>{let rt=typeof Te=="string"?Te:Te?.text??null;if(rt!==null&&rt.trim()!=="")return rt;let K=H.getExtractedText();return K!==null&&K.trim()!==""?K:v},Ge;try{Ge=H.processChunk(k)}catch{V(v),B();return}if(Ge instanceof Promise){Ge.then(Te=>{V(ae(Te)),B()}).catch(()=>{V(v),B()});return}V(ae(Ge)),B()},mt=null,at=(E,F,v,T)=>{E.rawContent=F,Ve.has(E.id)||Ve.set(E.id,this.createStreamParser());let k=Ve.get(E.id),H=F.trim().startsWith("{")||F.trim().startsWith("[");if(H&&ke.set(E.id,F),k.__isPlainTextParser===!0){E.content=T!==void 0?F:E.content+v,ke.delete(E.id),Ve.delete(E.id),E.rawContent=void 0,g(E);return}let B=k.processChunk(F);if(B instanceof Promise)B.then(j=>{let ae=typeof j=="string"?j:j?.text??null;ae!==null&&ae.trim()!==""?(E.content=ae,g(E)):!H&&!F.trim().startsWith("<")&&(E.content=T!==void 0?F:E.content+v,ke.delete(E.id),Ve.delete(E.id),E.rawContent=void 0,g(E))}).catch(()=>{E.content=T!==void 0?F:E.content+v,ke.delete(E.id),Ve.delete(E.id),E.rawContent=void 0,g(E)});else{let j=typeof B=="string"?B:B?.text??null;j!==null&&j.trim()!==""?(E.content=j,g(E)):!H&&!F.trim().startsWith("<")&&(E.content=T!==void 0?F:E.content+v,ke.delete(E.id),Ve.delete(E.id),E.rawContent=void 0,g(E))}},Oe=(E,F)=>{let v=F??E.content;if(v==null||v===""){E.streaming=!1,g(E);return}let k=ke.get(E.id)??Ue(v);E.rawContent=k;let H=Ve.get(E.id),V=null,B=!1;if(H&&(V=H.getExtractedText(),V===null&&(V=ls(k)),V===null)){let j=H.processChunk(k);j instanceof Promise?(B=!0,j.then(ae=>{let Ge=typeof ae=="string"?ae:ae?.text??null;Ge!==null&&(E.content=Ge,E.streaming=!1,Ve.delete(E.id),ke.delete(E.id),g(E))}).catch(()=>{})):V=typeof j=="string"?j:j?.text??null}if(!B){V!==null&&V.trim()!==""?E.content=V:ke.has(E.id)||(E.content=Ue(v));let j=Ve.get(E.id);if(j){let ae=j.close?.();ae instanceof Promise&&ae.catch(()=>{}),Ve.delete(E.id)}ke.delete(E.id),E.streaming=!1,g(E)}},ye=(E,F,v)=>{let T=$.get(E);if(T)return T;let k={id:`nested-${F}-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...v?{variant:v}:{},...v==="reasoning"?{reasoning:{id:E,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:F}};return $.set(E,k),g(k),k},Xe=[],Le,ue=new Map,le=0,ve="agent",xt=!1,xe=null,pe=null,gn=new Map,X=this.config.iterationDisplay??"separate";for(Le=()=>{for(let E=0;E<Xe.length;E++){let F=Xe[E].payloadType,v=Xe[E].payload;if(!xt&&ve!=="flow"&&typeof v.stepType=="string"&&(ve="flow"),F==="reasoning_start"){let T=typeof v.id=="string"?v.id:null,k=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(T&&k){R.set(T,k),ye(T,k,"reasoning");continue}let H=fe(v,!0)??`reason-${c()}`,V=Y(H);V.reasoning=V.reasoning??{id:H,status:"streaming",chunks:[]},V.reasoning.startedAt=V.reasoning.startedAt??He(v.startedAt??v.timestamp),V.reasoning.completedAt=void 0,V.reasoning.durationMs=void 0,(v.scope==="loop"||v.scope==="turn")&&(V.reasoning.scope=v.scope),V.streaming=!0,V.reasoning.status="streaming",g(V)}else if(F==="reasoning_delta"){let T=typeof v.id=="string"?v.id:null;if(T&&R.has(T)&&$.has(T)){let B=$.get(T),j=v.reasoningText??v.text??v.delta??"";j&&v.hidden!==!0&&B.reasoning&&(B.reasoning.chunks.push(String(j)),g(B));continue}let k=fe(v,!1)??fe(v,!0)??`reason-${c()}`,H=Y(k);H.reasoning=H.reasoning??{id:k,status:"streaming",chunks:[]},H.reasoning.startedAt=H.reasoning.startedAt??He(v.startedAt??v.timestamp);let V=v.reasoningText??v.text??v.delta??"";if(V&&v.hidden!==!0){let B=typeof v.sequenceIndex=="number"?v.sequenceIndex:void 0;if(B!==void 0){let j=Be(k,B,String(V));H.reasoning.chunks=[j]}else H.reasoning.chunks.push(String(V))}if(H.reasoning.status=v.done?"complete":"streaming",v.done){H.reasoning.completedAt=He(v.completedAt??v.timestamp);let B=H.reasoning.startedAt??Date.now();H.reasoning.durationMs=Math.max(0,(H.reasoning.completedAt??Date.now())-B)}H.streaming=H.reasoning.status!=="complete",g(H)}else if(F==="reasoning_complete"){let T=typeof v.id=="string"?v.id:null;if(T&&R.has(T)&&$.has(T)){let j=$.get(T);if(j.reasoning){let ae=typeof v.text=="string"?v.text:"";ae&&j.reasoning.chunks.length===0&&j.reasoning.chunks.push(ae),j.reasoning.status="complete",j.streaming=!1,g(j)}R.delete(T),$.delete(T);continue}let k=fe(v,!1)??fe(v,!0)??`reason-${c()}`,H=typeof v.text=="string"?v.text:"";!w.get(k)&&(H||v.scope==="loop")&&Y(k);let V=w.get(k);if(V?.reasoning){(v.scope==="loop"||v.scope==="turn")&&(V.reasoning.scope=v.scope),H&&V.reasoning.chunks.length===0&&V.reasoning.chunks.push(H),V.reasoning.status="complete",V.reasoning.completedAt=He(v.completedAt??v.timestamp);let j=V.reasoning.startedAt??Date.now();V.reasoning.durationMs=Math.max(0,(V.reasoning.completedAt??Date.now())-j),V.streaming=!1,g(V)}let B=D(v);B&&q.byStep.delete(B)}else if(F==="tool_start"){y&&(y.streaming=!1,g(y),y=null),typeof v.iteration=="number"&&(le=v.iteration);let T=(typeof v.toolCallId=="string"?v.toolCallId:void 0)??De(v,!0)??`tool-${c()}`,k=v.toolName??v.name;if(Me(k)){Z.add(T);continue}ce(ie(v),T);let H=_e(T),V=H.toolCall??{id:T,status:"pending"};V.name=k??V.name,V.status="running",v.parameters!==void 0?V.args=v.parameters:v.args!==void 0&&(V.args=v.args),V.startedAt=V.startedAt??He(v.startedAt??v.timestamp),V.completedAt=void 0,V.durationMs=void 0,H.toolCall=V,H.streaming=!0,v.executionId&&(H.agentMetadata={executionId:v.executionId,iteration:v.iteration}),g(H)}else if(F==="tool_output_delta"){let T=De(v,!1)??De(v,!0)??`tool-${c()}`;if(Z.has(T))continue;let k=_e(T),H=k.toolCall??{id:T,status:"running"};H.startedAt=H.startedAt??He(v.startedAt??v.timestamp);let V=v.text??v.delta??v.message??"";V&&(H.chunks=H.chunks??[],H.chunks.push(String(V))),H.status="running",k.toolCall=H,k.streaming=!0;let B=v.agentContext;(B||v.executionId)&&(k.agentMetadata=k.agentMetadata??{executionId:B?.executionId??v.executionId,iteration:B?.iteration??v.iteration}),g(k)}else if(F==="tool_complete"){let T=De(v,!1)??De(v,!0)??`tool-${c()}`;if(Z.has(T)){Z.delete(T);continue}let k=_e(T),H=k.toolCall??{id:T,status:"running"};H.status="complete",v.result!==void 0&&(H.result=v.result),typeof v.duration=="number"&&(H.duration=v.duration),H.completedAt=He(v.completedAt??v.timestamp);let V=v.duration??v.executionTime;if(typeof V=="number")H.durationMs=V;else{let ae=H.startedAt??Date.now();H.durationMs=Math.max(0,(H.completedAt??Date.now())-ae)}k.toolCall=H,k.streaming=!1;let B=v.agentContext;(B||v.executionId)&&(k.agentMetadata=k.agentMetadata??{executionId:B?.executionId??v.executionId,iteration:B?.iteration??v.iteration}),g(k);let j=ie(v);j&&Q.byCall.delete(j)}else if(F==="await"&&v.toolName){let T=typeof v.toolCallId=="string"&&v.toolCallId.length>0?v.toolCallId:void 0,k=T??v.toolId??`local-${c()}`,H=_e(k),V=v.toolName,B=v.origin==="webmcp"&&!Ho(V)?`webmcp:${V}`:V,j=Ho(B),ae=H.toolCall??{id:k,status:"pending"};ae.name=B,ae.args=v.parameters,ae.status=j?"running":"complete",ae.chunks=ae.chunks??[],ae.startedAt=ae.startedAt??He(v.startedAt??v.timestamp??v.awaitedAt),j?(ae.completedAt=void 0,ae.duration=void 0,ae.durationMs=void 0):ae.completedAt=ae.completedAt??ae.startedAt,H.toolCall=ae,H.streaming=!1,H.agentMetadata={...H.agentMetadata,executionId:v.executionId??H.agentMetadata?.executionId,awaitingLocalTool:!0,...T?{webMcpToolCallId:T}:{}},g(H)}else if(F==="text_start"){let T=typeof v.id=="string"?v.id:null,k=typeof v.parentToolCallId=="string"&&v.parentToolCallId?v.parentToolCallId:null;if(T&&k){R.set(T,k);continue}let H=y;H&&(ve==="flow"?(Oe(H),mt=H):(H.streaming=!1,g(H)),y=null),I=typeof v.id=="string"?v.id:I,S=""}else if(F==="text_delta"){let T=typeof v.id=="string"?v.id:null,k=T?R.get(T):void 0;if(T&&k){let V=typeof v.delta=="string"?v.delta:"",B=(z.get(T)??"")+V;if(z.set(T,B),B.trim()==="")continue;let j=ye(T,k);j.agentMetadata={...j.agentMetadata,executionId:v.executionId,parentToolId:k},at(j,B,V,void 0);continue}if(I=typeof v.id=="string"?v.id:I,ve==="flow"){let V=typeof v.delta=="string"?v.delta:"";if(S+=V,S.trim()==="")continue;let B=Ee();B.agentMetadata={executionId:v.executionId,iteration:v.iteration},at(B,S,V,void 0),C=B;continue}let H=Ee();H.content+=v.delta??"",H.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:xe??void 0,agentName:pe?.agentName},C=H,g(H)}else if(F==="text_complete"){let T=typeof v.id=="string"?v.id:null;if(T&&R.has(T)){let H=$.get(T);H&&Oe(H),R.delete(T),z.delete(T),$.delete(T);continue}let k=y;k&&(ve==="flow"?(Oe(k),mt=k):((k.content??"")===""&&typeof v.text=="string"&&(k.content=v.text),k.streaming=!1,g(k)),y=null),I=null,S=""}else if(F==="step_complete"){let T=v.stepType,k=v.executionType;if(T==="tool"||k==="context")continue;if(v.success===!1){let H=v.error,V=typeof H=="string"&&H!==""?H:H!=null&&typeof H=="object"&&Reflect.has(H,"message")?String(H.message??"Step failed"):"Step failed";n({type:"error",error:new Error(V)});let B=y;B&&B.streaming&&(B.streaming=!1,g(B)),n({type:"status",status:"idle"});continue}{let H=mt;mt=null;let V=v.stopReason,B=v.result?.response;if(H)V&&(H.stopReason=V),B!=null?vt(H,B):H.streaming!==!1&&(Ve.delete(H.id),ke.delete(H.id),H.streaming=!1,g(H));else{let j=B!=null&&B!=="";if(j||V){let ae=Ee();V&&(ae.stopReason=V),j?Oe(ae,B):(ae.streaming=!1,g(ae))}}continue}}else if(F==="execution_start")ve=v.kind==="flow"?"flow":"agent",xt=!0,ve==="agent"&&(pe={executionId:v.executionId,agentId:v.agentId??"virtual",agentName:v.agentName??"",status:"running",currentIteration:0,maxTurns:v.maxTurns??1,startedAt:He(v.startedAt)});else if(F==="turn_start"){let T=typeof v.iteration=="number"?v.iteration:le;if(T!==le){if(pe&&(pe.currentIteration=T),X==="separate"&&T>1){let k=y;k&&(k.streaming=!1,g(k),gn.set(T-1,k),y=null)}le=T}xe=typeof v.id=="string"?v.id:null,C=null}else if(F==="tool_input_delta"){let T=v.toolCallId??Q.lastId;if(T){let k=U.get(T);k?.toolCall&&(k.toolCall.chunks=k.toolCall.chunks??[],k.toolCall.chunks.push(v.delta??""),g(k))}}else{if(F==="tool_input_complete")continue;if(F==="turn_complete"){let T=v.stopReason,k=y??C;if(T&&k!==null){let H=v.id;(!H||k.agentMetadata?.turnId===H)&&(k.stopReason=T,g(k))}xe===v.id&&(xe=null)}else if(F==="media_start"){let T=String(v.id);ue.set(T,{mediaType:typeof v.mediaType=="string"?v.mediaType:void 0,role:typeof v.role=="string"?v.role:void 0,toolCallId:v.toolCallId,parts:[]})}else if(F==="media_delta"){let T=ue.get(String(v.id));T&&typeof v.delta=="string"&&T.parts.push(v.delta)}else if(F==="media_complete"){let T=String(v.id),k=ue.get(T);ue.delete(T);let H=(typeof v.mediaType=="string"?v.mediaType:void 0)??k?.mediaType??"application/octet-stream",V=typeof v.data=="string"?v.data:void 0,B=typeof v.url=="string"?v.url:k&&k.parts.length>0?k.parts.join(""):void 0,j=null;if(V)j={type:"media",data:V,mediaType:H};else if(B){let rt=H.toLowerCase();j={type:rt==="image"||rt.startsWith("image/")?"image-url":"file-url",url:B,mediaType:H}}let ae=v.toolCallId??k?.toolCallId,Ge=j?[j]:[],Te=[];for(let rt of Ge){if(!rt||typeof rt!="object")continue;let K=rt,ze=typeof K.type=="string"?K.type:void 0,Ae=typeof K.mediaType=="string"?K.mediaType.toLowerCase():"",We=null,Pe="";if(ze==="media"){let Ye=typeof K.data=="string"?K.data:void 0;if(!Ye)continue;Pe=Ae.length>0?Ae:"application/octet-stream",We=`data:${Pe};base64,${Ye}`}else if(ze==="image-url"){let Ye=typeof K.url=="string"?K.url:void 0;if(!Ye)continue;Pe=Ae,We=Ye}else if(ze==="file-url"){let Ye=typeof K.url=="string"?K.url:void 0;if(!Ye)continue;Pe=Ae,We=Ye}else continue;if(We)if(ze==="image-url"||Pe.startsWith("image/"))Te.push({type:"image",image:We,...Pe.includes("/")?{mimeType:Pe}:{}});else if(Pe.startsWith("audio/"))Te.push({type:"audio",audio:We,mimeType:Pe});else if(Pe.startsWith("video/"))Te.push({type:"video",video:We,mimeType:Pe});else{let Ye=Pe||"application/octet-stream";Te.push({type:"file",data:We,mimeType:Ye,filename:sh(Ye)})}}if(Te.length>0){let rt=c(),K=ae,Ae={id:`agent-media-${typeof K=="string"&&K.length>0?`${K}-${rt}`:String(rt)}`,role:"assistant",content:"",contentParts:Te,createdAt:new Date().toISOString(),streaming:!1,sequence:rt,agentMetadata:{executionId:v.executionId,iteration:typeof v.iteration=="number"?v.iteration:le}};g(Ae);let We=y;We&&(We.streaming=!1,g(We)),y=null,M.current=null}}else if(F==="execution_complete"){let T=v.kind??ve;T==="agent"&&pe&&(pe.status=v.success?"complete":"error",pe.completedAt=He(v.completedAt),pe.stopReason=v.stopReason);let k=y;k&&(T==="flow"&&k.streaming!==!1?Oe(k):(k.streaming=!1,g(k)),y=null),I=null,S="",mt=null,n({type:"status",status:"idle",terminal:!0})}else if(F==="execution_error"){let T=typeof v.error=="string"?v.error:v.error?.message??"Execution error";n({type:"error",error:new Error(T)})}else if(F!=="ping"){if(F==="approval_start"){let T=v.approvalId??`approval-${c()}`,k={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:pe?.agentId??"virtual",executionId:v.executionId??pe?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};g(k)}else if(F==="step_await"&&v.awaitReason==="approval_required"){let T=v.approvalId??`approval-${c()}`,k={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:pe?.agentId??"virtual",executionId:v.executionId??pe?.executionId??"",toolName:v.toolName??"",toolType:v.toolType,description:v.description??`Execute ${v.toolName??"tool"}`,...typeof v.reason=="string"&&v.reason?{reason:v.reason}:{},parameters:v.parameters}};g(k)}else if(F==="approval_complete"){let T=v.approvalId;if(T){let H={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:v.decision??"approved",agentId:pe?.agentId??"virtual",executionId:v.executionId??pe?.executionId??"",toolName:v.toolName??"",description:v.description??"",resolvedAt:Date.now()}};g(H)}}else if(F==="artifact_start"||F==="artifact_delta"||F==="artifact_update"||F==="artifact_complete"){if(F==="artifact_start"){let T=v.artifactType,k=String(v.id),H=typeof v.title=="string"?v.title:void 0,V=v.file,B;V&&typeof V=="object"&&!Array.isArray(V)&&typeof V.path=="string"&&typeof V.mimeType=="string"&&(B={path:V.path,mimeType:V.mimeType,...typeof V.language=="string"?{language:V.language}:{}}),n({type:"artifact_start",id:k,artifactType:T,title:H,component:typeof v.component=="string"?v.component:void 0,...B?{file:B}:{}});let j=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?{...v.props}:void 0;if(de.set(k,{markdown:"",title:H,file:B,...j?{props:j}:{}}),!he.has(k)){he.add(k);let ae=Bo(this.config.features?.artifacts,T),Ge=typeof v.component=="string"?v.component:void 0,Te={id:`artifact-ref-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:ga(ae,{artifactId:k,title:H,artifactType:T,status:"streaming",...B?{file:B}:{},...Ge?{component:Ge}:{}})};be.set(k,Te),g(Te)}}else if(F==="artifact_delta"){let T=String(v.id),k=typeof v.delta=="string"?v.delta:String(v.delta??"");n({type:"artifact_delta",id:T,artDelta:k});let H=de.get(T);H&&(H.markdown+=k)}else if(F==="artifact_update"){let T=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};n({type:"artifact_update",id:String(v.id),props:T,component:typeof v.component=="string"?v.component:void 0});let k=de.get(String(v.id));k&&(k.props={...k.props??{},...T})}else if(F==="artifact_complete"){let T=String(v.id);n({type:"artifact_complete",id:T});let k=be.get(T);if(k){k.streaming=!1;try{let H=JSON.parse(k.rawContent??"{}");if(H.props){H.props.status="complete";let V=de.get(T);V?.markdown&&(H.props.markdown=V.markdown),V?.file&&(H.props.file=V.file),H.component==="PersonaArtifactInline"&&V?.props&&Object.keys(V.props).length>0&&(H.props.componentProps=V.props)}k.rawContent=JSON.stringify(H)}catch{}de.delete(T),g(k),be.delete(T)}}}else if(F==="transcript_insert"){let T=v.message;if(!T||typeof T!="object")continue;let k=String(T.id??`msg-${c()}`),H=T.role,B={id:k,role:H==="user"?"user":H==="system"?"system":"assistant",content:typeof T.content=="string"?T.content:"",rawContent:typeof T.rawContent=="string"?T.rawContent:void 0,createdAt:typeof T.createdAt=="string"?T.createdAt:new Date().toISOString(),streaming:T.streaming===!0,...typeof T.variant=="string"?{variant:T.variant}:{},sequence:c()};if(g(B),B.rawContent)try{let ae=JSON.parse(B.rawContent)?.props?.artifactId;typeof ae=="string"&&he.add(ae)}catch{}y=null,M.current=null,Ve.delete(k),ke.delete(k)}else if(F==="error"){if(v.recoverable===!1&&v.error!=null&&v.error!==""){let T=typeof v.error=="string"?v.error:v.error?.message!=null?String(v.error.message):"Execution error";n({type:"error",error:new Error(T)});let k=y;k&&k.streaming&&(k.streaming=!1,g(k)),n({type:"status",status:"idle"})}}else if(F==="step_error"||F==="dispatch_error"||F==="flow_error"){let T=null;if(v.error instanceof Error)T=v.error;else if(F==="dispatch_error"){let k=v.message??v.error;k!=null&&k!==""&&(T=new Error(String(k)))}else{let k=v.error;typeof k=="string"&&k!==""?T=new Error(k):k!=null&&typeof k=="object"&&Reflect.has(k,"message")&&(T=new Error(String(k.message??k)))}if(T){n({type:"error",error:T});let k=y;k&&k.streaming&&(k.streaming=!1,g(k)),n({type:"status",status:"idle"})}}}}}Xe.length=0};;){let{done:E,value:F}=await s.read();if(E)break;i+=a.decode(F,{stream:!0});let v=i.split(`
12
12
 
13
13
  `);i=v.pop()??"";for(let T of v){let k=T.split(`
14
- `),H="message",V="",B=null;for(let Te of k)Te.startsWith("event:")?H=Te.replace("event:","").trim():Te.startsWith("data:")?V+=Te.replace("data:","").trim():Te.startsWith("id:")&&(B=Te.slice(3).trim());let j=()=>{B!==null&&B!==""&&n({type:"cursor",id:B})};if(!V){j();continue}let ae;try{ae=JSON.parse(V)}catch(Te){n({type:"error",error:Te instanceof Error?Te:new Error("Failed to parse chat stream payload")});continue}let Ge=H!=="message"?H:ae.type??"message";if(this.onSSEEvent?.(Ge,ae),this.parseSSEEvent){M.current=y;let Te=await this.handleCustomSSEEvent(ae,n,M,g,c,L);if(M.current&&M.current!==y&&(y=M.current),Te){j();continue}}Xe.push({payloadType:Ge,payload:ae}),Le(),j()}}Le()}};function ih(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function cs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function No(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Sa="[Image]";function lh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function ch(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function bl(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function dh(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Fo(e){return{type:"text",text:e}}function ph(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function uh(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function gh(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Pp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],fh=["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"],jn=[...Pp,...fh];function mh(e){return Pp.includes(e)||e.startsWith("image/")}function Ta(e){return mh(e.type)}async function Rp(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ta(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Ip(e,t=jn,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function hh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Wp(e,t){let n=hh(t).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"}[e]||n||"FILE"}vl();var Hp=16e3,yh=24e3,bh=4096,vh=1380533830;function xh(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===vh?new Uint8Array(e,44):new Uint8Array(e)}function Ch(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var ds=class{constructor(t){this.config=t;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 t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)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:Hp,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,i=new a({sampleRate:Hp});i.state==="suspended"&&await i.resume().catch(()=>{}),this.captureContext=i;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new gr(yh);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(u=>u.stop()),i.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 d=`${Ch(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(i,s,c,r))},c.onmessage=u=>this.handleMessage(u,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.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(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(bh,1,1);this.processor=a,a.onaudioprocess=i=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=i.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}o.send(d.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.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(t,n){if(n!==this.callGeneration||!this.playback)return;let o=xh(t);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(t=>t.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(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var _o=class{constructor(t={}){this.config=t;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(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,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(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function $o(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ds(e.runtype);case"browser":if(!_o.isSupported())throw new Error("Browser speech recognition not supported");return new _o(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;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: ${e.type}`)}}function xl(e){if(e?.type==="custom"&&e.custom)return $o({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return $o({type:"runtype",runtype:e.runtype});if(_o.isSupported())return $o({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ea(e){try{return xl(e),!0}catch{return!1}}function ps(e){let t=["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 t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var jo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(i=>i.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):ps(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let i=a.error;i==="canceled"||i==="interrupted"?n.onEnd?.():n.onError?.(new Error(i||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var fr=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"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(t,"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(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function Cl(e){if(!e)return"";let t=wh(e);return Bp(t!==null?t:e)}function wh(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Bp(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
14
+ `),H="message",V="",B=null;for(let Te of k)Te.startsWith("event:")?H=Te.replace("event:","").trim():Te.startsWith("data:")?V+=Te.replace("data:","").trim():Te.startsWith("id:")&&(B=Te.slice(3).trim());let j=()=>{B!==null&&B!==""&&n({type:"cursor",id:B})};if(!V){j();continue}let ae;try{ae=JSON.parse(V)}catch(Te){n({type:"error",error:Te instanceof Error?Te:new Error("Failed to parse chat stream payload")});continue}let Ge=H!=="message"?H:ae.type??"message";if(this.onSSEEvent?.(Ge,ae),this.parseSSEEvent){M.current=y;let Te=await this.handleCustomSSEEvent(ae,n,M,g,c,L);if(M.current&&M.current!==y&&(y=M.current),Te){j();continue}}Xe.push({payloadType:Ge,payload:ae}),Le(),j()}}Le()}};function lh(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function cs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function No(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Sa="[Image]";function ch(e){return typeof e=="string"?[{type:"text",text:e}]:e}function dh(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function bl(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function ph(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Fo(e){return{type:"text",text:e}}function uh(e,t){return{type:"image",image:e,...t?.mimeType&&{mimeType:t.mimeType},...t?.alt&&{alt:t.alt}}}async function gh(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;t({type:"image",image:r,mimeType:e.type,alt:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function fh(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Rp=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],mh=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],$n=[...Rp,...mh];function hh(e){return Rp.includes(e)||e.startsWith("image/")}function Ta(e){return hh(e.type)}async function Ip(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let r=o.result;Ta(e)?t({type:"image",image:r,mimeType:e.type,alt:e.name}):t({type:"file",data:r,mimeType:e.type,filename:e.name})},o.onerror=()=>n(new Error("Failed to read file")),o.readAsDataURL(e)})}function Wp(e,t=$n,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function yh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Hp(e,t){let n=yh(t).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"}[e]||n||"FILE"}vl();var Bp=16e3,bh=24e3,vh=4096,xh=1380533830;function Ch(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===xh?new Uint8Array(e,44):new Uint8Array(e)}function wh(e){let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window<"u"&&window.location?.protocol==="https:"?"wss:":"ws:"}//${t}`}var ds=class{constructor(t){this.config=t;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 t=this.config?.agentId,n=this.config?.clientToken,o=this.config?.host;if(!t)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:Bp,channelCount:1,echoCancellation:!0}});if(r!==this.callGeneration){s.getTracks().forEach(u=>u.stop());return}this.mediaStream=s;let a=window.AudioContext||window.webkitAudioContext,i=new a({sampleRate:Bp});i.state==="suspended"&&await i.resume().catch(()=>{}),this.captureContext=i;let p=this.config?.createPlaybackEngine?await this.config.createPlaybackEngine():new gr(bh);if(r!==this.callGeneration){p.destroy(),s.getTracks().forEach(u=>u.stop()),i.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 d=`${wh(o)}/ws/agents/${encodeURIComponent(t)}/voice`,c=new WebSocket(d,["runtype.bearer",n]);c.binaryType="arraybuffer",this.ws=c,c.onopen=()=>{r===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(i,s,c,r))},c.onmessage=u=>this.handleMessage(u,r),c.onerror=()=>{r===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},c.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(t,n,o,r){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(vh,1,1);this.processor=a,a.onaudioprocess=i=>{if(r!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let p=i.inputBuffer.getChannelData(0),d=new Int16Array(p.length);for(let c=0;c<p.length;c++){let u=Math.max(-1,Math.min(1,p[c]));d[c]=u<0?u*32768:u*32767}o.send(d.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let o;try{o=JSON.parse(t.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(t,n){if(n!==this.callGeneration||!this.playback)return;let o=Ch(t);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(t=>t.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(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,o){this.transcriptCallbacks.forEach(r=>r(t,n,o))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var _o=class{constructor(t={}){this.config=t;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(t=>t("connected"))}async startListening(){try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let t=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!t)throw new Error("Browser speech recognition not supported");this.recognition=new t,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(t){throw this.errorCallbacks.forEach(n=>n(t)),this.statusCallbacks.forEach(n=>n("error")),t}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function $o(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ds(e.runtype);case"browser":if(!_o.isSupported())throw new Error("Browser speech recognition not supported");return new _o(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;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: ${e.type}`)}}function xl(e){if(e?.type==="custom"&&e.custom)return $o({type:"custom",custom:e.custom});if(e?.type==="runtype"&&e.runtype)return $o({type:"runtype",runtype:e.runtype});if(_o.isSupported())return $o({type:"browser",browser:e?.browser||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ea(e){try{return xl(e),!0}catch{return!1}}function ps(e){let t=["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 t){let o=e.find(r=>r.name===n);if(o)return o}return e.find(n=>n.lang.startsWith("en"))??e[0]}var jo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window<"u"&&"speechSynthesis"in window}speak(t,n){if(!e.isSupported()){n.onError?.(new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let r=new SpeechSynthesisUtterance(t.text),s=o.getVoices();if(t.voice){let a=s.find(i=>i.name===t.voice);a&&(r.voice=a)}else s.length>0&&(r.voice=this.options.pickVoice?this.options.pickVoice(s):ps(s));t.rate!==void 0&&(r.rate=t.rate),t.pitch!==void 0&&(r.pitch=t.pitch),r.onend=()=>n.onEnd?.(),r.onerror=a=>{let i=a.error;i==="canceled"||i==="interrupted"?n.onEnd?.():n.onError?.(new Error(i||"Speech synthesis failed"))},setTimeout(()=>{o.speak(r),n.onStart?.()},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var fr=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){return this.engine?.supportsPause??!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){if(this.activeId===t){if(this.state==="playing"){this.engine?.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){this.engine?.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){let o=++this.generation;this.engine?.stop(),this.set(t,"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(t,"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(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let o of this.listeners)o(this.activeId,this.state)}};function Cl(e){if(!e)return"";let t=Ah(e);return Op(t!==null?t:e)}function Ah(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Op(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
15
15
  `),t=t.replace(/\n{2,}/g,`
16
- `),t.trim()}var _p=null;var wl=()=>_p?_p():Promise.resolve().then(()=>(Fp(),Np));var Mh=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function kh(e,t){return Mh.some(n=>e[n]!==t[n])}function Al(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(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}
16
+ `),t.trim()}var $p=null;var wl=()=>$p?$p():Promise.resolve().then(()=>(_p(),Fp));var kh=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Lh(e,t){return kh.some(n=>e[n]!==t[n])}function Al(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(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}
17
17
 
18
- _Details: ${n.message}_`:o}var us=e=>({isError:!0,content:[{type:"text",text:e}]}),Up=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,zp=e=>Ho(e)||e===Mn,gs=class{constructor(t={},n){this.config=t;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 fr(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(Ho(n.name)||n.name===Mn&&this.config.features?.suggestReplies?.enabled!==!1);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.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"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.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?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new ur(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||wl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Ea(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 t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=jo.isSupported()?new jo({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return wl().then(({RuntypeSpeechEngine:i,FallbackSpeechEngine:p})=>{let d=new i({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=$o(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,i)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!i});else{let p=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!i});this.pendingVoiceUserMessageId=p.id}if(i){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:a,createdAt:new Date().toISOString(),streaming:!i,voiceProcessing:!i});else{let p=this.injectMessage({role:"assistant",content:a,streaming:!i,voiceProcessing:!i});this.pendingVoiceAssistantMessageId=p.id}i&&(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(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!kh(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 ur(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=t,g={id:a??(n==="user"?cs():n==="assistant"?No():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:i??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:b,rawContent:g}=o,C={id:p??(r==="user"?cs():r==="assistant"?No():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...b!==void 0&&{voiceProcessing:b},...g!==void 0&&{rawContent:g}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:p}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
18
+ _Details: ${n.message}_`:o}var us=e=>({isError:!0,content:[{type:"text",text:e}]}),zp=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,qp=e=>Ho(e)||e===En,gs=class{constructor(t={},n){this.config=t;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 fr(()=>this.createSpeechEngine());this.handleEvent=t=>{if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let n=t.message.toolCall,o=!!n?.name&&(Ho(n.name)||n.name===En&&this.config.features?.suggestReplies?.enabled!==!1);t.message.agentMetadata?.awaitingLocalTool===!0&&o&&this.enqueueWebMcpAwait(t.message),t.message.agentMetadata?.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:t.message.agentMetadata.agentName??"",status:"running",currentIteration:t.message.agentMetadata.iteration??0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.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"&&(t.status==="error"?this.agentExecution.status="error":n||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.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?.(t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};this.messages=[...t.initialMessages??[]].map(o=>({...o,sequence:o.sequence??this.nextSequence()})),this.messages=this.sortMessages(this.messages),this.client=new ur(t),this.wireDefaultWebMcpConfirm();for(let o of t.initialArtifacts??[])this.artifacts.set(o.id,{...o,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){let t=this.config.textToSpeech;if(t?.provider!=="runtype"||t.createEngine)return;let n=t.host??this.config.apiUrl,o=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId;!n||!o||!this.config.clientToken||wl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){return this.agentExecution?.status==="running"}isVoiceSupported(){return Ea(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 t=this.config.textToSpeech;if(t?.createEngine)return t.createEngine();let n=jo.isSupported()?new jo({pickVoice:t?.pickVoice}):null;if(t?.provider==="runtype"){let o=t.host??this.config.apiUrl,r=t.agentId??this.config.voiceRecognition?.provider?.runtype?.agentId??this.config.agentId,s=this.config.clientToken,a=t.browserFallback!==!1;if(o&&r&&s)return wl().then(({RuntypeSpeechEngine:i,FallbackSpeechEngine:p})=>{let d=new i({host:o,agentId:r,clientToken:s,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return a&&n?new p(d,n,{onFallback:c=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${c.message}`)}):d});if(a&&n)return s&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=$o(n);let r=(this.config.voiceRecognition??{}).processingErrorText??"Voice processing failed. Please try again.";this.voiceProvider.onResult(s=>{s.provider!=="runtype"&&s.text&&s.text.trim()&&this.sendMessage(s.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((s,a,i)=>{if(s==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!i});else{let p=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!i});this.pendingVoiceUserMessageId=p.id}if(i){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:a,createdAt:new Date().toISOString(),streaming:!i,voiceProcessing:!i});else{let p=this.injectMessage({role:"assistant",content:a,streaming:!i,voiceProcessing:!i});this.pendingVoiceAssistantMessageId=p.id}i&&(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(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){if(!this.config.voiceRecognition?.provider)return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:t.runtype?.agentId??this.config.agentId??"",clientToken:t.runtype?.clientToken??this.config.clientToken,host:t.runtype?.host??this.config.apiUrl,voiceId:t.runtype?.voiceId,createPlaybackEngine:t.runtype?.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:t.browser?.language||"en-US",continuous:t.browser?.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return this.callbacks.onError?.(t instanceof Error?t:new Error(String(t))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){return this.clientSession??this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!Lh(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 ur(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:o,llmContent:r,contentParts:s,id:a,createdAt:i,sequence:p,streaming:d=!1,voiceProcessing:c,rawContent:u}=t,g={id:a??(n==="user"?cs():n==="assistant"?No():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:n,content:o,createdAt:i??new Date().toISOString(),sequence:p??this.nextSequence(),streaming:d,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s},...c!==void 0&&{voiceProcessing:c},...u!==void 0&&{rawContent:u}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let o of t){let{role:r,content:s,llmContent:a,contentParts:i,id:p,createdAt:d,sequence:c,streaming:u=!1,voiceProcessing:b,rawContent:g}=o,C={id:p??(r==="user"?cs():r==="assistant"?No():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`),role:r,content:s,createdAt:d??new Date().toISOString(),sequence:c??this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...b!==void 0&&{voiceProcessing:b},...g!==void 0&&{rawContent:g}};n.push(C)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:o={},text:r="",llmContent:s,id:a,createdAt:i,sequence:p}=t,d={text:r,component:n,props:o};return this.injectMessage({role:"assistant",content:r,rawContent:JSON.stringify(d),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...p!==void 0&&{sequence:p}})}async applyMentionBundle(t,n,o){let r;try{r=await o()}catch{return}let s=r.blocks.join(`
19
19
 
20
20
  `),a=[s,n].filter(Boolean).join(`
21
21
 
22
- `),i=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(i){let d=[];s&&d.push(Fo(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];a&&d.push(Fo(a)),d.push(...r.contentParts),t.contentParts=d}else s&&(t.llmContent=a);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.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=cs(),s=No();this.activeAssistantMessageId=null;let a=n?.contentParts&&bl(n.contentParts)?Sa:"",i={id:r,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(i),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let c=this.messages.find(u=>u.id===r)??i;if(await this.applyMentionBundle(c,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:p.signal,assistantMessageId:s},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let b=Al(c,this.config.errorMessage);if(b){let g={id:s,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=No();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:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=Al(r,this.config.errorMessage);if(a){let i={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(i)}}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(t,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(t,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 t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.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(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===r),i={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let b=await c.json().catch(()=>null);throw new Error(b?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.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(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let b=typeof u[0]?.question=="string"?u[0].question:"";b&&(a={[b]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,p=t.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,b])=>`${u}: ${Array.isArray(b)?b.join(", "):b}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((u,b)=>{let g=typeof u?.question=="string"?u.question:"";if(!g)return;let y=c[g],C=Array.isArray(y)?y.join(", "):typeof y=="string"?y:"";this.appendMessage({id:`ask-user-q-${i}-${b}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${b}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[s]:n});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});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(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==Mn?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let u=`${t}:${c}`;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),g=p.agentMetadata?.webMcpToolCallId??d;if(d===Mn)return{dedupeKey:u,resumeKey:g,output:dl(),toolMessage:p,startedAt:b,completedAt:Date.now()};let y=new AbortController;this.webMcpResolveControllers.add(y),r.push(y);let C=this.client.executeWebMcpToolCall(d,p.toolCall?.args,y.signal),M;if(!C)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await C}catch(L){let I=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));return I||this.callbacks.onError?.(L instanceof Error?L:new Error(String(L))),this.markWebMcpToolComplete(p,us(I?"Aborted by cancel()":Up(L)),b),this.webMcpInflightKeys.delete(u),null}return y.signal.aborted?(this.markWebMcpToolComplete(p,us("Aborted by cancel()"),b),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:g,output:M,toolMessage:p,startedAt:b,completedAt:Date.now()}})),i=[];try{if(i=a.filter(c=>c!==null),i.length===0)return;let p={};for(let c of i)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,p,{signal:s.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of i)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===Mn?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.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 c of i)this.markWebMcpToolComplete(c.toolMessage,us("Aborted by cancel()"),c.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(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let y=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(y)||this.webMcpResolvedKeys.has(y))return;this.webMcpInflightKeys.add(y);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(y)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(y)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:p}=i;this.setStreaming(!0);let d=o===Mn,c=t.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),b="execute",g=a;try{let y;if(d?y=dl():u?y=await u:y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),p.aborted){this.markWebMcpToolComplete(t,us("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;b="resume",await this.resumeWithToolOutput(n,C,y,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,y,a,g,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(y){let C=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));(b==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(t,us(C||p.aborted?"Aborted by cancel()":Up(y)),a),C||this.callbacks.onError?.(y instanceof Error?y:new Error(String(y)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"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(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=Bo(this.config.features?.artifacts,t.artifactType),r=ga(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}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(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,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(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.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(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(jp(),$p)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>Al(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=No(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];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 t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){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(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.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=Cl(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return ps(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=Cl(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,u=n.approval;a.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let i=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(i&&zp(i)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),b=this.webMcpResolvedKeys.has(c),g=r.toolCall?.name,y=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&g!==void 0&&zp(g)&&r.toolCall?.status==="complete";(u||b||y)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,i=o.sequence??0;return a!==i?a-i:n.id.localeCompare(o.id)})}};import{Activity as Lh,ArrowDown as Ph,ArrowUp as Rh,ArrowUpRight as Ih,Bot as Wh,ChevronDown as Hh,ChevronUp as Bh,ChevronRight as Oh,ChevronLeft as Dh,Check as Nh,Clipboard as Fh,ClipboardCopy as _h,CodeXml as $h,Copy as jh,File as Uh,FileCode as zh,FileSpreadsheet as qh,FileText as Vh,ImagePlus as Kh,Loader as Gh,LoaderCircle as Jh,Mic as Xh,Paperclip as Qh,RefreshCw as Yh,Search as Zh,Send as ey,ShieldAlert as ty,ShieldCheck as ny,ShieldX as oy,Square as ry,ThumbsDown as sy,ThumbsUp as ay,Upload as iy,Volume2 as ly,X as cy,User as dy,Mail as py,Phone as uy,Calendar as gy,Clock as fy,Building as my,MapPin as hy,Lock as yy,Key as by,CreditCard as vy,AtSign as xy,Hash as Cy,Globe as wy,Link as Ay,CircleCheck as Sy,CircleX as Ty,TriangleAlert as Ey,Info as My,Ban as ky,Shield as Ly,ArrowLeft as Py,ArrowRight as Ry,ExternalLink as Iy,Ellipsis as Wy,EllipsisVertical as Hy,Menu as By,House as Oy,Plus as Dy,Minus as Ny,Pencil as Fy,Trash as _y,Trash2 as $y,Save as jy,Download as Uy,Share as zy,Funnel as qy,Settings as Vy,RotateCw as Ky,Maximize as Gy,Minimize as Jy,ShoppingCart as Xy,ShoppingBag as Qy,Package as Yy,Truck as Zy,Tag as eb,Gift as tb,Receipt as nb,Wallet as ob,Store as rb,DollarSign as sb,Percent as ab,Play as ib,Pause as lb,VolumeX as cb,Camera as db,Image as pb,Film as ub,Headphones as gb,MessageCircle as fb,MessageSquare as mb,Bell as hb,Heart as yb,Star as bb,Eye as vb,EyeOff as xb,Bookmark as Cb,CalendarDays as wb,History as Ab,Timer as Sb,Folder as Tb,FolderOpen as Eb,Files as Mb,Sparkles as kb,Zap as Lb,Sun as Pb,Moon as Rb,Flag as Ib,Monitor as Wb,Smartphone as Hb}from"lucide";var Bb={activity:Lh,"arrow-down":Ph,"arrow-up":Rh,"arrow-up-right":Ih,bot:Wh,"chevron-down":Hh,"chevron-up":Bh,"chevron-right":Oh,"chevron-left":Dh,check:Nh,clipboard:Fh,"clipboard-copy":_h,"code-xml":$h,copy:jh,file:Uh,"file-code":zh,"file-spreadsheet":qh,"file-text":Vh,"image-plus":Kh,loader:Gh,"loader-circle":Jh,mic:Xh,paperclip:Qh,"refresh-cw":Yh,search:Zh,send:ey,"shield-alert":ty,"shield-check":ny,"shield-x":oy,square:ry,"thumbs-down":sy,"thumbs-up":ay,upload:iy,"volume-2":ly,x:cy,user:dy,mail:py,phone:uy,calendar:gy,clock:fy,building:my,"map-pin":hy,lock:yy,key:by,"credit-card":vy,"at-sign":xy,hash:Cy,globe:wy,link:Ay,"circle-check":Sy,"circle-x":Ty,"triangle-alert":Ey,info:My,ban:ky,shield:Ly,"arrow-left":Py,"arrow-right":Ry,"external-link":Iy,ellipsis:Wy,"ellipsis-vertical":Hy,menu:By,house:Oy,plus:Dy,minus:Ny,pencil:Fy,trash:_y,"trash-2":$y,save:jy,download:Uy,share:zy,funnel:qy,settings:Vy,"rotate-cw":Ky,maximize:Gy,minimize:Jy,"shopping-cart":Xy,"shopping-bag":Qy,package:Yy,truck:Zy,tag:eb,gift:tb,receipt:nb,wallet:ob,store:rb,"dollar-sign":sb,percent:ab,play:ib,pause:lb,"volume-x":cb,camera:db,image:pb,film:ub,headphones:gb,"message-circle":fb,"message-square":mb,bell:hb,heart:yb,star:bb,eye:vb,"eye-off":xb,bookmark:Cb,"calendar-days":wb,history:Ab,timer:Sb,folder:Tb,"folder-open":Eb,files:Mb,sparkles:kb,zap:Lb,sun:Pb,moon:Rb,flag:Ib,monitor:Wb,smartphone:Hb},te=(e,t=24,n="currentColor",o=2)=>{let r=Bb[e];return r?Ob(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Ob(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),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"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([d,c])=>{d!=="stroke"&&p.setAttribute(d,String(c))}),r.appendChild(p)}),r}var La={allowedTypes:jn,maxFileSize:10*1024*1024,maxFiles:4};function Db(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Nb(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var mr=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??La.allowedTypes,maxFileSize:t.maxFileSize??La.maxFileSize,maxFiles:t.maxFiles??La.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:La.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(t.length){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=Ip(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 Rp(n),s=Ta(n)?URL.createObjectURL(n):null,a={id:Db(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);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="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ta(t.file),o=m("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=m("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=m("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Nb(t.file.type),p=te(i,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=m("span");d.textContent=Wp(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let r=m("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=te("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var qp=/\s/;function Fb(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
23
- `:o===""||qp.test(o)}function _b(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let s=t-1;for(;s>=0;){let a=e[s];if(a===n)return Fb(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(a===`
24
- `||a==="\uFFFC"||!r&&qp.test(a))return null;s--}return null}function Vp(e,t,n){for(let o of n){let r=_b(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Kp(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function Gp(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.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[t,...n]}var It={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Ut=1e5,Pa=Ut+1;var $b=8,jb=8,Sl=10,Tl=new WeakMap,Jp=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,Ub=e=>{let t=e.getRootNode?.();return Jp(t)?t:e.ownerDocument.body},El=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function Dt(e){Tl.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:s=$b,viewportPadding:a=jb}=e,i=()=>t.ownerDocument,p=()=>i().defaultView??window,d=null,c=null,u=null,b=!1,g=!1,y=!1,C=()=>(typeof o=="function"?o():o).trim(),M=()=>{u?.(),u=null,d?.remove(),d=null,c=null},L=()=>{if(!d)return;let Q=i(),O=p(),D=t.getBoundingClientRect(),ie=d.getBoundingClientRect(),me=Q.documentElement.clientWidth||O.innerWidth,we=Q.documentElement.clientHeight||O.innerHeight,Ee=me-a-ie.width,se=D.left+D.width/2-ie.width/2,fe=El(se,a,Ee),Y=D.top-a,ce=we-a-D.bottom,Z=ie.height+s,be=Y>=Z||Y>=ce?"top":"bottom",he=be==="top"?D.top-s-ie.height:D.bottom+s,de=we-a-ie.height,Me=El(he,a,de),De=D.left+D.width/2,_e=Math.max(Sl,ie.width-Sl),He=El(De-fe,Sl,_e);d.dataset.placement=be,d.style.left=`${fe}px`,d.style.top=`${Me}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${He}px`)},I=()=>{if(y||!r||d||!t.isConnected)return;let Q=C(),O=Ub(t);if(!Q||!O)return;let D=i(),ie=p();d=D.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(Pa),c=D.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=Q,d.appendChild(c);let me=D.createElement("span");me.className="persona-control-tooltip__arrow",d.appendChild(me),O.appendChild(d),L(),d.dataset.state="open";let we=()=>{if(!t.isConnected){M();return}c&&(c.textContent=C()),L()};ie.addEventListener("scroll",we,!0),ie.addEventListener("resize",we);let Ee=t.getRootNode(),se=Jp(Ee)?Ee:D.documentElement,fe=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||M()});fe?.observe(se,{childList:!0,subtree:!0}),u=()=>{ie.removeEventListener("scroll",we,!0),ie.removeEventListener("resize",we),fe?.disconnect()}},S=()=>{b||g?I():M()},R=()=>{let Q=p();(!Q.matchMedia||!Q.matchMedia("(hover: none)").matches)&&(b=!0,S())},$=()=>{b=!1,S()},z=()=>{g=!0,S()},w=()=>{g=!1,S()},U=Q=>{Q.key==="Escape"&&(b=!1,g=!1,M())};n.addEventListener("mouseenter",R),n.addEventListener("mouseleave",$),t.addEventListener("focus",z),t.addEventListener("blur",w),t.addEventListener("keydown",U);let q={get isOpen(){return d!==null},show:I,hide:M,reposition:L,destroy:()=>{y||(y=!0,M(),n.removeEventListener("mouseenter",R),n.removeEventListener("mouseleave",$),t.removeEventListener("focus",z),t.removeEventListener("blur",w),t.removeEventListener("keydown",U),Tl.delete(t))}};return Tl.set(t,q),q}function Xp(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=t.buttonIconName??"plus",i=t.buttonTooltipText??"Add context",p=m("div","persona-send-button-wrapper"),d=Fe("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":i,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=te(a,s,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(d),Dt({anchor:d,trigger:p,text:()=>d.getAttribute("aria-label")??i}),{button:d,wrapper:p}}var{setLoader:fS,load:zb}=lr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var Ml=zb;var{setLoader:yS,load:qb}=lr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var Qp=qb;function fs(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Fe("span",{className:$n("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=te(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=m("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Fe("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function Yp(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Gp(t).filter(S=>S.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(S=>S.sources.some(R=>typeof R.matchCommand=="function")),r=S=>o.some(R=>R.trigger?R.position==="line-start"?S.split(`
22
+ `),i=Array.isArray(t.contentParts)&&t.contentParts.length>0,p=r.contentParts.length>0;if(i){let d=[];s&&d.push(Fo(s)),d.push(...r.contentParts),d.push(...t.contentParts),t.contentParts=d}else if(p){let d=[];a&&d.push(Fo(a)),d.push(...r.contentParts),t.contentParts=d}else s&&(t.llmContent=a);Object.keys(r.context).length>0&&(t.mentionContext=r.context)}async sendMessage(t,n){let o=t.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=cs(),s=No();this.activeAssistantMessageId=null;let a=n?.contentParts&&bl(n.contentParts)?Sa:"",i={id:r,role:"user",content:o||a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:n?.viaVoice||!1,...n?.contentParts&&n.contentParts.length>0&&{contentParts:n.contentParts},...n?.mentions&&n.mentions.refs.length>0&&{contextMentions:n.mentions.refs},...n?.contentSegments&&n.contentSegments.length>0&&{contentSegments:n.contentSegments}};this.appendMessage(i),this.setStreaming(!0);let p=new AbortController;if(this.abortController=p,n?.mentions){let c=this.messages.find(u=>u.id===r)??i;if(await this.applyMentionBundle(c,o,n.mentions.finalize),p.signal.aborted||this.abortController!==p)return;this.callbacks.onMessagesChanged([...this.messages])}let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:p.signal,assistantMessageId:s},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let b=Al(c,this.config.errorMessage);if(b){let g={id:s,role:"assistant",createdAt:new Date().toISOString(),content:b,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?this.callbacks.onError?.(c):this.callbacks.onError?.(new Error(String(c))))}}async continueConversation(){if(this.streaming)return;this.abortController?.abort(),this.teardownReconnect();let t=No();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:t},this.handleEvent)}catch(r){if(this.status==="resuming"||this.reconnecting)return;let s=r instanceof Error&&(r.name==="AbortError"||r.message.includes("aborted")||r.message.includes("abort"));if(!s){let a=Al(r,this.config.errorMessage);if(a){let i={id:t,role:"assistant",createdAt:new Date().toISOString(),content:a,sequence:this.nextSequence()};this.appendMessage(i)}}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(t,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(t,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 t=this.config.webmcp;t?.enabled===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){try{if(this.config.webmcp?.autoApprove?.(t)===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:t.description??`Allow the assistant to run ${t.toolName}?`,parameters:t.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(t,n){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let r=this.messages.find(s=>s.id===t);r?.approval&&this.upsertMessage({...r,approval:{...r.approval,status:n,resolvedAt:Date.now()}}),o(n==="approved")}async resolveApproval(t,n,o){let r=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(c=>c.id===r),i={id:r,role:"assistant",content:"",createdAt:a?.createdAt??new Date().toISOString(),...a?.sequence!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let p=this.config.approval,d=p&&typeof p=="object"?p.onDecision:void 0;try{let c;if(d?c=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,o):c=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),c){let u=null;if(c instanceof Response){if(!c.ok){let b=await c.json().catch(()=>null);throw new Error(b?.error??`Approval request failed: ${c.status}`)}u=c.body}else c instanceof ReadableStream&&(u=c);u?await this.connectStream(u,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.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(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}persistAskUserQuestionProgress(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let o=this.messages.find(r=>r.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){if(this.messages.find(c=>c.id===t.id)?.agentMetadata?.askUserQuestionAnswered===!0)return;let r=t.agentMetadata?.executionId,s=t.toolCall?.name;if(!r||!s){this.callbacks.onError?.(new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let c=t.toolCall?.args,u=Array.isArray(c?.questions)?c.questions:[];if(u.length===1){let b=typeof u[0]?.question=="string"?u[0].question:"";b&&(a={[b]:n})}}this.markAskUserQuestionResolved(t,a),this.abortController?.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,p=t.toolCall?.args,d=Array.isArray(p?.questions)?p.questions:[];if(d.length===0){let c=typeof n=="string"?n:Object.entries(n).map(([u,b])=>`${u}: ${Array.isArray(b)?b.join(", "):b}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let c=a??{};d.forEach((u,b)=>{let g=typeof u?.question=="string"?u.question:"";if(!g)return;let y=c[g],C=Array.isArray(y)?y.join(", "):typeof y=="string"?y:"";this.appendMessage({id:`ask-user-q-${i}-${b}`,role:"assistant",content:g,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${b}`,role:"user",content:C||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let c=await this.client.resumeFlow(r,{[s]:n});if(!c.ok){let u=await c.json().catch(()=>null);throw new Error(u?.error??`Resume failed: ${c.status}`)}c.body?await this.connectStream(c.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));this.setStreaming(!1),this.abortController=null,u||this.callbacks.onError?.(c instanceof Error?c:new Error(String(c)))}}enqueueWebMcpAwait(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.id;if(!n||!o){let s=this.webMcpEpoch;queueMicrotask(()=>{s===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});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(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=n;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){let o=[this.messages.find(r=>r.id===t.id)?.toolCall?.startedAt,t.toolCall?.startedAt];for(let r of o)if(typeof r=="number"&&Number.isFinite(r))return r;return Date.now()}isSuggestRepliesAlreadyResolved(t){return t.toolCall?.name!==En?!1:(this.messages.find(o=>o.id===t.id)??t).agentMetadata?.suggestRepliesResolved===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,o,r=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:o,completedAt:r,duration:void 0,durationMs:Math.max(0,r-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){let o=[],r=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async p=>{let d=p.toolCall?.name,c=p.toolCall?.id;if(!d||!c)return null;let u=`${t}:${c}`;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),g=p.agentMetadata?.webMcpToolCallId??d;if(d===En)return{dedupeKey:u,resumeKey:g,output:dl(),toolMessage:p,startedAt:b,completedAt:Date.now()};let y=new AbortController;this.webMcpResolveControllers.add(y),r.push(y);let C=this.client.executeWebMcpToolCall(d,p.toolCall?.args,y.signal),M;if(!C)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await C}catch(L){let I=L instanceof Error&&(L.name==="AbortError"||L.message.includes("aborted")||L.message.includes("abort"));return I||this.callbacks.onError?.(L instanceof Error?L:new Error(String(L))),this.markWebMcpToolComplete(p,us(I?"Aborted by cancel()":zp(L)),b),this.webMcpInflightKeys.delete(u),null}return y.signal.aborted?(this.markWebMcpToolComplete(p,us("Aborted by cancel()"),b),this.webMcpInflightKeys.delete(u),null):{dedupeKey:u,resumeKey:g,output:M,toolMessage:p,startedAt:b,completedAt:Date.now()}})),i=[];try{if(i=a.filter(c=>c!==null),i.length===0)return;let p={};for(let c of i)p[c.resumeKey]=c.output;let d=await this.client.resumeFlow(t,p,{signal:s.signal});if(!d.ok){let c=await d.json().catch(()=>null);throw new Error(c?.error??`Resume failed: ${d.status}`)}for(let c of i)this.webMcpResolvedKeys.add(c.dedupeKey),this.markWebMcpToolComplete(c.toolMessage,c.output,c.startedAt,c.completedAt,c.toolMessage.toolCall?.name===En?{suggestRepliesResolved:!0}:void 0);d.body&&await this.connectStream(d.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 c of i)this.markWebMcpToolComplete(c.toolMessage,us("Aborted by cancel()"),c.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(t){let n=t.agentMetadata?.executionId,o=t.toolCall?.name,r=t.toolCall?.id;if(!n){this.callbacks.onError?.(new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!r){let y=`${n}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(y)||this.webMcpResolvedKeys.has(y))return;this.webMcpInflightKeys.add(y);try{await this.resumeWithToolOutput(n,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(y)}catch(C){this.callbacks.onError?.(C instanceof Error?C:new Error(String(C)))}finally{this.webMcpInflightKeys.delete(y)}return}let s=`${n}:${r}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:p}=i;this.setStreaming(!0);let d=o===En,c=t.toolCall?.args,u=d?null:this.client.executeWebMcpToolCall(o,c,p),b="execute",g=a;try{let y;if(d?y=dl():u?y=await u:y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),p.aborted){this.markWebMcpToolComplete(t,us("Aborted by cancel()"),a);return}let C=t.agentMetadata?.webMcpToolCallId??o;b="resume",await this.resumeWithToolOutput(n,C,y,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,y,a,g,d?{suggestRepliesResolved:!0}:void 0)},signal:p})}catch(y){let C=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));(b==="execute"||C||p.aborted)&&this.markWebMcpToolComplete(t,us(C||p.aborted?"Aborted by cancel()":zp(y)),a),C||this.callbacks.onError?.(y instanceof Error?y:new Error(String(y)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,o,r){let s=await this.client.resumeFlow(t,{[n]:o},{signal:r?.signal});if(!s.ok){let a=await s.json().catch(()=>null);throw new Error(a?.error??`Resume failed: ${s.status}`)}r?.onHttpOk?.(),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"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(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,o=t.artifactType==="markdown"?{id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content,...t.file?{file:t.file}:{}}:{id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:t.props??{}};return this.artifacts.set(n,o),this.selectedArtifactId=n,this.emitArtifactsState(),t.transcript!==!1&&this.injectArtifactRefBlock(o),o}injectArtifactRefBlock(t){let n=`artifact-ref-${t.id}`,o=Bo(this.config.features?.artifacts,t.artifactType),r=ga(o,{artifactId:t.id,title:t.title,artifactType:t.artifactType,status:"complete",...t.file?{file:t.file}:{},...t.component?{component:t.component}:{},...t.props?{componentProps:t.props}:{},...t.markdown!==void 0?{markdown:t.markdown}:{}}),s=this.messages.find(a=>a.id===n);if(s){s.rawContent=r,s.streaming=!1,this.callbacks.onMessagesChanged([...this.messages]);return}this.injectAssistantMessage({id:n,content:"",rawContent:r})}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(t){switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:"",...t.file?{file:t.file}:{}}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:t.component??"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);n?.artifactType==="markdown"&&(n.markdown=(n.markdown??"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);n?.artifactType==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){this.abortController?.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(n=>({...n,streaming:!1,sequence:n.sequence??this.nextSequence()}))),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){let n=this.agentExecution?.executionId;if(!n||!this.activeAssistantMessageId||this.agentExecution?.status!=="running")return;let o=this.resumable===null;this.resumable={executionId:n,lastEventId:t,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(t=>t.agentMetadata?.awaitingLocalTool===!0&&t.agentMetadata?.askUserQuestionAnswered!==!0||t.variant==="approval"&&t.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(t=>{this.reconnecting&&this.resumable&&t.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(Up(),jp)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,o,r)=>t.connectStream(n,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:r}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>t.callbacks.onReconnect?.(n),buildErrorContent:n=>Al(new Error(n),t.config.errorMessage),onError:n=>t.callbacks.onError?.(n)}}reconnectNow(){if(this.reconnecting){this.reconnectController?.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=No(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];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 t=this.resumable!==null;this.resumable=null,t&&this.config.onExecutionState?.(null)}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){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(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!t?.enabled||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.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=Cl(o.content);r.trim()&&this.readAloud.play(o.id,{text:r,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return ps(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let o=Cl(n.content||"");if(!o.trim())return;let r=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:r?.voice,rate:r?.rate,pitch:r?.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),o=this.messages.findIndex(r=>r.id===n.id);if(o===-1){this.appendMessage(n);return}this.messages=this.messages.map((r,s)=>{if(s!==o)return r;let a={...r,...n};if(r.agentMetadata?.askUserQuestionAnswered===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...r.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:r.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),r.agentMetadata?.suggestRepliesResolved===!0&&n.agentMetadata&&(a.agentMetadata={...a.agentMetadata??n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),r.approval&&n.approval&&r.approval.id===n.approval.id){let c=r.approval,u=n.approval;a.approval={...c,...u,executionId:u.executionId||c.executionId,toolName:u.toolName||c.toolName,description:u.description||c.description,toolType:u.toolType??c.toolType,reason:u.reason??c.reason,parameters:u.parameters??c.parameters}}let i=n.toolCall?.name,p=n.agentMetadata?.executionId,d=n.toolCall?.id;if(i&&qp(i)&&p&&d&&n.agentMetadata?.awaitingLocalTool===!0){let c=`${p}:${d}`,u=this.webMcpInflightKeys.has(c),b=this.webMcpResolvedKeys.has(c),g=r.toolCall?.name,y=r.agentMetadata?.executionId===p&&r.toolCall?.id===d&&g!==void 0&&qp(g)&&r.toolCall?.status==="complete";(u||b||y)&&(a.agentMetadata={...a.agentMetadata??{},awaitingLocalTool:!1},a.toolCall=r.toolCall,a.streaming=r.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,o)=>{let r=new Date(n.createdAt).getTime(),s=new Date(o.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let a=n.sequence??0,i=o.sequence??0;return a!==i?a-i:n.id.localeCompare(o.id)})}};import{Activity as Ph,ArrowDown as Rh,ArrowUp as Ih,ArrowUpRight as Wh,Bot as Hh,ChevronDown as Bh,ChevronUp as Oh,ChevronRight as Dh,ChevronLeft as Nh,Check as Fh,Clipboard as _h,ClipboardCopy as $h,CodeXml as jh,Copy as Uh,File as zh,FileCode as qh,FileSpreadsheet as Vh,FileText as Kh,ImagePlus as Gh,Loader as Jh,LoaderCircle as Xh,Mic as Qh,Paperclip as Yh,RefreshCw as Zh,Search as ey,Send as ty,ShieldAlert as ny,ShieldCheck as oy,ShieldX as ry,Square as sy,ThumbsDown as ay,ThumbsUp as iy,Upload as ly,Volume2 as cy,X as dy,User as py,Mail as uy,Phone as gy,Calendar as fy,Clock as my,Building as hy,MapPin as yy,Lock as by,Key as vy,CreditCard as xy,AtSign as Cy,Hash as wy,Globe as Ay,Link as Sy,CircleCheck as Ty,CircleX as Ey,TriangleAlert as My,Info as ky,Ban as Ly,Shield as Py,ArrowLeft as Ry,ArrowRight as Iy,ExternalLink as Wy,Ellipsis as Hy,EllipsisVertical as By,Menu as Oy,House as Dy,Plus as Ny,Minus as Fy,Pencil as _y,Trash as $y,Trash2 as jy,Save as Uy,Download as zy,Share as qy,Funnel as Vy,Settings as Ky,RotateCw as Gy,Maximize as Jy,Minimize as Xy,ShoppingCart as Qy,ShoppingBag as Yy,Package as Zy,Truck as eb,Tag as tb,Gift as nb,Receipt as ob,Wallet as rb,Store as sb,DollarSign as ab,Percent as ib,Play as lb,Pause as cb,VolumeX as db,Camera as pb,Image as ub,Film as gb,Headphones as fb,MessageCircle as mb,MessageSquare as hb,Bell as yb,Heart as bb,Star as vb,Eye as xb,EyeOff as Cb,Bookmark as wb,CalendarDays as Ab,History as Sb,Timer as Tb,Folder as Eb,FolderOpen as Mb,Files as kb,Sparkles as Lb,Zap as Pb,Sun as Rb,Moon as Ib,Flag as Wb,Monitor as Hb,Smartphone as Bb}from"lucide";var Ob={activity:Ph,"arrow-down":Rh,"arrow-up":Ih,"arrow-up-right":Wh,bot:Hh,"chevron-down":Bh,"chevron-up":Oh,"chevron-right":Dh,"chevron-left":Nh,check:Fh,clipboard:_h,"clipboard-copy":$h,"code-xml":jh,copy:Uh,file:zh,"file-code":qh,"file-spreadsheet":Vh,"file-text":Kh,"image-plus":Gh,loader:Jh,"loader-circle":Xh,mic:Qh,paperclip:Yh,"refresh-cw":Zh,search:ey,send:ty,"shield-alert":ny,"shield-check":oy,"shield-x":ry,square:sy,"thumbs-down":ay,"thumbs-up":iy,upload:ly,"volume-2":cy,x:dy,user:py,mail:uy,phone:gy,calendar:fy,clock:my,building:hy,"map-pin":yy,lock:by,key:vy,"credit-card":xy,"at-sign":Cy,hash:wy,globe:Ay,link:Sy,"circle-check":Ty,"circle-x":Ey,"triangle-alert":My,info:ky,ban:Ly,shield:Py,"arrow-left":Ry,"arrow-right":Iy,"external-link":Wy,ellipsis:Hy,"ellipsis-vertical":By,menu:Oy,house:Dy,plus:Ny,minus:Fy,pencil:_y,trash:$y,"trash-2":jy,save:Uy,download:zy,share:qy,funnel:Vy,settings:Ky,"rotate-cw":Gy,maximize:Jy,minimize:Xy,"shopping-cart":Qy,"shopping-bag":Yy,package:Zy,truck:eb,tag:tb,gift:nb,receipt:ob,wallet:rb,store:sb,"dollar-sign":ab,percent:ib,play:lb,pause:cb,"volume-x":db,camera:pb,image:ub,film:gb,headphones:fb,"message-circle":mb,"message-square":hb,bell:yb,heart:bb,star:vb,eye:xb,"eye-off":Cb,bookmark:wb,"calendar-days":Ab,history:Sb,timer:Tb,folder:Eb,"folder-open":Mb,files:kb,sparkles:Lb,zap:Pb,sun:Rb,moon:Ib,flag:Wb,monitor:Hb,smartphone:Bb},te=(e,t=24,n="currentColor",o=2)=>{let r=Ob[e];return r?Db(r,t,n,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Db(e,t,n,o){if(!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(t)),r.setAttribute("height",String(t)),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"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([d,c])=>{d!=="stroke"&&p.setAttribute(d,String(c))}),r.appendChild(p)}),r}var La={allowedTypes:$n,maxFileSize:10*1024*1024,maxFiles:4};function Nb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Fb(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var mr=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;this.config={allowedTypes:t.allowedTypes??La.allowedTypes,maxFileSize:t.maxFileSize??La.maxFileSize,maxFiles:t.maxFiles??La.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:La.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){if(t.length){for(let n of t){if(this.attachments.length>=this.config.maxFiles){this.config.onFileRejected?.(n,"count");continue}let o=Wp(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 Ip(n),s=Ta(n)?URL.createObjectURL(n):null,a={id:Nb(),file:n,previewUrl:s,contentPart:r};this.attachments.push(a),this.renderPreview(a)}catch(r){console.error("[AttachmentManager] Failed to process file:",r)}}this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}}removeAttachment(t){let n=this.attachments.findIndex(s=>s.id===t);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="${t}"]`);r&&r.remove(),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}clearAttachments(){for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),this.config.onAttachmentsChange?.(this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ta(t.file),o=m("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",n&&t.previewUrl){let a=m("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",o.appendChild(a)}else{let a=m("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Fb(t.file.type),p=te(i,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let d=m("span");d.textContent=Hp(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",a.appendChild(d),o.appendChild(a)}let r=m("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=te("x",10,"var(--persona-text-inverse, #ffffff)",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="var(--persona-text-inverse, #ffffff)",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(r),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t?.allowedTypes,maxFileSize:t?.maxFileSize,maxFiles:t?.maxFiles,onFileRejected:t?.onFileRejected,onAttachmentsChange:n})}};var Vp=/\s/;function _b(e,t,n){if(n==="input-start")return t===0;let o=t>0?e[t-1]:"";return n==="line-start"?o===""||o===`
23
+ `:o===""||Vp.test(o)}function $b(e,t,n="@",o="anywhere",r=!1){if(!n||t<=0||t>e.length)return null;let s=t-1;for(;s>=0;){let a=e[s];if(a===n)return _b(e,s,o)?{triggerIndex:s,query:e.slice(s+1,t)}:null;if(a===`
24
+ `||a==="\uFFFC"||!r&&Vp.test(a))return null;s--}return null}function Kp(e,t,n){for(let o of n){let r=$b(e,t,o.trigger,o.position??"anywhere",o.allowSpaces??!1);if(r)return{channel:o,match:r}}return null}function Gp(e){return e?e!=="insertFromPaste"&&e!=="insertFromDrop":!0}function Jp(e){let t={trigger:e.trigger??"@",position:e.triggerPosition??"anywhere",allowSpaces:!1,sources:Array.isArray(e.sources)?e.sources:[],searchPlaceholder:e.searchPlaceholder,showButton:e.showButton!==!1,buttonIconName:e.buttonIconName,buttonTooltipText:e.buttonTooltipText},n=(e.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[t,...n]}var It={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},Ut=1e5,Pa=Ut+1;var jb=8,Ub=8,Sl=10,Tl=new WeakMap,Xp=e=>e.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in e,zb=e=>{let t=e.getRootNode?.();return Xp(t)?t:e.ownerDocument.body},El=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function Dt(e){Tl.get(e.anchor)?.destroy();let{anchor:t,trigger:n=t,text:o,enabled:r=!0,gap:s=jb,viewportPadding:a=Ub}=e,i=()=>t.ownerDocument,p=()=>i().defaultView??window,d=null,c=null,u=null,b=!1,g=!1,y=!1,C=()=>(typeof o=="function"?o():o).trim(),M=()=>{u?.(),u=null,d?.remove(),d=null,c=null},L=()=>{if(!d)return;let Q=i(),O=p(),D=t.getBoundingClientRect(),ie=d.getBoundingClientRect(),me=Q.documentElement.clientWidth||O.innerWidth,we=Q.documentElement.clientHeight||O.innerHeight,Ee=me-a-ie.width,se=D.left+D.width/2-ie.width/2,fe=El(se,a,Ee),Y=D.top-a,ce=we-a-D.bottom,Z=ie.height+s,be=Y>=Z||Y>=ce?"top":"bottom",he=be==="top"?D.top-s-ie.height:D.bottom+s,de=we-a-ie.height,Me=El(he,a,de),De=D.left+D.width/2,_e=Math.max(Sl,ie.width-Sl),He=El(De-fe,Sl,_e);d.dataset.placement=be,d.style.left=`${fe}px`,d.style.top=`${Me}px`,d.style.setProperty("--persona-tooltip-arrow-x",`${He}px`)},I=()=>{if(y||!r||d||!t.isConnected)return;let Q=C(),O=zb(t);if(!Q||!O)return;let D=i(),ie=p();d=D.createElement("div"),d.className="persona-control-tooltip",d.setAttribute("role","tooltip"),d.dataset.state="measuring",d.style.zIndex=String(Pa),c=D.createElement("span"),c.className="persona-control-tooltip__label",c.textContent=Q,d.appendChild(c);let me=D.createElement("span");me.className="persona-control-tooltip__arrow",d.appendChild(me),O.appendChild(d),L(),d.dataset.state="open";let we=()=>{if(!t.isConnected){M();return}c&&(c.textContent=C()),L()};ie.addEventListener("scroll",we,!0),ie.addEventListener("resize",we);let Ee=t.getRootNode(),se=Xp(Ee)?Ee:D.documentElement,fe=typeof MutationObserver>"u"?null:new MutationObserver(()=>{t.isConnected||M()});fe?.observe(se,{childList:!0,subtree:!0}),u=()=>{ie.removeEventListener("scroll",we,!0),ie.removeEventListener("resize",we),fe?.disconnect()}},S=()=>{b||g?I():M()},R=()=>{let Q=p();(!Q.matchMedia||!Q.matchMedia("(hover: none)").matches)&&(b=!0,S())},$=()=>{b=!1,S()},z=()=>{g=!0,S()},w=()=>{g=!1,S()},U=Q=>{Q.key==="Escape"&&(b=!1,g=!1,M())};n.addEventListener("mouseenter",R),n.addEventListener("mouseleave",$),t.addEventListener("focus",z),t.addEventListener("blur",w),t.addEventListener("keydown",U);let q={get isOpen(){return d!==null},show:I,hide:M,reposition:L,destroy:()=>{y||(y=!0,M(),n.removeEventListener("mouseenter",R),n.removeEventListener("mouseleave",$),t.removeEventListener("focus",z),t.removeEventListener("blur",w),t.removeEventListener("keydown",U),Tl.delete(t))}};return Tl.set(t,q),q}function Qp(e){let{config:t,onOpen:n}=e,o=e.buttonSize??"40px",r=parseFloat(o)||40,s=Math.round(r*.6),a=t.buttonIconName??"plus",i=t.buttonTooltipText??"Add context",p=m("div","persona-send-button-wrapper"),d=Fe("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":i,"aria-haspopup":"listbox","aria-expanded":"false"},style:{width:o,height:o,minWidth:o,minHeight:o,fontSize:"18px",lineHeight:"1"}}),c=te(a,s,"currentColor",1.5);return c?d.appendChild(c):d.textContent="+",d.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),n()}),p.appendChild(d),Dt({anchor:d,trigger:p,text:()=>d.getAttribute("aria-label")??i}),{button:d,wrapper:p}}var{setLoader:mS,load:qb}=lr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions")});var Ml=qb;var{setLoader:bS,load:Vb}=lr({fallbackImport:()=>import("@runtypelabs/persona/context-mentions-inline"),resetOnSetLoader:!0});var Yp=Vb;function fs(e,t={}){if(t.render)return t.render({ref:e,readonly:!!t.readonly});let n=Fe("span",{className:_n("persona-mention-token",t.readonly&&"persona-mention-token-readonly"),attrs:{"data-mention-source":e.sourceId,title:e.label,role:"img","aria-label":`${e.label} mention`}});e.color&&n.style.setProperty("--persona-mention-token-accent",e.color);let o=te(e.iconName??"at-sign",13,"currentColor",2);if(o){let r=m("span","persona-mention-token-icon");r.appendChild(o),n.appendChild(r)}return n.appendChild(Fe("span",{className:"persona-mention-token-label",text:`@${e.label}`})),n}function Zp(e){let t=e.config.contextMentions;if(!t?.enabled)return null;let n=Jp(t).filter(S=>S.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(S=>S.sources.some(R=>typeof R.matchCommand=="function")),r=S=>o.some(R=>R.trigger?R.position==="line-start"?S.split(`
25
25
  `).some(z=>z.startsWith(R.trigger)):(R.position==="anywhere"?S:S.split(`
26
- `)[0]).startsWith(R.trigger):!1),s=(S,R)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${S}`,{detail:R}))}catch{}},a=Fe("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),i=null,p=null,d=e.textarea,c=null,u=null,b=null,g=null,y=()=>{if(i)return Promise.resolve(i);if(p)return p;let S=Ml().then(R=>(i=R.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:a,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:I,emit:s}),i)).catch(R=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",R),p===S&&(p=null),null));return p=S,S},C=()=>{Qp().then(S=>{let R=S.mountInlineComposer({textarea:e.textarea,renderToken:z=>fs(z,{render:t.renderMentionToken}),onMentionRemoved:z=>i?.untrackMention(z)});c=R.input,u=R.destroy;let $=d;$.replaceWith(R.element),d=R.element,g={next:R.element,prev:$},b?.(R.element,$),i?i.rebindComposer(R.input):p&&p.then(z=>z?.rebindComposer(R.input))}).catch(S=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",S)})};t.display==="inline"&&C();let M=[],L=new Map;for(let S of n){if(!S.showButton)continue;let R=Xp({config:{...t,buttonIconName:S.buttonIconName,buttonTooltipText:S.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{y().then($=>$?.openMenu(S.trigger))}});M.push(R),L.set(S.trigger,R.button)}let I=(S,R,$)=>{let z=L.get(R);z&&(z.setAttribute("aria-expanded",S?"true":"false"),S?z.setAttribute("aria-controls",$):z.removeAttribute("aria-controls"))};return{affordanceButtons:M.map(S=>S.wrapper),contextRow:a,handleInput:S=>{if(i){i.handleInput();return}if(!Kp(S))return;let R=d,$=R.selectionStart??0;Vp(R.value,$,n)&&y().then(z=>z?.handleInput())},handleKeydown:S=>{if(i?.isMenuOpen())return i.handleKeydown(S);if(S.key==="Backspace"&&i?.hasMentions()&&!g){let R=d,$=R.selectionStart===0&&R.selectionEnd===0;if((R.value.length===0||$)&&i.removeLastChip())return S.preventDefault(),!0}return!1},isMenuOpen:()=>i?.isMenuOpen()??!1,hasMentions:()=>i?.hasMentions()??!1,collectForSubmit:()=>i?.collectForSubmit()??null,takeInlineCommand:async S=>r(S)?(i??await y())?.dispatchInlineCommand(S)??null:null,clear:()=>i?.clear(),prefetch:()=>{Ml().catch(()=>{})},onComposerSwap:S=>{b=S,g&&S(g.next,g.prev)},destroy:()=>{i?.destroy(),u?.();for(let S of M)S.wrapper.remove();a.remove()}}}var Zp=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ms(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];Zp(s)&&Zp(r)?n[o]=ms(s,r):n[o]=r}return n}var un="min(440px, calc(100vw - 24px))",kl="440px",Vb={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)"},it={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Vb,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 eu(e,t){if(!(!e&&!t))return e?t?ms(e,t):e:t}function hs(e){return e?{...it,...e,theme:eu(it.theme,e.theme),darkTheme:eu(it.darkTheme,e.darkTheme),launcher:{...it.launcher,...e.launcher,dock:{...it.launcher?.dock,...e.launcher?.dock},clearChat:{...it.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...it.copy,...e.copy},sendButton:{...it.sendButton,...e.sendButton},statusIndicator:{...it.statusIndicator,...e.statusIndicator},voiceRecognition:{...it.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=it.features?.artifacts,n=e.features?.artifacts,o=it.features?.scrollToBottom,r=e.features?.scrollToBottom,s=it.features?.scrollBehavior,a=e.features?.scrollBehavior,i=it.features?.streamAnimation,p=e.features?.streamAnimation,d=it.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},b=o===void 0&&r===void 0?void 0:{...o,...r},g=s===void 0&&a===void 0?void 0:{...s,...a},y=i===void 0&&p===void 0?void 0:{...i,...p},C=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...it.features,...e.features,...b!==void 0?{scrollToBottom:b}:{},...g!==void 0?{scrollBehavior:g}:{},...u!==void 0?{artifacts:u}:{},...y!==void 0?{streamAnimation:y}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??it.suggestionChips,suggestionChipsConfig:{...it.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...it.layout,...e.layout,header:{...it.layout?.header,...e.layout?.header},messages:{...it.layout?.messages,...e.layout?.messages,avatar:{...it.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...it.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...it.layout?.slots,...e.layout?.slots}},markdown:{...it.markdown,...e.markdown,options:{...it.markdown?.options,...e.markdown?.options}},messageActions:{...it.messageActions,...e.messageActions}}:it}var Ra="16px",Ia="transparent",tu={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"}},nu={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"}},ou={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:kl,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Ra,canvasBackground:Ia},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"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 Vt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;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."))?Vt(e,o):o}function Ll(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let p=Vt(e,a);p!==void 0&&(t[i]={path:i,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 a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function ru(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function su(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=su(s,r):n[o]=r}return n}function Kb(e,t){return t?su(e,t):e}function Wa(e,t={}){let n={palette:tu,semantic:nu,components:ou},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:Kb(n.components,e?.components)};if(t.validate!==!1){let r=ru(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function Pl(e){let t=Ll(e),n={};for(let[w,U]of Object.entries(t)){let q=w.replace(/\./g,"-");n[`--persona-${q}`]=U.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"]??Ra,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Ia,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-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=e.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 a=n["--persona-components-markdown-heading-h2-fontSize"];a&&(n["--persona-md-h2-size"]=a);let i=n["--persona-components-markdown-heading-h2-fontWeight"];i&&(n["--persona-md-h2-weight"]=i);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 d=e.components,c=d?.iconButton;c&&(c.background&&(n["--persona-icon-btn-bg"]=c.background),c.border&&(n["--persona-icon-btn-border"]=c.border),c.color&&(n["--persona-icon-btn-color"]=c.color),c.padding&&(n["--persona-icon-btn-padding"]=c.padding),c.borderRadius&&(n["--persona-icon-btn-radius"]=c.borderRadius),c.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=c.hoverBackground),c.hoverColor&&(n["--persona-icon-btn-hover-color"]=c.hoverColor),c.activeBackground&&(n["--persona-icon-btn-active-bg"]=c.activeBackground),c.activeBorder&&(n["--persona-icon-btn-active-border"]=c.activeBorder));let u=d?.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=d?.toggleGroup;b&&(b.gap&&(n["--persona-toggle-group-gap"]=b.gap),b.borderRadius&&(n["--persona-toggle-group-radius"]=b.borderRadius));let g=d?.artifact;if(g?.toolbar){let w=g.toolbar;w.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=w.iconHoverColor),w.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=w.iconHoverBackground),w.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=w.iconPadding),w.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=w.iconBorderRadius),w.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=w.iconBorder),w.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=w.toggleGroupGap),w.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=w.toggleBorderRadius),w.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=w.toggleGroupPadding),w.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=w.toggleGroupBorder),w.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=w.toggleGroupBorderRadius),w.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Vt(e,w.toggleGroupBackground)??w.toggleGroupBackground),w.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=w.copyBackground),w.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=w.copyBorder),w.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=w.copyColor),w.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=w.copyBorderRadius),w.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=w.copyPadding),w.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=w.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??w.copyMenuBackground),w.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=w.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??w.copyMenuBorder),w.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=w.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??w.copyMenuShadow),w.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=w.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??w.copyMenuBorderRadius),w.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=w.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??w.copyMenuItemHoverBackground),w.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=w.iconBackground),w.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=w.toolbarBorder)}if(g?.tab){let w=g.tab;w.background&&(n["--persona-artifact-tab-bg"]=w.background),w.activeBackground&&(n["--persona-artifact-tab-active-bg"]=w.activeBackground),w.activeBorder&&(n["--persona-artifact-tab-active-border"]=w.activeBorder),w.borderRadius&&(n["--persona-artifact-tab-radius"]=w.borderRadius),w.textColor&&(n["--persona-artifact-tab-color"]=w.textColor),w.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=w.hoverBackground),w.listBackground&&(n["--persona-artifact-tab-list-bg"]=w.listBackground),w.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=w.listBorderColor),w.listPadding&&(n["--persona-artifact-tab-list-padding"]=w.listPadding)}if(g?.pane){let w=g.pane;if(w.toolbarBackground){let U=Vt(e,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=U}}if(g?.card){let w=g.card;w.background&&(n["--persona-artifact-card-bg"]=w.background),w.border&&(n["--persona-artifact-card-border"]=w.border),w.borderRadius&&(n["--persona-artifact-card-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=w.hoverBackground),w.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=w.hoverBorderColor)}if(g?.inline){let w=g.inline;w.background&&(n["--persona-artifact-inline-bg"]=Vt(e,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"]=Vt(e,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Vt(e,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Vt(e,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Vt(e,w.mutedColor)??w.mutedColor),w.frameHeight&&(n["--persona-artifact-inline-frame-height"]=w.frameHeight)}let y=d?.code;y&&(y.keywordColor&&(n["--persona-code-keyword-color"]=y.keywordColor),y.stringColor&&(n["--persona-code-string-color"]=y.stringColor),y.commentColor&&(n["--persona-code-comment-color"]=y.commentColor),y.numberColor&&(n["--persona-code-number-color"]=y.numberColor),y.tagColor&&(n["--persona-code-tag-color"]=y.tagColor),y.attrColor&&(n["--persona-code-attr-color"]=y.attrColor),y.propertyColor&&(n["--persona-code-property-color"]=y.propertyColor),y.lineNumberColor&&(n["--persona-code-line-number-color"]=y.lineNumberColor),y.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=y.gutterBorderColor),y.background&&(n["--persona-code-bg"]=Vt(e,y.background)??y.background));let C=n["--persona-surface"],M=n["--persona-container"],L=n["--persona-palette-colors-gray-100"]??"#f3f4f6",I=n["--persona-palette-colors-gray-200"]??"#e5e7eb",S=n["--persona-palette-colors-gray-300"]??"#d1d5db",R=!M||M===C,$=R?L:M,z=R?I:M;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??$,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??z,R&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??S),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??$,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??$,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??$,n}var Gb={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var Jb={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"}}},au=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ha=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Xb=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Ha()},Rl=e=>Xb(e),Qb=e=>Wa(e),Yb=e=>Wa({...e,palette:{...e?.palette,colors:{...Jb.colors,...e?.palette?.colors}}},{validate:!1}),Uo=e=>{let t=Rl(e),n=au(e?.theme),o=au(e?.darkTheme);return t==="dark"?Yb(ms(n??{},o??{})):Qb(n)},Zb=e=>Pl(e),hr=(e,t)=>{let n=Uo(t),o=Zb(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",Rl(t))},ys=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Ha())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Ha());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function kn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function iu(e){let t=kn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Ba(e){if(typeof e!="string")return"";let t=e.indexOf(`
26
+ `)[0]).startsWith(R.trigger):!1),s=(S,R)=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(`persona:mention:${S}`,{detail:R}))}catch{}},a=Fe("div",{className:"persona-mention-context-row",attrs:{"data-persona-mention-context-row":""}}),i=null,p=null,d=e.textarea,c=null,u=null,b=null,g=null,y=()=>{if(i)return Promise.resolve(i);if(p)return p;let S=Ml().then(R=>(i=R.mountContextMentions({mentionConfig:t,textarea:e.textarea,composerInput:c??void 0,anchor:e.anchor,contextRow:a,getMessages:e.getMessages,getConfig:()=>e.config,liveRegionHost:e.liveRegionHost,popoverContainer:e.popoverContainer,onPickerOpenChange:I,emit:s}),i)).catch(R=>(typeof console<"u"&&console.warn("[Persona] Failed to load context mentions runtime",R),p===S&&(p=null),null));return p=S,S},C=()=>{Yp().then(S=>{let R=S.mountInlineComposer({textarea:e.textarea,renderToken:z=>fs(z,{render:t.renderMentionToken}),onMentionRemoved:z=>i?.untrackMention(z)});c=R.input,u=R.destroy;let $=d;$.replaceWith(R.element),d=R.element,g={next:R.element,prev:$},b?.(R.element,$),i?i.rebindComposer(R.input):p&&p.then(z=>z?.rebindComposer(R.input))}).catch(S=>{typeof console<"u"&&console.warn("[Persona] Failed to load inline mention composer",S)})};t.display==="inline"&&C();let M=[],L=new Map;for(let S of n){if(!S.showButton)continue;let R=Qp({config:{...t,buttonIconName:S.buttonIconName,buttonTooltipText:S.buttonTooltipText},buttonSize:e.config.sendButton?.size,onOpen:()=>{y().then($=>$?.openMenu(S.trigger))}});M.push(R),L.set(S.trigger,R.button)}let I=(S,R,$)=>{let z=L.get(R);z&&(z.setAttribute("aria-expanded",S?"true":"false"),S?z.setAttribute("aria-controls",$):z.removeAttribute("aria-controls"))};return{affordanceButtons:M.map(S=>S.wrapper),contextRow:a,handleInput:S=>{if(i){i.handleInput();return}if(!Gp(S))return;let R=d,$=R.selectionStart??0;Kp(R.value,$,n)&&y().then(z=>z?.handleInput())},handleKeydown:S=>{if(i?.isMenuOpen())return i.handleKeydown(S);if(S.key==="Backspace"&&i?.hasMentions()&&!g){let R=d,$=R.selectionStart===0&&R.selectionEnd===0;if((R.value.length===0||$)&&i.removeLastChip())return S.preventDefault(),!0}return!1},isMenuOpen:()=>i?.isMenuOpen()??!1,hasMentions:()=>i?.hasMentions()??!1,collectForSubmit:()=>i?.collectForSubmit()??null,takeInlineCommand:async S=>r(S)?(i??await y())?.dispatchInlineCommand(S)??null:null,clear:()=>i?.clear(),prefetch:()=>{Ml().catch(()=>{})},onComposerSwap:S=>{b=S,g&&S(g.next,g.prev)},destroy:()=>{i?.destroy(),u?.();for(let S of M)S.wrapper.remove();a.remove()}}}var eu=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ms(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];eu(s)&&eu(r)?n[o]=ms(s,r):n[o]=r}return n}var un="min(440px, calc(100vw - 24px))",kl="440px",Kb={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)"},it={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:Kb,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 tu(e,t){if(!(!e&&!t))return e?t?ms(e,t):e:t}function hs(e){return e?{...it,...e,theme:tu(it.theme,e.theme),darkTheme:tu(it.darkTheme,e.darkTheme),launcher:{...it.launcher,...e.launcher,dock:{...it.launcher?.dock,...e.launcher?.dock},clearChat:{...it.launcher?.clearChat,...e.launcher?.clearChat}},copy:{...it.copy,...e.copy},sendButton:{...it.sendButton,...e.sendButton},statusIndicator:{...it.statusIndicator,...e.statusIndicator},voiceRecognition:{...it.voiceRecognition,...e.voiceRecognition},features:(()=>{let t=it.features?.artifacts,n=e.features?.artifacts,o=it.features?.scrollToBottom,r=e.features?.scrollToBottom,s=it.features?.scrollBehavior,a=e.features?.scrollBehavior,i=it.features?.streamAnimation,p=e.features?.streamAnimation,d=it.features?.askUserQuestion,c=e.features?.askUserQuestion,u=t===void 0&&n===void 0?void 0:{...t,...n,layout:{...t?.layout,...n?.layout}},b=o===void 0&&r===void 0?void 0:{...o,...r},g=s===void 0&&a===void 0?void 0:{...s,...a},y=i===void 0&&p===void 0?void 0:{...i,...p},C=d===void 0&&c===void 0?void 0:{...d,...c,styles:{...d?.styles,...c?.styles}};return{...it.features,...e.features,...b!==void 0?{scrollToBottom:b}:{},...g!==void 0?{scrollBehavior:g}:{},...u!==void 0?{artifacts:u}:{},...y!==void 0?{streamAnimation:y}:{},...C!==void 0?{askUserQuestion:C}:{}}})(),suggestionChips:e.suggestionChips??it.suggestionChips,suggestionChipsConfig:{...it.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...it.layout,...e.layout,header:{...it.layout?.header,...e.layout?.header},messages:{...it.layout?.messages,...e.layout?.messages,avatar:{...it.layout?.messages?.avatar,...e.layout?.messages?.avatar},timestamp:{...it.layout?.messages?.timestamp,...e.layout?.messages?.timestamp}},slots:{...it.layout?.slots,...e.layout?.slots}},markdown:{...it.markdown,...e.markdown,options:{...it.markdown?.options,...e.markdown?.options}},messageActions:{...it.messageActions,...e.messageActions}}:it}var Ra="16px",Ia="transparent",nu={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"}},ou={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"}},ru={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:kl,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl",inset:Ra,canvasBackground:Ia},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"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 Vt(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),o=e;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."))?Vt(e,o):o}function Ll(e){let t={};function n(o,r){for(let[s,a]of Object.entries(o)){let i=`${r}.${s}`;if(typeof a=="string"){let p=Vt(e,a);p!==void 0&&(t[i]={path:i,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 a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function su(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function au(e,t){let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];s&&typeof s=="object"&&!Array.isArray(s)&&r&&typeof r=="object"&&!Array.isArray(r)?n[o]=au(s,r):n[o]=r}return n}function Gb(e,t){return t?au(e,t):e}function Wa(e,t={}){let n={palette:nu,semantic:ou,components:ru},o={palette:{...n.palette,...e?.palette,colors:{...n.palette.colors,...e?.palette?.colors},spacing:{...n.palette.spacing,...e?.palette?.spacing},typography:{...n.palette.typography,...e?.palette?.typography},shadows:{...n.palette.shadows,...e?.palette?.shadows},borders:{...n.palette.borders,...e?.palette?.borders},radius:{...n.palette.radius,...e?.palette?.radius}},semantic:{...n.semantic,...e?.semantic,colors:{...n.semantic.colors,...e?.semantic?.colors,interactive:{...n.semantic.colors.interactive,...e?.semantic?.colors?.interactive},feedback:{...n.semantic.colors.feedback,...e?.semantic?.colors?.feedback}},spacing:{...n.semantic.spacing,...e?.semantic?.spacing},typography:{...n.semantic.typography,...e?.semantic?.typography}},components:Gb(n.components,e?.components)};if(t.validate!==!1){let r=su(o);if(!r.valid)throw new Error(`Theme validation failed: ${r.errors.map(s=>s.message).join(", ")}`)}if(t.plugins)for(let r of t.plugins)o=r.transform(o);return o}function Pl(e){let t=Ll(e),n={};for(let[w,U]of Object.entries(t)){let q=w.replace(/\./g,"-");n[`--persona-${q}`]=U.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"]??Ra,n["--persona-panel-canvas-bg"]=n["--persona-components-panel-canvasBackground"]??Ia,n["--persona-launcher-shadow"]=n["--persona-components-launcher-shadow"]??"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=n["--persona-components-input-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-user-radius"]=n["--persona-components-message-user-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-message-assistant-radius"]=n["--persona-components-message-assistant-borderRadius"]??n["--persona-radius-lg"]??"0.5rem",n["--persona-header-bg"]=n["--persona-components-header-background"]??n["--persona-surface"],n["--persona-header-border"]=n["--persona-components-header-border"]??n["--persona-divider"],n["--persona-header-icon-bg"]=n["--persona-components-header-iconBackground"]??n["--persona-primary"],n["--persona-header-icon-fg"]=n["--persona-components-header-iconForeground"]??n["--persona-text-inverse"],n["--persona-header-title-fg"]=n["--persona-components-header-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=e.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 a=n["--persona-components-markdown-heading-h2-fontSize"];a&&(n["--persona-md-h2-size"]=a);let i=n["--persona-components-markdown-heading-h2-fontWeight"];i&&(n["--persona-md-h2-weight"]=i);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 d=e.components,c=d?.iconButton;c&&(c.background&&(n["--persona-icon-btn-bg"]=c.background),c.border&&(n["--persona-icon-btn-border"]=c.border),c.color&&(n["--persona-icon-btn-color"]=c.color),c.padding&&(n["--persona-icon-btn-padding"]=c.padding),c.borderRadius&&(n["--persona-icon-btn-radius"]=c.borderRadius),c.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=c.hoverBackground),c.hoverColor&&(n["--persona-icon-btn-hover-color"]=c.hoverColor),c.activeBackground&&(n["--persona-icon-btn-active-bg"]=c.activeBackground),c.activeBorder&&(n["--persona-icon-btn-active-border"]=c.activeBorder));let u=d?.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=d?.toggleGroup;b&&(b.gap&&(n["--persona-toggle-group-gap"]=b.gap),b.borderRadius&&(n["--persona-toggle-group-radius"]=b.borderRadius));let g=d?.artifact;if(g?.toolbar){let w=g.toolbar;w.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=w.iconHoverColor),w.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=w.iconHoverBackground),w.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=w.iconPadding),w.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=w.iconBorderRadius),w.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=w.iconBorder),w.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=w.toggleGroupGap),w.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=w.toggleBorderRadius),w.toggleGroupPadding&&(n["--persona-artifact-toolbar-toggle-group-padding"]=w.toggleGroupPadding),w.toggleGroupBorder&&(n["--persona-artifact-toolbar-toggle-group-border"]=w.toggleGroupBorder),w.toggleGroupBorderRadius&&(n["--persona-artifact-toolbar-toggle-group-radius"]=w.toggleGroupBorderRadius),w.toggleGroupBackground&&(n["--persona-artifact-toolbar-toggle-group-bg"]=Vt(e,w.toggleGroupBackground)??w.toggleGroupBackground),w.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=w.copyBackground),w.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=w.copyBorder),w.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=w.copyColor),w.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=w.copyBorderRadius),w.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=w.copyPadding),w.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=w.copyMenuBackground,n["--persona-dropdown-bg"]=n["--persona-dropdown-bg"]??w.copyMenuBackground),w.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=w.copyMenuBorder,n["--persona-dropdown-border"]=n["--persona-dropdown-border"]??w.copyMenuBorder),w.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=w.copyMenuShadow,n["--persona-dropdown-shadow"]=n["--persona-dropdown-shadow"]??w.copyMenuShadow),w.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=w.copyMenuBorderRadius,n["--persona-dropdown-radius"]=n["--persona-dropdown-radius"]??w.copyMenuBorderRadius),w.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=w.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=n["--persona-dropdown-item-hover-bg"]??w.copyMenuItemHoverBackground),w.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=w.iconBackground),w.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=w.toolbarBorder)}if(g?.tab){let w=g.tab;w.background&&(n["--persona-artifact-tab-bg"]=w.background),w.activeBackground&&(n["--persona-artifact-tab-active-bg"]=w.activeBackground),w.activeBorder&&(n["--persona-artifact-tab-active-border"]=w.activeBorder),w.borderRadius&&(n["--persona-artifact-tab-radius"]=w.borderRadius),w.textColor&&(n["--persona-artifact-tab-color"]=w.textColor),w.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=w.hoverBackground),w.listBackground&&(n["--persona-artifact-tab-list-bg"]=w.listBackground),w.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=w.listBorderColor),w.listPadding&&(n["--persona-artifact-tab-list-padding"]=w.listPadding)}if(g?.pane){let w=g.pane;if(w.toolbarBackground){let U=Vt(e,w.toolbarBackground)??w.toolbarBackground;n["--persona-artifact-toolbar-bg"]=U}}if(g?.card){let w=g.card;w.background&&(n["--persona-artifact-card-bg"]=w.background),w.border&&(n["--persona-artifact-card-border"]=w.border),w.borderRadius&&(n["--persona-artifact-card-radius"]=w.borderRadius),w.hoverBackground&&(n["--persona-artifact-card-hover-bg"]=w.hoverBackground),w.hoverBorderColor&&(n["--persona-artifact-card-hover-border"]=w.hoverBorderColor)}if(g?.inline){let w=g.inline;w.background&&(n["--persona-artifact-inline-bg"]=Vt(e,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"]=Vt(e,w.chromeBackground)??w.chromeBackground),w.chromeBorder&&(n["--persona-artifact-inline-chrome-border"]=Vt(e,w.chromeBorder)??w.chromeBorder),w.titleColor&&(n["--persona-artifact-inline-title-color"]=Vt(e,w.titleColor)??w.titleColor),w.mutedColor&&(n["--persona-artifact-inline-muted-color"]=Vt(e,w.mutedColor)??w.mutedColor),w.frameHeight&&(n["--persona-artifact-inline-frame-height"]=w.frameHeight)}let y=d?.code;y&&(y.keywordColor&&(n["--persona-code-keyword-color"]=y.keywordColor),y.stringColor&&(n["--persona-code-string-color"]=y.stringColor),y.commentColor&&(n["--persona-code-comment-color"]=y.commentColor),y.numberColor&&(n["--persona-code-number-color"]=y.numberColor),y.tagColor&&(n["--persona-code-tag-color"]=y.tagColor),y.attrColor&&(n["--persona-code-attr-color"]=y.attrColor),y.propertyColor&&(n["--persona-code-property-color"]=y.propertyColor),y.lineNumberColor&&(n["--persona-code-line-number-color"]=y.lineNumberColor),y.gutterBorderColor&&(n["--persona-code-gutter-border-color"]=y.gutterBorderColor),y.background&&(n["--persona-code-bg"]=Vt(e,y.background)??y.background));let C=n["--persona-surface"],M=n["--persona-container"],L=n["--persona-palette-colors-gray-100"]??"#f3f4f6",I=n["--persona-palette-colors-gray-200"]??"#e5e7eb",S=n["--persona-palette-colors-gray-300"]??"#d1d5db",R=!M||M===C,$=R?L:M,z=R?I:M;return n["--persona-icon-btn-hover-bg"]=n["--persona-icon-btn-hover-bg"]??$,n["--persona-icon-btn-active-bg"]=n["--persona-icon-btn-active-bg"]??z,R&&(n["--persona-icon-btn-active-border"]=n["--persona-icon-btn-active-border"]??S),n["--persona-label-btn-hover-bg"]=n["--persona-label-btn-hover-bg"]??$,n["--persona-artifact-tab-hover-bg"]=n["--persona-artifact-tab-hover-bg"]??$,n["--persona-artifact-card-hover-bg"]=n["--persona-artifact-card-hover-bg"]??$,n}var Jb={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar","artifact-inline":"Inline artifact block","artifact-inline-chrome":"Inline artifact title bar"};var Xb={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"}}},iu=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ha=()=>typeof document<"u"&&document.documentElement.classList.contains("dark")||typeof window<"u"&&window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light",Qb=e=>{let t=e?.colorScheme??"light";return t==="light"?"light":t==="dark"?"dark":Ha()},Rl=e=>Qb(e),Yb=e=>Wa(e),Zb=e=>Wa({...e,palette:{...e?.palette,colors:{...Xb.colors,...e?.palette?.colors}}},{validate:!1}),Uo=e=>{let t=Rl(e),n=iu(e?.theme),o=iu(e?.darkTheme);return t==="dark"?Zb(ms(n??{},o??{})):Yb(n)},ev=e=>Pl(e),hr=(e,t)=>{let n=Uo(t),o=ev(n);for(let[r,s]of Object.entries(o))e.style.setProperty(r,s);e.setAttribute("data-persona-color-scheme",Rl(t))},ys=e=>{let t=[];if(typeof document<"u"&&typeof MutationObserver<"u"){let n=new MutationObserver(()=>{e(Ha())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window<"u"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Ha());n.addEventListener?(n.addEventListener("change",o),t.push(()=>n.removeEventListener("change",o))):n.addListener&&(n.addListener(o),t.push(()=>n.removeListener(o)))}return()=>{t.forEach(n=>n())}};function Mn(e){let t=String(e).split(/[\\/]/);return t[t.length-1]??""}function lu(e){let t=Mn(e),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()}function Ba(e){if(typeof e!="string")return"";let t=e.indexOf(`
27
27
  `);if(t===-1||!e.slice(0,t).startsWith("```"))return e;let o=e.slice(t+1),r=o.lastIndexOf(`
28
- `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function bs(e){let t=iu(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let n=(e.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function lo(e){switch(bs(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=iu(e.path);return t?t.toUpperCase():"File"}}}function lu(e){let t=e.markdown??"";return e.file?{filename:kn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Ba(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var Il="http://www.w3.org/2000/svg";function cu(e){let t=document.createElementNS(Il,"svg");t.setAttribute("class",$n("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(Il,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Il,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),t.appendChild(n),t.appendChild(o),t}var co=(e,t,n)=>{let o=n;for(let r of t){let s=m("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};function du(e,t,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),co(e,t,0)}var Wl="persona-artifact-status-label",pu="persona-artifact-status-detail",uu="data-artifact-status-label",Hl=new Map,gu=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function yr(e){e&&Hl.delete(e)}function ev(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?lo(t):e.artifactType==="component"?"Component":"Document"}function br(e,t,n){let o=ev(e),r=`Generating ${o.toLowerCase()}...`,s=t?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=e.id,i=Hl.get(a);e.status!=="complete"&&i===void 0&&(i=gu(),Hl.set(a,i));let p=i===void 0?0:Math.max(0,gu()-i),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",u=d?0:c.length,b=d||c===""?0:c.split(`
29
- `).length,g=e.artifactType==="markdown"?e.file:void 0,y={artifactId:a,artifactType:e.artifactType,title:e.title,typeLabel:o,file:g,chars:u,lines:b,elapsedMs:p,content:()=>d?"":c,surface:n};try{let C=s(y);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:r}}catch{return{label:r}}}function tv(e){e.className=Wl,e.removeAttribute("data-preserve-animation"),e.style.removeProperty("--persona-tool-anim-duration"),e.style.removeProperty("--persona-tool-anim-color"),e.style.removeProperty("--persona-tool-anim-secondary-color"),e.replaceChildren()}function zo(e,t,n){let o=e.querySelector(`:scope > .${Wl}`);o||(o=m("span",Wl),e.appendChild(o)),o.getAttribute(uu)!==t.label&&(tv(o),du(o,t.label,n),o.setAttribute(uu,t.label));let r=e.querySelector(`:scope > .${pu}`),s=t.detail;s?(r||(r=m("span",pu),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var nv={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"},ov=15e4,Oa={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 rv(e,t){let n=(e||"").trim().toLowerCase();if(n&&Oa[n])return Oa[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(Oa[r])return Oa[r]}}return null}function Da(e,t){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:e.slice(r,a)})};for(;o<e.length;){let a=!1;for(let i of t){i.re.lastIndex=o;let p=i.re.exec(e);if(p&&p.index===o&&p[0].length>0){s(o);let d=i.map?i.map(p[0]):i.type;n.push({type:d,value:p[0]}),o+=p[0].length,r=o,a=!0;break}}a||(o+=1)}return s(e.length),n}var sv=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"]),av=[{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:e=>sv.has(e)?"keyword":"plain"}];function fu(e){return Da(e,av)}var iv=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:e=>e==="true"||e==="false"||e==="null"?"keyword":"plain"}];function lv(e){let t=Da(e,iv);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let r=t[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}var cv=[{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 mu(e){let t=Da(e,cv),n="";for(let o=0;o<t.length;o+=1){let r=t[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let a=o+1;for(;a<t.length&&t[a].value.trim()==="";)a+=1;let i=t[a];i&&i.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 t}var dv=[{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 pv(e){let t=[],n=(s,a)=>{a&&t.push({type:s,value:a})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let a=e.indexOf("-->",r+4),i=a===-1?o:a+3;n("comment",e.slice(r,i)),r=i;continue}if(e[r]==="<"&&e[r+1]==="!"){let a=e.indexOf(">",r),i=a===-1?o:a+1;n("tag",e.slice(r,i)),r=i;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let a=e.indexOf(">",r),i=a===-1?o:a+1,p=e.slice(r,i);for(let c of Da(p,dv))t.push(c);r=i;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),b=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(r)),g=b?r+b.index:o,y=e.slice(r,g),C=c==="script"?fu(y):mu(y);for(let M of C)t.push(M);r=g}continue}let s=e.indexOf("<",r);if(s===r)n("plain",e[r]),r+=1;else{let a=s===-1?o:s;n("plain",e.slice(r,a)),r=a}}return t}function uv(e,t){switch(t){case"html":return pv(e);case"css":return mu(e);case"js":return fu(e);case"json":return lv(e)}}function gv(e){let t=sp(),n=m("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=nv[r];if(a){let i=m("span",a);i.textContent=s,n.appendChild(i)}else n.appendChild(document.createTextNode(s))};for(let r of e){let s=r.value.split(`
28
+ `);return(r===-1?o:o.slice(0,r)).split("`\u200B``").join("```")}function bs(e){let t=lu(e.path);if(t)return t==="html"||t==="htm"?"html":t==="svg"?"svg":t==="md"||t==="mdx"?"markdown":"other";let n=(e.mimeType||"").toLowerCase();return n.includes("html")?"html":n.includes("svg")?"svg":n.includes("markdown")?"markdown":"other"}function lo(e){switch(bs(e)){case"html":return"HTML";case"svg":return"SVG";case"markdown":return"Markdown";default:{let t=lu(e.path);return t?t.toUpperCase():"File"}}}function cu(e){let t=e.markdown??"";return e.file?{filename:Mn(e.file.path)||"artifact",mime:e.file.mimeType||"application/octet-stream",content:Ba(t)}:{filename:`${e.title||"artifact"}.md`,mime:"text/markdown",content:t}}var Il="http://www.w3.org/2000/svg";function du(e){let t=document.createElementNS(Il,"svg");t.setAttribute("class",_n("persona-spinner",e)),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let n=document.createElementNS(Il,"circle");n.setAttribute("class","persona-spinner-track"),n.setAttribute("cx","12"),n.setAttribute("cy","12"),n.setAttribute("r","9");let o=document.createElementNS(Il,"circle");return o.setAttribute("class","persona-spinner-arc"),o.setAttribute("cx","12"),o.setAttribute("cy","12"),o.setAttribute("r","9"),t.appendChild(n),t.appendChild(o),t}var co=(e,t,n)=>{let o=n;for(let r of t){let s=m("span","persona-tool-char");s.style.setProperty("--char-index",String(o)),s.textContent=r===" "?"\xA0":r,e.appendChild(s),o++}return o};function pu(e,t,n){let o=n?.loadingAnimation??"shimmer",r=n?.loadingAnimationDuration??2e3;if(o==="none"){e.textContent=t;return}if(o==="pulse"){e.setAttribute("data-preserve-animation","true"),e.classList.add("persona-tool-loading-pulse"),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),e.textContent=t;return}e.setAttribute("data-preserve-animation","true"),e.classList.add(`persona-tool-loading-${o}`),e.style.setProperty("--persona-tool-anim-duration",`${r}ms`),o==="shimmer-color"&&(n?.loadingAnimationColor&&e.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n?.loadingAnimationSecondaryColor&&e.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),co(e,t,0)}var Wl="persona-artifact-status-label",uu="persona-artifact-status-detail",gu="data-artifact-status-label",Hl=new Map,fu=()=>typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();function yr(e){e&&Hl.delete(e)}function tv(e){let t=e.artifactType==="markdown"?e.file:void 0;return t?lo(t):e.artifactType==="component"?"Component":"Document"}function br(e,t,n){let o=tv(e),r=`Generating ${o.toLowerCase()}...`,s=t?.statusLabel;if(typeof s=="string")return{label:s};if(typeof s!="function")return{label:r};let a=e.id,i=Hl.get(a);e.status!=="complete"&&i===void 0&&(i=fu(),Hl.set(a,i));let p=i===void 0?0:Math.max(0,fu()-i),d=e.artifactType==="component",c=!d&&typeof e.markdown=="string"?e.markdown:"",u=d?0:c.length,b=d||c===""?0:c.split(`
29
+ `).length,g=e.artifactType==="markdown"?e.file:void 0,y={artifactId:a,artifactType:e.artifactType,title:e.title,typeLabel:o,file:g,chars:u,lines:b,elapsedMs:p,content:()=>d?"":c,surface:n};try{let C=s(y);return typeof C=="string"?{label:C}:C&&typeof C=="object"&&typeof C.label=="string"?{label:C.label,detail:typeof C.detail=="string"?C.detail:void 0}:{label:r}}catch{return{label:r}}}function nv(e){e.className=Wl,e.removeAttribute("data-preserve-animation"),e.style.removeProperty("--persona-tool-anim-duration"),e.style.removeProperty("--persona-tool-anim-color"),e.style.removeProperty("--persona-tool-anim-secondary-color"),e.replaceChildren()}function zo(e,t,n){let o=e.querySelector(`:scope > .${Wl}`);o||(o=m("span",Wl),e.appendChild(o)),o.getAttribute(gu)!==t.label&&(nv(o),pu(o,t.label,n),o.setAttribute(gu,t.label));let r=e.querySelector(`:scope > .${uu}`),s=t.detail;s?(r||(r=m("span",uu),e.appendChild(r)),r.textContent!==s&&(r.textContent=s)):r&&r.remove()}var ov={keyword:"persona-code-token-keyword",string:"persona-code-token-string",comment:"persona-code-token-comment",number:"persona-code-token-number",tag:"persona-code-token-tag",attr:"persona-code-token-attr",property:"persona-code-token-property"},rv=15e4,Oa={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 sv(e,t){let n=(e||"").trim().toLowerCase();if(n&&Oa[n])return Oa[n];if(t){let o=t.lastIndexOf(".");if(o>=0){let r=t.slice(o+1).toLowerCase();if(Oa[r])return Oa[r]}}return null}function Da(e,t){let n=[],o=0,r=0,s=a=>{a>r&&n.push({type:"plain",value:e.slice(r,a)})};for(;o<e.length;){let a=!1;for(let i of t){i.re.lastIndex=o;let p=i.re.exec(e);if(p&&p.index===o&&p[0].length>0){s(o);let d=i.map?i.map(p[0]):i.type;n.push({type:d,value:p[0]}),o+=p[0].length,r=o,a=!0;break}}a||(o+=1)}return s(e.length),n}var av=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"]),iv=[{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:e=>av.has(e)?"keyword":"plain"}];function mu(e){return Da(e,iv)}var lv=[{type:"string",re:/"(?:\\.|[^"\\])*"/y},{type:"number",re:/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y},{type:"plain",re:/[A-Za-z_]\w*/y,map:e=>e==="true"||e==="false"||e==="null"?"keyword":"plain"}];function cv(e){let t=Da(e,lv);for(let n=0;n<t.length;n+=1){if(t[n].type!=="string")continue;let o=n+1;for(;o<t.length&&t[o].value.trim()==="";)o+=1;let r=t[o];r&&r.value.replace(/^\s*/,"").startsWith(":")&&(t[n].type="property")}return t}var dv=[{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 hu(e){let t=Da(e,dv),n="";for(let o=0;o<t.length;o+=1){let r=t[o];if(r.type==="plain"&&/^[A-Za-z_-][\w-]*$/.test(r.value)){let a=o+1;for(;a<t.length&&t[a].value.trim()==="";)a+=1;let i=t[a];i&&i.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 t}var pv=[{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 uv(e){let t=[],n=(s,a)=>{a&&t.push({type:s,value:a})},o=e.length,r=0;for(;r<o;){if(e.startsWith("<!--",r)){let a=e.indexOf("-->",r+4),i=a===-1?o:a+3;n("comment",e.slice(r,i)),r=i;continue}if(e[r]==="<"&&e[r+1]==="!"){let a=e.indexOf(">",r),i=a===-1?o:a+1;n("tag",e.slice(r,i)),r=i;continue}if(e[r]==="<"&&/[A-Za-z/]/.test(e[r+1]||"")){let a=e.indexOf(">",r),i=a===-1?o:a+1,p=e.slice(r,i);for(let c of Da(p,pv))t.push(c);r=i;let d=/^<\s*(script|style)\b/i.exec(p);if(d&&!/\/>\s*$/.test(p)){let c=d[1].toLowerCase(),b=new RegExp("</\\s*"+c+"\\s*>","i").exec(e.slice(r)),g=b?r+b.index:o,y=e.slice(r,g),C=c==="script"?mu(y):hu(y);for(let M of C)t.push(M);r=g}continue}let s=e.indexOf("<",r);if(s===r)n("plain",e[r]),r+=1;else{let a=s===-1?o:s;n("plain",e.slice(r,a)),r=a}}return t}function gv(e,t){switch(t){case"html":return uv(e);case"css":return hu(e);case"js":return mu(e);case"json":return cv(e)}}function fv(e){let t=ap(),n=m("span","persona-code-line"),o=(r,s)=>{if(!s)return;let a=ov[r];if(a){let i=m("span",a);i.textContent=s,n.appendChild(i)}else n.appendChild(document.createTextNode(s))};for(let r of e){let s=r.value.split(`
30
30
  `);for(let a=0;a<s.length;a+=1)a>0&&(t.appendChild(n),t.appendChild(document.createTextNode(`
31
- `)),n=m("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function hu(e,t,n){let o=e.length<=ov?rv(t,n):null,r=o?uv(e,o):[{type:"plain",value:e}];return gv(r)}function qo(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=m("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Pa)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let y=document.createElement("button");if(y.type="button",y.setAttribute("role","menuitem"),y.setAttribute("data-dropdown-item-id",g.id),g.destructive&&y.setAttribute("data-destructive",""),g.icon){let M=te(g.icon,16,"currentColor",1.5);M&&y.appendChild(M)}let C=document.createElement("span");C.textContent=g.label,y.appendChild(C),y.addEventListener("click",M=>{M.stopPropagation(),c(),n(g.id)}),a.appendChild(y)}let i=null;function p(){if(!s)return;let g=o.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function d(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=y=>{!a.contains(y.target)&&!o.contains(y.target)&&c()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function c(){a.classList.add("persona-hidden"),i?.(),i=null}function u(){a.classList.contains("persona-hidden")?d():c()}function b(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:u,destroy:b}}function dt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,p=m("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=te(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),a&&p.addEventListener("click",a),i)for(let[c,u]of Object.entries(i))p.setAttribute(c,u);return p}function po(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=m("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let b=te(t,s??14,"currentColor",2);b&&c.appendChild(b)}let u=m("span");if(u.textContent=n,c.appendChild(u),i&&c.addEventListener("click",i),p)for(let[b,g]of Object.entries(p))c.setAttribute(b,g);return c}function uo(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=m("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,i=[];function p(){for(let c of i)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let u;c.icon?u=dt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,p(),o(c.id)}}):(u=m("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{a=c.id,p(),o(c.id)})),u.setAttribute("aria-pressed",c.id===a?"true":"false"),i.push({id:c.id,btn:u}),s.appendChild(u)}function d(c){a=c,p()}return{element:s,setSelected:d}}function Bl(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:p}=e,d=m("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=m("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let u=te(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",d.appendChild(u)),p&&(d.style.borderRadius=p.borderRadius??"10px",d.style.padding=p.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=p.background??"",d.style.borderColor=p.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let b=qo({items:o,onSelect:g=>{d.setAttribute("aria-expanded","false"),r(g)},anchor:d,position:s,portal:a});return a||d.appendChild(b.element),d.addEventListener("click",g=>{g.stopPropagation();let y=!b.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",y?"false":"true"),b.toggle()}),d.addEventListener("keydown",g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),d.click())}),{element:d,setLabel:g=>{c.textContent=g,d.setAttribute("aria-label",g)},open:()=>{d.setAttribute("aria-expanded","true"),b.show()},close:()=>{d.setAttribute("aria-expanded","false"),b.hide()},toggle:()=>{let g=!b.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",g?"false":"true"),b.toggle()},destroy:()=>{b.destroy(),d.remove()}}}var Na="persona-artifact-custom-action-btn";function vr(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+Na+(n?" persona-artifact-doc-copy-btn":"");o=m("button",r)}else{let r="persona-icon-btn "+Na+(n?" persona-artifact-doc-icon-btn":"");o=m("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=m("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=po({icon:e.icon,label:e.label,className:Na+(n?" persona-artifact-doc-copy-btn":"")}):o=dt({icon:e.icon,label:e.label,className:Na+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function vs(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function yu(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?kn(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n?lo(n):i==="component"?"Component":"Document",d=document.createElement("div");d.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&d.setAttribute("data-open-artifact",s);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.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 g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let y=t?.config?.features?.artifacts,C={id:s,artifactType:i==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{}},M=br(C,y,"card");zo(g,M,y)}else s&&yr(s),g.textContent=p;if(u.append(b,g),d.append(c,u),a==="complete"){let y=t?.config?.features?.artifacts?.cardActions;if(y&&y.length>0){let M={artifactId:s||null,title:r,artifactType:i,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let L of y)try{if(L.visible===void 0||L.visible(M)){let I=vr(L);I.setAttribute("data-artifact-custom-action",L.id),I.className=`${I.className} persona-flex-shrink-0`,d.append(I)}}catch{}}let C=po({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${r}`,C.setAttribute("data-download-artifact",s),d.append(C)}return d}var Fa=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>yu(e,t)});if(i)return i}return yu(e,t)};var go=new WeakMap;function Ol(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=go.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function wu(e){return go.has(e)}function fv(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete";if(e.artifactType==="component"){let s=e.componentProps,a=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:a}}let r=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...r?{file:r}:{}}}function bu(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?kn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?lo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function mv(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var vu=180,hv=240,yv=.8,bv=300,vv=500,xv="cubic-bezier(0.2, 0, 0, 1)",xu=240,Cv=.35;function wv(e,t,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(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let i of Array.from(e.children))i instanceof HTMLElement&&a.push(i.animate([{opacity:1},{opacity:0}],{duration:vu,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let L of a)L.cancel();o();let i=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){i(),r();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){i(),r();return}let d=Math.abs(t-p),c=Math.round(Math.min(vv,Math.max(bv,hv+d*yv))),u=Math.round(c*Cv),b=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,g=b?b.animate([{opacity:0},{opacity:1}],{duration:xu,delay:u,easing:"ease-out",fill:"backwards"}):null,y=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:xv});e.style.height=`${p}px`;let C=!1,M=()=>{C||(C=!0,i(),r())};Promise.allSettled([y.finished,g?.finished].filter(Boolean)).then(M),window.setTimeout(M,Math.max(c,u+xu)+120)},vu)}function Av(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t: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 Sv(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,a=t?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let i=t?.overflow==="clip"?"clip":"scroll",p=i==="clip"?!1:t?.followOutput!==!1,d,c,u=t?.fadeMask;u===!0?(d=!0,c=!0):u===!1?(d=!1,c=!1):u&&typeof u=="object"?(d=u.top===!0,c=u.bottom===!0):i==="clip"?(d=!1,c=!0):(d=!0,c=!0);let b=t?.transition==="none"?"none":"auto",g=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:i,fadeTop:d,fadeBottom:c,transition:b,completeDisplay:g}}function Cu(e,t){let n=fv(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:i}=Av(o),p=o?.inlineActions??[],d=Sv(o),c=d.completeDisplay==="card",u=null,b=n,g=m("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let y=Y=>Fa(mv(Y),t),C=Y=>{g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(xs),g.replaceChildren(y(Y)),go.set(g,ce=>{g.replaceChildren(y(ce))})};if(c&&n.status==="complete")return C(n),g;let M=_a(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),L=m("div","persona-artifact-inline-body");L.appendChild(M.el);let I=Y=>{let ce=Y.status!=="complete",Z=ce?d.streamingHeight:d.completeHeight,be=typeof Z=="number";be?g.style.setProperty(xs,`${Z}px`):g.style.removeProperty(xs);let he=!!M.el.querySelector(".persona-code-pre"),de=!!M.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");L.classList.toggle("persona-artifact-content-flush",he),L.classList.toggle("persona-artifact-inline-body--sized",be&&de),L.classList.toggle("persona-artifact-inline-body--cap",!ce&&!de&&typeof d.completeHeight=="number")},S=n.status,R=(Y,ce)=>{S!=="complete"&&Y.status==="complete"?(typeof d.completeHeight=="number"?g.style.setProperty(xs,`${d.completeHeight}px`):g.style.removeProperty(xs),Su(L,ce?.suppressTransition?"none":d.transition,Y.id,()=>{M.update(Y),I(Y)})):M.update(Y),I(Y),S=Y.status};I(n);let $=d.overflow==="clip"&&a&&!!n.id;if($&&(L.setAttribute("data-expand-artifact-inline",n.id),L.setAttribute("role","button"),L.setAttribute("tabindex","0"),L.classList.add("persona-cursor-pointer"),L.setAttribute("aria-label",`Open ${bu(n).title} in panel`)),!r)return g.appendChild(L),go.set(g,R),g;let z=m("div","persona-artifact-inline-chrome");z.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let w=m("div","persona-artifact-inline-chrome-lead"),U=m("span","persona-flex persona-items-center persona-flex-shrink-0"),q=te("file-text",16,"currentColor",2);q&&U.appendChild(q);let Q=m("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),O=m("span","persona-artifact-inline-type");w.append(U,Q,O);let D=m("div","persona-artifact-inline-chrome-actions"),ie=m("span","persona-flex persona-items-center persona-gap-1"),me=()=>u??d.viewMode,we=i?uo({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:me(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Y=>{let ce=Y==="source"?"source":"rendered";ce!==me()&&(u=ce,M.update(b),I(b))}}):null,Ee=s?dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Ee&&n.id&&Ee.setAttribute("data-copy-artifact",n.id);let se=a?dt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;se&&n.id&&se.setAttribute("data-expand-artifact-inline",n.id),D.appendChild(ie),we&&D.appendChild(we.element),Ee&&D.appendChild(Ee),se&&D.appendChild(se),z.append(w,D),g.append(z,L);let fe=Y=>{let{title:ce,typeLabel:Z}=bu(Y);Q.textContent=ce,Q.title=ce,$&&L.setAttribute("aria-label",`Open ${ce} in panel`);let be=Y.status!=="complete";if(be){O.classList.contains("persona-artifact-inline-status")||(O.className="persona-artifact-inline-status",O.removeAttribute("data-preserve-animation"),O.replaceChildren());let he=br(Y,o,"inline-chrome");zo(O,he,o)}else yr(Y.id),O.className="persona-artifact-inline-type",O.removeAttribute("data-preserve-animation"),O.replaceChildren(),O.textContent=Z;if(Ee&&Ee.classList.toggle("persona-hidden",be),we){let he=Y.artifactType==="markdown"?Y.file:void 0,de=!1;if(!be&&he&&d.viewMode!=="source"){let Me=bs(he);Me==="markdown"?de=!0:(Me==="html"||Me==="svg")&&(de=o?.filePreview?.enabled!==!1)}we.element.classList.toggle("persona-hidden",!de),we.setSelected(me())}if(ie.replaceChildren(),!be&&p.length>0){let he=vs(Y);if(he)for(let de of p)try{if(de.visible===void 0||de.visible(he)){let Me=vr(de,{documentChrome:!0});Me.setAttribute("data-artifact-custom-action",de.id),Me.classList.add("persona-flex-shrink-0"),ie.appendChild(Me)}}catch{}}};return fe(n),go.set(g,(Y,ce)=>{if(c&&S!=="complete"&&Y.status==="complete"){let Z=g.isConnected?g.getBoundingClientRect().height:0;S="complete";let be=Y,he=!1,de=Me=>{be=Me,he=!0};go.set(g,de),wv(g,Z,{swap:()=>{C(be),he=!1,go.set(g,de)},onSettled:()=>{he?C(be):go.set(g,Me=>{g.replaceChildren(y(Me))})}});return}(Y.status!=="complete"||Y.id!==b.id)&&(u=null),b=Y,R(Y,ce),fe(Y)}),g}var Au=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>Cu(e,t)});if(i)return i}return Cu(e,t)};var Dl=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},Ln=new Dl;Ln.register("PersonaArtifactCard",Fa,{bubbleChrome:!1});Ln.register("PersonaArtifactInline",Au,{bubbleChrome:!1});function Cs(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Ba(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var Nl=!1;function Tv(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Su(e,t,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(t!=="auto"||!e||typeof r!="function"||Nl||s){o();return}Nl=!0;let a=Tv(n);e.style.setProperty("view-transition-name",a);let i=()=>{Nl=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(i,i)}catch{i(),o()}}var Ev="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",Mv="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function kv(e){let t=m("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=m("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=m("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function Lv(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var Pv=220;function Rv(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function Iv(e){return`
32
- <script>(function(){var d=false;var t=`+JSON.stringify(e)+";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 Wv(e,t,n){let o=m("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=m("div","persona-artifact-frame-loading-indicator");r.appendChild(cu());let s=null;return n.label!==!1&&(s=m("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 Hv(e,t,n,o,r,s){let a=null,i=0,p=!1,d=new Set,c=()=>{d.forEach(S=>clearTimeout(S)),d.clear()},u=(S,R)=>{let $=setTimeout(()=>{d.delete($),S()},R);d.add($)},b=()=>{a&&a.parentElement&&a.remove(),a=null},g=()=>{if(a||p)return;let S=Wv(r,s,o);a=S.el,e.appendChild(a),i=Date.now(),o.label!==!1&&u(S.revealLabel,o.labelDelayMs)},y=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(b,Pv))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",L):t.removeEventListener("load",I)},M=()=>{if(p||(p=!0,C(),c(),!a))return;let S=Math.max(0,o.minVisibleMs-(Date.now()-i));S>0?u(y,S):y()};function L(S){if(n===null)return;let R=S.data;!R||R.persona!=="artifact-preview-ready"||R.token!==n||S.source===t.contentWindow&&M()}function I(){let S=R=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>R()):setTimeout(R,0)};S(()=>S(()=>M()))}return u(g,o.delayMs),u(M,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",L):t.addEventListener("load",I),()=>{p=!0,c(),C(),b()}}function _a(e,t){let{config:n}=t,o=t.registry??Ln,r=t.bodyLayout,s=n.markdown?cr(n.markdown):null,a=Zr(n.sanitize),i=e,p=!1,d=se=>{let fe=Fn()!==null;s&&!fe&&!p&&(p=!0,Yr(()=>Ee(i)));let Y=s?s(se):_n(se);return s&&fe&&a?a(Y):Y},c=m("div","persona-artifact-preview-body"),u=null,b=null,g=null,y=()=>{g&&(g(),g=null),u=null,b=null},C=null,M=null,L=null,I=!1,S=()=>{C=null,M=null,L=null,I=!1},R=null,$=null,z=()=>{R=null,$=null},w=40,U=0,q=se=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>se()):setTimeout(se,0),Q=se=>se.scrollHeight-se.clientHeight-se.scrollTop<=w,O=se=>{if(!r)return;let fe=se.scrollHeight-se.clientHeight>1,Y=se.scrollHeight-se.clientHeight-se.scrollTop;se.classList.toggle("persona-artifact-fade-top",r.fadeTop&&fe&&se.scrollTop>1),se.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&fe&&Y>1)},D=se=>{U||(U=q(()=>{U=0,se.scrollTop=se.scrollHeight,O(se)}))},ie=(se,fe,Y,ce)=>{let Z=!!r,be=Y.id+"|"+(Z?"w":"p");if(!C||L!==be||C.parentElement!==c){y(),z(),c.replaceChildren();let Me=m("pre",Ev+" persona-code-pre"),De=m("code","persona-code");if(Me.appendChild(De),Z){let _e=m("div","persona-artifact-source-window");if(_e.appendChild(Me),c.appendChild(_e),!(r?.overflow==="clip")&&typeof _e.addEventListener=="function"){let Ue=()=>_e.scrollHeight-_e.clientHeight>1;_e.addEventListener("scroll",()=>{Q(_e)&&(I=!1),O(_e)},{passive:!0}),_e.addEventListener("wheel",Ve=>{Ue()&&Ve.deltaY<0&&(I=!0)},{passive:!0}),_e.addEventListener("touchmove",()=>{Ue()&&(I=!0)},{passive:!0})}C=_e}else c.appendChild(Me),C=Me;M=De,L=be}let he=Z?C:null;he&&(he.classList.toggle("persona-artifact-source-window--fixed",ce),he.classList.toggle("persona-artifact-source-window--clip",ce&&r?.overflow==="clip"));let de=he?Q(he):!0;if(M.replaceChildren(hu(se,fe?.language,fe?.path)),he){let Me=Y.status!=="complete";ce&&Me&&r?.followOutput&&!I&&de?D(he):Me||(I=!1),O(he)}},me=se=>{y(),S(),z(),c.replaceChildren();let fe=m("div",Mv);fe.innerHTML=d(se),c.appendChild(fe)},we=se=>{let fe=se.id,Y=n.features?.artifacts,ce=br(se,Y,"status-body");if(R&&$===fe&&R.parentElement===c){let he=R.querySelector(".persona-artifact-status-view-text");he&&zo(he,ce,Y);return}y(),S(),c.replaceChildren();let Z=m("div","persona-artifact-status-view"),be=m("div","persona-artifact-status-view-text");zo(be,ce,Y),Z.appendChild(be),c.appendChild(Z),R=Z,$=fe},Ee=se=>{i=se;let fe=t.resolveViewMode?.(se)??r?.viewMode??"rendered",Y=se.artifactType==="markdown"?se.file:void 0,ce=se.status!=="complete";ce||yr(se.id);let Z=ce?r?.streamingHeight:r?.completeHeight,be=!!r&&typeof Z=="number";if(r?.streamingView==="status"&&ce){we(se);return}if(Y){let de=Ba(se.markdown??""),Me=bs(Y),De=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ce&&fe==="rendered"&&De&&(Me==="html"||Me==="svg")){let He=se.id+"\0"+de;if(u&&b===He&&u.parentElement===c)return;S(),z(),y(),c.replaceChildren();let Ue=n.features?.artifacts?.filePreview,Ve=Ue?.iframeSandbox??"allow-scripts";!Ue?.dangerouslyAllowSameOrigin&&Ve.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."),Ve=Ve.split(/\s+/).filter(mt=>mt&&mt!=="allow-same-origin").join(" "));let ke=Lv(Ue?.loading),ne=m("div","persona-artifact-frame"),Be=m("iframe","persona-artifact-iframe");Be.setAttribute("sandbox",Ve),Be.setAttribute("data-artifact-id",se.id);let vt=null;ke.enabled&&ke.injectReadySignal?(vt=Rv(),Be.srcdoc=de+Iv(vt)):Be.srcdoc=de,ne.appendChild(Be),c.appendChild(ne),ke.enabled&&(g=Hv(ne,Be,vt,ke,se.id,n)),u=ne,b=He;return}if(y(),!ce&&Me==="markdown"&&fe==="rendered"){me(de);return}ie(de,{language:Y.language,path:Y.path},se,be);return}if(se.artifactType==="markdown"){if(fe==="source"){y(),ie(se.markdown??"",void 0,se,be);return}me(se.markdown??"");return}y(),S(),z(),c.replaceChildren();let he=se.component?o.get(se.component):void 0;if(he){let Me={message:{id:se.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let De=he(se.props??{},Me);if(De){c.appendChild(De);return}}catch{}}c.appendChild(kv(se))};return Ee(e),{el:c,update(se){Ee(se)}}}import{Idiomorph as Bv}from"idiomorph";var $a=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Bv.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",i=s.textContent??"";if(a!==i)return}return!1}}}}})};var Tu=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Fl={index:-1,draft:""};function Eu(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function Mu(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function ku(){return new Map}function Lu(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Pu(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Ru(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ja(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Pn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function fo(e,t){return Pn(e)-e.scrollTop<=t}function Ua(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&i&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function za(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function Iu(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Wu(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function Hu(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var ws={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Ov=["pre","code","a","script","style"],qa=e=>({type:e?.type??ws.type,placeholder:e?.placeholder??ws.placeholder,speed:e?.speed??ws.speed,duration:e?.duration??ws.duration,buffer:e?.buffer??ws.buffer}),Ou=[{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"}],As=new Map;for(let e of Ou)As.set(e.name,e);var Dv=e=>{As.set(e.name,e)},Nv=e=>{Ou.some(t=>t.name===e)||As.delete(e)},Fv=()=>Array.from(As.keys()),xr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:As.get(e)??null,Va=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
33
- `);return s<0?"":e.slice(0,s)}return e},_v=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},$v=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},_l=/\s/,jv=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Uv=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),i=0;for(;i<s.length;)if(_l.test(s[i])){let p=i;for(;p<s.length&&_l.test(s[p]);)p+=1;a.appendChild(o.createTextNode(s.slice(i,p))),i=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=i;for(;d<s.length&&!_l.test(s[d]);)p.appendChild(_v(o,s[d],t,n.value)),n.value+=1,d+=1;a.appendChild(p),i=d}r.replaceChild(a,e)},zv=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),i=s.split(/(\s+)/);for(let p of i)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild($v(o,p,t,n.value)),n.value+=1));r.replaceChild(a,e)},Ss=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??Ov).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],p=a.nextNode();for(;p;)jv(p,s)||i.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?Uv:zv;for(let u of i)c(u,n,d);return r.innerHTML},Ka=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Ts=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},Bu=new WeakMap,qv=(e,t)=>{if(!e.styles)return;let n=Bu.get(t);if(n||(n=new Set,Bu.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},$l=new WeakMap,Vv=(e,t)=>{if(!e.onAttach)return;let n=$l.get(t);if(n||(n=new Map,$l.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},Du=e=>{let t=$l.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Ga=(e,t)=>{qv(e,t),Vv(e,t)};function jl(e,t=Ut){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var Es=0,mo=null;function Ul(e=document){if(Es++,Es===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;mo={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 t=!1;return()=>{if(!t&&(t=!0,Es=Math.max(0,Es-1),Es===0&&mo)){let n=e.body,o=e.defaultView??window;n.style.overflow=mo.originalOverflow,n.style.position=mo.originalPosition,n.style.top=mo.originalTop,n.style.width=mo.originalWidth,o.scrollTo(0,mo.scrollY),mo=null}}}var Ms={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Wt=e=>(e?.launcher?.mountMode??"floating")==="docked",ho=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",on=e=>{let t=e?.launcher?.dock;return{side:t?.side??Ms.side,width:t?.width??Ms.width,animate:t?.animate??Ms.animate,reveal:t?.reveal??Ms.reveal,maxHeight:t?.maxHeight??Ms.maxHeight}};var wn={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Kv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ja=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Kv,buttonSize:r,iconSize:s="28px"}=t,a=e?.launcher??{},i=r??a.closeButtonSize??"32px",p=m("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",b=a.closeButtonIconText??"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),y=Fe("button",{className:$n("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Kt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=te(u,s,"currentColor",1);return C?(C.style.display="block",y.appendChild(C)):y.textContent=b,p.appendChild(y),Dt({anchor:y,trigger:p,text:()=>y.getAttribute("aria-label")??d,enabled:c}),{button:y,wrapper:p}},Gv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Xa=(e,t={})=>{let{wrapperClassName:n=Gv,buttonSize:o,iconSize:r="20px"}=t,a=(e?.launcher??{}).clearChat??{},i=o??a.size??"32px",p=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",u=a.borderWidth??"",b=a.borderColor??"",g=a.borderRadius??"",y=a.paddingX??"",C=a.paddingY??"",M=a.tooltipText??"Clear chat",L=a.showTooltip??!0,I=m("div",n),S=!!(u||b),R=Fe("button",{className:$n("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!S&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":M},style:{height:i,width:i,color:d||Kt.actionIconColor,backgroundColor:c||void 0,border:S?`${u||"0px"} solid ${b||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:y||void 0,paddingRight:y||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),$=te(p,r,"currentColor",1);return $&&($.style.display="block",R.appendChild($)),I.appendChild(R),Dt({anchor:R,trigger:I,text:()=>R.getAttribute("aria-label")??M,enabled:L}),{button:R,wrapper:I}};var Kt={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))"},yo=e=>{let{config:t,showClose:n=!0}=e,o=Fe("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=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",i=r.headerIconHidden??!1,p=r.headerIconName,d=Fe("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(p){let $=parseFloat(s)||24,z=te(p,$*.6,"currentColor",1);z?d.replaceChildren(z):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let $=m("img");$.src=t.launcher.iconUrl,$.alt="",$.className="persona-rounded-xl persona-object-cover",$.style.height=s,$.style.width=s,d.replaceChildren($)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=m("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Fe("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Kt.titleColor}}),b=Fe("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Kt.subtitleColor}});c.append(u,b),i?o.append(c):o.append(d,c);let g=r.clearChat??{},y=g.enabled??!0,C=g.placement??"inline",M=null,L=null;if(y){let z=Xa(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=z.button,L=z.wrapper,C==="top-right"&&(L.style.right="48px"),C==="inline"&&o.appendChild(L)}let I=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:S,wrapper:R}=Ja(t,{showClose:n,wrapperClassName:I});return a!=="top-right"&&o.appendChild(R),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:b,closeButton:S,closeButtonWrapper:R,clearChatButton:M,clearChatButtonWrapper:L}},Cr=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var Nu=e=>{let t=yo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.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 t};function Jv(e,t,n){if(t?.length)for(let o of t){let r=m("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=te(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=m("div","persona-relative");s.appendChild(r);let a=qo({items:o.menuItems,onSelect:i=>n?.(i),anchor:s,position:"bottom-left"});s.appendChild(a.element),r.addEventListener("click",i=>{i.stopPropagation(),a.toggle()}),e.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var Fu=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},i=m("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,d,c;if(p)d=Bl({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Kt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=m("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=m("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Kt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),Jv(d,r?.trailingActions,r?.onAction??s),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let S=r.onTitleClick;d.addEventListener("click",R=>{R.target.closest("button")||S()}),d.addEventListener("keydown",R=>{(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),S())})}let I=r?.titleRowHover;I&&(d.style.borderRadius=I.borderRadius??"10px",d.style.padding=I.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=I.background??"",d.style.borderColor=I.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let u=a.closeButtonSize??"32px",b=m("div",""),g=m("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=u,g.style.width=u,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Kt.actionIconColor;let y=a.closeButtonIconName??"x",C=te(y,"28px","currentColor",1);C?g.appendChild(C):g.textContent="\xD7",o&&g.addEventListener("click",o),b.appendChild(g),i.appendChild(b);let M=m("div");M.style.display="none";let L=m("span");return L.style.display="none",{header:i,iconHolder:M,headerTitle:c,headerSubtitle:L,closeButton:g,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}},zl={default:Nu,minimal:Fu},_u=e=>zl[e]??zl.default,ks=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=m("div");i.style.display="none";let p=m("span"),d=m("span"),c=m("button");c.style.display="none";let u=m("div");return u.style.display="none",{header:a,iconHolder:i,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=_u(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Qa=e=>{let t=m("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.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",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let a=parseFloat(t.style.maxHeight);return Number.isFinite(a)&&a>0?a:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let a=Math.min(t.scrollHeight,r());t.style.height=`${a}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},Ya=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",i=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,u=t.size??"40px",b=t.backgroundColor,g=t.textColor,y=m("div","persona-send-button-wrapper"),C=Fe("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&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&b||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),M=null,L=null;if(n){let R=parseFloat(u)||24,$=g?.trim()||"currentColor";r?(M=te(r,R,$,2),M?C.appendChild(M):C.textContent=o):C.textContent=o,L=te(s,R,$,2)}else C.textContent=p;C.setAttribute("aria-label",a),y.appendChild(C),Dt({anchor:C,trigger:y,text:()=>C.getAttribute("aria-label")??"",enabled:c});let I="send";return{button:C,wrapper:y,setMode:R=>{if(R===I)return;I=R;let $=R==="stop"?i:a;if(C.setAttribute("aria-label",$),n){if(M&&L){let z=R==="stop"?L:M;C.replaceChildren(z)}}else C.textContent=R==="stop"?d:p}}},Za=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let a=e?.sendButton?.size??"40px",i=t.iconName??"mic",p=t.iconSize??a,d=parseFloat(p)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,b=m("div","persona-send-button-wrapper"),g=Fe("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":t.tooltipText??"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=te(i,d,u||"currentColor",1.5);C?g.appendChild(C):g.textContent="\u{1F3A4}",b.appendChild(g);let M=t.tooltipText??"Start voice recognition",L=t.showTooltip??!1;return Dt({anchor:g,trigger:b,text:()=>g.getAttribute("aria-label")??M,enabled:L}),{button:g,wrapper:b}},ei=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=m("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=m("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??jn).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",a=n,i=parseFloat(a)||40,p=Math.round(i*.6),d=m("div","persona-send-button-wrapper"),c=Fe("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":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),u=te(s,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",g=>{g.preventDefault(),r.click()}),d.appendChild(c);let b=t.buttonTooltipText??"Attach file";return Dt({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??b}),{button:c,wrapper:d,input:r,previewsContainer:o}},ti=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=m("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=m("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},ni=()=>Fe("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ls=e=>{let{config:t}=e,n=Fe("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=ni(),r=Fe("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Qa(t);a();let i=Ya(t),p=Za(t),d=ei(t),c=ti(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let u=Fe("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),b=m("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=m("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&b.append(d.wrapper),p&&g.append(p.wrapper),g.append(i.wrapper),u.append(b,g),r.append(u),r.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==p?.button&&y.target!==p?.wrapper&&y.target!==d?.button&&y.target!==d?.wrapper&&s.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:b,rightActions:g,setSendButtonMode:i.setMode}};var $u=()=>{let e=Fe("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=m("span","persona-pill-peek__icon"),n=te("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=m("span","persona-pill-peek__text"),r=m("span","persona-pill-peek__caret"),s=te("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},ju=e=>{let{config:t}=e,n=Fe("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ni(),r=ti(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Qa(t);s.style.maxHeight="100px",a();let i=Ya(t),p=Za(t),d=ei(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=Fe("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=m("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let b=m("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&b.append(p.wrapper),b.append(i.wrapper),c.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==p?.button&&y.target!==p?.wrapper&&y.target!==d?.button&&y.target!==d?.wrapper&&s.focus()}),d&&c.append(d.input),c.append(u,s,b),d&&n.append(d.previewsContainer),n.append(o,c,r);let g=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:g,leftActions:u,rightActions:b,setSendButtonMode:i.setMode}};var Uu=e=>{let t=e?.launcher?.enabled??!0,n=Wt(e);if(ho(e)){let c=e?.launcher?.composerBar??{},u=m("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??Ut);let b=m("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 g=m("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=c.expandedSize??"anchored",g.style.zIndex=String(e?.launcher?.zIndex??Ut),{wrapper:u,panel:b,pillRoot:g}}if(n){let c=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!t){let c=m("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=m("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),b=e?.launcher?.width??"100%";return c.style.width=b,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=e?.launcher??{},s=r.position&&wn[r.position]?wn[r.position]:wn["bottom-right"],a=m("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??Ut);let i=m("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??un;return i.style.width=d,i.style.maxWidth=d,a.appendChild(i),{wrapper:a,panel:i}},Xv=(e,t)=>{let n=m("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}=Ja(e,{showClose:t,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=e?.launcher?.clearChat?.enabled??!0,a=null,i=null;if(s){let R=Xa(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=R.button,i=R.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let p=Fe("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Fe("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"}});d.style.setProperty("scrollbar-gutter","stable");let c=Fe("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Fe("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),b=Fe("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)"}},c,u),g=m("div","persona-flex persona-flex-col persona-gap-3"),y=e?.layout?.contentMaxWidth;y&&(g.style.maxWidth=y,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(b.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(b,g);let M=Fe("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),L=ju({config:e}),{root:I,textNode:S}=$u();return n.append(p,r,d,M),i&&n.appendChild(i),{container:n,body:d,messagesWrapper:g,composerOverlay:M,suggestions:L.suggestions,textarea:L.textarea,sendButton:L.sendButton,sendButtonWrapper:L.sendButtonWrapper,micButton:L.micButton,micButtonWrapper:L.micButtonWrapper,composerForm:L.composerForm,statusText:L.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:m("span"),headerTitle:m("span"),headerSubtitle:m("span"),header:p,footer:L.footer,attachmentButton:L.attachmentButton,attachmentButtonWrapper:L.attachmentButtonWrapper,attachmentInput:L.attachmentInput,attachmentPreviewsContainer:L.attachmentPreviewsContainer,actionsRow:L.actionsRow,leftActions:L.leftActions,rightActions:L.rightActions,setSendButtonMode:L.setSendButtonMode,peekBanner:I,peekTextNode:S}},zu=(e,t=!0)=>{if(ho(e))return Xv(e,t);let n=Fe("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=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?ks(e,o,{showClose:t}):yo({config:e,showClose:t}),a=Fe("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=Fe("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=Fe("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=Fe("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Wt(e)?"none":"var(--persona-intro-card-shadow, none)"}},i,p),c=m("div","persona-flex persona-flex-col persona-gap-3"),u=e?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,c);let g=Ls({config:e}),y=e?.layout?.showFooter!==!1;r?Cr(n,s,e):(s.header.style.display="none",Cr(n,s,e)),n.append(a);let C=Fe("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 y||(g.footer.style.display="none"),n.append(g.footer),n.append(C),{container:n,body:a,messagesWrapper:c,composerOverlay:C,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:i,introSubtitle:p,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var ql=(e,t)=>{let n=m("button");n.type="button",n.innerHTML=`
31
+ `)),n=m("span","persona-code-line")),o(r.type,s[a])}return n.childNodes.length>0?t.appendChild(n):t.lastChild||t.appendChild(n),t}function yu(e,t,n){let o=e.length<=rv?sv(t,n):null,r=o?gv(e,o):[{type:"plain",value:e}];return fv(r)}function qo(e){let{items:t,onSelect:n,anchor:o,position:r="bottom-left",portal:s}=e,a=m("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Pa)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",r==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let M=document.createElement("hr");a.appendChild(M)}let y=document.createElement("button");if(y.type="button",y.setAttribute("role","menuitem"),y.setAttribute("data-dropdown-item-id",g.id),g.destructive&&y.setAttribute("data-destructive",""),g.icon){let M=te(g.icon,16,"currentColor",1.5);M&&y.appendChild(M)}let C=document.createElement("span");C.textContent=g.label,y.appendChild(C),y.addEventListener("click",M=>{M.stopPropagation(),c(),n(g.id)}),a.appendChild(y)}let i=null;function p(){if(!s)return;let g=o.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,r==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function d(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=y=>{!a.contains(y.target)&&!o.contains(y.target)&&c()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function c(){a.classList.add("persona-hidden"),i?.(),i=null}function u(){a.classList.contains("persona-hidden")?d():c()}function b(){c(),a.remove()}return s&&s.appendChild(a),{element:a,show:d,hide:c,toggle:u,destroy:b}}function dt(e){let{icon:t,label:n,size:o,strokeWidth:r,className:s,onClick:a,aria:i}=e,p=m("button","persona-icon-btn"+(s?" "+s:""));p.type="button",p.setAttribute("aria-label",n),p.title=n;let d=te(t,o??16,"currentColor",r??2);if(d&&p.appendChild(d),a&&p.addEventListener("click",a),i)for(let[c,u]of Object.entries(i))p.setAttribute(c,u);return p}function po(e){let{icon:t,label:n,variant:o="default",size:r="sm",iconSize:s,className:a,onClick:i,aria:p}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+r,a&&(d+=" "+a);let c=m("button",d);if(c.type="button",c.setAttribute("aria-label",n),t){let b=te(t,s??14,"currentColor",2);b&&c.appendChild(b)}let u=m("span");if(u.textContent=n,c.appendChild(u),i&&c.addEventListener("click",i),p)for(let[b,g]of Object.entries(p))c.setAttribute(b,g);return c}function uo(e){let{items:t,selectedId:n,onSelect:o,className:r}=e,s=m("div","persona-toggle-group"+(r?" "+r:""));s.setAttribute("role","group");let a=n,i=[];function p(){for(let c of i)c.btn.setAttribute("aria-pressed",c.id===a?"true":"false")}for(let c of t){let u;c.icon?u=dt({icon:c.icon,label:c.label,className:c.className,onClick:()=>{a=c.id,p(),o(c.id)}}):(u=m("button","persona-icon-btn"+(c.className?" "+c.className:"")),u.type="button",u.setAttribute("aria-label",c.label),u.title=c.label,u.textContent=c.label,u.addEventListener("click",()=>{a=c.id,p(),o(c.id)})),u.setAttribute("aria-pressed",c.id===a?"true":"false"),i.push({id:c.id,btn:u}),s.appendChild(u)}function d(c){a=c,p()}return{element:s,setSelected:d}}function Bl(e){let{label:t,icon:n="chevron-down",menuItems:o,onSelect:r,position:s="bottom-left",portal:a,className:i,hover:p}=e,d=m("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let c=m("span","persona-combo-btn-label");c.textContent=t,d.appendChild(c);let u=te(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",d.appendChild(u)),p&&(d.style.borderRadius=p.borderRadius??"10px",d.style.padding=p.padding??"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=p.background??"",d.style.borderColor=p.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let b=qo({items:o,onSelect:g=>{d.setAttribute("aria-expanded","false"),r(g)},anchor:d,position:s,portal:a});return a||d.appendChild(b.element),d.addEventListener("click",g=>{g.stopPropagation();let y=!b.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",y?"false":"true"),b.toggle()}),d.addEventListener("keydown",g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),d.click())}),{element:d,setLabel:g=>{c.textContent=g,d.setAttribute("aria-label",g)},open:()=>{d.setAttribute("aria-expanded","true"),b.show()},close:()=>{d.setAttribute("aria-expanded","false"),b.hide()},toggle:()=>{let g=!b.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",g?"false":"true"),b.toggle()},destroy:()=>{b.destroy(),d.remove()}}}var Na="persona-artifact-custom-action-btn";function vr(e,t){let n=t?.documentChrome??!1,o;if(typeof e.icon=="function"){if(e.showLabel){let r="persona-label-btn persona-label-btn--sm "+Na+(n?" persona-artifact-doc-copy-btn":"");o=m("button",r)}else{let r="persona-icon-btn "+Na+(n?" persona-artifact-doc-icon-btn":"");o=m("button",r)}o.type="button",o.setAttribute("aria-label",e.label),o.title=e.label;try{let r=e.icon();r&&o.appendChild(r)}catch{}if(e.showLabel){let r=m("span");r.textContent=e.label,o.appendChild(r)}}else e.showLabel||!e.icon?o=po({icon:e.icon,label:e.label,className:Na+(n?" persona-artifact-doc-copy-btn":"")}):o=dt({icon:e.icon,label:e.label,className:Na+(n?" persona-artifact-doc-icon-btn":"")});return t?.onClick&&o.addEventListener("click",t.onClick),o}function vs(e){if(!e)return null;let t={artifactId:e.id,title:e.title??"",artifactType:e.artifactType};return e.artifactType==="markdown"?(t.markdown=e.markdown??"",e.file&&(t.file=e.file)):t.jsonPayload=JSON.stringify({component:e.component,props:e.props},null,2),t}function bu(e,t){let n=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0,o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=n?Mn(n.path):o,s=typeof e.artifactId=="string"?e.artifactId:"",a=e.status==="streaming"?"streaming":"complete",i=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n?lo(n):i==="component"?"Component":"Document",d=document.createElement("div");d.className="persona-artifact-card persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-px-4 persona-py-3",d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",`Open ${r} in artifact panel`),s&&d.setAttribute("data-open-artifact",s);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.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 g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",a==="streaming"){let y=t?.config?.features?.artifacts,C={id:s,artifactType:i==="component"?"component":"markdown",title:o,status:"streaming",...typeof e.markdown=="string"?{markdown:e.markdown}:{},...n?{file:n}:{}},M=br(C,y,"card");zo(g,M,y)}else s&&yr(s),g.textContent=p;if(u.append(b,g),d.append(c,u),a==="complete"){let y=t?.config?.features?.artifacts?.cardActions;if(y&&y.length>0){let M={artifactId:s||null,title:r,artifactType:i,markdown:typeof e.markdown=="string"?e.markdown:void 0,file:n};for(let L of y)try{if(L.visible===void 0||L.visible(M)){let I=vr(L);I.setAttribute("data-artifact-custom-action",L.id),I.className=`${I.className} persona-flex-shrink-0`,d.append(I)}}catch{}}let C=po({label:"Download",className:"persona-flex-shrink-0"});C.title=`Download ${r}`,C.setAttribute("data-download-artifact",s),d.append(C)}return d}var Fa=(e,t)=>{let n=t?.config?.features?.artifacts?.renderCard;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>bu(e,t)});if(i)return i}return bu(e,t)};var go=new WeakMap;function Ol(e,t,n){if(t.length===0)return;let o=new Map(t.map(r=>[r.id,r]));e.querySelectorAll("[data-artifact-inline]").forEach(r=>{let s=go.get(r);if(!s)return;let a=o.get(r.getAttribute("data-artifact-inline")??"");a&&s(a,n)})}function Au(e){return go.has(e)}function mv(e){let t=typeof e.artifactId=="string"?e.artifactId:"",n=typeof e.title=="string"&&e.title?e.title:void 0,o=e.status==="streaming"?"streaming":"complete";if(e.artifactType==="component"){let s=e.componentProps,a=s&&typeof s=="object"&&!Array.isArray(s)?s:{};return{id:t,artifactType:"component",title:n,status:o,component:typeof e.component=="string"?e.component:"",props:a}}let r=e.file&&typeof e.file=="object"&&!Array.isArray(e.file)?e.file:void 0;return{id:t,artifactType:"markdown",title:n,status:o,markdown:typeof e.markdown=="string"?e.markdown:"",...r?{file:r}:{}}}function vu(e){let t=e.artifactType==="markdown"?e.file:void 0,n=t?Mn(t.path):e.title&&e.title.trim()?e.title:"Untitled artifact",o=t?lo(t):e.artifactType==="component"?"Component":"Document";return{title:n,typeLabel:o}}function hv(e){let t={artifactId:e.id,title:e.title??"",status:e.status,artifactType:e.artifactType};return e.artifactType==="markdown"&&(typeof e.markdown=="string"&&(t.markdown=e.markdown),e.file&&(t.file=e.file)),t}var xu=180,yv=240,bv=.8,vv=300,xv=500,Cv="cubic-bezier(0.2, 0, 0, 1)",Cu=240,wv=.35;function Av(e,t,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(!t||!e.isConnected||s||typeof e.animate!="function"){o(),r();return}e.style.height=`${t}px`,e.style.overflow="hidden";let a=[];for(let i of Array.from(e.children))i instanceof HTMLElement&&a.push(i.animate([{opacity:1},{opacity:0}],{duration:xu,easing:"ease-out",fill:"forwards"}));window.setTimeout(()=>{for(let L of a)L.cancel();o();let i=()=>{e.style.removeProperty("height"),e.style.removeProperty("overflow")};if(!e.isConnected){i(),r();return}e.style.height="auto";let p=e.getBoundingClientRect().height;if(e.style.height=`${t}px`,!p||Math.abs(p-t)<1){i(),r();return}let d=Math.abs(t-p),c=Math.round(Math.min(xv,Math.max(vv,yv+d*bv))),u=Math.round(c*wv),b=e.firstElementChild instanceof HTMLElement?e.firstElementChild:null,g=b?b.animate([{opacity:0},{opacity:1}],{duration:Cu,delay:u,easing:"ease-out",fill:"backwards"}):null,y=e.animate([{height:`${t}px`},{height:`${p}px`}],{duration:c,easing:Cv});e.style.height=`${p}px`;let C=!1,M=()=>{C||(C=!0,i(),r())};Promise.allSettled([y.finished,g?.finished].filter(Boolean)).then(M),window.setTimeout(M,Math.max(c,u+Cu)+120)},xu)}function Sv(e){let t=e?.inlineChrome;if(t===!1)return{chromeEnabled:!1,showCopy:!1,showExpand:!1,showViewToggle:!1};let n=typeof t=="object"?t: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 Tv(e){let t=e?.inlineBody,n=t?.streamingView==="status"?"status":"source",o=t?.viewMode==="source"?"source":"rendered",r=320,s=320,a=t?.height;typeof a=="number"||a==="auto"?(r=a,s=a):a&&typeof a=="object"&&(r=a.streaming??320,s=a.complete??320);let i=t?.overflow==="clip"?"clip":"scroll",p=i==="clip"?!1:t?.followOutput!==!1,d,c,u=t?.fadeMask;u===!0?(d=!0,c=!0):u===!1?(d=!1,c=!1):u&&typeof u=="object"?(d=u.top===!0,c=u.bottom===!0):i==="clip"?(d=!1,c=!0):(d=!0,c=!0);let b=t?.transition==="none"?"none":"auto",g=t?.completeDisplay==="card"?"card":"inline";return{streamingView:n,viewMode:o,streamingHeight:r,completeHeight:s,followOutput:p,overflow:i,fadeTop:d,fadeBottom:c,transition:b,completeDisplay:g}}function wu(e,t){let n=mv(e),o=t.config?.features?.artifacts,{chromeEnabled:r,showCopy:s,showExpand:a,showViewToggle:i}=Sv(o),p=o?.inlineActions??[],d=Tv(o),c=d.completeDisplay==="card",u=null,b=n,g=m("div","persona-artifact-inline persona-w-full persona-max-w-full");g.setAttribute("data-persona-theme-zone","artifact-inline"),n.id&&g.setAttribute("data-artifact-inline",n.id);let y=Y=>Fa(hv(Y),t),C=Y=>{g.classList.add("persona-artifact-inline--card"),g.style.removeProperty(xs),g.replaceChildren(y(Y)),go.set(g,ce=>{g.replaceChildren(y(ce))})};if(c&&n.status==="complete")return C(n),g;let M=_a(n,{config:t.config,bodyLayout:d,resolveViewMode:()=>u??d.viewMode}),L=m("div","persona-artifact-inline-body");L.appendChild(M.el);let I=Y=>{let ce=Y.status!=="complete",Z=ce?d.streamingHeight:d.completeHeight,be=typeof Z=="number";be?g.style.setProperty(xs,`${Z}px`):g.style.removeProperty(xs);let he=!!M.el.querySelector(".persona-code-pre"),de=!!M.el.querySelector("iframe, .persona-artifact-source-window--fixed, .persona-artifact-status-view");L.classList.toggle("persona-artifact-content-flush",he),L.classList.toggle("persona-artifact-inline-body--sized",be&&de),L.classList.toggle("persona-artifact-inline-body--cap",!ce&&!de&&typeof d.completeHeight=="number")},S=n.status,R=(Y,ce)=>{S!=="complete"&&Y.status==="complete"?(typeof d.completeHeight=="number"?g.style.setProperty(xs,`${d.completeHeight}px`):g.style.removeProperty(xs),Tu(L,ce?.suppressTransition?"none":d.transition,Y.id,()=>{M.update(Y),I(Y)})):M.update(Y),I(Y),S=Y.status};I(n);let $=d.overflow==="clip"&&a&&!!n.id;if($&&(L.setAttribute("data-expand-artifact-inline",n.id),L.setAttribute("role","button"),L.setAttribute("tabindex","0"),L.classList.add("persona-cursor-pointer"),L.setAttribute("aria-label",`Open ${vu(n).title} in panel`)),!r)return g.appendChild(L),go.set(g,R),g;let z=m("div","persona-artifact-inline-chrome");z.setAttribute("data-persona-theme-zone","artifact-inline-chrome");let w=m("div","persona-artifact-inline-chrome-lead"),U=m("span","persona-flex persona-items-center persona-flex-shrink-0"),q=te("file-text",16,"currentColor",2);q&&U.appendChild(q);let Q=m("span","persona-artifact-inline-title persona-truncate persona-min-w-0"),O=m("span","persona-artifact-inline-type");w.append(U,Q,O);let D=m("div","persona-artifact-inline-chrome-actions"),ie=m("span","persona-flex persona-items-center persona-gap-1"),me=()=>u??d.viewMode,we=i?uo({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:me(),className:"persona-artifact-toggle-group persona-flex-shrink-0",onSelect:Y=>{let ce=Y==="source"?"source":"rendered";ce!==me()&&(u=ce,M.update(b),I(b))}}):null,Ee=s?dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;Ee&&n.id&&Ee.setAttribute("data-copy-artifact",n.id);let se=a?dt({icon:"maximize",label:"Open in panel",className:"persona-artifact-doc-icon-btn persona-flex-shrink-0"}):null;se&&n.id&&se.setAttribute("data-expand-artifact-inline",n.id),D.appendChild(ie),we&&D.appendChild(we.element),Ee&&D.appendChild(Ee),se&&D.appendChild(se),z.append(w,D),g.append(z,L);let fe=Y=>{let{title:ce,typeLabel:Z}=vu(Y);Q.textContent=ce,Q.title=ce,$&&L.setAttribute("aria-label",`Open ${ce} in panel`);let be=Y.status!=="complete";if(be){O.classList.contains("persona-artifact-inline-status")||(O.className="persona-artifact-inline-status",O.removeAttribute("data-preserve-animation"),O.replaceChildren());let he=br(Y,o,"inline-chrome");zo(O,he,o)}else yr(Y.id),O.className="persona-artifact-inline-type",O.removeAttribute("data-preserve-animation"),O.replaceChildren(),O.textContent=Z;if(Ee&&Ee.classList.toggle("persona-hidden",be),we){let he=Y.artifactType==="markdown"?Y.file:void 0,de=!1;if(!be&&he&&d.viewMode!=="source"){let Me=bs(he);Me==="markdown"?de=!0:(Me==="html"||Me==="svg")&&(de=o?.filePreview?.enabled!==!1)}we.element.classList.toggle("persona-hidden",!de),we.setSelected(me())}if(ie.replaceChildren(),!be&&p.length>0){let he=vs(Y);if(he)for(let de of p)try{if(de.visible===void 0||de.visible(he)){let Me=vr(de,{documentChrome:!0});Me.setAttribute("data-artifact-custom-action",de.id),Me.classList.add("persona-flex-shrink-0"),ie.appendChild(Me)}}catch{}}};return fe(n),go.set(g,(Y,ce)=>{if(c&&S!=="complete"&&Y.status==="complete"){let Z=g.isConnected?g.getBoundingClientRect().height:0;S="complete";let be=Y,he=!1,de=Me=>{be=Me,he=!0};go.set(g,de),Av(g,Z,{swap:()=>{C(be),he=!1,go.set(g,de)},onSettled:()=>{he?C(be):go.set(g,Me=>{g.replaceChildren(y(Me))})}});return}(Y.status!=="complete"||Y.id!==b.id)&&(u=null),b=Y,R(Y,ce),fe(Y)}),g}var Su=(e,t)=>{let n=t?.config?.features?.artifacts?.renderInline;if(n){let o=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=typeof e.artifactType=="string"?e.artifactType:"markdown",i=n({artifact:{artifactId:r,title:o,artifactType:a,status:s},config:t.config,defaultRenderer:()=>wu(e,t)});if(i)return i}return wu(e,t)};var Dl=class{constructor(){this.components=new Map;this.options=new Map}register(t,n,o){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n),o?this.options.set(t,o):this.options.delete(t)}unregister(t){this.components.delete(t),this.options.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getOptions(t){return this.options.get(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear(),this.options.clear()}registerAll(t){Object.entries(t).forEach(([n,o])=>{this.register(n,o)})}},kn=new Dl;kn.register("PersonaArtifactCard",Fa,{bubbleChrome:!1});kn.register("PersonaArtifactInline",Su,{bubbleChrome:!1});function Cs(e){if(!e)return"";if(e.artifactType==="markdown"){let t=e.markdown??"";return e.file?Ba(t):t}return JSON.stringify({component:e.component,props:e.props},null,2)}var Nl=!1;function Ev(e){return"persona-artifact-vt-"+((e||"artifact").replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+/,"")||"artifact")}function Tu(e,t,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(t!=="auto"||!e||typeof r!="function"||Nl||s){o();return}Nl=!0;let a=Ev(n);e.style.setProperty("view-transition-name",a);let i=()=>{Nl=!1,e.style.removeProperty("view-transition-name")};try{r.call(document,()=>{o()}).finished.then(i,i)}catch{i(),o()}}var Mv="persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary",kv="persona-text-sm persona-leading-relaxed persona-markdown-bubble";function Lv(e){let t=m("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=m("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let o=m("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify(e.props??{},null,2),t.appendChild(n),t.appendChild(o),t}function Pv(e){if(e===!1)return{enabled:!1,delayMs:0,minVisibleMs:0,timeoutMs:0,injectReadySignal:!1,label:"Starting preview...",labelDelayMs:2e3};let t=e&&typeof e=="object"?e:void 0;return{enabled:!0,delayMs:t?.delayMs??200,minVisibleMs:t?.minVisibleMs??300,timeoutMs:t?.timeoutMs??8e3,injectReadySignal:t?.injectReadySignal!==!1,label:t?.label===!1?!1:t?.label??"Starting preview...",labelDelayMs:t?.labelDelayMs??2e3,renderIndicator:t?.renderIndicator}}var Rv=220;function Iv(){try{if(typeof crypto<"u"&&crypto.getRandomValues){let e=new Uint32Array(2);return crypto.getRandomValues(e),e[0].toString(36)+e[1].toString(36)}}catch{}return Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2)}function Wv(e){return`
32
+ <script>(function(){var d=false;var t=`+JSON.stringify(e)+";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 Hv(e,t,n){let o=m("div","persona-artifact-frame-loading");if(n.renderIndicator)try{let a=n.renderIndicator({artifactId:e,config:t});if(a)return o.appendChild(a),{el:o,revealLabel:()=>{}}}catch{}let r=m("div","persona-artifact-frame-loading-indicator");r.appendChild(du());let s=null;return n.label!==!1&&(s=m("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 Bv(e,t,n,o,r,s){let a=null,i=0,p=!1,d=new Set,c=()=>{d.forEach(S=>clearTimeout(S)),d.clear()},u=(S,R)=>{let $=setTimeout(()=>{d.delete($),S()},R);d.add($)},b=()=>{a&&a.parentElement&&a.remove(),a=null},g=()=>{if(a||p)return;let S=Hv(r,s,o);a=S.el,e.appendChild(a),i=Date.now(),o.label!==!1&&u(S.revealLabel,o.labelDelayMs)},y=()=>{a&&(a.classList.add("persona-artifact-frame-loading--out"),u(b,Rv))},C=()=>{n!==null?typeof window<"u"&&window.removeEventListener("message",L):t.removeEventListener("load",I)},M=()=>{if(p||(p=!0,C(),c(),!a))return;let S=Math.max(0,o.minVisibleMs-(Date.now()-i));S>0?u(y,S):y()};function L(S){if(n===null)return;let R=S.data;!R||R.persona!=="artifact-preview-ready"||R.token!==n||S.source===t.contentWindow&&M()}function I(){let S=R=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>R()):setTimeout(R,0)};S(()=>S(()=>M()))}return u(g,o.delayMs),u(M,o.timeoutMs),n!==null?typeof window<"u"&&window.addEventListener("message",L):t.addEventListener("load",I),()=>{p=!0,c(),C(),b()}}function _a(e,t){let{config:n}=t,o=t.registry??kn,r=t.bodyLayout,s=n.markdown?cr(n.markdown):null,a=Zr(n.sanitize),i=e,p=!1,d=se=>{let fe=Nn()!==null;s&&!fe&&!p&&(p=!0,Yr(()=>Ee(i)));let Y=s?s(se):Fn(se);return s&&fe&&a?a(Y):Y},c=m("div","persona-artifact-preview-body"),u=null,b=null,g=null,y=()=>{g&&(g(),g=null),u=null,b=null},C=null,M=null,L=null,I=!1,S=()=>{C=null,M=null,L=null,I=!1},R=null,$=null,z=()=>{R=null,$=null},w=40,U=0,q=se=>typeof requestAnimationFrame=="function"?requestAnimationFrame(()=>se()):setTimeout(se,0),Q=se=>se.scrollHeight-se.clientHeight-se.scrollTop<=w,O=se=>{if(!r)return;let fe=se.scrollHeight-se.clientHeight>1,Y=se.scrollHeight-se.clientHeight-se.scrollTop;se.classList.toggle("persona-artifact-fade-top",r.fadeTop&&fe&&se.scrollTop>1),se.classList.toggle("persona-artifact-fade-bottom",r.fadeBottom&&fe&&Y>1)},D=se=>{U||(U=q(()=>{U=0,se.scrollTop=se.scrollHeight,O(se)}))},ie=(se,fe,Y,ce)=>{let Z=!!r,be=Y.id+"|"+(Z?"w":"p");if(!C||L!==be||C.parentElement!==c){y(),z(),c.replaceChildren();let Me=m("pre",Mv+" persona-code-pre"),De=m("code","persona-code");if(Me.appendChild(De),Z){let _e=m("div","persona-artifact-source-window");if(_e.appendChild(Me),c.appendChild(_e),!(r?.overflow==="clip")&&typeof _e.addEventListener=="function"){let Ue=()=>_e.scrollHeight-_e.clientHeight>1;_e.addEventListener("scroll",()=>{Q(_e)&&(I=!1),O(_e)},{passive:!0}),_e.addEventListener("wheel",Ve=>{Ue()&&Ve.deltaY<0&&(I=!0)},{passive:!0}),_e.addEventListener("touchmove",()=>{Ue()&&(I=!0)},{passive:!0})}C=_e}else c.appendChild(Me),C=Me;M=De,L=be}let he=Z?C:null;he&&(he.classList.toggle("persona-artifact-source-window--fixed",ce),he.classList.toggle("persona-artifact-source-window--clip",ce&&r?.overflow==="clip"));let de=he?Q(he):!0;if(M.replaceChildren(yu(se,fe?.language,fe?.path)),he){let Me=Y.status!=="complete";ce&&Me&&r?.followOutput&&!I&&de?D(he):Me||(I=!1),O(he)}},me=se=>{y(),S(),z(),c.replaceChildren();let fe=m("div",kv);fe.innerHTML=d(se),c.appendChild(fe)},we=se=>{let fe=se.id,Y=n.features?.artifacts,ce=br(se,Y,"status-body");if(R&&$===fe&&R.parentElement===c){let he=R.querySelector(".persona-artifact-status-view-text");he&&zo(he,ce,Y);return}y(),S(),c.replaceChildren();let Z=m("div","persona-artifact-status-view"),be=m("div","persona-artifact-status-view-text");zo(be,ce,Y),Z.appendChild(be),c.appendChild(Z),R=Z,$=fe},Ee=se=>{i=se;let fe=t.resolveViewMode?.(se)??r?.viewMode??"rendered",Y=se.artifactType==="markdown"?se.file:void 0,ce=se.status!=="complete";ce||yr(se.id);let Z=ce?r?.streamingHeight:r?.completeHeight,be=!!r&&typeof Z=="number";if(r?.streamingView==="status"&&ce){we(se);return}if(Y){let de=Ba(se.markdown??""),Me=bs(Y),De=n.features?.artifacts?.filePreview?.enabled!==!1;if(!ce&&fe==="rendered"&&De&&(Me==="html"||Me==="svg")){let He=se.id+"\0"+de;if(u&&b===He&&u.parentElement===c)return;S(),z(),y(),c.replaceChildren();let Ue=n.features?.artifacts?.filePreview,Ve=Ue?.iframeSandbox??"allow-scripts";!Ue?.dangerouslyAllowSameOrigin&&Ve.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."),Ve=Ve.split(/\s+/).filter(mt=>mt&&mt!=="allow-same-origin").join(" "));let ke=Pv(Ue?.loading),ne=m("div","persona-artifact-frame"),Be=m("iframe","persona-artifact-iframe");Be.setAttribute("sandbox",Ve),Be.setAttribute("data-artifact-id",se.id);let vt=null;ke.enabled&&ke.injectReadySignal?(vt=Iv(),Be.srcdoc=de+Wv(vt)):Be.srcdoc=de,ne.appendChild(Be),c.appendChild(ne),ke.enabled&&(g=Bv(ne,Be,vt,ke,se.id,n)),u=ne,b=He;return}if(y(),!ce&&Me==="markdown"&&fe==="rendered"){me(de);return}ie(de,{language:Y.language,path:Y.path},se,be);return}if(se.artifactType==="markdown"){if(fe==="source"){y(),ie(se.markdown??"",void 0,se,be);return}me(se.markdown??"");return}y(),S(),z(),c.replaceChildren();let he=se.component?o.get(se.component):void 0;if(he){let Me={message:{id:se.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let De=he(se.props??{},Me);if(De){c.appendChild(De);return}}catch{}}c.appendChild(Lv(se))};return Ee(e),{el:c,update(se){Ee(se)}}}import{Idiomorph as Ov}from"idiomorph";var $a=(e,t,n={})=>{let{preserveTypingAnimation:o=!0}=n;Ov.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&o){if(r.classList.contains("persona-animate-typing")||r.hasAttribute("data-preserve-runtime"))return!1;if(r.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===r.getAttribute("data-tool-elapsed")?!1:void 0;if(r.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let a=r.textContent??"",i=s.textContent??"";if(a!==i)return}return!1}}}}})};var Eu=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Fl={index:-1,draft:""};function Mu(e){let{direction:t,history:n,currentValue:o,atStart:r,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!r)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:o}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{index:-1,draft:s.draft}}}function ku(e,t){return[e.id,e.role,e.content?.length??0,e.content?.slice(-32)??"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",e.variant??"",e.rawContent?.length??0,e.llmContent?.length??0,e.approval?.status??"",e.toolCall?.status??"",e.toolCall?.name??"",e.toolCall?.chunks?.length??0,e.toolCall?.chunks?.[e.toolCall.chunks.length-1]?.slice(-32)??"",typeof e.toolCall?.args=="string"?e.toolCall.args.length:e.toolCall?.args?JSON.stringify(e.toolCall.args).length:0,e.reasoning?.chunks?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.length??0,e.reasoning?.chunks?.[e.reasoning.chunks.length-1]?.slice(-32)??"",e.contentParts?.length??0,e.stopReason??"",t].join("\0")}function Lu(){return new Map}function Pu(e,t,n){let o=e.get(t);return o&&o.fingerprint===n?o.wrapper:null}function Ru(e,t,n,o){e.set(t,{fingerprint:n,wrapper:o})}function Iu(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ja(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Ln(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function fo(e,t){return Ln(e)-e.scrollTop<=t}function Ua(e){let{following:t,currentScrollTop:n,lastScrollTop:o,nearBottom:r,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:p=!0,resumeRequiresDownwardScroll:d=!1}=e,c=n-o;return a||Math.abs(c)<s?{action:"none",delta:c,nextLastScrollTop:n}:!t&&r&&(!d||c>0)?{action:"resume",delta:c,nextLastScrollTop:n}:t&&i&&c<0?{action:"pause",delta:c,nextLastScrollTop:n}:t&&p&&!r?{action:"pause",delta:c,nextLastScrollTop:n}:{action:"none",delta:c,nextLastScrollTop:n}}function za(e){let{following:t,deltaY:n,nearBottom:o=!1,resumeWhenNearBottom:r=!1}=e;return t&&n<0?"pause":!t&&r&&n>0&&o?"resume":"none"}function Wu(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Hu(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function Bu(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var ws={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Dv=["pre","code","a","script","style"],qa=e=>({type:e?.type??ws.type,placeholder:e?.placeholder??ws.placeholder,speed:e?.speed??ws.speed,duration:e?.duration??ws.duration,buffer:e?.buffer??ws.buffer}),Du=[{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"}],As=new Map;for(let e of Du)As.set(e.name,e);var Nv=e=>{As.set(e.name,e)},Fv=e=>{Du.some(t=>t.name===e)||As.delete(e)},_v=()=>Array.from(As.keys()),xr=(e,t)=>e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]??null:As.get(e)??null,Va=(e,t,n,o,r)=>{if(!r)return e;if(n?.bufferContent)return n.bufferContent(e,o);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
33
+ `);return s<0?"":e.slice(0,s)}return e},$v=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-char",r.id=`stream-c-${n}-${o}`,r.style.setProperty("--char-index",String(o)),r.textContent=t,r},jv=(e,t,n,o)=>{let r=e.createElement("span");return r.className="persona-stream-word",r.id=`stream-w-${n}-${o}`,r.style.setProperty("--word-index",String(o)),r.textContent=t,r},_l=/\s/,Uv=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let o=n;if(t.has(o.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},zv=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),i=0;for(;i<s.length;)if(_l.test(s[i])){let p=i;for(;p<s.length&&_l.test(s[p]);)p+=1;a.appendChild(o.createTextNode(s.slice(i,p))),i=p}else{let p=o.createElement("span");p.className="persona-stream-word-group";let d=i;for(;d<s.length&&!_l.test(s[d]);)p.appendChild($v(o,s[d],t,n.value)),n.value+=1,d+=1;a.appendChild(p),i=d}r.replaceChild(a,e)},qv=(e,t,n)=>{let o=e.ownerDocument,r=e.parentNode;if(!o||!r)return;let s=e.nodeValue??"";if(!s)return;let a=o.createDocumentFragment(),i=s.split(/(\s+)/);for(let p of i)p&&(/^\s+$/.test(p)?a.appendChild(o.createTextNode(p)):(a.appendChild(jv(o,p,t,n.value)),n.value+=1));r.replaceChild(a,e)},Ss=(e,t,n,o)=>{if(!e||typeof document>"u")return e;let r=document.createElement("div");r.innerHTML=e;let s=new Set((o?.skipTags??Dv).map(u=>u.toLowerCase())),a=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null),i=[],p=a.nextNode();for(;p;)Uv(p,s)||i.push(p),p=a.nextNode();let d={value:o?.startIndex??0},c=t==="char"?zv:qv;for(let u of i)c(u,n,d);return r.innerHTML},Ka=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Ts=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},Ou=new WeakMap,Vv=(e,t)=>{if(!e.styles)return;let n=Ou.get(t);if(n||(n=new Set,Ou.set(t,n)),n.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;n.delete(e.name)}n.add(e.name);let r=(t instanceof ShadowRoot?t.ownerDocument:t.ownerDocument??document).createElement("style");r.setAttribute("data-persona-animation",e.name),r.textContent=e.styles,t.appendChild(r)},$l=new WeakMap,Kv=(e,t)=>{if(!e.onAttach)return;let n=$l.get(t);if(n||(n=new Map,$l.set(t,n)),n.has(e.name))return;let o=e.onAttach(t);n.set(e.name,o)},Nu=e=>{let t=$l.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Ga=(e,t)=>{Vv(e,t),Kv(e,t)};function jl(e,t=Ut){let n=e.style.position,o=e.style.zIndex,r=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=o,e.style.isolation=r}}var Es=0,mo=null;function Ul(e=document){if(Es++,Es===1){let n=e.body,r=(e.defaultView??window).scrollY||e.documentElement.scrollTop;mo={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 t=!1;return()=>{if(!t&&(t=!0,Es=Math.max(0,Es-1),Es===0&&mo)){let n=e.body,o=e.defaultView??window;n.style.overflow=mo.originalOverflow,n.style.position=mo.originalPosition,n.style.top=mo.originalTop,n.style.width=mo.originalWidth,o.scrollTo(0,mo.scrollY),mo=null}}}var Ms={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},Wt=e=>(e?.launcher?.mountMode??"floating")==="docked",ho=e=>(e?.launcher?.mountMode??"floating")==="composer-bar",on=e=>{let t=e?.launcher?.dock;return{side:t?.side??Ms.side,width:t?.width??Ms.width,animate:t?.animate??Ms.animate,reveal:t?.reveal??Ms.reveal,maxHeight:t?.maxHeight??Ms.maxHeight}};var Cn={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Gv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ja=(e,t={})=>{let{showClose:n=!0,wrapperClassName:o=Gv,buttonSize:r,iconSize:s="28px"}=t,a=e?.launcher??{},i=r??a.closeButtonSize??"32px",p=m("div",o),d=a.closeButtonTooltipText??"Close chat",c=a.closeButtonShowTooltip??!0,u=a.closeButtonIconName??"x",b=a.closeButtonIconText??"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),y=Fe("button",{className:_n("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Kt.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),C=te(u,s,"currentColor",1);return C?(C.style.display="block",y.appendChild(C)):y.textContent=b,p.appendChild(y),Dt({anchor:y,trigger:p,text:()=>y.getAttribute("aria-label")??d,enabled:c}),{button:y,wrapper:p}},Jv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Xa=(e,t={})=>{let{wrapperClassName:n=Jv,buttonSize:o,iconSize:r="20px"}=t,a=(e?.launcher??{}).clearChat??{},i=o??a.size??"32px",p=a.iconName??"refresh-cw",d=a.iconColor??"",c=a.backgroundColor??"",u=a.borderWidth??"",b=a.borderColor??"",g=a.borderRadius??"",y=a.paddingX??"",C=a.paddingY??"",M=a.tooltipText??"Clear chat",L=a.showTooltip??!0,I=m("div",n),S=!!(u||b),R=Fe("button",{className:_n("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!c&&"hover:persona-bg-gray-100",!S&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":M},style:{height:i,width:i,color:d||Kt.actionIconColor,backgroundColor:c||void 0,border:S?`${u||"0px"} solid ${b||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:y||void 0,paddingRight:y||void 0,paddingTop:C||void 0,paddingBottom:C||void 0}}),$=te(p,r,"currentColor",1);return $&&($.style.display="block",R.appendChild($)),I.appendChild(R),Dt({anchor:R,trigger:I,text:()=>R.getAttribute("aria-label")??M,enabled:L}),{button:R,wrapper:I}};var Kt={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))"},yo=e=>{let{config:t,showClose:n=!0}=e,o=Fe("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=t?.launcher??{},s=r.headerIconSize??"48px",a=r.closeButtonPlacement??"inline",i=r.headerIconHidden??!1,p=r.headerIconName,d=Fe("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(p){let $=parseFloat(s)||24,z=te(p,$*.6,"currentColor",1);z?d.replaceChildren(z):d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}"}else if(t?.launcher?.iconUrl){let $=m("img");$.src=t.launcher.iconUrl,$.alt="",$.className="persona-rounded-xl persona-object-cover",$.style.height=s,$.style.width=s,d.replaceChildren($)}else d.textContent=t?.launcher?.agentIconText??"\u{1F4AC}";let c=m("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Fe("span",{className:"persona-text-base persona-font-semibold",text:t?.launcher?.title??"Chat Assistant",style:{color:Kt.titleColor}}),b=Fe("span",{className:"persona-text-xs",text:t?.launcher?.subtitle??"Here to help you get answers fast",style:{color:Kt.subtitleColor}});c.append(u,b),i?o.append(c):o.append(d,c);let g=r.clearChat??{},y=g.enabled??!0,C=g.placement??"inline",M=null,L=null;if(y){let z=Xa(t,{wrapperClassName:C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});M=z.button,L=z.wrapper,C==="top-right"&&(L.style.right="48px"),C==="inline"&&o.appendChild(L)}let I=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&C==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:S,wrapper:R}=Ja(t,{showClose:n,wrapperClassName:I});return a!=="top-right"&&o.appendChild(R),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:b,closeButton:S,closeButtonWrapper:R,clearChatButton:M,clearChatButtonWrapper:L}},Cr=(e,t,n)=>{let o=n?.launcher??{},r=o.closeButtonPlacement??"inline",s=o.clearChat?.placement??"inline";e.appendChild(t.header),r==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var Fu=e=>{let t=yo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=e.layoutHeaderConfig?.onTitleClick;if(n){let o=t.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 t};function Xv(e,t,n){if(t?.length)for(let o of t){let r=m("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=te(o.icon,14,"currentColor",2);s&&r.appendChild(s)}else o.label&&(r.textContent=o.label);if(o.menuItems?.length){let s=m("div","persona-relative");s.appendChild(r);let a=qo({items:o.menuItems,onSelect:i=>n?.(i),anchor:s,position:"bottom-left"});s.appendChild(a.element),r.addEventListener("click",i=>{i.stopPropagation(),a.toggle()}),e.appendChild(s)}else r.addEventListener("click",()=>n?.(o.id)),e.appendChild(r)}}var _u=e=>{let{config:t,showClose:n=!0,onClose:o,layoutHeaderConfig:r,onHeaderAction:s}=e,a=t?.launcher??{},i=m("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=r?.titleMenu,d,c;if(p)d=Bl({label:a.title??"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,d.style.color=Kt.titleColor,c=d.querySelector(".persona-combo-btn-label")??d;else{if(d=m("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=m("span","persona-text-base persona-font-semibold persona-truncate"),c.style.color=Kt.titleColor,c.textContent=a.title??"Chat Assistant",d.appendChild(c),Xv(d,r?.trailingActions,r?.onAction??s),r?.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let S=r.onTitleClick;d.addEventListener("click",R=>{R.target.closest("button")||S()}),d.addEventListener("keydown",R=>{(R.key==="Enter"||R.key===" ")&&(R.preventDefault(),S())})}let I=r?.titleRowHover;I&&(d.style.borderRadius=I.borderRadius??"10px",d.style.padding=I.padding??"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{d.style.backgroundColor=I.background??"",d.style.borderColor=I.border??""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let u=a.closeButtonSize??"32px",b=m("div",""),g=m("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=u,g.style.width=u,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Kt.actionIconColor;let y=a.closeButtonIconName??"x",C=te(y,"28px","currentColor",1);C?g.appendChild(C):g.textContent="\xD7",o&&g.addEventListener("click",o),b.appendChild(g),i.appendChild(b);let M=m("div");M.style.display="none";let L=m("span");return L.style.display="none",{header:i,iconHolder:M,headerTitle:c,headerSubtitle:L,closeButton:g,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}},zl={default:Fu,minimal:_u},$u=e=>zl[e]??zl.default,ks=(e,t,n)=>{if(t?.render){let a=t.render({config:e,onClose:n?.onClose,onClearChat:n?.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),i=m("div");i.style.display="none";let p=m("span"),d=m("span"),c=m("button");c.style.display="none";let u=m("div");return u.style.display="none",{header:a,iconHolder:i,headerTitle:p,headerSubtitle:d,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}}let o=t?.layout??"default",s=$u(o)({config:e,showClose:t?.showCloseButton??n?.showClose??!0,onClose:n?.onClose,onClearChat:n?.onClearChat,layoutHeaderConfig:t,onHeaderAction:t?.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Qa=e=>{let t=m("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=e?.copy?.inputPlaceholder??"Type your message\u2026",t.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",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,o=20;t.style.maxHeight=`${n*o}px`,t.style.overflowY="auto";let r=()=>{let a=parseFloat(t.style.maxHeight);return Number.isFinite(a)&&a>0?a:n*o},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let a=Math.min(t.scrollHeight,r());t.style.height=`${a}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},Ya=e=>{let t=e?.sendButton??{},n=t.useIcon??!1,o=t.iconText??"\u2191",r=t.iconName,s=t.stopIconName??"square",a=t.tooltipText??"Send message",i=t.stopTooltipText??"Stop generating",p=e?.copy?.sendButtonLabel??"Send",d=e?.copy?.stopButtonLabel??"Stop",c=t.showTooltip??!1,u=t.size??"40px",b=t.backgroundColor,g=t.textColor,y=m("div","persona-send-button-wrapper"),C=Fe("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&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&b||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),M=null,L=null;if(n){let R=parseFloat(u)||24,$=g?.trim()||"currentColor";r?(M=te(r,R,$,2),M?C.appendChild(M):C.textContent=o):C.textContent=o,L=te(s,R,$,2)}else C.textContent=p;C.setAttribute("aria-label",a),y.appendChild(C),Dt({anchor:C,trigger:y,text:()=>C.getAttribute("aria-label")??"",enabled:c});let I="send";return{button:C,wrapper:y,setMode:R=>{if(R===I)return;I=R;let $=R==="stop"?i:a;if(C.setAttribute("aria-label",$),n){if(M&&L){let z=R==="stop"?L:M;C.replaceChildren(z)}}else C.textContent=R==="stop"?d:p}}},Za=e=>{let t=e?.voiceRecognition??{};if(!(t.enabled===!0))return null;let o=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),r=t.provider?.type==="runtype";if(!(o||r))return null;let a=e?.sendButton?.size??"40px",i=t.iconName??"mic",p=t.iconSize??a,d=parseFloat(p)||24,c=t.backgroundColor??e?.sendButton?.backgroundColor,u=t.iconColor??e?.sendButton?.textColor,b=m("div","persona-send-button-wrapper"),g=Fe("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":t.tooltipText??"Start voice recognition"},style:{width:p,height:p,minWidth:p,minHeight:p,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:c||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),C=te(i,d,u||"currentColor",1.5);C?g.appendChild(C):g.textContent="\u{1F3A4}",b.appendChild(g);let M=t.tooltipText??"Start voice recognition",L=t.showTooltip??!1;return Dt({anchor:g,trigger:b,text:()=>g.getAttribute("aria-label")??M,enabled:L}),{button:g,wrapper:b}},ei=e=>{let t=e?.attachments??{};if(t.enabled!==!0)return null;let n=e?.sendButton?.size??"40px",o=m("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=m("input");r.type="file",r.setAttribute("data-persona-composer-attachment-input",""),r.accept=(t.allowedTypes??$n).join(","),r.multiple=(t.maxFiles??4)>1,r.style.display="none",r.setAttribute("aria-label","Attach files");let s=t.buttonIconName??"paperclip",a=n,i=parseFloat(a)||40,p=Math.round(i*.6),d=m("div","persona-send-button-wrapper"),c=Fe("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":t.buttonTooltipText??"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1"}}),u=te(s,p,"currentColor",1.5);u?c.appendChild(u):c.textContent="\u{1F4CE}",c.addEventListener("click",g=>{g.preventDefault(),r.click()}),d.appendChild(c);let b=t.buttonTooltipText??"Attach file";return Dt({anchor:c,trigger:d,text:()=>c.getAttribute("aria-label")??b}),{button:c,wrapper:d,input:r,previewsContainer:o}},ti=e=>{let t=e?.statusIndicator??{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=m("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let r=t.visible??!0;o.style.display=r?"":"none";let s=t.idleText??"Online";if(t.idleLink){let a=m("a");a.href=t.idleLink,a.target="_blank",a.rel="noopener noreferrer",a.textContent=s,a.style.color="inherit",a.style.textDecoration="none",o.appendChild(a)}else o.textContent=s;return o},ni=()=>Fe("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ls=e=>{let{config:t}=e,n=Fe("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=ni(),r=Fe("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=Qa(t);a();let i=Ya(t),p=Za(t),d=ei(t),c=ti(t);d&&(d.previewsContainer.style.gap="8px",r.append(d.previewsContainer,d.input)),r.append(s);let u=Fe("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),b=m("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=m("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&b.append(d.wrapper),p&&g.append(p.wrapper),g.append(i.wrapper),u.append(b,g),r.append(u),r.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==p?.button&&y.target!==p?.wrapper&&y.target!==d?.button&&y.target!==d?.wrapper&&s.focus()}),n.append(o,r,c),{footer:n,suggestions:o,composerForm:r,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:c,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:u,leftActions:b,rightActions:g,setSendButtonMode:i.setMode}};var ju=()=>{let e=Fe("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=m("span","persona-pill-peek__icon"),n=te("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let o=m("span","persona-pill-peek__text"),r=m("span","persona-pill-peek__caret"),s=te("chevron-up",16,"currentColor",1.5);return s&&r.appendChild(s),e.append(t,o,r),{root:e,textNode:o}},Uu=e=>{let{config:t}=e,n=Fe("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=ni(),r=ti(t);r.style.display="none";let{textarea:s,attachAutoResize:a}=Qa(t);s.style.maxHeight="100px",a();let i=Ya(t),p=Za(t),d=ei(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let c=Fe("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=m("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let b=m("div","persona-widget-composer__right-actions persona-pill-composer__right");p&&b.append(p.wrapper),b.append(i.wrapper),c.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==p?.button&&y.target!==p?.wrapper&&y.target!==d?.button&&y.target!==d?.wrapper&&s.focus()}),d&&c.append(d.input),c.append(u,s,b),d&&n.append(d.previewsContainer),n.append(o,c,r);let g=c;return{footer:n,suggestions:o,composerForm:c,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:p?.button??null,micButtonWrapper:p?.wrapper??null,statusText:r,attachmentButton:d?.button??null,attachmentButtonWrapper:d?.wrapper??null,attachmentInput:d?.input??null,attachmentPreviewsContainer:d?.previewsContainer??null,actionsRow:g,leftActions:u,rightActions:b,setSendButtonMode:i.setMode}};var zu=e=>{let t=e?.launcher?.enabled??!0,n=Wt(e);if(ho(e)){let c=e?.launcher?.composerBar??{},u=m("div","persona-widget-wrapper persona-fixed persona-transition");u.setAttribute("data-persona-composer-bar",""),u.dataset.state="collapsed",u.dataset.expandedSize=c.expandedSize??"anchored",u.style.zIndex=String(e?.launcher?.zIndex??Ut);let b=m("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 g=m("div","persona-widget-pill-root");return g.setAttribute("data-persona-composer-bar",""),g.dataset.state="collapsed",g.dataset.expandedSize=c.expandedSize??"anchored",g.style.zIndex=String(e?.launcher?.zIndex??Ut),{wrapper:u,panel:b,pillRoot:g}}if(n){let c=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),u=m("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return c.appendChild(u),{wrapper:c,panel:u}}if(!t){let c=m("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),u=m("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),b=e?.launcher?.width??"100%";return c.style.width=b,u.style.width="100%",c.appendChild(u),{wrapper:c,panel:u}}let r=e?.launcher??{},s=r.position&&Cn[r.position]?Cn[r.position]:Cn["bottom-right"],a=m("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String(e?.launcher?.zIndex??Ut);let i=m("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=e?.launcher?.width??e?.launcherWidth??un;return i.style.width=d,i.style.maxWidth=d,a.appendChild(i),{wrapper:a,panel:i}},Qv=(e,t)=>{let n=m("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}=Ja(e,{showClose:t,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=e?.launcher?.clearChat?.enabled??!0,a=null,i=null;if(s){let R=Xa(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=R.button,i=R.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let p=Fe("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Fe("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"}});d.style.setProperty("scrollbar-gutter","stable");let c=Fe("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),u=Fe("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),b=Fe("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)"}},c,u),g=m("div","persona-flex persona-flex-col persona-gap-3"),y=e?.layout?.contentMaxWidth;y&&(g.style.maxWidth=y,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(b.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(b,g);let M=Fe("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),L=Uu({config:e}),{root:I,textNode:S}=ju();return n.append(p,r,d,M),i&&n.appendChild(i),{container:n,body:d,messagesWrapper:g,composerOverlay:M,suggestions:L.suggestions,textarea:L.textarea,sendButton:L.sendButton,sendButtonWrapper:L.sendButtonWrapper,micButton:L.micButton,micButtonWrapper:L.micButtonWrapper,composerForm:L.composerForm,statusText:L.statusText,introTitle:c,introSubtitle:u,closeButton:o,closeButtonWrapper:r,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:m("span"),headerTitle:m("span"),headerSubtitle:m("span"),header:p,footer:L.footer,attachmentButton:L.attachmentButton,attachmentButtonWrapper:L.attachmentButtonWrapper,attachmentInput:L.attachmentInput,attachmentPreviewsContainer:L.attachmentPreviewsContainer,actionsRow:L.actionsRow,leftActions:L.leftActions,rightActions:L.rightActions,setSendButtonMode:L.setSendButtonMode,peekBanner:I,peekTextNode:S}},qu=(e,t=!0)=>{if(ho(e))return Qv(e,t);let n=Fe("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=e?.layout?.header,r=e?.layout?.showHeader!==!1,s=o?ks(e,o,{showClose:t}):yo({config:e,showClose:t}),a=Fe("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=Fe("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:e?.copy?.welcomeTitle??"Hello \u{1F44B}"}),p=Fe("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:e?.copy?.welcomeSubtitle??"Ask anything about your account or products."}),d=Fe("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, transparent)",boxShadow:Wt(e)?"none":"var(--persona-intro-card-shadow, none)"}},i,p),c=m("div","persona-flex persona-flex-col persona-gap-3"),u=e?.layout?.contentMaxWidth;u&&(c.style.maxWidth=u,c.style.marginLeft="auto",c.style.marginRight="auto",c.style.width="100%"),e?.copy?.showWelcomeCard!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,c);let g=Ls({config:e}),y=e?.layout?.showFooter!==!1;r?Cr(n,s,e):(s.header.style.display="none",Cr(n,s,e)),n.append(a);let C=Fe("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 y||(g.footer.style.display="none"),n.append(g.footer),n.append(C),{container:n,body:a,messagesWrapper:c,composerOverlay:C,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:i,introSubtitle:p,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var ql=(e,t)=>{let n=m("button");n.type="button",n.innerHTML=`
34
34
  <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>
35
35
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
36
36
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -38,14 +38,14 @@ _Details: ${n.message}_`:o}var us=e=>({isError:!0,content:[{type:"text",text:e}]
38
38
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
39
39
  </span>
40
40
  <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>
41
- `,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},i=Wt(s),p=n.querySelector("[data-role='launcher-title']");if(p){let S=a.title??"Chat Assistant";p.textContent=S,p.setAttribute("title",S)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let S=a.subtitle??"Here to help you get answers fast";d.textContent=S,d.setAttribute("title",S)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||i?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let S=a.agentIconSize??"40px";if(u.style.height=S,u.style.width=S,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let R=parseFloat(S)||24,$=te(a.agentIconName,R*.6,"var(--persona-text-inverse, #ffffff)",2);$?(u.appendChild($),u.style.display=""):(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}let b=n.querySelector("[data-role='launcher-image']");if(b){let S=a.agentIconSize??"40px";b.style.height=S,b.style.width=S,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(b.src=a.iconUrl,b.style.display="block"):b.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let S=a.callToActionIconSize??"32px";g.style.height=S,g.style.width=S,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let R=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,R=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let $=parseFloat(S)||24,z=Math.max($-R,8),w=te(a.callToActionIconName,z,"currentColor",2);w?g.appendChild(w):g.textContent=a.callToActionIconText??"\u2197"}else g.textContent=a.callToActionIconText??"\u2197"}let y=a.position&&wn[a.position]?wn[a.position]:wn["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",M="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?M:`${C} ${y}`,i||(n.style.zIndex=String(a.zIndex??Ut));let L="1px solid var(--persona-border, #e5e7eb)",I="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??L,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:I,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var qu=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=Uu(e),s=zu(e,t),a={wrapper:n,panel:o,pillRoot:r},i={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},d={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:p,composer:d,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=>{d.footer.replaceWith(b),d.footer=b}}},Vl=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>ql(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=ql(e,n);return{instance:r,element:r.element}};var Qv=e=>{switch(e){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}},Yv=(e,t)=>{if(!e)return null;let n=Qv(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},Zv=(e,t)=>{let n=m("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},ex=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Kl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Gl=320,Ju=320,tx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),nx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),ox=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),rx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),sx=e=>{if(!e||e.length===0)return null;let t=Fe("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Fe("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=m("span","persona-mention-chip-icon"),s=te(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Fe("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},ax=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(fs(o.ref,{readonly:!0,render:t}))}return n},Vu="\uE000",Ku="\uE001",ix=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=b=>`${Vu}${r}:${b}${Ku}`,a=t.map((b,g)=>b.kind==="text"?b.text:s(g)).join(""),i=n(a);if(!t.every((b,g)=>b.kind==="text"||i.includes(s(g)))){e.replaceChildren(ax(t,o));return}e.innerHTML=i;let d=new RegExp(`${Vu}${r}:(\\d+)${Ku}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let b=c.nextNode();b;b=c.nextNode())u.push(b);for(let b of u){let g=b;for(let y=d.exec(g.data);y;y=d.exec(g.data)){let C=t[Number(y[1])],M=g.splitText(y.index);M.data=M.data.slice(y[0].length),C?.kind==="mention"&&M.parentNode?.insertBefore(fs(C.ref,{readonly:!0,render:o}),M),g=M}}},lx=(e,t,n)=>{if(e.length===0)return null;try{let o=m("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((i,p)=>{let d=m("img");d.alt=i.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Gl}px`,d.style.maxHeight=`${Ju}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,d.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),d.remove(),r===0&&a())}),d.addEventListener("load",()=>{c=!0}),ex(i.image)?(d.src=i.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},cx=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Kl(o.audio))return;let r=m("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Gl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},dx=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Kl(o.video))return;let r=m("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Gl}px`,r.style.maxHeight=`${Ju}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},px=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Kl(o.data))return;let r=m("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",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},wr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="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",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Xu=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:wr};if(t){let r=t(o);if(r!==null)return r}return wr()},ux=(e,t)=>{let n=m("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=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=m("img");r.src=o,r.alt=t==="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(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Gu=(e,t,n="div")=>{let o=m(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},gx=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="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"),e==="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"),e==="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},Qu=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!r&&!s&&!a){let y=m("div");return y.style.display="none",y.id=`actions-${e.id}`,y.setAttribute("data-actions-for",e.id),y}let i=t.visibility??"hover",p=t.align??"right",d=t.layout??"pill-inside",c={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"}[d],b=m("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);b.id=`actions-${e.id}`,b.setAttribute("data-actions-for",e.id);let g=(y,C,M)=>{let L=dt({icon:y,label:C,size:14,className:"persona-message-action-btn"});return L.setAttribute("data-action",M),L};return o&&b.appendChild(g("copy","Copy message","copy")),a&&b.appendChild(g("volume-2","Read aloud","read-aloud")),r&&b.appendChild(g("thumbs-up","Upvote","upvote")),s&&b.appendChild(g("thumbs-down","Downvote","downvote")),b},Ps=(e,t,n,o,r,s)=>{let a=n??{},i=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,u=d?.show??!1,b=p?.position??"left",g=d?.position??"below",y=gx(e.role,i),C=m("div",y.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),i==="flat"?(C.style.backgroundColor="transparent",C.style.color="var(--persona-primary, var(--persona-text))"):e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.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 M=tx(e),L=e.content?.trim()??"",S=M.length>0&&L===Sa,R=qa(s?.widgetConfig?.features?.streamAnimation),$=s?.widgetConfig?.features?.streamAnimation?.plugins,z=e.role==="assistant"&&R.type!=="none"?xr(R.type,$):null,w=e.role==="assistant"&&z?.isAnimating?.(e)===!0,U=e.role==="assistant"&&z!==null&&(!!e.streaming||w);U&&z?.bubbleClass&&C.classList.add(z.bubbleClass);let q=document.createElement("div");q.classList.add("persona-message-content"),e.streaming&&q.classList.add("persona-content-streaming"),U&&z&&(z.containerClass&&q.classList.add(z.containerClass),q.style.setProperty("--persona-stream-step",`${R.speed}ms`),q.style.setProperty("--persona-stream-duration",`${R.duration}ms`));let Q=U?Va(e.content??"",R.buffer,z,e,!!e.streaming):e.content??"",O=()=>{let Z=t({text:Q,message:e,streaming:!!e.streaming,raw:e.rawContent});return U&&z?.wrap==="char"?Ss(Z,"char",e.id,{skipTags:z.skipTags}):U&&z?.wrap==="word"?Ss(Z,"word",e.id,{skipTags:z.skipTags}):Z},D=null;if(S?(D=document.createElement("div"),D.innerHTML=O(),D.style.display="none",q.appendChild(D)):e.contentSegments?.length?ix(q,e.contentSegments,Z=>t({text:Z,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):q.innerHTML=O(),U&&z?.useCaret&&!S&&L){let Z=Ka(),be=q.querySelectorAll(".persona-stream-char, .persona-stream-word"),he=be[be.length-1];if(he?.parentNode)he.parentNode.insertBefore(Z,he.nextSibling);else{let de=q.lastElementChild;de?de.appendChild(Z):q.appendChild(Z)}}if(u&&g==="inline"&&e.createdAt){let Z=Gu(e,d,"span");Z.classList.add("persona-timestamp-inline");let be=q.lastElementChild;be?be.appendChild(Z):q.appendChild(Z)}if(M.length>0){let Z=lx(M,!S&&!!L,()=>{S&&D&&(D.style.display="")});Z?C.appendChild(Z):S&&D&&(D.style.display="")}let ie=nx(e);if(ie.length>0){let Z=cx(ie);Z&&C.appendChild(Z)}let me=ox(e);if(me.length>0){let Z=dx(me);Z&&C.appendChild(Z)}let we=rx(e);if(we.length>0){let Z=px(we);Z&&C.appendChild(Z)}let Ee=e.contentSegments?.length?null:sx(e.contextMentions);if(Ee&&C.appendChild(Ee),C.appendChild(q),u&&g==="below"&&e.createdAt){let Z=Gu(e,d);Z.classList.add("persona-mt-1"),C.appendChild(Z)}let se=e.role==="assistant"?Yv(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Z=!!(Q&&Q.trim()),be=R.placeholder==="skeleton",he=be&&R.buffer==="line"&&Z;if(Z)he&&C.appendChild(Ts());else if(be)C.appendChild(Ts());else{let de=Xu("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);de&&C.appendChild(de)}}if(se&&e.stopReason&&!e.streaming&&(L||(q.style.display="none"),C.appendChild(Zv(e.stopReason,se))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Z=Qu(e,o,r);C.appendChild(Z)}if(!c||e.role==="system")return C;let Y=m("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ce=ux(p,e.role);return b==="right"||b==="left"&&e.role==="user"?Y.append(C,ce):Y.append(ce,C),Y},fx=(e,t,n,o,r,s)=>{let a=n??{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ps(e,t,n,o,r,s)};var Ar=new Set,mx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),hx=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
42
- `):""},Yu=(e,t)=>{let n=Ar.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let d=te(n?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Jl=(e,t)=>{let n=e.reasoning,o=m("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=t?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&Ar.has(e.id),i=n.status!=="complete",p=hx(e,r.previewMaxLines??3),d=m("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");d.type="button",s&&(d.setAttribute("aria-expanded",a?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=m("div","persona-flex persona-flex-col persona-text-left"),u=m("span","persona-text-xs persona-text-persona-primary"),b="Thinking...",g=t?.reasoning??{},y=String(n.startedAt??Date.now()),C=()=>{let me=m("span","");return me.setAttribute("data-tool-elapsed",y),me.textContent=Ca(n),me},M=g.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:b,previewText:p,isActive:i,config:t??{},elapsed:Ca(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(u.textContent=M,c.appendChild(u)):M instanceof HTMLElement?c.appendChild(M):(u.textContent=b,c.appendChild(u));let L=m("span","persona-text-xs persona-text-persona-primary");L.textContent=Ep(n),c.appendChild(L);let I=r.loadingAnimation??"none",S=g.activeTextTemplate,R=g.completeTextTemplate,$=i?S:R,z=M instanceof HTMLElement,w=(me,we)=>{u.textContent="";let Ee=wa(me,""),se=0;for(let fe of Ee){let Y=fe.styles.length>0?(()=>{let ce=m("span",fe.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return u.appendChild(ce),ce})():u;if(fe.isDuration&&i)Y.appendChild(C());else{let ce=fe.isDuration?Ca(n):fe.text;we?se=co(Y,ce,se):Y.appendChild(document.createTextNode(ce))}}};if(!z&&$)if(L.style.display="none",u.style.display="",i&&I!=="none"){let me=g.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),I==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${me}ms`),w($,!1)):(u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${me}ms`),I==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),w($,!0))}else w($,!1);else if(!z&&i&&I!=="none"){u.style.display="";let me=g.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),I==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${me}ms`);else{u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${me}ms`),I==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let we=u.textContent||b;u.textContent="",co(u,we,0)}n.status==="complete"&&(u.style.display="none")}else z||(n.status==="complete"?u.style.display="none":u.style.display="");let U=null;if(s){U=m("div","persona-flex persona-items-center");let we=te(a?"chevron-up":"chevron-down",16,"currentColor",2);we?U.appendChild(we):U.textContent=a?"Hide":"Show";let Ee=m("div","persona-flex persona-items-center persona-ml-auto");Ee.append(U),d.append(c,Ee)}else d.append(c);let q=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(q.setAttribute("data-persona-collapsed-preview","reasoning"),q.style.display="none",q.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&p){let me=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:i,config:t??{}});mx(q,me)||(q.textContent=p),q.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(d,q),o;let Q=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");Q.style.display=a?"":"none";let O=n.chunks.join(""),D=m("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return D.textContent=O||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),Q.appendChild(D),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),U){U.innerHTML="";let we=te(a?"chevron-up":"chevron-down",16,"currentColor",2);we?U.appendChild(we):U.textContent=a?"Hide":"Show"}Q.style.display=a?"":"none",q.style.display=a?"none":q.textContent||q.childNodes.length?"":"none"})(),o.append(d,q,Q),o};var Sr=new Set,yx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),bx=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-t).join(`
43
- `);let r=io(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
44
- `):""},Xl=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},vx=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=bx(e,o?.previewMaxLines??3),a=n?Mp(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",p=t?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),i&&p.activeTextTemplate?d=ul(n,p.activeTextTemplate,d):!i&&p.completeTextTemplate&&(d=ul(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:i}},Zu=(e,t,n)=>{let o=Sr.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=te(o?"chevron-up":"chevron-down",16,c,2);u?d.appendChild(u):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},Ql=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=m("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.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=t?.features?.toolCallDisplay??{},a=s.expandable!==!1,i=a&&Sr.has(e.id),{summary:p,previewText:d,isActive:c}=vx(e,t),u=m("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"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=m("div","persona-flex persona-flex-col persona-text-left"),g=m("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let y=String(n.startedAt??Date.now()),C=()=>{let O=m("span","");return O.setAttribute("data-tool-elapsed",y),O.textContent=is(n),O},M=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:is(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(g.textContent=M,b.appendChild(g)):M instanceof HTMLElement?b.appendChild(M):(g.textContent=p,b.appendChild(g));let L=s.loadingAnimation??"none",I=o.activeTextTemplate,S=o.completeTextTemplate,R=c?I:S,$=M instanceof HTMLElement,z=(O,D)=>{g.textContent="";let ie=n.name?.trim()||"tool",me=wa(O,ie),we=0;for(let Ee of me){let se=Ee.styles.length>0?(()=>{let fe=m("span",Ee.styles.map(Y=>`persona-tool-text-${Y}`).join(" "));return g.appendChild(fe),fe})():g;if(Ee.isDuration&&c)se.appendChild(C());else{let fe=Ee.isDuration?is(n):Ee.text;D?we=co(se,fe,we):se.appendChild(document.createTextNode(fe))}}};if(!$)if(c&&L!=="none"){let O=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),L==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${O}ms`),R&&z(R,!1);else if(g.classList.add(`persona-tool-loading-${L}`),g.style.setProperty("--persona-tool-anim-duration",`${O}ms`),L==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),R)z(R,!0);else{let D=g.textContent||p;g.textContent="",co(g,D,0)}}else R&&z(R,!1);let w=null;if(a){w=m("div","persona-flex persona-items-center");let O=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",D=te(i?"chevron-up":"chevron-down",16,O,2);D?w.appendChild(D):w.textContent=i?"Hide":"Show";let ie=m("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ie.append(w),u.append(b,ie)}else u.append(b);let U=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(U.setAttribute("data-persona-collapsed-preview","tool"),U.style.display="none",U.style.whiteSpace="pre-wrap",!i&&c&&s.activePreview&&d){let O=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});yx(U,O)||(U.textContent=d),U.style.display=""}if(!i&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,U),r;let q=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(q.style.display=i?"":"none",o.contentBackgroundColor&&(q.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(q.style.color=o.contentTextColor),o.contentPaddingX&&(q.style.paddingLeft=o.contentPaddingX,q.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(q.style.paddingTop=o.contentPaddingY,q.style.paddingBottom=o.contentPaddingY),n.name){let O=m("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?O.style.color=o.contentTextColor:o.headerTextColor&&(O.style.color=o.headerTextColor),O.textContent=n.name,q.appendChild(O)}if(n.args!==void 0){let O=m("div","persona-space-y-1"),D=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(D.style.color=o.labelTextColor),D.textContent="Arguments";let ie=m("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Xl(ie,o),ie.textContent=io(n.args),O.append(D,ie),q.appendChild(O)}if(n.chunks&&n.chunks.length){let O=m("div","persona-space-y-1"),D=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(D.style.color=o.labelTextColor),D.textContent="Activity";let ie=m("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Xl(ie,o),ie.textContent=n.chunks.join(""),O.append(D,ie),q.appendChild(O)}if(n.status==="complete"&&n.result!==void 0){let O=m("div","persona-space-y-1"),D=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(D.style.color=o.labelTextColor),D.textContent="Result";let ie=m("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Xl(ie,o),ie.textContent=io(n.result),O.append(D,ie),q.appendChild(O)}if(n.status==="complete"&&typeof n.duration=="number"){let O=m("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(O.style.color=o.contentTextColor),O.textContent=`Duration: ${n.duration}ms`,q.appendChild(O)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),w){w.innerHTML="";let O=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",D=te(i?"chevron-up":"chevron-down",16,O,2);D?w.appendChild(D):w.textContent=i?"Hide":"Show"}q.style.display=i?"":"none",U.style.display=i?"none":U.textContent||U.childNodes.length?"":"none"})(),r.append(u,U,q),r};var Vo=new Map,oi=e=>{let n=(e.startsWith(En)?e.slice(En.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},eg=e=>e?.approval!==!1?e?.approval:void 0,tg=(e,t)=>{let n=eg(t)?.detailsDisplay??"collapsed";return Vo.get(e)??n==="expanded"},ng=(e,t,n)=>{let o=eg(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=te(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},og=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=tg(e,n);ng(o,s,n),r.style.display=s?"":"none"};var ri=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",s=m("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=m("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=m("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=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",c=te(p,20,d,2);c&&i.appendChild(c);let u=m("div","persona-flex-1 persona-min-w-0"),b=m("div","persona-flex persona-items-center persona-gap-2"),g=m("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(g.style.color=o.titleColor),g.textContent=o?.title??"Approval Required",b.appendChild(g),!r){let w=m("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(En)?ts(n.toolName):void 0,M=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),L=!n.toolName,I=M||(L?n.description:`The assistant wants to use \u201C${C??oi(n.toolName)}\u201D.`),S=m("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(S.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(S.style.color=o.descriptionColor),S.textContent=I,u.appendChild(S),n.reason){let w=m("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 U=m("span","persona-font-medium");U.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,w.appendChild(U),w.appendChild(document.createTextNode(n.reason)),u.appendChild(w)}let R=o?.detailsDisplay??"collapsed",$=!!n.description&&!L,z=$||!!n.parameters;if(R!=="hidden"&&z){let w=tg(e.id,t),U=m("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");U.type="button",U.setAttribute("data-expand-header","true"),U.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(U.style.color=o.descriptionColor);let q=m("span");q.setAttribute("data-approval-details-label","true");let Q=m("span","persona-inline-flex persona-items-center");Q.setAttribute("data-approval-details-chevron","true"),U.append(q,Q),ng(U,w,t),u.appendChild(U);let O=m("div");if(O.setAttribute("data-approval-details","true"),O.style.display=w?"":"none",$){let D=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(D.style.color=o.descriptionColor),D.textContent=n.description,O.appendChild(D)}if(n.parameters){let D=m("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&&(D.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(D.style.color=o.parameterTextColor),D.style.fontSize="0.75rem",D.style.lineHeight="1rem",D.textContent=io(n.parameters),O.appendChild(D)}u.appendChild(O)}if(r){let w=m("div","persona-flex persona-gap-2 persona-mt-2");w.setAttribute("data-approval-buttons","true");let U=m("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");U.type="button",U.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",U.style.color=o?.approveButtonTextColor??"#ffffff",U.setAttribute("data-approval-action","approve");let q=te("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);q&&(q.style.marginRight="4px",U.appendChild(q));let Q=document.createTextNode(o?.approveLabel??"Approve");U.appendChild(Q);let O=m("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");O.type="button",O.style.backgroundColor=o?.denyButtonColor??"transparent",O.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",O.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,O.setAttribute("data-approval-action","deny");let D=te("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);D&&(D.style.marginRight="4px",O.appendChild(D));let ie=document.createTextNode(o?.denyLabel??"Deny");O.appendChild(ie),w.append(U,O),u.appendChild(w)}return a.append(i,u),s.appendChild(a),s};function xx(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function rg(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:i,zIndex:p=2147483e3,onOpen:d,onDismiss:c}=e,u=e.container??xx(t),b=!1,g=null,y=()=>{if(!b)return;let L=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${L.width}px`),a&&(n.style.maxWidth=`${L.width}px`);let I=n.getBoundingClientRect(),S=i?.()??null,R=S!=null?L.top+S:L.top,$=o==="top-start"||o==="top-end"?R-r-I.height:L.bottom+r,w=o==="bottom-end"||o==="top-end"?L.right-I.width:L.left,U=a?.()??null;if(U!=null){let q=Math.max(L.left,L.right-I.width);w=Math.min(Math.max(L.left+U,L.left),q)}n.style.top=`${$}px`,n.style.left=`${w}px`},C=()=>{b&&(b=!1,g&&(g(),g=null),n.remove())},M=()=>{if(b)return;b=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),y();let L=(t.ownerDocument??document).defaultView??window,I=t.ownerDocument??document,S=()=>{if(!t.isConnected){C(),c?.("anchor-removed");return}y()},R=z=>{let w=typeof z.composedPath=="function"?z.composedPath():[];w.includes(n)||w.includes(t)||(C(),c?.("outside"))},$=L.setTimeout(()=>{I.addEventListener("pointerdown",R,!0)},0);L.addEventListener("scroll",S,!0),L.addEventListener("resize",S),g=()=>{L.clearTimeout($),I.removeEventListener("pointerdown",R,!0),L.removeEventListener("scroll",S,!0),L.removeEventListener("resize",S)},d?.()};return{get isOpen(){return b},open:M,close:C,toggle:()=>b?C():M(),reposition:y,destroy:C}}function sg(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Cx=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),ag=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},Ko=(e,t)=>{ag(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},wx=e=>e?.approval!==!1?e?.approval:void 0,Ax=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return Vo.get(e)??n==="expanded"},Yl=e=>{let t=m("span","persona-approval-kbd");return t.textContent=e,t},Sx=(e,t)=>{let n=m("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(En)?ts(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=r??oi(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=a,n.appendChild(p),i){n.append(" from ");let d=document.createElement("strong");d.textContent=i,n.appendChild(d)}return n},Tx=e=>{let t=m("div","persona-approval-resolved"),n=te("ban",15,"currentColor",2);n&&t.appendChild(n);let o=m("span","persona-approval-resolved-name");return o.textContent=e.toolName?oi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Ex=(e,t,n,o,r,s,a)=>{let i=m("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(i.style.background=o.backgroundColor),o?.borderColor&&(i.style.borderColor=o.borderColor),o?.shadow!==void 0&&(i.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",u=d||c,b=u&&Ax(t.id,o),g=o?.showDetailsLabel??"Show details",y=o?.hideDetailsLabel??"Hide details",C=m("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?y:g)):C.setAttribute("data-static","true");let M=m("span","persona-approval-logo"),L=te("shield-check",16,"currentColor",2);L&&M.appendChild(L),C.appendChild(M);let I=Sx(n,o);if(u){let U=m("span","persona-approval-toggle");U.setAttribute("aria-hidden","true");let q=te("chevron-down",14,"currentColor",2);q&&U.appendChild(q),I.append(" "),I.appendChild(U)}C.appendChild(I),i.appendChild(C);let S=m("div","persona-approval-body");if(u){let U=m("div","persona-approval-details");if(U.setAttribute("data-role","params"),U.hidden=!b,d){let q=m("p","persona-approval-desc");o?.descriptionColor&&(q.style.color=o.descriptionColor),q.textContent=n.description,U.appendChild(q)}if(c){let q=m("pre","persona-approval-params");o?.parameterBackgroundColor&&(q.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(q.style.color=o.parameterTextColor),q.textContent=io(n.parameters),U.appendChild(q)}S.appendChild(U)}if(n.reason){let U=m("p","persona-approval-reason");o?.reasonColor?U.style.color=o.reasonColor:o?.descriptionColor&&(U.style.color=o.descriptionColor);let q=m("span","persona-approval-reason-label");q.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,U.append(q,document.createTextNode(n.reason)),S.appendChild(U)}let R=m("div","persona-approval-actions"),$=null,z=U=>{o?.approveButtonColor&&(U.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(U.style.color=o.approveButtonTextColor)},w=m("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"),a){let U=m("div","persona-approval-split"),q=m("button","persona-approval-primary");q.type="button",q.setAttribute("data-action","always"),z(q),q.append(o?.approveLabel??"Always allow",Yl("\u23CE"));let Q=m("button","persona-approval-caret");Q.type="button",Q.setAttribute("data-action","toggle-menu"),Q.setAttribute("aria-label","More options"),z(Q);let O=te("chevron-down",15,"currentColor",2);O&&Q.appendChild(O),U.append(q,Q),R.append(U,w),w.append(Yl("Esc"));let D=m("div","persona-approval-menu"),ie=m("button","persona-approval-menu-item");ie.type="button",ie.append("Allow once",Yl("\u2318\u23CE")),D.appendChild(ie),$=rg({anchor:U,content:D,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,$),ie.addEventListener("click",()=>{Ko(e,t.id),r()})}else{let U=m("button","persona-approval-primary persona-approval-primary--solo");U.type="button",U.setAttribute("data-action","allow"),z(U),U.append(o?.approveLabel??"Allow"),R.append(U,w)}return S.appendChild(R),i.appendChild(S),i.addEventListener("click",U=>{let q=U.target instanceof Element?U.target.closest("[data-action]"):null;if(!q)return;let Q=q.getAttribute("data-action");if(Q==="toggle-params"){let O=i.querySelector('[data-role="params"]');if(O){let D=O.hidden;O.hidden=!D,C.setAttribute("aria-expanded",D?"true":"false"),C.setAttribute("aria-label",D?y:g),Vo.set(t.id,D)}return}if(Q==="toggle-menu"){$?.toggle();return}if(Q==="always"){Ko(e,t.id),r({remember:!0});return}if(Q==="allow"){Ko(e,t.id),r();return}if(Q==="deny"){Ko(e,t.id),s();return}}),i},ig=()=>{let e=Cx();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let i=o?.approval;if(!i)return null;let p=wx(a);if(i.status!=="pending"){if(Ko(e,o.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Tx(i)}ag(e,o.id);let d=p?.enableAlwaysAllow===!0,c=Ex(e,o,i,p,r,s,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=b=>{sg(b)||o.id===e.latestPendingApprovalId&&(b.key!=="Escape"&&b.key!=="Enter"||(b.preventDefault(),b.stopImmediatePropagation(),Ko(e,o.id),b.key==="Escape"?s():b.metaKey||b.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])Ko(e,o);e.latestPendingApprovalId=null}}};var lg=e=>{let t=[],n=null;return{buttons:t,render:(r,s,a,i,p,d)=>{e.innerHTML="",t.length=0;let c=d?.agentPushed===!0;if(c||(n=null),!r||!r.length||!c&&(i??(s?s.getMessages():[])).some(M=>M.role==="user"))return;let u=document.createDocumentFragment(),b=s?s.isStreaming():!1,g=y=>{switch(y){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(y=>{let C=m("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=y,C.disabled=b,p?.fontFamily&&(C.style.fontFamily=g(p.fontFamily)),p?.fontWeight&&(C.style.fontWeight=p.fontWeight),p?.paddingX&&(C.style.paddingLeft=p.paddingX,C.style.paddingRight=p.paddingX),p?.paddingY&&(C.style.paddingTop=p.paddingY,C.style.paddingBottom=p.paddingY),C.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",c&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:y},bubbles:!0,composed:!0})),s.sendMessage(y))}),u.appendChild(C),t.push(C)}),e.appendChild(u),c){let y=JSON.stringify(r);y!==n&&(n=y,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var Rs=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),this.store?.put(t)}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 t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;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=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}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(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,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,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},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((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var Mx=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),kx=new Set(["step_start","execution_start"]),Lx=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Px=new Set(["step_complete","agent_turn_complete"]),Rx=new Set(["flow_complete","agent_complete"]),cg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),pg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Go=(e,t)=>{let n=e[t];return pg(n)?n:void 0};function Zl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function si(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Ix(e,t){return typeof t.type=="string"?t.type:e}function Wx(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Hx(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function dg(e){let t=Go(e,"result"),n=[Go(e,"tokens"),Go(e,"totalTokens"),t?Go(t,"tokens"):void 0,Go(e,"usage"),t?Go(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=rn(o.output)??rn(o.outputTokens)??rn(o.completionTokens);if(r!==void 0)return r}return rn(e.outputTokens)??rn(e.completionTokens)??(t?rn(t.outputTokens)??rn(t.completionTokens):void 0)}function Bx(e){let t=Go(e,"result");return rn(e.executionTime)??rn(e.executionTimeMs)??rn(e.execution_time)??rn(e.duration)??(t?rn(t.executionTime)??rn(t.executionTimeMs):void 0)}function Ox(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Ws=class{constructor(t=Ox){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:si(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){if(!pg(n)){cg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Ix(t,n),r=this.now();if(Mx.has(o)){this.startRun(r);return}if(kx.has(o)){this.run||this.startRun(r);return}if(Lx.has(o)){if(!Hx(o,n))return;let s=Wx(n);if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let i=a.exactOutputTokens+Zl(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:si(i,p),outputTokens:i,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(Px.has(o)){if(!this.run)return;let s=this.run,a=dg(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let i=s.exactOutputTokens>0,p=s.exactOutputTokens+Zl(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:si(p,d),outputTokens:p,durationMs:d,source:i?"usage":"estimate"};return}if(Rx.has(o)){if(!this.run)return;let s=this.run,a=dg(n),i=a??s.exactOutputTokens+Zl(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:si(i,d),outputTokens:i,durationMs:d,source:p},this.run=null;return}if(cg.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:Bx(n)??o-t.startedAt}};function Tr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Dx={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)"}},Nx={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Fx=["flowName","stepName","reasoningText","text","name","tool","toolName"],_x=100;function $x(e,t){let n={...Dx,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Nx}function jx(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Ux(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function zx(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function qx(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function Vx(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Kx(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Gx(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Jx(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(i)return i}return a();function a(){let i=m("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=m("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,i.appendChild(p),i}}function ec(e,t,n,o,r,s,a,i){let p=r.has(e.id),d=m("div","persona-border-b persona-border-persona-divider persona-text-xs");Tr(d,o.classNames?.eventRow);let c=a.find(b=>b.renderEventStreamRow);if(c?.renderEventStreamRow&&i){let b=c.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(e.id)});if(b)return d.appendChild(b),d}return d.appendChild(u()),d;function u(){let b=m("div",""),g=m("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");g.setAttribute("data-event-id",e.id);let y=m("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=te(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&y.appendChild(C);let M=m("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=o.timestampFormat??"relative";M.textContent=L==="relative"?jx(e.timestamp,n):Ux(e.timestamp);let I=null;o.showSequenceNumbers!==!1&&(I=m("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),I.textContent=String(t+1));let S=$x(e.type,o.badgeColors),R=m("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");R.style.backgroundColor=S.bg,R.style.color=S.text,R.style.borderColor=S.text+"50",R.textContent=e.type;let $=o.descriptionFields??Fx,z=zx(e.payload,$),w=null;z&&(w=m("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=z);let U=m("div","persona-flex-1 persona-min-w-0"),q=m("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"),Q=te("clipboard","12px","currentColor",1.5);return Q&&q.appendChild(Q),q.addEventListener("click",async O=>{O.stopPropagation(),await qx(Vx(e)),q.innerHTML="";let D=te("check","12px","currentColor",1.5);D&&q.appendChild(D),setTimeout(()=>{q.innerHTML="";let ie=te("clipboard","12px","currentColor",1.5);ie&&q.appendChild(ie)},1500)}),g.appendChild(y),g.appendChild(M),I&&g.appendChild(I),g.appendChild(R),w&&g.appendChild(w),g.appendChild(U),g.appendChild(q),b.appendChild(g),p&&b.appendChild(Jx(e,a,i)),b}}function ug(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=r?.features?.scrollToBottom,p=i?.enabled!==!1,d=i?.iconName??"arrow-down",c=i?.label??"",u=r?.features?.eventStream??{},b=s.find(y=>y.renderEventStreamView);if(b?.renderEventStreamView&&r){let y=b.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>g().element,onClose:o});if(y)return{element:y,update:()=>{},destroy:()=>{}}}return g();function g(){let y=u.classNames,C=m("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Tr(C,y?.panel);let M=[],L="",I="",S=null,R=[],$={},z=0,w=ja(),U=0,q=0,Q=!1,O=null,D=!1,ie=0,me=new Set,we=new Map,Ee="",se="",fe=null,Y,ce,Z,be,he=null,de=null,Me=null;function De(){let B=m("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),j=m("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(Tr(j,y?.headerBar),a){de=m("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),de.style.cursor="help",he=m("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"),he.textContent="-- tok/s",Me=m("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"),Me.style.display="none",Me.style.pointerEvents="none";let Ye=de,vo=Me,xo=()=>{if(!vo.textContent)return;let Ds=Ye.getBoundingClientRect(),Jt=B.getBoundingClientRect();vo.style.left=`${Ds.left-Jt.left}px`,vo.style.top=`${Ds.bottom-Jt.top+4}px`,vo.style.display="block"},xi=()=>{vo.style.display="none"};de.addEventListener("mouseenter",xo),de.addEventListener("mouseleave",xi),de.appendChild(he)}let ae=m("div","persona-flex-1");Y=m("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 Ge=m("option","");Ge.value="",Ge.textContent="All events (0)",Y.appendChild(Ge),ce=m("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"),ce.type="button",ce.title="Copy All";let rt=te("clipboard-copy","12px","currentColor",1.5);rt&&ce.appendChild(rt);let K=m("span","persona-event-copy-all persona-text-xs");K.textContent="Copy All",ce.appendChild(K),de&&j.appendChild(de),j.appendChild(ae),j.appendChild(Y),j.appendChild(ce);let ze=m("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Tr(ze,y?.searchBar);let Ae=te("search","14px","var(--persona-muted, #9ca3af)",1.5),We=m("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Ae&&We.appendChild(Ae),Z=m("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"),Tr(Z,y?.searchInput),Z.type="text",Z.placeholder="Search event payloads...",be=m("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"),be.type="button",be.style.display="none";let Pe=te("x","12px","currentColor",2);return Pe&&be.appendChild(Pe),ze.appendChild(We),ze.appendChild(Z),ze.appendChild(be),B.appendChild(j),B.appendChild(ze),Me&&B.appendChild(Me),B}let _e,He=s.find(B=>B.renderEventStreamToolbar);He?.renderEventStreamToolbar&&r?_e=He.renderEventStreamToolbar({config:r,defaultRenderer:()=>De(),eventCount:t.getSize(),filteredCount:0,onFilterChange:j=>{L=j,Le(),ve()},onSearchChange:j=>{I=j,Le(),ve()}})??De():_e=De();let Ue=m("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");Ue.style.display="none";function Ve(){if(!a||!he||!de)return;let B=a(),j=Kx(B);he.textContent=j;let ae=Gx(B);Me&&(Me.textContent=ae,ae||(Me.style.display="none")),de.setAttribute("aria-label",ae?`Throughput: ${j}, ${ae}`:`Throughput: ${j}`)}let ke=m("div","persona-flex-1 persona-min-h-0 persona-relative"),ne=m("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ne.style.height="100%";let Be=m("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");Tr(Be,y?.scrollIndicator),Be.style.display="none",Be.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let vt=te(d,"14px","currentColor",2);vt&&Be.appendChild(vt);let mt=m("span","");mt.textContent=c,Be.appendChild(mt);let at=m("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");at.style.display="none",ke.appendChild(ne),ke.appendChild(at),ke.appendChild(Be),C.setAttribute("tabindex","0"),C.appendChild(_e),C.appendChild(Ue),C.appendChild(ke);function Oe(){let B=t.getAll(),j={};for(let ze of B)j[ze.type]=(j[ze.type]||0)+1;let ae=Object.keys(j).sort(),Ge=ae.length!==R.length||!ae.every((ze,Ae)=>ze===R[Ae]),Te=!Ge&&ae.some(ze=>j[ze]!==$[ze]),rt=B.length!==Object.values($).reduce((ze,Ae)=>ze+Ae,0);if(!Ge&&!Te&&!rt||(R=ae,$=j,!Y))return;let K=Y.value;if(Y.options[0].textContent=`All events (${B.length})`,Ge){for(;Y.options.length>1;)Y.remove(1);for(let ze of ae){let Ae=m("option","");Ae.value=ze,Ae.textContent=`${ze} (${j[ze]||0})`,Y.appendChild(Ae)}K&&ae.includes(K)?Y.value=K:K&&(Y.value="",L="")}else for(let ze=1;ze<Y.options.length;ze++){let Ae=Y.options[ze];Ae.textContent=`${Ae.value} (${j[Ae.value]||0})`}}function ye(){let B=t.getAll();if(L&&(B=B.filter(j=>j.type===L)),I){let j=I.toLowerCase();B=B.filter(ae=>ae.type.toLowerCase().includes(j)||ae.payload.toLowerCase().includes(j))}return B}function Xe(){return L!==""||I!==""}function Le(){z=0,U=0,w.resume(),Be.style.display="none"}function ue(B){me.has(B)?me.delete(B):me.add(B),fe=B;let j=ne.scrollTop,ae=w.isFollowing();D=!0,w.pause(),ve(),ne.scrollTop=j,ae&&w.resume(),D=!1}function le(){return fo(ne,50)}function ve(){q=Date.now(),Q=!1,Ve(),Oe();let B=t.getEvictedCount();B>0?(Ue.textContent=`${B.toLocaleString()} older events truncated`,Ue.style.display=""):Ue.style.display="none",M=ye();let j=M.length,ae=t.getSize()>0;j===0&&ae&&Xe()?(at.textContent=I?`No events matching '${I}'`:"No events matching filter",at.style.display="",ne.style.display="none"):(at.style.display="none",ne.style.display=""),ce&&(ce.title=Xe()?`Copy Filtered (${j})`:"Copy All"),p&&!w.isFollowing()&&j>z&&(U+=j-z,mt.textContent=c?`${c}${U>0?` (${U})`:""}`:"",Be.style.display=""),z=j;let Ge=t.getAll(),Te=Ge.length>0?Ge[0].timestamp:0,rt=new Set(M.map(Ae=>Ae.id));for(let Ae of me)rt.has(Ae)||me.delete(Ae);let K=L!==Ee||I!==se,ze=we.size===0&&M.length>0;if(K||ze||M.length===0){ne.innerHTML="",we.clear();let Ae=document.createDocumentFragment();for(let We=0;We<M.length;We++){let Pe=ec(M[We],We,Te,u,me,ue,s,r);we.set(M[We].id,Pe),Ae.appendChild(Pe)}ne.appendChild(Ae),Ee=L,se=I,fe=null}else{if(fe!==null){let We=we.get(fe);if(We&&We.parentNode===ne){let Pe=M.findIndex(Ye=>Ye.id===fe);if(Pe>=0){let Ye=ec(M[Pe],Pe,Te,u,me,ue,s,r);ne.insertBefore(Ye,We),We.remove(),we.set(fe,Ye)}}fe=null}let Ae=new Set(M.map(We=>We.id));for(let[We,Pe]of we)Ae.has(We)||(Pe.remove(),we.delete(We));for(let We=0;We<M.length;We++){let Pe=M[We];if(!we.has(Pe.id)){let Ye=ec(Pe,We,Te,u,me,ue,s,r);we.set(Pe.id,Ye),ne.appendChild(Ye)}}}w.isFollowing()&&(ne.scrollTop=ne.scrollHeight)}function xt(){if(Date.now()-q>=_x){O!==null&&(cancelAnimationFrame(O),O=null),ve();return}Q||(Q=!0,O=requestAnimationFrame(()=>{O=null,ve()}))}let xe=(B,j)=>{if(!ce)return;ce.innerHTML="";let ae=te(B,"12px","currentColor",1.5);ae&&ce.appendChild(ae);let Ge=m("span","persona-text-xs");Ge.textContent="Copy All",ce.appendChild(Ge),setTimeout(()=>{ce.innerHTML="";let Te=te("clipboard-copy","12px","currentColor",1.5);Te&&ce.appendChild(Te);let rt=m("span","persona-text-xs");rt.textContent="Copy All",ce.appendChild(rt),ce.disabled=!1},j)},pe=async()=>{if(ce){ce.disabled=!0;try{let B;Xe()?B=M:n?(B=await n(),B.length===0&&(B=t.getAll())):B=t.getAll();let j=B.map(ae=>{try{return JSON.parse(ae.payload)}catch{return ae.payload}});await navigator.clipboard.writeText(JSON.stringify(j,null,2)),xe("check",1500)}catch{xe("x",1500)}}},gn=()=>{Y&&(L=Y.value,Le(),ve())},X=()=>{!Z||!be||(be.style.display=Z.value?"":"none",S&&clearTimeout(S),S=setTimeout(()=>{I=Z.value,Le(),ve()},150))},E=()=>{!Z||!be||(Z.value="",I="",be.style.display="none",S&&clearTimeout(S),Le(),ve())},F=()=>{if(D)return;let B=ne.scrollTop,{action:j,nextLastScrollTop:ae}=Ua({following:w.isFollowing(),currentScrollTop:B,lastScrollTop:ie,nearBottom:le(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ie=ae,j==="resume"?(w.resume(),U=0,Be.style.display="none"):j==="pause"&&(w.pause(),p&&(mt.textContent=c,Be.style.display=""))},v=B=>{let j=za({following:w.isFollowing(),deltaY:B.deltaY,nearBottom:le(),resumeWhenNearBottom:!0});j==="pause"?(w.pause(),p&&(mt.textContent=c,Be.style.display="")):j==="resume"&&(w.resume(),U=0,Be.style.display="none")},T=()=>{p&&(ne.scrollTop=ne.scrollHeight,w.resume(),U=0,Be.style.display="none")},k=B=>{let j=B.target;if(!j||j.closest("button"))return;let ae=j.closest("[data-event-id]");if(!ae)return;let Ge=ae.getAttribute("data-event-id");Ge&&ue(Ge)},H=B=>{if((B.metaKey||B.ctrlKey)&&B.key==="f"){B.preventDefault(),Z?.focus(),Z?.select();return}B.key==="Escape"&&(Z&&document.activeElement===Z?(E(),Z.blur(),C.focus()):o&&o())};ce&&ce.addEventListener("click",pe),Y&&Y.addEventListener("change",gn),Z&&Z.addEventListener("input",X),be&&be.addEventListener("click",E),ne.addEventListener("scroll",F),ne.addEventListener("wheel",v,{passive:!0}),ne.addEventListener("click",k),Be.addEventListener("click",T),C.addEventListener("keydown",H);function V(){S&&clearTimeout(S),O!==null&&(cancelAnimationFrame(O),O=null),Q=!1,we.clear(),ce&&ce.removeEventListener("click",pe),Y&&Y.removeEventListener("change",gn),Z&&Z.removeEventListener("input",X),be&&be.removeEventListener("click",E),ne.removeEventListener("scroll",F),ne.removeEventListener("wheel",v),ne.removeEventListener("click",k),Be.removeEventListener("click",T),C.removeEventListener("keydown",H)}return{element:C,update:xt,destroy:V}}}function tc(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,i=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let b=u;return s.findIndex(g=>g===b||g.contains(b))},d=u=>{let b=p(u.target);if(b<0)return;let g=b;if(u.key===r)g=Math.min(b+1,s.length-1);else if(u.key===o)g=Math.max(b-1,0);else if(u.key==="Home")g=0;else if(u.key==="End")g=s.length-1;else return;u.preventDefault(),g!==b&&t.onSelect(g)},c=u=>{let b=p(u.target);b>=0&&i(s[b])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(u,b){if(s=u,u.forEach((g,y)=>{g.setAttribute("role","tab");let C=y===b;g.setAttribute("aria-selected",C?"true":"false"),g.tabIndex=C||b<0&&y===0?0:-1}),a){let g=(b>=0?u[b]:void 0)??u[0];g&&typeof g.focus=="function"&&(i(g),g.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function gg(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",i=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=X=>({start:X===!1?!1:typeof X=="object"&&X?X.start!==!1:!0,end:X===!1?!1:typeof X=="object"&&X?X.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),b=typeof document<"u"?m("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{b?.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open"),D?.hide()};b&&b.addEventListener("click",()=>{g(),t.onDismiss?.()});let y=m("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");y.setAttribute("data-persona-theme-zone","artifact-pane"),r&&y.classList.add("persona-artifact-pane-document");let C=m("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let M=m("span","persona-text-xs persona-font-medium persona-truncate");M.textContent=s;let L=dt({icon:"x",label:a});L.addEventListener("click",()=>{g(),t.onDismiss?.()});let I="rendered",S=uo({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:X=>{I=X==="source"?"source":"rendered",xe()}}),R=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),$=n?.documentToolbarShowCopyLabel===!0,z=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,U=!!(z&&w&&w.length>0),q=null,Q,O=null,D=null;if(r&&($||z)&&!U){if(Q=$?po({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),z){let X=te("chevron-down",14,"currentColor",2);X&&Q.appendChild(X)}}else r&&U?(q=m("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Q=$?po({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),O=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"}}),q.append(Q,O)):r?Q=dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(Q=dt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&Q.classList.add("persona-hidden"));let ie=r?dt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):dt({icon:"refresh-cw",label:"Refresh"}),me=r?dt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):dt({icon:"x",label:a}),we=dt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&we.classList.add("persona-hidden");let Ee=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),se=e.features?.artifacts?.toolbarActions??[],fe=()=>{let X=ke.find(T=>T.id===ne)??ke[ke.length-1],E=X?.id??null,F=X?.artifactType==="markdown"?X.markdown??"":"",v=X?JSON.stringify({component:X.component,props:X.props},null,2):"";return{markdown:F,jsonPayload:v,id:E}},Y=async()=>{let X=ke.find(E=>E.id===ne)??ke[ke.length-1];try{await navigator.clipboard.writeText(Cs(X))}catch{}};if(Q.addEventListener("click",async()=>{let X=n?.onDocumentToolbarCopyMenuSelect;if(X&&U){let{markdown:E,jsonPayload:F,id:v}=fe();try{await X({actionId:"primary",artifactId:v,markdown:E,jsonPayload:F})}catch{}return}await Y()}),O&&w?.length){let X=()=>y.closest("[data-persona-root]")??document.body,E=()=>{D=qo({items:w.map(F=>({id:F.id,label:F.label})),onSelect:async F=>{let{markdown:v,jsonPayload:T,id:k}=fe(),H=n?.onDocumentToolbarCopyMenuSelect;try{H?await H({actionId:F,artifactId:k,markdown:v,jsonPayload:T}):F==="markdown"||F==="md"?await navigator.clipboard.writeText(v):F==="json"||F==="source"?await navigator.clipboard.writeText(T):await navigator.clipboard.writeText(v||T)}catch{}},anchor:q??O,position:"bottom-right",portal:X()})};y.isConnected?E():requestAnimationFrame(E),O.addEventListener("click",F=>{F.stopPropagation(),D?.toggle()})}ie.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}xe()}),me.addEventListener("click",()=>{g(),t.onDismiss?.()});let ce=m("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(),q?R.append(q,ie,me):R.append(Q,ie,me),R.insertBefore(Ee,me),R.insertBefore(we,me),C.append(S.element,ce,R);else{let X=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");X.append(Q,Ee,we,L),C.appendChild(M),C.appendChild(X)}i&&(C.style.paddingLeft=i,C.style.paddingRight=i);let Z=m("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&&Z.style.setProperty("--persona-artifact-tab-fade-size",p);let be=e.features?.artifacts?.renderTabBar,he=m("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),de=tc(Z,{onSelect:X=>t.onSelect(ke[X].id)}),Me=X=>{let E=X.scrollWidth-X.clientWidth,F=E>1,v=Math.abs(X.scrollLeft);X.classList.toggle("persona-artifact-tab-fade-start",c&&F&&v>1),X.classList.toggle("persona-artifact-tab-fade-end",u&&F&&v<E-1)},De=0,_e=()=>{if(De)return;let X=()=>{De=0,Me(Z)};De=typeof requestAnimationFrame=="function"?requestAnimationFrame(X):setTimeout(X,0)};Z.addEventListener("scroll",()=>_e(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Me(Z)).observe(Z);let He=m("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Ue=()=>{He.scrollLeft=0},Ve=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Ue):setTimeout(Ue,0)};if(i){for(let X of[Z,he])X.style.paddingLeft=i,X.style.paddingRight=i;He.style.padding=i}y.appendChild(C),y.appendChild(Z),y.appendChild(he),y.appendChild(He);let ke=[],ne=null,Be=!1,vt=!1,mt=!0,at=!1,Oe=null,ye="",Xe=null,Le=!1,ue=X=>X.artifactType==="markdown"&&!!X.file||r?I:"rendered",le=X=>{r||(X&&!Le?(C.insertBefore(S.element,M),Le=!0):!X&&Le&&(S.element.remove(),Le=!1))},ve=()=>ne&&ke.find(X=>X.id===ne)||ke[ke.length-1],xt=()=>{let X=vs(ve());if(!X){Ee.replaceChildren();return}let E=se.filter(F=>F.visible===void 0||F.visible(X)).map(F=>vr(F,{documentChrome:r,onClick:()=>{let v=vs(ve());if(v)try{Promise.resolve(F.onClick(v)).catch(()=>{})}catch{}}}));Ee.replaceChildren(...E)},xe=()=>{xt();let X=r&&ke.length<=1,E=!!be;if(Z.classList.toggle("persona-hidden",X||E),he.classList.toggle("persona-hidden",X||!E),E&&be){let T=ke.map(k=>k.id).join("|")+" "+(ne??"");if(T!==ye){ye=T;let k=be({records:ke,selectedId:ne,onSelect:t.onSelect});he.firstElementChild!==k&&he.replaceChildren(k)}}else{de.beforeRender(),Z.replaceChildren();let T=[],k=-1;for(let[H,V]of ke.entries()){let B=m("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");B.type="button";let j=V.artifactType==="markdown"?V.file:void 0,ae=j?kn(j.path):V.title||V.id.slice(0,8),Ge=j?.path||V.title||ae;B.textContent=ae,B.title=Ge,B.setAttribute("aria-label",Ge),V.id===ne&&(B.classList.add("persona-bg-persona-container","persona-border-persona-border"),k=H),B.addEventListener("click",()=>t.onSelect(V.id)),Z.appendChild(B),T.push(B)}if(de.render(T,k),k>=0&&ne!==Oe){Oe=ne;let H=T[k];typeof H.scrollIntoView=="function"&&H.scrollIntoView({block:"nearest",inline:"nearest"})}Me(Z)}let F=ne&&ke.find(T=>T.id===ne)||ke[ke.length-1];if(!F){He.replaceChildren(),Xe=null,le(!1);return}let v=F.artifactType==="markdown"?F.file:void 0;if(le(!!v),r){let T=v?lo(v):F.artifactType==="markdown"?"MD":F.component??"Component",k=(F.title||"Document").trim(),H=v?kn(v.path):k.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ce.textContent=`${H} \xB7 ${T}`}else M.textContent=v?kn(v.path):s;Xe?(Xe.el.parentElement!==He&&He.replaceChildren(Xe.el),Xe.update(F)):(Xe=_a(F,{config:e,resolveViewMode:ue}),He.replaceChildren(Xe.el)),He.classList.toggle("persona-artifact-content-flush",!!He.querySelector(".persona-code-pre"))},pe=()=>{let X=ke.length>0;if(y.classList.toggle("persona-hidden",!X),b){let v=((typeof y.closest=="function"?y.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;X&&v&&Be?(b.classList.remove("persona-hidden"),y.classList.add("persona-artifact-drawer-open")):(b.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open"))}},gn=()=>{at=!1,xe(),pe()};return{element:y,backdrop:b,update(X){let E=X.selectedId??X.artifacts[X.artifacts.length-1]?.id??null,F=E!==ne;ke=X.artifacts,ne=E,ke.length>0&&(Be=!0),at=!0,mt&&gn(),F&&Ue()},setMobileOpen(X){Be=X,!X&&b?(b.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open")):pe()},setExpanded(X){X!==vt&&(vt=X,Ve());let E=te(X?"minimize":"maximize",16,"currentColor",2);E&&we.replaceChildren(E);let F=X?"Collapse artifacts panel":"Expand artifacts panel";we.setAttribute("aria-label",F),we.title=F},setExpandToggleVisible(X){we.classList.toggle("persona-hidden",!X)},setCopyButtonVisible(X){r||Q.classList.toggle("persona-hidden",!X)},setCustomActions(X){se=X,xt()},setTabFade(X){let E=d(X);E.start===c&&E.end===u||(c=E.start,u=E.end,Me(Z))},setRenderTabBar(X){X!==be&&(be=X,ye="",xe())},setVisible(X){X!==mt&&(mt=X,X&&at&&gn())}}}function Gt(e){return e?.features?.artifacts?.enabled===!0}function fg(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Gt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Xx(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var mg=["panel","seamless","detached"];function nc(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&mg.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function oc(e){return!e||!Gt(e)?!1:nc(e)==="detached"}function Hs(e,t){if(!Gt(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Xx(e),fg(e,t);return}let n=t.features?.artifacts?.layout,o=nc(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let i=n?.documentToolbarToggleActiveBackground?.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?e.style.setProperty("--persona-artifact-doc-toggle-active-border",p):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),fg(e,t)}function Bs(e,t){for(let i of mg)e.classList.remove(`persona-artifact-appearance-${i}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Gt(t))return;let n=t.features?.artifacts?.layout,o=nc(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function hg(e,t){return!t||!Gt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function Qx(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Yx(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Zx(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function eC(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function rc(e,t){let o=(t.getComputedStyle(e).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 yg(e,t,n,o,r,s){let a=Qx(r,200),i=eC(t,n,o,200);i=Math.max(a,i);let p=Yx(s);return p!==null&&(i=Math.min(i,p)),Zx(e,a,i)}var bg={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"}},sc=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let i=bg[a]??bg.init;s.classList.add("persona-form-card","persona-space-y-4");let p=m("div","persona-space-y-1"),d=m("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=i.title,p.appendChild(d),i.description){let y=m("p","persona-text-sm persona-text-persona-muted");y.textContent=i.description,p.appendChild(y)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",i.fields.forEach(y=>{let C=m("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${y.name}`;let M=m("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=y.label,C.appendChild(M);let L=y.type??"text",I;L==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=L),I.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",I.id=`${t.id}-${a}-${y.name}`,I.name=y.name,I.placeholder=y.placeholder??"",y.required&&(I.required=!0),C.appendChild(I),c.appendChild(C)});let u=m("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),b=m("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=m("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=i.submitLabel??"Submit",u.appendChild(b),u.appendChild(g),c.appendChild(u),s.replaceChildren(p,c),c.addEventListener("submit",async y=>{y.preventDefault();let C=n.formEndpoint??"/form",M=new FormData(c),L={};M.forEach((I,S)=>{L[S]=I}),L.type=a,g.disabled=!0,b.textContent="Submitting\u2026";try{let I=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let S=await I.json();b.textContent=S.message??"Thanks! We'll be in touch soon.",S.success&&S.nextPrompt&&await o.sendMessage(String(S.nextPrompt))}catch(I){b.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var ac=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},ai=new ac;var vg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),tC=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.streamAnimation.plugins"]),xg=(e,t,n)=>{if(!vg(e)||!vg(t)||tC.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=xg(e[r],t[r],s)}return o};function ii(e,t){let n=xg(e,t,"");return hs(n)}var Cg=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(a=>{try{a(s)}catch(i){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",i)}})}}};var nC=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},oC=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},li=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=nC(e),n=oC(t);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}},ic=e=>typeof e=="string"?e:e==null?"":String(e),Er={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ic(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=ic(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:ic(n.text)}}},wg=e=>Array.isArray(e)?e.map(t=>String(t)):[],ci=e=>{let t=new Set(wg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(wg(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!i)return null;t.add(s.message.id),o();let p={action:i,message:s.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",p)},u=d(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});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(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var rC=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},sC=e=>e.map(t=>({...t,streaming:!1})),aC=e=>e.map(t=>({...t,status:"complete"})),lc=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?rC(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?sC(n.messages):void 0,artifacts:n.artifacts?aC(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as iC,STR as lC,OBJ as cC}from"partial-json";function dC(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function pC(e,t){if(!dC(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function cc(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=iC(n,lC|cC),s=pC(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function uC(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function dc(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=Ln.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{r&&r(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function gC(){let e=cc();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ag(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function di(e){let t=Ag(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function pc(e){let t=Ag(e);if(!t)return null;try{let n=JSON.parse(t);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:t}}}catch{}return null}var fC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function uc(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,ratingLabels:d=fC}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,b=document.createElement("div");b.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=o,g.appendChild(y);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,g.appendChild(C),b.appendChild(g);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let z=1;z<=5;z++){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",`${z} star${z>1?"s":""}: ${d[z-1]}`),w.title=d[z-1],w.dataset.rating=String(z),w.innerHTML=`
41
+ `,n.addEventListener("click",t);let o=s=>{let a=s.launcher??{},i=Wt(s),p=n.querySelector("[data-role='launcher-title']");if(p){let S=a.title??"Chat Assistant";p.textContent=S,p.setAttribute("title",S)}let d=n.querySelector("[data-role='launcher-subtitle']");if(d){let S=a.subtitle??"Here to help you get answers fast";d.textContent=S,d.setAttribute("title",S)}let c=n.querySelector(".persona-flex-col");c&&(a.textHidden||i?c.style.display="none":c.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let S=a.agentIconSize??"40px";if(u.style.height=S,u.style.width=S,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let R=parseFloat(S)||24,$=te(a.agentIconName,R*.6,"var(--persona-text-inverse, #ffffff)",2);$?(u.appendChild($),u.style.display=""):(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=a.agentIconText??"\u{1F4AC}",u.style.display="")}let b=n.querySelector("[data-role='launcher-image']");if(b){let S=a.agentIconSize??"40px";b.style.height=S,b.style.width=S,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(b.src=a.iconUrl,b.style.display="block"):b.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let S=a.callToActionIconSize??"32px";g.style.height=S,g.style.width=S,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let R=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,R=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let $=parseFloat(S)||24,z=Math.max($-R,8),w=te(a.callToActionIconName,z,"currentColor",2);w?g.appendChild(w):g.textContent=a.callToActionIconText??"\u2197"}else g.textContent=a.callToActionIconText??"\u2197"}let y=a.position&&Cn[a.position]?Cn[a.position]:Cn["bottom-right"],C="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",M="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?M:`${C} ${y}`,i||(n.style.zIndex=String(a.zIndex??Ut));let L="1px solid var(--persona-border, #e5e7eb)",I="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=a.border??L,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:I,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=a.collapsedMaxWidth??"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},r=()=>{n.removeEventListener("click",t),n.remove()};return e&&o(e),{element:n,update:o,destroy:r}};var Vu=({config:e,showClose:t})=>{let{wrapper:n,panel:o,pillRoot:r}=zu(e),s=qu(e,t),a={wrapper:n,panel:o,pillRoot:r},i={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},d={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:p,composer:d,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=>{d.footer.replaceWith(b),d.footer=b}}},Vl=({config:e,plugins:t,onToggle:n})=>{let o=t.find(s=>s.renderLauncher);if(o?.renderLauncher){let s=o.renderLauncher({config:e,defaultRenderer:()=>ql(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let r=ql(e,n);return{instance:r,element:r.element}};var Yv=e=>{switch(e){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}},Zv=(e,t)=>{if(!e)return null;let n=Yv(e);if(n===null)return null;let o=t?.[e],r=o!==void 0?o:n;return r||null},ex=(e,t)=>{let n=m("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},tx=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Kl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Gl=320,Xu=320,nx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),ox=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),rx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),sx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),ax=e=>{if(!e||e.length===0)return null;let t=Fe("div",{className:"persona-mention-context-row persona-message-mentions",attrs:{"data-message-mentions":""}});t.style.display="flex";for(let n of e){let o=Fe("div",{className:"persona-mention-chip persona-mention-chip-readonly",attrs:{"data-status":"ready",title:n.label}}),r=m("span","persona-mention-chip-icon"),s=te(n.iconName??"at-sign",13,"currentColor",2);s&&r.appendChild(s),o.appendChild(r),o.appendChild(Fe("span",{className:"persona-mention-chip-label",text:n.label})),t.appendChild(o)}return t},ix=(e,t)=>{let n=document.createDocumentFragment();for(let o of e){if(o.kind==="text"){n.appendChild(document.createTextNode(o.text));continue}n.appendChild(fs(o.ref,{readonly:!0,render:t}))}return n},Ku="\uE000",Gu="\uE001",lx=(e,t,n,o)=>{let r=Math.random().toString(36).slice(2,8),s=b=>`${Ku}${r}:${b}${Gu}`,a=t.map((b,g)=>b.kind==="text"?b.text:s(g)).join(""),i=n(a);if(!t.every((b,g)=>b.kind==="text"||i.includes(s(g)))){e.replaceChildren(ix(t,o));return}e.innerHTML=i;let d=new RegExp(`${Ku}${r}:(\\d+)${Gu}`),c=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),u=[];for(let b=c.nextNode();b;b=c.nextNode())u.push(b);for(let b of u){let g=b;for(let y=d.exec(g.data);y;y=d.exec(g.data)){let C=t[Number(y[1])],M=g.splitText(y.index);M.data=M.data.slice(y[0].length),C?.kind==="mention"&&M.parentNode?.insertBefore(fs(C.ref,{readonly:!0,render:o}),M),g=M}}},cx=(e,t,n)=>{if(e.length===0)return null;try{let o=m("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let r=0,s=!1,a=()=>{s||(s=!0,o.remove(),n?.())};return e.forEach((i,p)=>{let d=m("img");d.alt=i.alt?.trim()||`Attached image ${p+1}`,d.loading="lazy",d.decoding="async",d.referrerPolicy="no-referrer",d.style.display="block",d.style.width="100%",d.style.maxWidth=`${Gl}px`,d.style.maxHeight=`${Xu}px`,d.style.height="auto",d.style.objectFit="contain",d.style.borderRadius="10px",d.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",d.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let c=!1;r+=1,d.addEventListener("error",()=>{c||(c=!0,r=Math.max(0,r-1),d.remove(),r===0&&a())}),d.addEventListener("load",()=>{c=!0}),tx(i.image)?(d.src=i.image,o.appendChild(d)):(c=!0,r=Math.max(0,r-1),d.remove())}),r===0?(a(),null):o}catch{return n?.(),null}},dx=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(o=>{if(!Kl(o.audio))return;let r=m("audio");r.controls=!0,r.preload="metadata",r.src=o.audio,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Gl}px`,t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},px=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(o=>{if(!Kl(o.video))return;let r=m("video");r.controls=!0,r.preload="metadata",r.src=o.video,r.style.display="block",r.style.width="100%",r.style.maxWidth=`${Gl}px`,r.style.maxHeight=`${Xu}px`,r.style.borderRadius="10px",r.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ux=e=>{if(e.length===0)return null;try{let t=m("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(o=>{if(!Kl(o.data))return;let r=m("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",t.appendChild(r),n+=1}),n===0?(t.remove(),null):t}catch{return null}},wr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="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",e.appendChild(t),e.appendChild(n),e.appendChild(o),e.appendChild(r),e},Qu=(e,t,n)=>{let o={config:n??{},streaming:!0,location:e,defaultRenderer:wr};if(t){let r=t(o);if(r!==null)return r}return wr()},gx=(e,t)=>{let n=m("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=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let r=m("img");r.src=o,r.alt=t==="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(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Ju=(e,t,n="div")=>{let o=m(n,"persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?o.textContent=t.format(r):o.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},fx=(e,t="bubble")=>{let n=["persona-message-bubble"];switch(t){case"flat":e==="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"),e==="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"),e==="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},Yu=(e,t,n)=>{let o=t.showCopy??!0,r=t.showUpvote??!0,s=t.showDownvote??!0,a=t.showReadAloud??!1;if(!o&&!r&&!s&&!a){let y=m("div");return y.style.display="none",y.id=`actions-${e.id}`,y.setAttribute("data-actions-for",e.id),y}let i=t.visibility??"hover",p=t.align??"right",d=t.layout??"pill-inside",c={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"}[d],b=m("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);b.id=`actions-${e.id}`,b.setAttribute("data-actions-for",e.id);let g=(y,C,M)=>{let L=dt({icon:y,label:C,size:14,className:"persona-message-action-btn"});return L.setAttribute("data-action",M),L};return o&&b.appendChild(g("copy","Copy message","copy")),a&&b.appendChild(g("volume-2","Read aloud","read-aloud")),r&&b.appendChild(g("thumbs-up","Upvote","upvote")),s&&b.appendChild(g("thumbs-down","Downvote","downvote")),b},Ps=(e,t,n,o,r,s)=>{let a=n??{},i=a.layout??"bubble",p=a.avatar,d=a.timestamp,c=p?.show??!1,u=d?.show??!1,b=p?.position??"left",g=d?.position??"below",y=fx(e.role,i),C=m("div",y.join(" "));C.id=`bubble-${e.id}`,C.setAttribute("data-message-id",e.id),C.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),i==="flat"?(C.style.backgroundColor="transparent",C.style.color="var(--persona-primary, var(--persona-text))"):e.role==="user"?(C.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",C.style.color="var(--persona-message-user-text, white)"):e.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 M=nx(e),L=e.content?.trim()??"",S=M.length>0&&L===Sa,R=qa(s?.widgetConfig?.features?.streamAnimation),$=s?.widgetConfig?.features?.streamAnimation?.plugins,z=e.role==="assistant"&&R.type!=="none"?xr(R.type,$):null,w=e.role==="assistant"&&z?.isAnimating?.(e)===!0,U=e.role==="assistant"&&z!==null&&(!!e.streaming||w);U&&z?.bubbleClass&&C.classList.add(z.bubbleClass);let q=document.createElement("div");q.classList.add("persona-message-content"),e.streaming&&q.classList.add("persona-content-streaming"),U&&z&&(z.containerClass&&q.classList.add(z.containerClass),q.style.setProperty("--persona-stream-step",`${R.speed}ms`),q.style.setProperty("--persona-stream-duration",`${R.duration}ms`));let Q=U?Va(e.content??"",R.buffer,z,e,!!e.streaming):e.content??"",O=()=>{let Z=t({text:Q,message:e,streaming:!!e.streaming,raw:e.rawContent});return U&&z?.wrap==="char"?Ss(Z,"char",e.id,{skipTags:z.skipTags}):U&&z?.wrap==="word"?Ss(Z,"word",e.id,{skipTags:z.skipTags}):Z},D=null;if(S?(D=document.createElement("div"),D.innerHTML=O(),D.style.display="none",q.appendChild(D)):e.contentSegments?.length?lx(q,e.contentSegments,Z=>t({text:Z,message:e,streaming:!!e.streaming,raw:e.rawContent}),s?.widgetConfig?.contextMentions?.renderMentionToken):q.innerHTML=O(),U&&z?.useCaret&&!S&&L){let Z=Ka(),be=q.querySelectorAll(".persona-stream-char, .persona-stream-word"),he=be[be.length-1];if(he?.parentNode)he.parentNode.insertBefore(Z,he.nextSibling);else{let de=q.lastElementChild;de?de.appendChild(Z):q.appendChild(Z)}}if(u&&g==="inline"&&e.createdAt){let Z=Ju(e,d,"span");Z.classList.add("persona-timestamp-inline");let be=q.lastElementChild;be?be.appendChild(Z):q.appendChild(Z)}if(M.length>0){let Z=cx(M,!S&&!!L,()=>{S&&D&&(D.style.display="")});Z?C.appendChild(Z):S&&D&&(D.style.display="")}let ie=ox(e);if(ie.length>0){let Z=dx(ie);Z&&C.appendChild(Z)}let me=rx(e);if(me.length>0){let Z=px(me);Z&&C.appendChild(Z)}let we=sx(e);if(we.length>0){let Z=ux(we);Z&&C.appendChild(Z)}let Ee=e.contentSegments?.length?null:ax(e.contextMentions);if(Ee&&C.appendChild(Ee),C.appendChild(q),u&&g==="below"&&e.createdAt){let Z=Ju(e,d);Z.classList.add("persona-mt-1"),C.appendChild(Z)}let se=e.role==="assistant"?Zv(e.stopReason,s?.widgetConfig?.copy?.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let Z=!!(Q&&Q.trim()),be=R.placeholder==="skeleton",he=be&&R.buffer==="line"&&Z;if(Z)he&&C.appendChild(Ts());else if(be)C.appendChild(Ts());else{let de=Qu("inline",s?.loadingIndicatorRenderer,s?.widgetConfig);de&&C.appendChild(de)}}if(se&&e.stopReason&&!e.streaming&&(L||(q.style.display="none"),C.appendChild(ex(e.stopReason,se))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&o?.enabled!==!1&&o){let Z=Yu(e,o,r);C.appendChild(Z)}if(!c||e.role==="system")return C;let Y=m("div",`persona-message-with-avatar persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ce=gx(p,e.role);return b==="right"||b==="left"&&e.role==="user"?Y.append(C,ce):Y.append(ce,C),Y},mx=(e,t,n,o,r,s)=>{let a=n??{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ps(e,t,n,o,r,s)};var Ar=new Set,hx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),yx=(e,t)=>{let n=e.reasoning?.chunks.join("").trim()??"";return n?n.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,t).join(`
42
+ `):""},Zu=(e,t)=>{let n=Ar.has(e),o=t.querySelector('button[data-expand-header="true"]'),r=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!r)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let d=te(n?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=n?"Hide":"Show"}r.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Jl=(e,t)=>{let n=e.reasoning,o=m("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let r=t?.features?.reasoningDisplay??{},s=r.expandable!==!1,a=s&&Ar.has(e.id),i=n.status!=="complete",p=yx(e,r.previewMaxLines??3),d=m("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");d.type="button",s&&(d.setAttribute("aria-expanded",a?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","reasoning");let c=m("div","persona-flex persona-flex-col persona-text-left"),u=m("span","persona-text-xs persona-text-persona-primary"),b="Thinking...",g=t?.reasoning??{},y=String(n.startedAt??Date.now()),C=()=>{let me=m("span","");return me.setAttribute("data-tool-elapsed",y),me.textContent=Ca(n),me},M=g.renderCollapsedSummary?.({message:e,reasoning:n,defaultSummary:b,previewText:p,isActive:i,config:t??{},elapsed:Ca(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(u.textContent=M,c.appendChild(u)):M instanceof HTMLElement?c.appendChild(M):(u.textContent=b,c.appendChild(u));let L=m("span","persona-text-xs persona-text-persona-primary");L.textContent=Mp(n),c.appendChild(L);let I=r.loadingAnimation??"none",S=g.activeTextTemplate,R=g.completeTextTemplate,$=i?S:R,z=M instanceof HTMLElement,w=(me,we)=>{u.textContent="";let Ee=wa(me,""),se=0;for(let fe of Ee){let Y=fe.styles.length>0?(()=>{let ce=m("span",fe.styles.map(Z=>`persona-tool-text-${Z}`).join(" "));return u.appendChild(ce),ce})():u;if(fe.isDuration&&i)Y.appendChild(C());else{let ce=fe.isDuration?Ca(n):fe.text;we?se=co(Y,ce,se):Y.appendChild(document.createTextNode(ce))}}};if(!z&&$)if(L.style.display="none",u.style.display="",i&&I!=="none"){let me=g.loadingAnimationDuration??2e3;u.setAttribute("data-preserve-animation","true"),I==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${me}ms`),w($,!1)):(u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${me}ms`),I==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),w($,!0))}else w($,!1);else if(!z&&i&&I!=="none"){u.style.display="";let me=g.loadingAnimationDuration??2e3;if(u.setAttribute("data-preserve-animation","true"),I==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${me}ms`);else{u.classList.add(`persona-tool-loading-${I}`),u.style.setProperty("--persona-tool-anim-duration",`${me}ms`),I==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let we=u.textContent||b;u.textContent="",co(u,we,0)}n.status==="complete"&&(u.style.display="none")}else z||(n.status==="complete"?u.style.display="none":u.style.display="");let U=null;if(s){U=m("div","persona-flex persona-items-center");let we=te(a?"chevron-up":"chevron-down",16,"currentColor",2);we?U.appendChild(we):U.textContent=a?"Hide":"Show";let Ee=m("div","persona-flex persona-items-center persona-ml-auto");Ee.append(U),d.append(c,Ee)}else d.append(c);let q=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(q.setAttribute("data-persona-collapsed-preview","reasoning"),q.style.display="none",q.style.whiteSpace="pre-wrap",!a&&i&&r.activePreview&&p){let me=t?.reasoning?.renderCollapsedPreview?.({message:e,reasoning:n,defaultPreview:p,isActive:i,config:t??{}});hx(q,me)||(q.textContent=p),q.style.display=""}if(!a&&i&&r.activeMinHeight&&(o.style.minHeight=r.activeMinHeight),!s)return o.append(d,q),o;let Q=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");Q.style.display=a?"":"none";let O=n.chunks.join(""),D=m("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return D.textContent=O||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),Q.appendChild(D),(()=>{if(d.setAttribute("aria-expanded",a?"true":"false"),U){U.innerHTML="";let we=te(a?"chevron-up":"chevron-down",16,"currentColor",2);we?U.appendChild(we):U.textContent=a?"Hide":"Show"}Q.style.display=a?"":"none",q.style.display=a?"none":q.textContent||q.childNodes.length?"":"none"})(),o.append(d,q,Q),o};var Sr=new Set,bx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),vx=(e,t)=>{let n=e.toolCall;if(!n)return"";let o=(n.chunks??[]).join("").trim();if(o)return o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(-t).join(`
43
+ `);let r=ao(n.args).trim();return r?r.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
44
+ `):""},Xl=(e,t)=>{e.style.backgroundColor=t.codeBlockBackgroundColor??"var(--persona-container, #f3f4f6)",e.style.borderColor=t.codeBlockBorderColor??"var(--persona-border, #e5e7eb)",e.style.color=t.codeBlockTextColor??"var(--persona-text, #171717)"},xx=(e,t)=>{let n=e.toolCall,o=t?.features?.toolCallDisplay,r=o?.collapsedMode??"tool-call",s=vx(e,o?.previewMaxLines??3),a=n?kp(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",p=t?.toolCall??{},d=a;return r==="tool-name"?d=n.name?.trim()||a:r==="tool-preview"&&s&&(d=s),i&&p.activeTextTemplate?d=ul(n,p.activeTextTemplate,d):!i&&p.completeTextTemplate&&(d=ul(n,p.completeTextTemplate,d)),{summary:d,previewText:s,isActive:i}},eg=(e,t,n)=>{let o=Sr.has(e),r=n?.toolCall??{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",o?"true":"false");let d=s.querySelector(".persona-ml-auto")?.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let c=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",u=te(o?"chevron-up":"chevron-down",16,c,2);u?d.appendChild(u):d.textContent=o?"Hide":"Show"}a.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},Ql=(e,t)=>{let n=e.toolCall,o=t?.toolCall??{},r=m("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.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=t?.features?.toolCallDisplay??{},a=s.expandable!==!1,i=a&&Sr.has(e.id),{summary:p,previewText:d,isActive:c}=xx(e,t),u=m("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"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=m("div","persona-flex persona-flex-col persona-text-left"),g=m("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(g.style.color=o.headerTextColor);let y=String(n.startedAt??Date.now()),C=()=>{let O=m("span","");return O.setAttribute("data-tool-elapsed",y),O.textContent=is(n),O},M=o.renderCollapsedSummary?.({message:e,toolCall:n,defaultSummary:p,previewText:d,collapsedMode:s.collapsedMode??"tool-call",isActive:c,config:t??{},elapsed:is(n),createElapsedElement:C});typeof M=="string"&&M.trim()?(g.textContent=M,b.appendChild(g)):M instanceof HTMLElement?b.appendChild(M):(g.textContent=p,b.appendChild(g));let L=s.loadingAnimation??"none",I=o.activeTextTemplate,S=o.completeTextTemplate,R=c?I:S,$=M instanceof HTMLElement,z=(O,D)=>{g.textContent="";let ie=n.name?.trim()||"tool",me=wa(O,ie),we=0;for(let Ee of me){let se=Ee.styles.length>0?(()=>{let fe=m("span",Ee.styles.map(Y=>`persona-tool-text-${Y}`).join(" "));return g.appendChild(fe),fe})():g;if(Ee.isDuration&&c)se.appendChild(C());else{let fe=Ee.isDuration?is(n):Ee.text;D?we=co(se,fe,we):se.appendChild(document.createTextNode(fe))}}};if(!$)if(c&&L!=="none"){let O=o.loadingAnimationDuration??2e3;if(g.setAttribute("data-preserve-animation","true"),L==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${O}ms`),R&&z(R,!1);else if(g.classList.add(`persona-tool-loading-${L}`),g.style.setProperty("--persona-tool-anim-duration",`${O}ms`),L==="shimmer-color"&&(o.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),R)z(R,!0);else{let D=g.textContent||p;g.textContent="",co(g,D,0)}}else R&&z(R,!1);let w=null;if(a){w=m("div","persona-flex persona-items-center");let O=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",D=te(i?"chevron-up":"chevron-down",16,O,2);D?w.appendChild(D):w.textContent=i?"Hide":"Show";let ie=m("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ie.append(w),u.append(b,ie)}else u.append(b);let U=m("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(U.setAttribute("data-persona-collapsed-preview","tool"),U.style.display="none",U.style.whiteSpace="pre-wrap",!i&&c&&s.activePreview&&d){let O=o.renderCollapsedPreview?.({message:e,toolCall:n,defaultPreview:d,isActive:c,config:t??{}});bx(U,O)||(U.textContent=d),U.style.display=""}if(!i&&c&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!a)return r.append(u,U),r;let q=m("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(q.style.display=i?"":"none",o.contentBackgroundColor&&(q.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(q.style.color=o.contentTextColor),o.contentPaddingX&&(q.style.paddingLeft=o.contentPaddingX,q.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(q.style.paddingTop=o.contentPaddingY,q.style.paddingBottom=o.contentPaddingY),n.name){let O=m("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?O.style.color=o.contentTextColor:o.headerTextColor&&(O.style.color=o.headerTextColor),O.textContent=n.name,q.appendChild(O)}if(n.args!==void 0){let O=m("div","persona-space-y-1"),D=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(D.style.color=o.labelTextColor),D.textContent="Arguments";let ie=m("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Xl(ie,o),ie.textContent=ao(n.args),O.append(D,ie),q.appendChild(O)}if(n.chunks&&n.chunks.length){let O=m("div","persona-space-y-1"),D=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(D.style.color=o.labelTextColor),D.textContent="Activity";let ie=m("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Xl(ie,o),ie.textContent=n.chunks.join(""),O.append(D,ie),q.appendChild(O)}if(n.status==="complete"&&n.result!==void 0){let O=m("div","persona-space-y-1"),D=m("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(D.style.color=o.labelTextColor),D.textContent="Result";let ie=m("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");ie.style.fontSize="0.75rem",ie.style.lineHeight="1rem",Xl(ie,o),ie.textContent=ao(n.result),O.append(D,ie),q.appendChild(O)}if(n.status==="complete"&&typeof n.duration=="number"){let O=m("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(O.style.color=o.contentTextColor),O.textContent=`Duration: ${n.duration}ms`,q.appendChild(O)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),w){w.innerHTML="";let O=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",D=te(i?"chevron-up":"chevron-down",16,O,2);D?w.appendChild(D):w.textContent=i?"Hide":"Show"}q.style.display=i?"":"none",U.style.display=i?"none":U.textContent||U.childNodes.length?"":"none"})(),r.append(u,U,q),r};var Vo=new Map,oi=e=>{let n=(e.startsWith(Tn)?e.slice(Tn.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let o=n.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},tg=e=>e?.approval!==!1?e?.approval:void 0,ng=(e,t)=>{let n=tg(t)?.detailsDisplay??"collapsed";return Vo.get(e)??n==="expanded"},og=(e,t,n)=>{let o=tg(n);e.setAttribute("aria-expanded",t?"true":"false");let r=e.querySelector("[data-approval-details-label]");r&&(r.textContent=t?o?.hideDetailsLabel??"Hide details":o?.showDetailsLabel??"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let a=te(t?"chevron-up":"chevron-down",14,"currentColor",2);a&&s.appendChild(a)}},rg=(e,t,n)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),r=t.querySelector("[data-approval-details]");if(!o||!r)return;let s=ng(e,n);og(o,s,n),r.style.display=s?"":"none"};var ri=(e,t)=>{let n=e.approval,o=t?.approval!==!1?t?.approval:void 0,r=n?.status==="pending",s=m("div",["persona-approval-bubble","persona-w-full","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=o?.backgroundColor??"var(--persona-approval-bg, #fefce8)",s.style.borderColor=o?.borderColor??"var(--persona-approval-border, #fef08a)",s.style.boxShadow=o?.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=m("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=m("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let p=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",d=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",c=te(p,20,d,2);c&&i.appendChild(c);let u=m("div","persona-flex-1 persona-min-w-0"),b=m("div","persona-flex persona-items-center persona-gap-2"),g=m("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o?.titleColor&&(g.style.color=o.titleColor),g.textContent=o?.title??"Approval Required",b.appendChild(g),!r){let w=m("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(Tn)?ts(n.toolName):void 0,M=o?.formatDescription?.({toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...C?{displayTitle:C}:{},...n.reason?{reason:n.reason}:{}}),L=!n.toolName,I=M||(L?n.description:`The assistant wants to use \u201C${C??oi(n.toolName)}\u201D.`),S=m("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(S.setAttribute("data-approval-summary","true"),o?.descriptionColor&&(S.style.color=o.descriptionColor),S.textContent=I,u.appendChild(S),n.reason){let w=m("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 U=m("span","persona-font-medium");U.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,w.appendChild(U),w.appendChild(document.createTextNode(n.reason)),u.appendChild(w)}let R=o?.detailsDisplay??"collapsed",$=!!n.description&&!L,z=$||!!n.parameters;if(R!=="hidden"&&z){let w=ng(e.id,t),U=m("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");U.type="button",U.setAttribute("data-expand-header","true"),U.setAttribute("data-bubble-type","approval"),o?.descriptionColor&&(U.style.color=o.descriptionColor);let q=m("span");q.setAttribute("data-approval-details-label","true");let Q=m("span","persona-inline-flex persona-items-center");Q.setAttribute("data-approval-details-chevron","true"),U.append(q,Q),og(U,w,t),u.appendChild(U);let O=m("div");if(O.setAttribute("data-approval-details","true"),O.style.display=w?"":"none",$){let D=m("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o?.descriptionColor&&(D.style.color=o.descriptionColor),D.textContent=n.description,O.appendChild(D)}if(n.parameters){let D=m("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&&(D.style.backgroundColor=o.parameterBackgroundColor),o?.parameterTextColor&&(D.style.color=o.parameterTextColor),D.style.fontSize="0.75rem",D.style.lineHeight="1rem",D.textContent=ao(n.parameters),O.appendChild(D)}u.appendChild(O)}if(r){let w=m("div","persona-flex persona-gap-2 persona-mt-2");w.setAttribute("data-approval-buttons","true");let U=m("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");U.type="button",U.style.backgroundColor=o?.approveButtonColor??"var(--persona-approval-approve-bg, #22c55e)",U.style.color=o?.approveButtonTextColor??"#ffffff",U.setAttribute("data-approval-action","approve");let q=te("shield-check",14,o?.approveButtonTextColor??"#ffffff",2);q&&(q.style.marginRight="4px",U.appendChild(q));let Q=document.createTextNode(o?.approveLabel??"Approve");U.appendChild(Q);let O=m("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");O.type="button",O.style.backgroundColor=o?.denyButtonColor??"transparent",O.style.color=o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",O.style.border=`1px solid ${o?.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,O.setAttribute("data-approval-action","deny");let D=te("shield-x",14,o?.denyButtonTextColor??"var(--persona-feedback-error, #dc2626)",2);D&&(D.style.marginRight="4px",O.appendChild(D));let ie=document.createTextNode(o?.denyLabel??"Deny");O.appendChild(ie),w.append(U,O),u.appendChild(w)}return a.append(i,u),s.appendChild(a),s};function Cx(e){let t=e.getRootNode?.();return t instanceof ShadowRoot?t:(e.ownerDocument??document).body}function sg(e){let{anchor:t,content:n,placement:o="bottom-start",offset:r=6,matchAnchorWidth:s=!1,horizontalOffset:a,verticalOffset:i,zIndex:p=2147483e3,onOpen:d,onDismiss:c}=e,u=e.container??Cx(t),b=!1,g=null,y=()=>{if(!b)return;let L=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${L.width}px`),a&&(n.style.maxWidth=`${L.width}px`);let I=n.getBoundingClientRect(),S=i?.()??null,R=S!=null?L.top+S:L.top,$=o==="top-start"||o==="top-end"?R-r-I.height:L.bottom+r,w=o==="bottom-end"||o==="top-end"?L.right-I.width:L.left,U=a?.()??null;if(U!=null){let q=Math.max(L.left,L.right-I.width);w=Math.min(Math.max(L.left+U,L.left),q)}n.style.top=`${$}px`,n.style.left=`${w}px`},C=()=>{b&&(b=!1,g&&(g(),g=null),n.remove())},M=()=>{if(b)return;b=!0,p!=null&&(n.style.zIndex=String(p)),u.appendChild(n),y();let L=(t.ownerDocument??document).defaultView??window,I=t.ownerDocument??document,S=()=>{if(!t.isConnected){C(),c?.("anchor-removed");return}y()},R=z=>{let w=typeof z.composedPath=="function"?z.composedPath():[];w.includes(n)||w.includes(t)||(C(),c?.("outside"))},$=L.setTimeout(()=>{I.addEventListener("pointerdown",R,!0)},0);L.addEventListener("scroll",S,!0),L.addEventListener("resize",S),g=()=>{L.clearTimeout($),I.removeEventListener("pointerdown",R,!0),L.removeEventListener("scroll",S,!0),L.removeEventListener("resize",S)},d?.()};return{get isOpen(){return b},open:M,close:C,toggle:()=>b?C():M(),reposition:y,destroy:C}}function ag(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var wx=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),ig=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},Ko=(e,t)=>{ig(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},Ax=e=>e?.approval!==!1?e?.approval:void 0,Sx=(e,t)=>{let n=t?.detailsDisplay??"collapsed";return Vo.get(e)??n==="expanded"},Yl=e=>{let t=m("span","persona-approval-kbd");return t.textContent=e,t},Tx=(e,t)=>{let n=m("span","persona-approval-title");t?.titleColor&&(n.style.color=t.titleColor);let r=e.toolType==="webmcp"||e.toolName.startsWith(Tn)?ts(e.toolName):void 0,s=t?.formatDescription?.({toolName:e.toolName,toolType:e.toolType,description:e.description??"",parameters:e.parameters,...r?{displayTitle:r}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=r??oi(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let p=document.createElement("strong");if(p.textContent=a,n.appendChild(p),i){n.append(" from ");let d=document.createElement("strong");d.textContent=i,n.appendChild(d)}return n},Ex=e=>{let t=m("div","persona-approval-resolved"),n=te("ban",15,"currentColor",2);n&&t.appendChild(n);let o=m("span","persona-approval-resolved-name");return o.textContent=e.toolName?oi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Mx=(e,t,n,o,r,s,a)=>{let i=m("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),o?.backgroundColor&&(i.style.background=o.backgroundColor),o?.borderColor&&(i.style.borderColor=o.borderColor),o?.shadow!==void 0&&(i.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let p=o?.detailsDisplay??"collapsed",d=!!n.description&&p!=="hidden",c=n.parameters!=null&&p!=="hidden",u=d||c,b=u&&Sx(t.id,o),g=o?.showDetailsLabel??"Show details",y=o?.hideDetailsLabel??"Hide details",C=m("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?y:g)):C.setAttribute("data-static","true");let M=m("span","persona-approval-logo"),L=te("shield-check",16,"currentColor",2);L&&M.appendChild(L),C.appendChild(M);let I=Tx(n,o);if(u){let U=m("span","persona-approval-toggle");U.setAttribute("aria-hidden","true");let q=te("chevron-down",14,"currentColor",2);q&&U.appendChild(q),I.append(" "),I.appendChild(U)}C.appendChild(I),i.appendChild(C);let S=m("div","persona-approval-body");if(u){let U=m("div","persona-approval-details");if(U.setAttribute("data-role","params"),U.hidden=!b,d){let q=m("p","persona-approval-desc");o?.descriptionColor&&(q.style.color=o.descriptionColor),q.textContent=n.description,U.appendChild(q)}if(c){let q=m("pre","persona-approval-params");o?.parameterBackgroundColor&&(q.style.background=o.parameterBackgroundColor),o?.parameterTextColor&&(q.style.color=o.parameterTextColor),q.textContent=ao(n.parameters),U.appendChild(q)}S.appendChild(U)}if(n.reason){let U=m("p","persona-approval-reason");o?.reasonColor?U.style.color=o.reasonColor:o?.descriptionColor&&(U.style.color=o.descriptionColor);let q=m("span","persona-approval-reason-label");q.textContent=`${o?.reasonLabel??"Agent's stated reason:"} `,U.append(q,document.createTextNode(n.reason)),S.appendChild(U)}let R=m("div","persona-approval-actions"),$=null,z=U=>{o?.approveButtonColor&&(U.style.background=o.approveButtonColor),o?.approveButtonTextColor&&(U.style.color=o.approveButtonTextColor)},w=m("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"),a){let U=m("div","persona-approval-split"),q=m("button","persona-approval-primary");q.type="button",q.setAttribute("data-action","always"),z(q),q.append(o?.approveLabel??"Always allow",Yl("\u23CE"));let Q=m("button","persona-approval-caret");Q.type="button",Q.setAttribute("data-action","toggle-menu"),Q.setAttribute("aria-label","More options"),z(Q);let O=te("chevron-down",15,"currentColor",2);O&&Q.appendChild(O),U.append(q,Q),R.append(U,w),w.append(Yl("Esc"));let D=m("div","persona-approval-menu"),ie=m("button","persona-approval-menu-item");ie.type="button",ie.append("Allow once",Yl("\u2318\u23CE")),D.appendChild(ie),$=sg({anchor:U,content:D,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,$),ie.addEventListener("click",()=>{Ko(e,t.id),r()})}else{let U=m("button","persona-approval-primary persona-approval-primary--solo");U.type="button",U.setAttribute("data-action","allow"),z(U),U.append(o?.approveLabel??"Allow"),R.append(U,w)}return S.appendChild(R),i.appendChild(S),i.addEventListener("click",U=>{let q=U.target instanceof Element?U.target.closest("[data-action]"):null;if(!q)return;let Q=q.getAttribute("data-action");if(Q==="toggle-params"){let O=i.querySelector('[data-role="params"]');if(O){let D=O.hidden;O.hidden=!D,C.setAttribute("aria-expanded",D?"true":"false"),C.setAttribute("aria-label",D?y:g),Vo.set(t.id,D)}return}if(Q==="toggle-menu"){$?.toggle();return}if(Q==="always"){Ko(e,t.id),r({remember:!0});return}if(Q==="allow"){Ko(e,t.id),r();return}if(Q==="deny"){Ko(e,t.id),s();return}}),i},lg=()=>{let e=wx();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:r,deny:s,config:a})=>{let i=o?.approval;if(!i)return null;let p=Ax(a);if(i.status!=="pending"){if(Ko(e,o.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Ex(i)}ig(e,o.id);let d=p?.enableAlwaysAllow===!0,c=Mx(e,o,i,p,r,s,d);if(d){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=b=>{ag(b)||o.id===e.latestPendingApprovalId&&(b.key!=="Escape"&&b.key!=="Enter"||(b.preventDefault(),b.stopImmediatePropagation(),Ko(e,o.id),b.key==="Escape"?s():b.metaKey||b.ctrlKey?r():r({remember:!0})))};e.keyHandlers.set(o.id,u),document.addEventListener("keydown",u)}return c}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])Ko(e,o);e.latestPendingApprovalId=null}}};var cg=e=>{let t=[],n=null;return{buttons:t,render:(r,s,a,i,p,d)=>{e.innerHTML="",t.length=0;let c=d?.agentPushed===!0;if(c||(n=null),!r||!r.length||!c&&(i??(s?s.getMessages():[])).some(M=>M.role==="user"))return;let u=document.createDocumentFragment(),b=s?s.isStreaming():!1,g=y=>{switch(y){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(y=>{let C=m("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=y,C.disabled=b,p?.fontFamily&&(C.style.fontFamily=g(p.fontFamily)),p?.fontWeight&&(C.style.fontWeight=p.fontWeight),p?.paddingX&&(C.style.paddingLeft=p.paddingX,C.style.paddingRight=p.paddingX),p?.paddingY&&(C.style.paddingTop=p.paddingY,C.style.paddingBottom=p.paddingY),C.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",c&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:y},bubbles:!0,composed:!0})),s.sendMessage(y))}),u.appendChild(C),t.push(C)}),e.appendChild(u),c){let y=JSON.stringify(r);y!==n&&(n=y,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...r]},bubbles:!0,composed:!0})))}}}};var Rs=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),this.store?.put(t)}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 t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;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=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}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(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,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,t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(o){n(o)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(o){n(o)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},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((t,n)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{n(o.error)}}catch(o){n(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let r of t)o.put(r)}catch{}}};var kx=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Lx=new Set(["step_start","execution_start"]),Px=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Rx=new Set(["step_complete","agent_turn_complete"]),Ix=new Set(["flow_complete","agent_complete"]),dg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),ug=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),rn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Go=(e,t)=>{let n=e[t];return ug(n)?n:void 0};function Zl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function si(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Wx(e,t){return typeof t.type=="string"?t.type:e}function Hx(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Bx(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function pg(e){let t=Go(e,"result"),n=[Go(e,"tokens"),Go(e,"totalTokens"),t?Go(t,"tokens"):void 0,Go(e,"usage"),t?Go(t,"usage"):void 0];for(let o of n){if(!o)continue;let r=rn(o.output)??rn(o.outputTokens)??rn(o.completionTokens);if(r!==void 0)return r}return rn(e.outputTokens)??rn(e.completionTokens)??(t?rn(t.outputTokens)??rn(t.completionTokens):void 0)}function Ox(e){let t=Go(e,"result");return rn(e.executionTime)??rn(e.executionTimeMs)??rn(e.execution_time)??rn(e.duration)??(t?rn(t.executionTime)??rn(t.executionTimeMs):void 0)}function Dx(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}var Ws=class{constructor(t=Dx){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:si(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){if(!ug(n)){dg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Wx(t,n),r=this.now();if(kx.has(o)){this.startRun(r);return}if(Lx.has(o)){this.run||this.startRun(r);return}if(Px.has(o)){if(!Bx(o,n))return;let s=Hx(n);if(!s)return;this.run||this.startRun(r);let a=this.run;a.firstDeltaAt??(a.firstDeltaAt=r),a.visibleCharCount+=s.length;let i=a.exactOutputTokens+Zl(a.visibleCharCount),p=r-a.firstDeltaAt;this.metric={status:"running",tokensPerSecond:si(i,p),outputTokens:i,durationMs:p,source:a.exactOutputTokens>0?"usage":"estimate"};return}if(Rx.has(o)){if(!this.run)return;let s=this.run,a=pg(n);a!==void 0&&(s.exactOutputTokens+=a,s.visibleCharCount=0);let i=s.exactOutputTokens>0,p=s.exactOutputTokens+Zl(s.visibleCharCount),d=this.resolveDuration(s,n,r);this.metric={status:"running",tokensPerSecond:si(p,d),outputTokens:p,durationMs:d,source:i?"usage":"estimate"};return}if(Ix.has(o)){if(!this.run)return;let s=this.run,a=pg(n),i=a??s.exactOutputTokens+Zl(s.visibleCharCount),p=a!==void 0||s.exactOutputTokens>0?"usage":"estimate",d=this.resolveDuration(s,n,r);this.metric={status:"complete",tokensPerSecond:si(i,d),outputTokens:i,durationMs:d,source:p},this.run=null;return}if(dg.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,o){let r=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;return r!==void 0&&r>=250?r:Ox(n)??o-t.startedAt}};function Tr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Nx={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)"}},Fx={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},_x=["flowName","stepName","reasoningText","text","name","tool","toolName"],$x=100;function jx(e,t){let n={...Nx,...t};if(n[e])return n[e];for(let o of Object.keys(n))if(o.endsWith("_")&&e.startsWith(o))return n[o];return Fx}function Ux(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function zx(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),r=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${o}:${r}.${s}`}function qx(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let o of t){let r=o.split("."),s=n;for(let a of r)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Vx(e){return navigator.clipboard?.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function Kx(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Gx(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Jx(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Xx(e,t,n){let o,r;try{r=JSON.parse(e.payload),o=JSON.stringify(r,null,2)}catch{r=e.payload,o=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s?.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:r});if(i)return i}return a();function a(){let i=m("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=m("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,i.appendChild(p),i}}function ec(e,t,n,o,r,s,a,i){let p=r.has(e.id),d=m("div","persona-border-b persona-border-persona-divider persona-text-xs");Tr(d,o.classNames?.eventRow);let c=a.find(b=>b.renderEventStreamRow);if(c?.renderEventStreamRow&&i){let b=c.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:p,onToggleExpand:()=>s(e.id)});if(b)return d.appendChild(b),d}return d.appendChild(u()),d;function u(){let b=m("div",""),g=m("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");g.setAttribute("data-event-id",e.id);let y=m("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=te(p?"chevron-down":"chevron-right","14px","currentColor",2);C&&y.appendChild(C);let M=m("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=o.timestampFormat??"relative";M.textContent=L==="relative"?Ux(e.timestamp,n):zx(e.timestamp);let I=null;o.showSequenceNumbers!==!1&&(I=m("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),I.textContent=String(t+1));let S=jx(e.type,o.badgeColors),R=m("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");R.style.backgroundColor=S.bg,R.style.color=S.text,R.style.borderColor=S.text+"50",R.textContent=e.type;let $=o.descriptionFields??_x,z=qx(e.payload,$),w=null;z&&(w=m("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),w.textContent=z);let U=m("div","persona-flex-1 persona-min-w-0"),q=m("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"),Q=te("clipboard","12px","currentColor",1.5);return Q&&q.appendChild(Q),q.addEventListener("click",async O=>{O.stopPropagation(),await Vx(Kx(e)),q.innerHTML="";let D=te("check","12px","currentColor",1.5);D&&q.appendChild(D),setTimeout(()=>{q.innerHTML="";let ie=te("clipboard","12px","currentColor",1.5);ie&&q.appendChild(ie)},1500)}),g.appendChild(y),g.appendChild(M),I&&g.appendChild(I),g.appendChild(R),w&&g.appendChild(w),g.appendChild(U),g.appendChild(q),b.appendChild(g),p&&b.appendChild(Xx(e,a,i)),b}}function gg(e){let{buffer:t,getFullHistory:n,onClose:o,config:r,plugins:s=[],getThroughput:a}=e,i=r?.features?.scrollToBottom,p=i?.enabled!==!1,d=i?.iconName??"arrow-down",c=i?.label??"",u=r?.features?.eventStream??{},b=s.find(y=>y.renderEventStreamView);if(b?.renderEventStreamView&&r){let y=b.renderEventStreamView({config:r,events:t.getAll(),defaultRenderer:()=>g().element,onClose:o});if(y)return{element:y,update:()=>{},destroy:()=>{}}}return g();function g(){let y=u.classNames,C=m("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Tr(C,y?.panel);let M=[],L="",I="",S=null,R=[],$={},z=0,w=ja(),U=0,q=0,Q=!1,O=null,D=!1,ie=0,me=new Set,we=new Map,Ee="",se="",fe=null,Y,ce,Z,be,he=null,de=null,Me=null;function De(){let B=m("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),j=m("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(Tr(j,y?.headerBar),a){de=m("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),de.style.cursor="help",he=m("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"),he.textContent="-- tok/s",Me=m("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"),Me.style.display="none",Me.style.pointerEvents="none";let Ye=de,vo=Me,xo=()=>{if(!vo.textContent)return;let Ds=Ye.getBoundingClientRect(),Jt=B.getBoundingClientRect();vo.style.left=`${Ds.left-Jt.left}px`,vo.style.top=`${Ds.bottom-Jt.top+4}px`,vo.style.display="block"},xi=()=>{vo.style.display="none"};de.addEventListener("mouseenter",xo),de.addEventListener("mouseleave",xi),de.appendChild(he)}let ae=m("div","persona-flex-1");Y=m("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 Ge=m("option","");Ge.value="",Ge.textContent="All events (0)",Y.appendChild(Ge),ce=m("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"),ce.type="button",ce.title="Copy All";let rt=te("clipboard-copy","12px","currentColor",1.5);rt&&ce.appendChild(rt);let K=m("span","persona-event-copy-all persona-text-xs");K.textContent="Copy All",ce.appendChild(K),de&&j.appendChild(de),j.appendChild(ae),j.appendChild(Y),j.appendChild(ce);let ze=m("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Tr(ze,y?.searchBar);let Ae=te("search","14px","var(--persona-muted, #9ca3af)",1.5),We=m("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Ae&&We.appendChild(Ae),Z=m("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"),Tr(Z,y?.searchInput),Z.type="text",Z.placeholder="Search event payloads...",be=m("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"),be.type="button",be.style.display="none";let Pe=te("x","12px","currentColor",2);return Pe&&be.appendChild(Pe),ze.appendChild(We),ze.appendChild(Z),ze.appendChild(be),B.appendChild(j),B.appendChild(ze),Me&&B.appendChild(Me),B}let _e,He=s.find(B=>B.renderEventStreamToolbar);He?.renderEventStreamToolbar&&r?_e=He.renderEventStreamToolbar({config:r,defaultRenderer:()=>De(),eventCount:t.getSize(),filteredCount:0,onFilterChange:j=>{L=j,Le(),ve()},onSearchChange:j=>{I=j,Le(),ve()}})??De():_e=De();let Ue=m("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");Ue.style.display="none";function Ve(){if(!a||!he||!de)return;let B=a(),j=Gx(B);he.textContent=j;let ae=Jx(B);Me&&(Me.textContent=ae,ae||(Me.style.display="none")),de.setAttribute("aria-label",ae?`Throughput: ${j}, ${ae}`:`Throughput: ${j}`)}let ke=m("div","persona-flex-1 persona-min-h-0 persona-relative"),ne=m("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ne.style.height="100%";let Be=m("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");Tr(Be,y?.scrollIndicator),Be.style.display="none",Be.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let vt=te(d,"14px","currentColor",2);vt&&Be.appendChild(vt);let mt=m("span","");mt.textContent=c,Be.appendChild(mt);let at=m("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");at.style.display="none",ke.appendChild(ne),ke.appendChild(at),ke.appendChild(Be),C.setAttribute("tabindex","0"),C.appendChild(_e),C.appendChild(Ue),C.appendChild(ke);function Oe(){let B=t.getAll(),j={};for(let ze of B)j[ze.type]=(j[ze.type]||0)+1;let ae=Object.keys(j).sort(),Ge=ae.length!==R.length||!ae.every((ze,Ae)=>ze===R[Ae]),Te=!Ge&&ae.some(ze=>j[ze]!==$[ze]),rt=B.length!==Object.values($).reduce((ze,Ae)=>ze+Ae,0);if(!Ge&&!Te&&!rt||(R=ae,$=j,!Y))return;let K=Y.value;if(Y.options[0].textContent=`All events (${B.length})`,Ge){for(;Y.options.length>1;)Y.remove(1);for(let ze of ae){let Ae=m("option","");Ae.value=ze,Ae.textContent=`${ze} (${j[ze]||0})`,Y.appendChild(Ae)}K&&ae.includes(K)?Y.value=K:K&&(Y.value="",L="")}else for(let ze=1;ze<Y.options.length;ze++){let Ae=Y.options[ze];Ae.textContent=`${Ae.value} (${j[Ae.value]||0})`}}function ye(){let B=t.getAll();if(L&&(B=B.filter(j=>j.type===L)),I){let j=I.toLowerCase();B=B.filter(ae=>ae.type.toLowerCase().includes(j)||ae.payload.toLowerCase().includes(j))}return B}function Xe(){return L!==""||I!==""}function Le(){z=0,U=0,w.resume(),Be.style.display="none"}function ue(B){me.has(B)?me.delete(B):me.add(B),fe=B;let j=ne.scrollTop,ae=w.isFollowing();D=!0,w.pause(),ve(),ne.scrollTop=j,ae&&w.resume(),D=!1}function le(){return fo(ne,50)}function ve(){q=Date.now(),Q=!1,Ve(),Oe();let B=t.getEvictedCount();B>0?(Ue.textContent=`${B.toLocaleString()} older events truncated`,Ue.style.display=""):Ue.style.display="none",M=ye();let j=M.length,ae=t.getSize()>0;j===0&&ae&&Xe()?(at.textContent=I?`No events matching '${I}'`:"No events matching filter",at.style.display="",ne.style.display="none"):(at.style.display="none",ne.style.display=""),ce&&(ce.title=Xe()?`Copy Filtered (${j})`:"Copy All"),p&&!w.isFollowing()&&j>z&&(U+=j-z,mt.textContent=c?`${c}${U>0?` (${U})`:""}`:"",Be.style.display=""),z=j;let Ge=t.getAll(),Te=Ge.length>0?Ge[0].timestamp:0,rt=new Set(M.map(Ae=>Ae.id));for(let Ae of me)rt.has(Ae)||me.delete(Ae);let K=L!==Ee||I!==se,ze=we.size===0&&M.length>0;if(K||ze||M.length===0){ne.innerHTML="",we.clear();let Ae=document.createDocumentFragment();for(let We=0;We<M.length;We++){let Pe=ec(M[We],We,Te,u,me,ue,s,r);we.set(M[We].id,Pe),Ae.appendChild(Pe)}ne.appendChild(Ae),Ee=L,se=I,fe=null}else{if(fe!==null){let We=we.get(fe);if(We&&We.parentNode===ne){let Pe=M.findIndex(Ye=>Ye.id===fe);if(Pe>=0){let Ye=ec(M[Pe],Pe,Te,u,me,ue,s,r);ne.insertBefore(Ye,We),We.remove(),we.set(fe,Ye)}}fe=null}let Ae=new Set(M.map(We=>We.id));for(let[We,Pe]of we)Ae.has(We)||(Pe.remove(),we.delete(We));for(let We=0;We<M.length;We++){let Pe=M[We];if(!we.has(Pe.id)){let Ye=ec(Pe,We,Te,u,me,ue,s,r);we.set(Pe.id,Ye),ne.appendChild(Ye)}}}w.isFollowing()&&(ne.scrollTop=ne.scrollHeight)}function xt(){if(Date.now()-q>=$x){O!==null&&(cancelAnimationFrame(O),O=null),ve();return}Q||(Q=!0,O=requestAnimationFrame(()=>{O=null,ve()}))}let xe=(B,j)=>{if(!ce)return;ce.innerHTML="";let ae=te(B,"12px","currentColor",1.5);ae&&ce.appendChild(ae);let Ge=m("span","persona-text-xs");Ge.textContent="Copy All",ce.appendChild(Ge),setTimeout(()=>{ce.innerHTML="";let Te=te("clipboard-copy","12px","currentColor",1.5);Te&&ce.appendChild(Te);let rt=m("span","persona-text-xs");rt.textContent="Copy All",ce.appendChild(rt),ce.disabled=!1},j)},pe=async()=>{if(ce){ce.disabled=!0;try{let B;Xe()?B=M:n?(B=await n(),B.length===0&&(B=t.getAll())):B=t.getAll();let j=B.map(ae=>{try{return JSON.parse(ae.payload)}catch{return ae.payload}});await navigator.clipboard.writeText(JSON.stringify(j,null,2)),xe("check",1500)}catch{xe("x",1500)}}},gn=()=>{Y&&(L=Y.value,Le(),ve())},X=()=>{!Z||!be||(be.style.display=Z.value?"":"none",S&&clearTimeout(S),S=setTimeout(()=>{I=Z.value,Le(),ve()},150))},E=()=>{!Z||!be||(Z.value="",I="",be.style.display="none",S&&clearTimeout(S),Le(),ve())},F=()=>{if(D)return;let B=ne.scrollTop,{action:j,nextLastScrollTop:ae}=Ua({following:w.isFollowing(),currentScrollTop:B,lastScrollTop:ie,nearBottom:le(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ie=ae,j==="resume"?(w.resume(),U=0,Be.style.display="none"):j==="pause"&&(w.pause(),p&&(mt.textContent=c,Be.style.display=""))},v=B=>{let j=za({following:w.isFollowing(),deltaY:B.deltaY,nearBottom:le(),resumeWhenNearBottom:!0});j==="pause"?(w.pause(),p&&(mt.textContent=c,Be.style.display="")):j==="resume"&&(w.resume(),U=0,Be.style.display="none")},T=()=>{p&&(ne.scrollTop=ne.scrollHeight,w.resume(),U=0,Be.style.display="none")},k=B=>{let j=B.target;if(!j||j.closest("button"))return;let ae=j.closest("[data-event-id]");if(!ae)return;let Ge=ae.getAttribute("data-event-id");Ge&&ue(Ge)},H=B=>{if((B.metaKey||B.ctrlKey)&&B.key==="f"){B.preventDefault(),Z?.focus(),Z?.select();return}B.key==="Escape"&&(Z&&document.activeElement===Z?(E(),Z.blur(),C.focus()):o&&o())};ce&&ce.addEventListener("click",pe),Y&&Y.addEventListener("change",gn),Z&&Z.addEventListener("input",X),be&&be.addEventListener("click",E),ne.addEventListener("scroll",F),ne.addEventListener("wheel",v,{passive:!0}),ne.addEventListener("click",k),Be.addEventListener("click",T),C.addEventListener("keydown",H);function V(){S&&clearTimeout(S),O!==null&&(cancelAnimationFrame(O),O=null),Q=!1,we.clear(),ce&&ce.removeEventListener("click",pe),Y&&Y.removeEventListener("change",gn),Z&&Z.removeEventListener("input",X),be&&be.removeEventListener("click",E),ne.removeEventListener("scroll",F),ne.removeEventListener("wheel",v),ne.removeEventListener("click",k),Be.removeEventListener("click",T),C.removeEventListener("keydown",H)}return{element:C,update:xt,destroy:V}}}function tc(e,t){let n=t.orientation??"horizontal",o=n==="vertical"?"ArrowUp":"ArrowLeft",r=n==="vertical"?"ArrowDown":"ArrowRight";e.setAttribute("role","tablist");let s=[],a=!1,i=u=>{typeof u.scrollIntoView=="function"&&u.scrollIntoView({block:"nearest",inline:"nearest"})},p=u=>{let b=u;return s.findIndex(g=>g===b||g.contains(b))},d=u=>{let b=p(u.target);if(b<0)return;let g=b;if(u.key===r)g=Math.min(b+1,s.length-1);else if(u.key===o)g=Math.max(b-1,0);else if(u.key==="Home")g=0;else if(u.key==="End")g=s.length-1;else return;u.preventDefault(),g!==b&&t.onSelect(g)},c=u=>{let b=p(u.target);b>=0&&i(s[b])};return e.addEventListener("keydown",d),e.addEventListener("focusin",c),{beforeRender(){a=typeof document<"u"&&e.contains(document.activeElement)},render(u,b){if(s=u,u.forEach((g,y)=>{g.setAttribute("role","tab");let C=y===b;g.setAttribute("aria-selected",C?"true":"false"),g.tabIndex=C||b<0&&y===0?0:-1}),a){let g=(b>=0?u[b]:void 0)??u[0];g&&typeof g.focus=="function"&&(i(g),g.focus())}},destroy(){e.removeEventListener("keydown",d),e.removeEventListener("focusin",c)}}}function fg(e,t){let n=e.features?.artifacts?.layout,r=(n?.toolbarPreset??"default")==="document",s=n?.toolbarTitle??"Artifacts",a=n?.closeButtonLabel??"Close",i=n?.panePadding?.trim(),p=n?.tabFadeSize?.trim(),d=X=>({start:X===!1?!1:typeof X=="object"&&X?X.start!==!1:!0,end:X===!1?!1:typeof X=="object"&&X?X.end!==!1:!0}),{start:c,end:u}=d(n?.tabFade),b=typeof document<"u"?m("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,g=()=>{b?.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open"),D?.hide()};b&&b.addEventListener("click",()=>{g(),t.onDismiss?.()});let y=m("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");y.setAttribute("data-persona-theme-zone","artifact-pane"),r&&y.classList.add("persona-artifact-pane-document");let C=m("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");C.setAttribute("data-persona-theme-zone","artifact-toolbar"),r&&C.classList.add("persona-artifact-toolbar-document");let M=m("span","persona-text-xs persona-font-medium persona-truncate");M.textContent=s;let L=dt({icon:"x",label:a});L.addEventListener("click",()=>{g(),t.onDismiss?.()});let I="rendered",S=uo({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:X=>{I=X==="source"?"source":"rendered",xe()}}),R=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),$=n?.documentToolbarShowCopyLabel===!0,z=n?.documentToolbarShowCopyChevron===!0,w=n?.documentToolbarCopyMenuItems,U=!!(z&&w&&w.length>0),q=null,Q,O=null,D=null;if(r&&($||z)&&!U){if(Q=$?po({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),z){let X=te("chevron-down",14,"currentColor",2);X&&Q.appendChild(X)}}else r&&U?(q=m("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Q=$?po({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),O=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"}}),q.append(Q,O)):r?Q=dt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):(Q=dt({icon:"copy",label:"Copy"}),n?.showCopyButton!==!0&&Q.classList.add("persona-hidden"));let ie=r?dt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):dt({icon:"refresh-cw",label:"Refresh"}),me=r?dt({icon:"x",label:a,className:"persona-artifact-doc-icon-btn"}):dt({icon:"x",label:a}),we=dt({icon:"maximize",label:"Expand artifacts panel",className:"persona-artifact-expand-btn"+(r?" persona-artifact-doc-icon-btn":""),onClick:()=>t.onToggleExpand?.()});n?.showExpandToggle!==!0&&we.classList.add("persona-hidden");let Ee=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toolbar-custom-actions"),se=e.features?.artifacts?.toolbarActions??[],fe=()=>{let X=ke.find(T=>T.id===ne)??ke[ke.length-1],E=X?.id??null,F=X?.artifactType==="markdown"?X.markdown??"":"",v=X?JSON.stringify({component:X.component,props:X.props},null,2):"";return{markdown:F,jsonPayload:v,id:E}},Y=async()=>{let X=ke.find(E=>E.id===ne)??ke[ke.length-1];try{await navigator.clipboard.writeText(Cs(X))}catch{}};if(Q.addEventListener("click",async()=>{let X=n?.onDocumentToolbarCopyMenuSelect;if(X&&U){let{markdown:E,jsonPayload:F,id:v}=fe();try{await X({actionId:"primary",artifactId:v,markdown:E,jsonPayload:F})}catch{}return}await Y()}),O&&w?.length){let X=()=>y.closest("[data-persona-root]")??document.body,E=()=>{D=qo({items:w.map(F=>({id:F.id,label:F.label})),onSelect:async F=>{let{markdown:v,jsonPayload:T,id:k}=fe(),H=n?.onDocumentToolbarCopyMenuSelect;try{H?await H({actionId:F,artifactId:k,markdown:v,jsonPayload:T}):F==="markdown"||F==="md"?await navigator.clipboard.writeText(v):F==="json"||F==="source"?await navigator.clipboard.writeText(T):await navigator.clipboard.writeText(v||T)}catch{}},anchor:q??O,position:"bottom-right",portal:X()})};y.isConnected?E():requestAnimationFrame(E),O.addEventListener("click",F=>{F.stopPropagation(),D?.toggle()})}ie.addEventListener("click",async()=>{try{await n?.onDocumentToolbarRefresh?.()}catch{}xe()}),me.addEventListener("click",()=>{g(),t.onDismiss?.()});let ce=m("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(),q?R.append(q,ie,me):R.append(Q,ie,me),R.insertBefore(Ee,me),R.insertBefore(we,me),C.append(S.element,ce,R);else{let X=m("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0");X.append(Q,Ee,we,L),C.appendChild(M),C.appendChild(X)}i&&(C.style.paddingLeft=i,C.style.paddingRight=i);let Z=m("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&&Z.style.setProperty("--persona-artifact-tab-fade-size",p);let be=e.features?.artifacts?.renderTabBar,he=m("div","persona-artifact-tab-custom persona-shrink-0 persona-border-b persona-border-persona-border persona-hidden"),de=tc(Z,{onSelect:X=>t.onSelect(ke[X].id)}),Me=X=>{let E=X.scrollWidth-X.clientWidth,F=E>1,v=Math.abs(X.scrollLeft);X.classList.toggle("persona-artifact-tab-fade-start",c&&F&&v>1),X.classList.toggle("persona-artifact-tab-fade-end",u&&F&&v<E-1)},De=0,_e=()=>{if(De)return;let X=()=>{De=0,Me(Z)};De=typeof requestAnimationFrame=="function"?requestAnimationFrame(X):setTimeout(X,0)};Z.addEventListener("scroll",()=>_e(),{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(()=>Me(Z)).observe(Z);let He=m("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3"),Ue=()=>{He.scrollLeft=0},Ve=()=>{typeof requestAnimationFrame=="function"?requestAnimationFrame(Ue):setTimeout(Ue,0)};if(i){for(let X of[Z,he])X.style.paddingLeft=i,X.style.paddingRight=i;He.style.padding=i}y.appendChild(C),y.appendChild(Z),y.appendChild(he),y.appendChild(He);let ke=[],ne=null,Be=!1,vt=!1,mt=!0,at=!1,Oe=null,ye="",Xe=null,Le=!1,ue=X=>X.artifactType==="markdown"&&!!X.file||r?I:"rendered",le=X=>{r||(X&&!Le?(C.insertBefore(S.element,M),Le=!0):!X&&Le&&(S.element.remove(),Le=!1))},ve=()=>ne&&ke.find(X=>X.id===ne)||ke[ke.length-1],xt=()=>{let X=vs(ve());if(!X){Ee.replaceChildren();return}let E=se.filter(F=>F.visible===void 0||F.visible(X)).map(F=>vr(F,{documentChrome:r,onClick:()=>{let v=vs(ve());if(v)try{Promise.resolve(F.onClick(v)).catch(()=>{})}catch{}}}));Ee.replaceChildren(...E)},xe=()=>{xt();let X=r&&ke.length<=1,E=!!be;if(Z.classList.toggle("persona-hidden",X||E),he.classList.toggle("persona-hidden",X||!E),E&&be){let T=ke.map(k=>k.id).join("|")+" "+(ne??"");if(T!==ye){ye=T;let k=be({records:ke,selectedId:ne,onSelect:t.onSelect});he.firstElementChild!==k&&he.replaceChildren(k)}}else{de.beforeRender(),Z.replaceChildren();let T=[],k=-1;for(let[H,V]of ke.entries()){let B=m("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");B.type="button";let j=V.artifactType==="markdown"?V.file:void 0,ae=j?Mn(j.path):V.title||V.id.slice(0,8),Ge=j?.path||V.title||ae;B.textContent=ae,B.title=Ge,B.setAttribute("aria-label",Ge),V.id===ne&&(B.classList.add("persona-bg-persona-container","persona-border-persona-border"),k=H),B.addEventListener("click",()=>t.onSelect(V.id)),Z.appendChild(B),T.push(B)}if(de.render(T,k),k>=0&&ne!==Oe){Oe=ne;let H=T[k];typeof H.scrollIntoView=="function"&&H.scrollIntoView({block:"nearest",inline:"nearest"})}Me(Z)}let F=ne&&ke.find(T=>T.id===ne)||ke[ke.length-1];if(!F){He.replaceChildren(),Xe=null,le(!1);return}let v=F.artifactType==="markdown"?F.file:void 0;if(le(!!v),r){let T=v?lo(v):F.artifactType==="markdown"?"MD":F.component??"Component",k=(F.title||"Document").trim(),H=v?Mn(v.path):k.replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ce.textContent=`${H} \xB7 ${T}`}else M.textContent=v?Mn(v.path):s;Xe?(Xe.el.parentElement!==He&&He.replaceChildren(Xe.el),Xe.update(F)):(Xe=_a(F,{config:e,resolveViewMode:ue}),He.replaceChildren(Xe.el)),He.classList.toggle("persona-artifact-content-flush",!!He.querySelector(".persona-code-pre"))},pe=()=>{let X=ke.length>0;if(y.classList.toggle("persona-hidden",!X),b){let v=((typeof y.closest=="function"?y.closest("[data-persona-root]"):null)?.classList.contains("persona-artifact-narrow-host")??!1)||typeof window<"u"&&window.matchMedia("(max-width: 640px)").matches;X&&v&&Be?(b.classList.remove("persona-hidden"),y.classList.add("persona-artifact-drawer-open")):(b.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open"))}},gn=()=>{at=!1,xe(),pe()};return{element:y,backdrop:b,update(X){let E=X.selectedId??X.artifacts[X.artifacts.length-1]?.id??null,F=E!==ne;ke=X.artifacts,ne=E,ke.length>0&&(Be=!0),at=!0,mt&&gn(),F&&Ue()},setMobileOpen(X){Be=X,!X&&b?(b.classList.add("persona-hidden"),y.classList.remove("persona-artifact-drawer-open")):pe()},setExpanded(X){X!==vt&&(vt=X,Ve());let E=te(X?"minimize":"maximize",16,"currentColor",2);E&&we.replaceChildren(E);let F=X?"Collapse artifacts panel":"Expand artifacts panel";we.setAttribute("aria-label",F),we.title=F},setExpandToggleVisible(X){we.classList.toggle("persona-hidden",!X)},setCopyButtonVisible(X){r||Q.classList.toggle("persona-hidden",!X)},setCustomActions(X){se=X,xt()},setTabFade(X){let E=d(X);E.start===c&&E.end===u||(c=E.start,u=E.end,Me(Z))},setRenderTabBar(X){X!==be&&(be=X,ye="",xe())},setVisible(X){X!==mt&&(mt=X,X&&at&&gn())}}}function Gt(e){return e?.features?.artifacts?.enabled===!0}function mg(e,t){if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!Gt(t))return;let n=t.features?.artifacts?.layout,o=n?.paneBorder?.trim(),r=n?.paneBorderLeft?.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):r&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",r))}function Qx(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}var hg=["panel","seamless","detached"];function nc(e){let t=e.features?.artifacts?.layout?.paneAppearance;return t&&hg.includes(t)?t:t?"panel":e.launcher?.detachedPanel?"detached":"panel"}function oc(e){return!e||!Gt(e)?!1:nc(e)==="detached"}function Hs(e,t){if(!Gt(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Qx(e),mg(e,t);return}let n=t.features?.artifacts?.layout,o=nc(t)==="detached"?"var(--persona-panel-inset)":"0";e.style.setProperty("--persona-artifact-split-gap",n?.splitGap??o),e.style.setProperty("--persona-artifact-pane-width",n?.paneWidth??"40%"),e.style.setProperty("--persona-artifact-pane-max-width",n?.paneMaxWidth??"28rem"),n?.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=n?.paneBackground?.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=n?.panePadding?.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let a=n?.documentToolbarIconColor?.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let i=n?.documentToolbarToggleActiveBackground?.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let p=n?.documentToolbarToggleActiveBorderColor?.trim();p?e.style.setProperty("--persona-artifact-doc-toggle-active-border",p):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),mg(e,t)}function Bs(e,t){for(let i of hg)e.classList.remove(`persona-artifact-appearance-${i}`);if(e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-chat-shadow"),!Gt(t))return;let n=t.features?.artifacts?.layout,o=nc(t);e.classList.add(`persona-artifact-appearance-${o}`);let r=n?.paneBorderRadius?.trim();r&&e.style.setProperty("--persona-artifact-pane-radius",r);let s=n?.paneShadow?.trim();s&&e.style.setProperty("--persona-artifact-pane-shadow",s);let a=n?.chatShadow?.trim();a&&e.style.setProperty("--persona-artifact-chat-shadow",a)}function yg(e,t){return!t||!Gt(e)?!1:e.features?.artifacts?.layout?.expandLauncherPanelWhenOpen!==!1}function Yx(e,t){if(!e?.trim())return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Zx(e){if(!e?.trim())return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function eC(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function tC(e,t,n,o){let r=e-o-2*t-n;return Math.max(0,r)}function rc(e,t){let o=(t.getComputedStyle(e).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 bg(e,t,n,o,r,s){let a=Yx(r,200),i=tC(t,n,o,200);i=Math.max(a,i);let p=Zx(s);return p!==null&&(i=Math.min(i,p)),eC(e,a,i)}var vg={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},sc=(e,t,n,o)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{if(s.dataset.enhanced==="true")return;let a=s.dataset.tvForm??"init";s.dataset.enhanced="true";let i=vg[a]??vg.init;s.classList.add("persona-form-card","persona-space-y-4");let p=m("div","persona-space-y-1"),d=m("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(d.textContent=i.title,p.appendChild(d),i.description){let y=m("p","persona-text-sm persona-text-persona-muted");y.textContent=i.description,p.appendChild(y)}let c=document.createElement("form");c.className="persona-form-grid persona-space-y-3",i.fields.forEach(y=>{let C=m("label","persona-form-field persona-flex persona-flex-col persona-gap-1");C.htmlFor=`${t.id}-${a}-${y.name}`;let M=m("span","persona-text-xs persona-font-medium persona-text-persona-muted");M.textContent=y.label,C.appendChild(M);let L=y.type??"text",I;L==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=L),I.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",I.id=`${t.id}-${a}-${y.name}`,I.name=y.name,I.placeholder=y.placeholder??"",y.required&&(I.required=!0),C.appendChild(I),c.appendChild(C)});let u=m("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),b=m("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=m("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=i.submitLabel??"Submit",u.appendChild(b),u.appendChild(g),c.appendChild(u),s.replaceChildren(p,c),c.addEventListener("submit",async y=>{y.preventDefault();let C=n.formEndpoint??"/form",M=new FormData(c),L={};M.forEach((I,S)=>{L[S]=I}),L.type=a,g.disabled=!0,b.textContent="Submitting\u2026";try{let I=await fetch(C,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let S=await I.json();b.textContent=S.message??"Thanks! We'll be in touch soon.",S.success&&S.nextPrompt&&await o.sendMessage(String(S.nextPrompt))}catch(I){b.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var ac=class{constructor(){this.plugins=new Map}register(t){this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),t.onRegister?.()}unregister(t){let n=this.plugins.get(t);n&&(n.onUnregister?.(),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>(n.priority??0)-(t.priority??0))}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let o=new Set(t.map(s=>s.id));return[...n.filter(s=>!o.has(s.id)),...t].sort((s,a)=>(a.priority??0)-(s.priority??0))}clear(){this.plugins.forEach(t=>t.onUnregister?.()),this.plugins.clear()}},ai=new ac;var xg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),nC=new Set(["headers","agent","storageAdapter","components","targetProviders","voiceRecognition.provider.custom","features.streamAnimation.plugins"]),Cg=(e,t,n)=>{if(!xg(e)||!xg(t)||nC.has(n))return t;let o={...e};for(let r of Object.keys(t)){if(t[r]===void 0){delete o[r];continue}let s=n?`${n}.${r}`:r;o[r]=Cg(e[r],t[r],s)}return o};function ii(e,t){let n=Cg(e,t,"");return hs(n)}var wg=()=>{let e=new Map,t=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>n(r,s)),n=(r,s)=>{e.get(r)?.delete(s)};return{on:t,off:n,emit:(r,s)=>{e.get(r)?.forEach(a=>{try{a(s)}catch(i){typeof console<"u"&&console.error("[AgentWidget] Event handler error:",i)}})}}};var oC=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},rC=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let o=0;for(let r=n;r<t.length;r+=1){let s=t[r];if(s==="{"&&(o+=1),s==="}"&&(o-=1,o===0))return t.slice(n,r+1)}return null},li=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=oC(e),n=rC(t);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}},ic=e=>typeof e=="string"?e:e==null?"":String(e),Er={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ic(e.payload.text)},messageAndClick:(e,t)=>{if(e.type!=="message_and_click")return;let n=e.payload,o=ic(n.element);if(o&&t.document?.querySelector){let r=t.document.querySelector(o);r?setTimeout(()=>{r.click()},400):typeof console<"u"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:ic(n.text)}}},Ag=e=>Array.isArray(e)?e.map(t=>String(t)):[],ci=e=>{let t=new Set(Ag(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Ag(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console<"u"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((d,c)=>d||c?.({text:a,message:s.message})||null,null):null;if(!i)return null;t.add(s.message.id),o();let p={action:i,message:s.message};e.emit("action:detected",p);for(let d of e.handlers)if(d)try{let c=()=>{e.emit("action:resubmit",p)},u=d(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:c});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(c){typeof console<"u"&&console.error("[AgentWidget] Action handler error:",c)}return{text:"",persist:!0}},syncFromMetadata:n}};var sC=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console<"u"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},aC=e=>e.map(t=>({...t,streaming:!1})),iC=e=>e.map(t=>({...t,status:"complete"})),lc=(e="persona-state")=>{let t=()=>typeof window>"u"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?sC(n.getItem(e)):null},save:n=>{let o=t();if(o)try{let r={...n,messages:n.messages?aC(n.messages):void 0,artifacts:n.artifacts?iC(n.artifacts):void 0};o.setItem(e,JSON.stringify(r))}catch(r){typeof console<"u"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(o){typeof console<"u"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};import{parse as lC,STR as cC,OBJ as dC}from"partial-json";function pC(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function uC(e,t){if(!pC(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function cc(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let o=n.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(n.length<=t)return e;try{let r=lC(n,cC|dC),s=uC(r,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function gC(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function dc(e,t){let{config:n,message:o,onPropsUpdate:r}=t,s=kn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:o,config:n,updateProps:i=>{r&&r(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function fC(){let e=cc();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Sg(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function di(e){let t=Sg(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function pc(e){let t=Sg(e);if(!t)return null;try{let n=JSON.parse(t);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:t}}}catch{}return null}var mC=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function uc(e){let{onSubmit:t,onDismiss:n,title:o="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,ratingLabels:d=mC}=e,c=document.createElement("div");c.className="persona-feedback-container persona-feedback-csat",c.setAttribute("role","dialog"),c.setAttribute("aria-label","Customer satisfaction feedback");let u=null,b=document.createElement("div");b.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=o,g.appendChild(y);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=r,g.appendChild(C),b.appendChild(g);let M=document.createElement("div");M.className="persona-feedback-rating persona-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let L=[];for(let z=1;z<=5;z++){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",`${z} star${z>1?"s":""}: ${d[z-1]}`),w.title=d[z-1],w.dataset.rating=String(z),w.innerHTML=`
45
45
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
46
46
  <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>
47
47
  </svg>
48
- `,w.addEventListener("click",()=>{u=z,L.forEach((U,q)=>{let Q=q<z;U.classList.toggle("selected",Q),U.setAttribute("aria-checked",q===z-1?"true":"false")})}),L.push(w),M.appendChild(w)}b.appendChild(M);let I=null;if(p){let z=document.createElement("div");z.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=s,I.rows=3,I.setAttribute("aria-label","Additional comments"),z.appendChild(I),b.appendChild(z)}let S=document.createElement("div");S.className="persona-feedback-actions";let R=document.createElement("button");R.type="button",R.className="persona-feedback-btn persona-feedback-btn-skip",R.textContent=i,R.addEventListener("click",()=>{n?.(),c.remove()});let $=document.createElement("button");return $.type="button",$.className="persona-feedback-btn persona-feedback-btn-submit",$.textContent=a,$.addEventListener("click",async()=>{if(u===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}$.disabled=!0,$.textContent="Submitting...";try{let z=I?.value.trim()||void 0;await t(u,z),c.remove()}catch(z){$.disabled=!1,$.textContent=a,console.error("[CSAT Feedback] Failed to submit:",z)}}),S.appendChild(R),S.appendChild($),b.appendChild(S),c.appendChild(b),c}function gc(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,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,g=document.createElement("div");g.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,y.appendChild(C);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,y.appendChild(M),g.appendChild(y);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let S=document.createElement("span");S.className="persona-feedback-label-low",S.textContent=d;let R=document.createElement("span");R.className="persona-feedback-label-high",R.textContent=c,I.appendChild(S),I.appendChild(R);let $=document.createElement("div");$.className="persona-feedback-numbers";let z=[];for(let O=0;O<=10;O++){let D=document.createElement("button");D.type="button",D.className="persona-feedback-rating-btn persona-feedback-number-btn",D.setAttribute("role","radio"),D.setAttribute("aria-checked","false"),D.setAttribute("aria-label",`Rating ${O} out of 10`),D.textContent=String(O),D.dataset.rating=String(O),O<=6?D.classList.add("persona-feedback-detractor"):O<=8?D.classList.add("persona-feedback-passive"):D.classList.add("persona-feedback-promoter"),D.addEventListener("click",()=>{b=O,z.forEach((ie,me)=>{ie.classList.toggle("selected",me===O),ie.setAttribute("aria-checked",me===O?"true":"false")})}),z.push(D),$.appendChild(D)}L.appendChild(I),L.appendChild($),g.appendChild(L);let w=null;if(p){let O=document.createElement("div");O.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"),O.appendChild(w),g.appendChild(O)}let U=document.createElement("div");U.className="persona-feedback-actions";let q=document.createElement("button");q.type="button",q.className="persona-feedback-btn persona-feedback-btn-skip",q.textContent=i,q.addEventListener("click",()=>{n?.(),u.remove()});let Q=document.createElement("button");return Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-submit",Q.textContent=a,Q.addEventListener("click",async()=>{if(b===null){$.classList.add("persona-feedback-shake"),setTimeout(()=>$.classList.remove("persona-feedback-shake"),500);return}Q.disabled=!0,Q.textContent="Submitting...";try{let O=w?.value.trim()||void 0;await t(b,O),u.remove()}catch(O){Q.disabled=!1,Q.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),U.appendChild(q),U.appendChild(Q),g.appendChild(U),u.appendChild(g),u}var Mr="persona-chat-history",mC=30*1e3,hC=641,yC={"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 bC(e){if(!e)return[];let t=[],n=Array.from(e.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){t.push(r);continue}let s=yC[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function pi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function vC(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function xC(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var fc=e=>!e||typeof e!="object"?{}:{...e},Sg=e=>e.map(t=>({...t,streaming:!1})),Tg=(e,t,n)=>{let o=e?.markdown?cr(e.markdown):null,r=Zr(e?.sanitize);return e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{let a=s.text??"",i=s.message.rawContent??null;if(t){let c=t.process({text:a,raw:i??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let p=Fn()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...s,text:a,raw:i??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?Gd(a):a,u=o(c);d=r&&p?r(u):u}else d=_n(a);return d}};function Eg(e){let t=m("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=te(n,o,r,s);if(a&&t.appendChild(a),e?.label){let i=m("span","persona-drop-overlay-label");i.textContent=e.label,t.appendChild(i)}return t}var CC=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},wC=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:CC(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),mc=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=hs(t),r=ai.getForInstance(o.plugins),{plugin:s,teardown:a}=ig();o.components&&Ln.registerAll(o.components);let i=Cg(),d=o.persistState===!1?null:o.storageAdapter??lc(),c={},u=null,b=!1,g=l=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(l);if(f&&typeof f=="object"&&"state"in f){let{state:h,open:x}=f;return x&&(b=!0),h}return f}catch(f){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return l};if(d?.load)try{let l=d.load();if(l&&typeof l.then=="function")u=l.then(f=>g(f??{messages:[],metadata:{}}));else{let h=g(l??{messages:[],metadata:{}});h.metadata&&(c=fc(h.metadata)),h.messages?.length&&(o={...o,initialMessages:h.messages}),h.artifacts?.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:h.selectedArtifactId??null})}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=g({messages:[],metadata:{}});l.messages?.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let y=()=>c,C=l=>{c=l({...c})??{},Oi()},M=o.actionParsers&&o.actionParsers.length?o.actionParsers:[li],L=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Er.message,Er.messageAndClick],I=ci({parsers:M,handlers:L,getSessionMetadata:y,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null});I.syncFromMetadata();let S=o.launcher?.enabled??!0,R=o.launcher?.autoExpand??!1,$=o.autoFocusInput??!1,z=R,w=S,U=o.layout?.header?.layout,q=!1,Q=()=>ho(o),O=()=>S||Q(),D=Q()?!1:S?R:!0,ie=!1,me=null,we=()=>{ie=!0,me&&clearTimeout(me),me=setTimeout(()=>{ie&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ie=!1)},1e4)},Ee=Tg(o,I,we),se=o.features?.showReasoning??!0,fe=o.features?.showToolCalls??!0,Y=o.features?.showEventStreamToggle??!1,ce=o.features?.scrollToBottom??{},Z=o.features?.scrollBehavior??{},he=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,de=Y?new Is(he):null,Me=o.features?.eventStream?.maxEvents??2e3,De=Y?new Rs(Me,de):null,_e=Y?new Ws:null,He=null,Ue=!1,Ve=null,ke=0;de?.open().then(()=>De?.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ne={onCopy:l=>{i.emit("message:copy",l),_?.isClientTokenMode()&&_.submitMessageFeedback(l.id,"copy").catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",f)}),o.messageActions?.onCopy?.(l)},onFeedback:l=>{i.emit("message:feedback",l),_?.isClientTokenMode()&&_.submitMessageFeedback(l.messageId,l.type).catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",f)}),o.messageActions?.onFeedback?.(l)}},Be=o.statusIndicator??{},vt=l=>l==="idle"?Be.idleText??It.idle:l==="connecting"?Be.connectingText??It.connecting:l==="connected"?Be.connectedText??It.connected:l==="error"?Be.errorText??It.error:l==="paused"?Be.pausedText??It.paused:l==="resuming"?Be.resumingText??It.resuming:It[l];function mt(l,f,h,x){if(x==="idle"&&h.idleLink){l.textContent="";let A=document.createElement("a");A.href=h.idleLink,A.target="_blank",A.rel="noopener noreferrer",A.textContent=f,A.style.color="inherit",A.style.textDecoration="none",l.appendChild(A)}else l.textContent=f}let at=qu({config:o,showClose:O()}),{wrapper:Oe,panel:ye,pillRoot:Xe}=at.shell,Le=at.panelElements,{container:ue,body:le,messagesWrapper:ve,suggestions:xt,textarea:xe,sendButton:pe,sendButtonWrapper:gn,composerForm:X,statusText:E,introTitle:F,introSubtitle:v,closeButton:T,iconHolder:k,headerTitle:H,headerSubtitle:V,header:B,footer:j,actionsRow:ae,rightActions:Ge}=Le,Te=Le.leftActions,rt=Le.setSendButtonMode,K=Le.micButton,ze=Le.micButtonWrapper,Ae=Le.attachmentButton,We=Le.attachmentButtonWrapper,Pe=Le.attachmentInput,Ye=Le.attachmentPreviewsContainer;ue.classList.add("persona-relative"),le.classList.add("persona-relative");let vo=12,xo=()=>ce.label??"",xi=()=>ce.iconName??"arrow-down",Ds=()=>ce.enabled!==!1,Jt=()=>Z.mode??"anchor-top",zn=()=>Jt()==="follow"||Jt()==="anchor-top"&&Or,Ec=()=>Z.anchorTopOffset??16,cf=()=>Z.restorePosition??"bottom",Mc=()=>Z.pauseOnInteraction===!0,kc=()=>Z.showActivityWhilePinned!==!1,Lc=()=>Z.announce===!0,kt=m("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");kt.type="button",kt.style.display="none",kt.setAttribute("data-persona-scroll-to-bottom","true");let kr=m("span","persona-flex persona-items-center"),Ci=m("span",""),Co=m("span","");Co.setAttribute("data-persona-scroll-to-bottom-count",""),Co.style.display="none",kt.append(kr,Ci,Co),ue.appendChild(kt);let qn=m("div","persona-stream-anchor-spacer");qn.setAttribute("aria-hidden","true"),qn.setAttribute("data-persona-anchor-spacer",""),qn.style.flexShrink="0",qn.style.pointerEvents="none",qn.style.height="0px",le.appendChild(qn);let wo=m("div","persona-sr-only");wo.setAttribute("aria-live","polite"),wo.setAttribute("aria-atomic","true"),wo.setAttribute("role","status"),wo.setAttribute("data-persona-live-region",""),Object.assign(wo.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"}),ue.appendChild(wo);let Lr=null,Ns=null,Pc=l=>{!Lc()||!l||(Ns=l,Lr===null&&(Lr=setTimeout(()=>{Lr=null,Ns&&Lc()&&(wo.textContent=Ns),Ns=null},400)))},Jo=()=>{let f=j.style.display==="none"?0:j.offsetHeight;kt.style.bottom=`${f+vo}px`};Jo();let Rc=()=>{let l=!!xo();kt.setAttribute("aria-label",xo()||"Jump to latest"),kt.title=xo(),kt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),kr.innerHTML="";let f=te(xi(),"14px","currentColor",2);f?(kr.appendChild(f),kr.style.display=""):kr.style.display="none",Ci.textContent=xo(),Ci.style.display=l?"":"none"};Rc();let St=null,Yt=null,Ic=null,Wc=r.find(l=>l.renderHeader);if(Wc?.renderHeader){let l=Wc.renderHeader({config:o,defaultRenderer:()=>{let f=yo({config:o,showClose:O()});return Cr(ue,f,o),f.header},onClose:()=>pt(!1,"user")});if(l){let f=ue.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(l),B=l,at.header.element=l)}}let wi=()=>{if(!De)return;if(Ue=!0,!He&&De&&(He=ug({buffer:De,getFullHistory:()=>De.getAllFromStore(),onClose:()=>Pr(),config:o,plugins:r,getThroughput:()=>_e?.getMetric()??{status:"idle"}})),He&&(le.style.display="none",j.parentNode?.insertBefore(He.element,j),He.update()),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${Kt.actionIconColor}`;let f=o.features?.eventStream?.classNames?.toggleButtonActive;f&&f.split(/\s+/).forEach(h=>h&&tt.classList.add(h))}let l=()=>{if(!Ue)return;let f=Date.now();f-ke>=200&&(He?.update(),ke=f),Ve=requestAnimationFrame(l)};ke=0,Ve=requestAnimationFrame(l),en(),i.emit("eventStream:opened",{timestamp:Date.now()})},Pr=()=>{if(Ue){if(Ue=!1,He&&He.element.remove(),le.style.display="",tt){tt.style.boxShadow="";let l=o.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(f=>f&&tt.classList.remove(f))}Ve!==null&&(cancelAnimationFrame(Ve),Ve=null),en(),i.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(Y){let l=o.features?.eventStream?.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l?.toggleButton?" "+l.toggleButton:"");tt=m("button",f),tt.style.width="28px",tt.style.height="28px",tt.style.color=Kt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let h=te("activity","18px","currentColor",1.5);h&&tt.appendChild(h);let x=Le.clearChatButtonWrapper,A=Le.closeButtonWrapper,P=x||A;P&&P.parentNode===B?B.insertBefore(tt,P):B.appendChild(tt),tt.addEventListener("click",()=>{Ue?Pr():wi()})}let df=l=>{let f=o.attachments;if(!f?.enabled)return;let h=l.querySelector("[data-persona-composer-attachment-previews]")??l.querySelector(".persona-attachment-previews");if(!h){h=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let A=l.querySelector("[data-persona-composer-form]");A?.parentNode?A.parentNode.insertBefore(h,A):l.insertBefore(h,l.firstChild)}if(!(l.querySelector("[data-persona-composer-attachment-input]")??l.querySelector('input[type="file"]'))){let A=m("input");A.type="file",A.setAttribute("data-persona-composer-attachment-input",""),A.accept=(f.allowedTypes??jn).join(","),A.multiple=(f.maxFiles??4)>1,A.style.display="none",A.setAttribute("aria-label",f.buttonTooltipText??"Attach files"),l.appendChild(A)}},Hc=r.find(l=>l.renderComposer);if(Hc?.renderComposer){let l=o.composer,f=Hc.renderComposer({config:o,defaultRenderer:()=>Ls({config:o}).footer,onSubmit:h=>{if(!_||_.isStreaming())return;let x=h.trim(),A=St?.hasAttachments()??!1;if(!x&&!A)return;cd();let P;A&&(P=[],P.push(...St.getContentParts()),x&&P.push(Fo(x))),_.sendMessage(x,{contentParts:P}),A&&St.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Pe?.click()},models:l?.models,selectedModelId:l?.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Ic?.()}:void 0});f&&(at.replaceComposer(f),j=at.composer.footer)}let pf=l=>{let f=(...ge)=>{for(let oe of ge){let Ce=l.querySelector(oe);if(Ce)return Ce}return null},h=l.querySelector("[data-persona-composer-form]"),x=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),P=l.querySelector("[data-persona-composer-mic]"),J=l.querySelector("[data-persona-composer-status]");h&&(X=h),x&&(xe=x),A&&(pe=A),P&&(K=P,ze=P.parentElement),J&&(E=J);let N=f("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(xt=N);let G=f("[data-persona-composer-attachment-button]",".persona-attachment-button");G&&(Ae=G,We=G.parentElement),Pe=f("[data-persona-composer-attachment-input]",'input[type="file"]'),Ye=f("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let re=f("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");re&&(ae=re),Te=f(".persona-widget-composer__left-actions")};df(j),pf(j);let Vn=o.layout?.contentMaxWidth??(Q()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(Vn&&(ve.style.maxWidth=Vn,ve.style.marginLeft="auto",ve.style.marginRight="auto",ve.style.width="100%"),Vn&&X&&!Q()&&(X.style.maxWidth=Vn,X.style.marginLeft="auto",X.style.marginRight="auto"),Vn&&xt&&!Q()&&(xt.style.maxWidth=Vn,xt.style.marginLeft="auto",xt.style.marginRight="auto"),Vn&&Ye&&!Q()&&(Ye.style.maxWidth=Vn,Ye.style.marginLeft="auto",Ye.style.marginRight="auto"),o.attachments?.enabled&&Pe&&Ye){St=mr.fromConfig(o.attachments),St.setPreviewsContainer(Ye),Pe.addEventListener("change",h=>{let x=h.target;St?.handleFileSelect(x.files),x.value=""});let l=o.attachments.dropOverlay,f=Eg(l);ue.appendChild(f)}let uf=()=>Yt?.prefetch();if(o.contextMentions?.enabled&&xe&&(Yt=Yp({config:o,textarea:xe,anchor:X??xe,getMessages:()=>_.getMessages(),liveRegionHost:ue}),Yt)){let l=xe;l.parentElement?.insertBefore(Yt.contextRow,l);let f=Yt.affordanceButtons;for(let h=f.length-1;h>=0;h--){let x=f[h];Te?Te.insertBefore(x,Te.firstChild):X?.appendChild(x)}}(()=>{let l=o.layout?.slots??{},f=x=>{switch(x){case"body-top":return ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ve;case"footer-top":return xt;case"composer":return X;case"footer-bottom":return E;default:return null}},h=(x,A)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")B.insertBefore(A,B.firstChild);else if(x==="header-right")B.appendChild(A);else{let P=B.querySelector(".persona-flex-col");P?P.parentNode?.insertBefore(A,P.nextSibling):B.appendChild(A)}break;case"body-top":{let P=le.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");P?P.replaceWith(A):le.insertBefore(A,le.firstChild);break}case"body-bottom":le.appendChild(A);break;case"footer-top":xt.replaceWith(A);break;case"footer-bottom":E.replaceWith(A);break;default:break}};for(let[x,A]of Object.entries(l))if(A)try{let P=A({config:o,defaultContent:()=>f(x)});P&&h(x,P)}catch(P){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,P)}})();let Bc=l=>{let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let x=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let P=h.getAttribute("data-bubble-type");if(P==="reasoning")Ar.has(A)?Ar.delete(A):Ar.add(A),Yu(A,x);else if(P==="tool")Sr.has(A)?Sr.delete(A):Sr.add(A),Zu(A,x,o);else if(P==="approval"){let N=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",G=Vo.get(A)??N;Vo.set(A,!G),og(A,x,o)}Eo.delete(A)};ve.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Bc(l))}),ve.addEventListener("keydown",l=>{let f=l.target;(l.key==="Enter"||l.key===" ")&&f.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Bc(l))}),ve.addEventListener("copy",l=>{let{clipboardData:f}=l;if(!f)return;let h=ve.getRootNode(),x=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let A=x.toString(),P=Tu(A);!P||P===A||(f.setData("text/plain",P),l.preventDefault())});let Ai=new Map,Oc=null,Dc="idle",gf={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},ff=(l,f)=>{let{icon:h,label:x}=gf[f];l.setAttribute("aria-label",x),l.title=x,l.setAttribute("aria-pressed",f==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",f!=="idle"),l.classList.toggle("persona-message-action-loading",f==="loading");let A=te(h,14,"currentColor",2);A&&(l.innerHTML="",l.appendChild(A))},Nc=()=>{ve.querySelectorAll('[data-action="read-aloud"]').forEach(f=>{let x=f.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;ff(f,x&&x===Oc?Dc:"idle")})};ve.addEventListener("click",l=>{let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest("[data-actions-for]");if(!x)return;let A=x.getAttribute("data-actions-for");if(!A)return;let P=h.getAttribute("data-action");if(P==="copy"){let N=_.getMessages().find(G=>G.id===A);if(N&&ne.onCopy){let G=N.content||"";navigator.clipboard.writeText(G).then(()=>{h.classList.add("persona-message-action-success");let re=te("check",14,"currentColor",2);re&&(h.innerHTML="",h.appendChild(re)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let ge=te("copy",14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge))},2e3)}).catch(re=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",re)}),ne.onCopy(N)}}else if(P==="read-aloud")_.toggleReadAloud(A);else if(P==="upvote"||P==="downvote"){let N=(Ai.get(A)??null)===P,G=P==="upvote"?"thumbs-up":"thumbs-down";if(N){Ai.delete(A),h.classList.remove("persona-message-action-active");let re=te(G,14,"currentColor",2);re&&(h.innerHTML="",h.appendChild(re))}else{let re=P==="upvote"?"downvote":"upvote",ge=x.querySelector(`[data-action="${re}"]`);if(ge){ge.classList.remove("persona-message-action-active");let nt=te(re==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);nt&&(ge.innerHTML="",ge.appendChild(nt))}Ai.set(A,P),h.classList.add("persona-message-action-active");let oe=te(G,14,"currentColor",2);oe&&(oe.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(oe)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ke=_.getMessages().find(ut=>ut.id===A);Ke&&ne.onFeedback&&ne.onFeedback({type:P,messageId:Ke.id,message:Ke})}}}),ve.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest(".persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let P=h.getAttribute("data-approval-action");if(!P)return;let J=P==="approve"?"approved":"denied",G=_.getMessages().find(ge=>ge.id===A);if(!G?.approval)return;let re=x.querySelector("[data-approval-buttons]");re&&re.querySelectorAll("button").forEach(oe=>{oe.disabled=!0,oe.style.opacity="0.5",oe.style.cursor="not-allowed"}),G.approval.toolType==="webmcp"?_.resolveWebMcpApproval(A,J):_.resolveApproval(G.approval,J)});let Ze=null,Rr=null,Ir=()=>{},Wr="none",Fs=null,fn={artifacts:[],selectedId:null},In=!1,mn=!1,Hr=!1,Xo=!1,Fc=()=>Xo||fn.artifacts.some(l=>Bo(o.features?.artifacts,l.artifactType)==="panel"),_s=()=>fn.artifacts.length>0&&!In&&Fc(),lt={current:null},Si=(l,f)=>{let h=_.getArtifactById(f),x=h?.markdown,A=h?.title||"artifact",P=h?.file,J=h?.artifactType??"markdown";if(!x){let re=l.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(re){let oe=_.getMessages().find(Ce=>Ce.id===re);if(oe?.rawContent)try{let Ce=JSON.parse(oe.rawContent);x=Ce?.props?.markdown,A=Ce?.props?.title||A,Ce?.props?.file&&typeof Ce.props.file=="object"&&(P=Ce.props.file),!h&&typeof Ce?.props?.artifactType=="string"&&(J=Ce.props.artifactType)}catch{}}}return{markdown:x,title:A,file:P,artifactType:J}};ve.addEventListener("click",l=>{let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:P,title:J,file:N}=Si(h,x);if(!P)return;let{filename:G,mime:re,content:ge}=lu({title:J,markdown:P,file:N}),oe=new Blob([ge],{type:re}),Ce=URL.createObjectURL(oe),Ke=document.createElement("a");Ke.href=Ce,Ke.download=G,Ke.click(),URL.revokeObjectURL(Ce)}),ve.addEventListener("click",l=>{let h=l.target.closest("[data-artifact-custom-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-artifact-custom-action");if(!x)return;let A=h.closest("[data-artifact-inline]"),P=A?null:h.closest("[data-open-artifact]"),J=A?A.getAttribute("data-artifact-inline"):P?.getAttribute("data-open-artifact")??null,G=(A?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ut=>ut.id===x);if(!G)return;let{markdown:re,title:ge,file:oe,artifactType:Ce}=Si(h,J??""),Ke={artifactId:J,title:ge,artifactType:Ce,markdown:re,file:oe};try{Promise.resolve(G.onClick(Ke)).catch(()=>{})}catch{}}),ve.addEventListener("click",l=>{let h=l.target.closest("[data-copy-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-copy-artifact");if(!x)return;let A=_.getArtifactById(x),P="";if(A)P=Cs(A);else{let{markdown:J,file:N,artifactType:G}=Si(h,x);G==="markdown"&&(P=Cs({id:x,artifactType:"markdown",status:"complete",markdown:J??"",...N?{file:N}:{}}))}P&&navigator.clipboard.writeText(P).then(()=>{let J=te("check",16,"currentColor",2);J&&(h.replaceChildren(J),setTimeout(()=>{let N=te("copy",16,"currentColor",2);N&&h.replaceChildren(N)},1500))}).catch(()=>{})}),ve.addEventListener("click",l=>{let h=l.target.closest("[data-expand-artifact-inline]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(In=!1,Xo=!0,mn=!0,Hr=!0,_.selectArtifact(x),Wn())}),ve.addEventListener("click",l=>{let f=l.target;if(f.closest("[data-download-artifact]")||f.closest("[data-artifact-custom-action]"))return;let h=f.closest("[data-open-artifact]");if(!h)return;let x=h.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(l.preventDefault(),l.stopPropagation(),In=!1,Xo=!0,_.selectArtifact(x),Wn())}),ve.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let f=l.target;!f.hasAttribute("data-open-artifact")&&!f.hasAttribute("data-expand-artifact-inline")||(l.preventDefault(),f.click())});let Qo=Le.composerOverlay,Yo=(l,f,h)=>{let x=f.trim();if(!x||!lt.current)return;let A=l.getAttribute("data-tool-call-id")??"",P=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:x,answers:h.structured,values:h.values??(h.source==="multi"?x.split(", "):[x]),isFreeText:P,source:h.source},bubbles:!0,composed:!0})),Do(Qo,A);let J=lt.current.getMessages().find(N=>N.toolCall?.id===A);J?.agentMetadata?.awaitingLocalTool?lt.current.resolveAskUserQuestion(J,h.structured??x):lt.current.sendMessage(x)},Ao=l=>{let f=lt.current;if(!f)return;let h=l.getAttribute("data-tool-call-id")??"",x=f.getMessages().find(A=>A.toolCall?.id===h);x&&f.persistAskUserQuestionProgress(x,{answers:ha(l,x),currentIndex:pn(l)})},_c=l=>Object.entries(l).map(([f,h])=>`${f}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Ti=l=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let f=pn(l),h=pr(l);if(f>=h-1)return;let x=lt.current?.getMessages().find(A=>A.toolCall?.id===l.getAttribute("data-tool-call-id"));x&&(ya(l,x,o,f+1),Ao(l))};Qo.addEventListener("click",l=>{let h=l.target.closest("[data-ask-user-action]");if(!h)return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;let A=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),A==="dismiss"){let P=x.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:P},bubbles:!0,composed:!0})),Do(Qo,P);let J=lt.current?.getMessages().find(N=>N.toolCall?.id===P);J?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(J),lt.current?.resolveAskUserQuestion(J,"(dismissed)"));return}if(A==="pick"){let P=h.getAttribute("data-option-label");if(!P)return;let J=x.getAttribute("data-multi-select")==="true",N=so(x);if(N&&J){let G=Oo(x)[pn(x)],re=new Set(Array.isArray(G)?G:[]);re.has(P)?re.delete(P):re.add(P),ao(x,Array.from(re)),Ao(x);return}if(N){ao(x,P),Ao(x),Ti(x);return}if(J){let G=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",G?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!G);let re=x.querySelector('[data-ask-user-action="submit-multi"]');re&&(re.disabled=ll(x).length===0);return}Yo(x,P,{source:"pick",values:[P]});return}if(A==="submit-multi"){let P=ll(x);if(P.length===0)return;Yo(x,P.join(", "),{source:"multi",values:P});return}if(A==="open-free-text"){let P=x.querySelector('[data-ask-free-text-row="true"]');P&&(P.classList.remove("persona-hidden"),P.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(A==="focus-free-text"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(A==="submit-free-text"){let J=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!J.trim())return;if(so(x)){ao(x,J.trim()),Ao(x),Ti(x);return}Yo(x,J,{source:"free-text"});return}if(A==="next"||A==="back"){if(!lt.current)return;let P=x.getAttribute("data-tool-call-id")??"",J=lt.current.getMessages().find(oe=>oe.toolCall?.id===P);if(!J)return;let G=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(G){let oe=Oo(x)[pn(x)];(typeof oe!="string"||oe!==G)&&ao(x,G)}let re=A==="next"?1:-1,ge=pn(x)+re;ya(x,J,o,ge),Ao(x);return}if(A==="submit-all"){if(!lt.current)return;let P=x.getAttribute("data-tool-call-id")??"",J=lt.current.getMessages().find(oe=>oe.toolCall?.id===P);if(!J)return;let G=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";G&&ao(x,G);let re=ha(x,J);lt.current.persistAskUserQuestionProgress(J,{answers:re,currentIndex:pn(x)});let ge=_c(re);Yo(x,ge||"(submitted)",{source:"submit-all",structured:re});return}if(A==="skip"){if(!lt.current)return;let P=x.getAttribute("data-tool-call-id")??"",J=lt.current.getMessages().find(Ce=>Ce.toolCall?.id===P);if(!J)return;let N=so(x),G=pn(x),re=pr(x),ge=G>=re-1;if(!N){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:P},bubbles:!0,composed:!0})),Do(Qo,P),J.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(J),lt.current.resolveAskUserQuestion(J,"(dismissed)"));return}ao(x,"");let oe=x.querySelector('[data-ask-free-text-input="true"]');if(oe&&(oe.value=""),ge){let Ce=ha(x,J),Ke=_c(Ce);Yo(x,Ke||"(skipped)",{source:"submit-all",structured:Ce});return}ya(x,J,o,G+1),Ao(x);return}}),Qo.addEventListener("keydown",l=>{if(l.key!=="Enter")return;let h=l.target;if(!h.matches?.('[data-ask-free-text-input="true"]'))return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;l.preventDefault();let A=h.value;if(A.trim()){if(so(x)){ao(x,A.trim()),Ao(x),Ti(x);return}Yo(x,A,{source:"free-text"})}});let $c=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let f=l.target;if(f?.tagName==="INPUT"||f?.tagName==="TEXTAREA"||f?.isContentEditable)return;let h=Qo.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let x=Number(l.key),P=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];P&&(l.preventDefault(),P.click())};document.addEventListener("keydown",$c);let Kn=null,Ct=null,Br=null,$s=null,Ei=()=>{},jc=!1,js="",Us="";function Mi(){$s?.(),$s=null}let Uc=()=>{if(!Kn||!Ct)return;let l=e.classList.contains("persona-artifact-welded-split"),f=e.ownerDocument.defaultView??window,h=f.innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){Ct.style.removeProperty("position"),Ct.style.removeProperty("left"),Ct.style.removeProperty("top"),Ct.style.removeProperty("bottom"),Ct.style.removeProperty("width"),Ct.style.removeProperty("z-index");return}let x=Kn.firstElementChild;if(!x||x===Ct)return;let A=10;Ct.style.position="absolute",Ct.style.top="0",Ct.style.bottom="0",Ct.style.width=`${A}px`,Ct.style.zIndex="5";let P=rc(Kn,f),J=x.offsetWidth+P/2-A/2;Ct.style.left=`${Math.max(0,J)}px`},zs=()=>{},mf=()=>{let l=e.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,h=o.launcher?.mobileBreakpoint??640;return!f||l.innerWidth>h?!1:S||Wt(o)},qs=()=>!Gt(o)||!_s()||e.classList.contains("persona-artifact-narrow-host")||mf()||(e.ownerDocument.defaultView??window).innerWidth<hC?"none":oc(o)?"detached":"welded",Wn=()=>{if(!Ze||!Gt(o))return;Hs(e,o),Bs(e,o),zs();let l=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,f=ye.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=l);let h=_s();Ze.setVisible(h),Ze.update(fn),In?(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),Ze.backdrop?.classList.add("persona-hidden"),mn=!1,Hr=!1):fn.artifacts.length>0&&Fc()?(Ze.element.classList.remove("persona-hidden"),Ze.setMobileOpen(!0)):(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),Ze.backdrop?.classList.add("persona-hidden"),mn=!1,Hr=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ze.setExpandToggleVisible(x),Ze.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ze.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ze.setTabFade(o.features?.artifacts?.layout?.tabFade),Ze.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!Hr&&(mn=!1),mn!==jc){let P=Ze.element;mn?(js=P.style.width,Us=P.style.maxWidth,P.style.removeProperty("width"),P.style.removeProperty("max-width")):(js&&(P.style.width=js),Us&&(P.style.maxWidth=Us),js="",Us=""),jc=mn}e.classList.toggle("persona-artifact-expanded",mn),Ze.setExpanded(mn);let A=qs();A!==Wr&&(Wr=A,Ir()),Ei()};if(Gt(o)){ye.style.position="relative";let l=m("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=m("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(ue),Ze=gg(o,{onSelect:h=>lt.current?.selectArtifact(h),onDismiss:()=>{In=!0,Wn()},onToggleExpand:()=>{let h=!mn,x=fn.selectedId??fn.artifacts[fn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:h})!==!0&&(mn=h,h||(Hr=!1),Wn())}}),Ze.element.classList.add("persona-hidden"),Kn=f,f.appendChild(l),f.appendChild(Ze.element),Ze.backdrop&&ye.appendChild(Ze.backdrop),ye.appendChild(f),Ei=()=>{if(!Kn||!Ze)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Br?.(),Br=null,Mi(),Ct&&(Ct.remove(),Ct=null),Ze.element.style.removeProperty("width"),Ze.element.style.removeProperty("maxWidth");return}if(!Ct){let x=m("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");x.setAttribute("role","separator"),x.setAttribute("aria-orientation","vertical"),x.setAttribute("aria-label","Resize artifacts panel"),x.tabIndex=0;let A=e.ownerDocument,P=A.defaultView??window,J=N=>{if(!Ze||N.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||P.innerWidth<=640)return;N.preventDefault(),Mi();let G=N.clientX,re=Ze.element.getBoundingClientRect().width,ge=o.features?.artifacts?.layout,oe=Ke=>{let ut=Kn.getBoundingClientRect().width,nt=e.classList.contains("persona-artifact-welded-split"),tn=rc(Kn,P),Tt=nt?0:x.getBoundingClientRect().width||6,Pt=re-(Ke.clientX-G),W=yg(Pt,ut,tn,Tt,ge?.resizableMinWidth,ge?.resizableMaxWidth);Ze.element.style.width=`${W}px`,Ze.element.style.maxWidth="none",Uc()},Ce=()=>{A.removeEventListener("pointermove",oe),A.removeEventListener("pointerup",Ce),A.removeEventListener("pointercancel",Ce),$s=null;try{x.releasePointerCapture(N.pointerId)}catch{}};$s=Ce,A.addEventListener("pointermove",oe),A.addEventListener("pointerup",Ce),A.addEventListener("pointercancel",Ce);try{x.setPointerCapture(N.pointerId)}catch{}};x.addEventListener("pointerdown",J),Ct=x,Kn.insertBefore(x,Ze.element),Br=()=>{x.removeEventListener("pointerdown",J)}}if(Ct){let x=_s();Ct.classList.toggle("persona-hidden",!x),Uc()}},zs=()=>{if(!S||!Ze||(o.launcher?.sidebarMode??!1)||Wt(o)&&on(o).reveal==="emerge")return;let x=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,P=o.launcher?.mobileBreakpoint??640;if(A&&x.innerWidth<=P||!hg(o,S))return;let J=o.launcher?.width??o.launcherWidth??un,N=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";_s()?(ye.style.width=N,ye.style.maxWidth=N):(ye.style.width=J,ye.style.maxWidth=J)},typeof ResizeObserver<"u"&&(Rr=new ResizeObserver(()=>{Wn()}),Rr.observe(ye))}else ye.appendChild(ue);Q()&&Xe&&(Le.peekBanner&&Xe.appendChild(Le.peekBanner),Xe.appendChild(j)),e.appendChild(Oe),Xe&&e.appendChild(Xe);let Vs=()=>{if(Q()){ye.style.width="100%",ye.style.maxWidth="100%";let Mt=o.launcher?.composerBar??{},Qt=Oe.dataset.state==="expanded",aa=Mt.expandedSize??"anchored";if(!(Qt&&aa!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let Xr=o.theme?.components?.panel,ia=Uo(o),ar=(Dn,Wo)=>Dn==null||Dn===""?Wo:Vt(ia,Dn)??Dn,la="1px solid var(--persona-border)",Yi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Io="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=ar(Xr?.border,la),ue.style.borderRadius=ar(Xr?.borderRadius,Io),ue.style.boxShadow=ar(Xr?.shadow,Yi),ue.style.overflow="hidden";return}let l=Wt(o),f=o.launcher?.sidebarMode??!1,h=l||f||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,A=o.launcher?.detachedPanel===!0,P=o.theme?.components?.panel,J=Uo(o),N=(Mt,Qt)=>Mt==null||Mt===""?Qt:Vt(J,Mt)??Mt,G=e.ownerDocument.defaultView??window,re=o.launcher?.mobileFullscreen??!0,ge=o.launcher?.mobileBreakpoint??640,oe=G.innerWidth<=ge,Ce=re&&oe&&S,Ke=l&&re&&oe,ut=o.launcher?.position??"bottom-left",nt=ut==="bottom-left"||ut==="top-left",tn=o.launcher?.zIndex??Ut,Tt="var(--persona-panel-border, 1px solid var(--persona-border))",Pt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",W="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Re=A&&!Ce&&!Ke;Re?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let $e=Re?Tt:f||Ce?"none":Tt,Se=Re?Pt:Ce?"none":f?nt?"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":Pt;l&&!Ce&&!Re&&(Se="none",$e="none");let Et=Re?W:f||Ce?"0":W,gt=N(P?.border,$e),qt=N(P?.shadow,Se),ft=N(P?.borderRadius,Et),Xt=qs(),Rt=Xt==="detached",Ie=Xt==="welded";e.classList.toggle("persona-artifact-detached-split",Rt),e.classList.toggle("persona-artifact-welded-split",Ie);let je="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",At=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Gt(o)&&oc(o)&&x&&!l;e.classList.toggle("persona-artifact-chat-flush",At);let ct=Rt||At?"none":qt,ht=Rt?Tt:Ie?"none":gt,et=Rt?W:ft;At&&(ht="none",et="0");let Ne=P?.borderRadius!=null&&P.borderRadius!=="",bt=At&&!Ne?"0":ft,_t=le.scrollTop;e.style.cssText="",Oe.style.cssText="",ye.style.cssText="",ue.style.cssText="",le.style.cssText="",j.style.cssText="",Ue&&(le.style.display="none"),(h||x)&&(e.style.minWidth="0");let dn=()=>{if(_t<=0)return;(le.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(le.scrollTop===_t)return;let Qt=le.scrollHeight-le.clientHeight;Qt<=0||(le.scrollTop=Math.min(_t,Qt))})};if(Ce){Oe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Oe.style.cssText=`
48
+ `,w.addEventListener("click",()=>{u=z,L.forEach((U,q)=>{let Q=q<z;U.classList.toggle("selected",Q),U.setAttribute("aria-checked",q===z-1?"true":"false")})}),L.push(w),M.appendChild(w)}b.appendChild(M);let I=null;if(p){let z=document.createElement("div");z.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=s,I.rows=3,I.setAttribute("aria-label","Additional comments"),z.appendChild(I),b.appendChild(z)}let S=document.createElement("div");S.className="persona-feedback-actions";let R=document.createElement("button");R.type="button",R.className="persona-feedback-btn persona-feedback-btn-skip",R.textContent=i,R.addEventListener("click",()=>{n?.(),c.remove()});let $=document.createElement("button");return $.type="button",$.className="persona-feedback-btn persona-feedback-btn-submit",$.textContent=a,$.addEventListener("click",async()=>{if(u===null){M.classList.add("persona-feedback-shake"),setTimeout(()=>M.classList.remove("persona-feedback-shake"),500);return}$.disabled=!0,$.textContent="Submitting...";try{let z=I?.value.trim()||void 0;await t(u,z),c.remove()}catch(z){$.disabled=!1,$.textContent=a,console.error("[CSAT Feedback] Failed to submit:",z)}}),S.appendChild(R),S.appendChild($),b.appendChild(S),c.appendChild(b),c}function gc(e){let{onSubmit:t,onDismiss:n,title:o="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:p=!0,lowLabel:d="Not likely",highLabel:c="Very likely"}=e,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,g=document.createElement("div");g.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=o,y.appendChild(C);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=r,y.appendChild(M),g.appendChild(y);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-nps",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let S=document.createElement("span");S.className="persona-feedback-label-low",S.textContent=d;let R=document.createElement("span");R.className="persona-feedback-label-high",R.textContent=c,I.appendChild(S),I.appendChild(R);let $=document.createElement("div");$.className="persona-feedback-numbers";let z=[];for(let O=0;O<=10;O++){let D=document.createElement("button");D.type="button",D.className="persona-feedback-rating-btn persona-feedback-number-btn",D.setAttribute("role","radio"),D.setAttribute("aria-checked","false"),D.setAttribute("aria-label",`Rating ${O} out of 10`),D.textContent=String(O),D.dataset.rating=String(O),O<=6?D.classList.add("persona-feedback-detractor"):O<=8?D.classList.add("persona-feedback-passive"):D.classList.add("persona-feedback-promoter"),D.addEventListener("click",()=>{b=O,z.forEach((ie,me)=>{ie.classList.toggle("selected",me===O),ie.setAttribute("aria-checked",me===O?"true":"false")})}),z.push(D),$.appendChild(D)}L.appendChild(I),L.appendChild($),g.appendChild(L);let w=null;if(p){let O=document.createElement("div");O.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"),O.appendChild(w),g.appendChild(O)}let U=document.createElement("div");U.className="persona-feedback-actions";let q=document.createElement("button");q.type="button",q.className="persona-feedback-btn persona-feedback-btn-skip",q.textContent=i,q.addEventListener("click",()=>{n?.(),u.remove()});let Q=document.createElement("button");return Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-submit",Q.textContent=a,Q.addEventListener("click",async()=>{if(b===null){$.classList.add("persona-feedback-shake"),setTimeout(()=>$.classList.remove("persona-feedback-shake"),500);return}Q.disabled=!0,Q.textContent="Submitting...";try{let O=w?.value.trim()||void 0;await t(b,O),u.remove()}catch(O){Q.disabled=!1,Q.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),U.appendChild(q),U.appendChild(Q),g.appendChild(U),u.appendChild(g),u}var Mr="persona-chat-history",hC=30*1e3,yC=641,bC={"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 vC(e){if(!e)return[];let t=[],n=Array.from(e.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){t.push(r);continue}let s=bC[r.type]??"png";t.push(new File([r],`clipboard-image-${Date.now()}.${s}`,{type:r.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let o of Array.from(e.files??[]))o.type.startsWith("image/")&&t.push(o);return t}function pi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function xC(e){return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:e.storage??"session",keyPrefix:e.keyPrefix??"persona-",persist:{openState:e.persist?.openState??!0,voiceState:e.persist?.voiceState??!0,focusInput:e.persist?.focusInput??!0},clearOnChatClear:e.clearOnChatClear??!0}:null}function CC(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var fc=e=>!e||typeof e!="object"?{}:{...e},Tg=e=>e.map(t=>({...t,streaming:!1})),Eg=(e,t,n)=>{let o=e?.markdown?cr(e.markdown):null,r=Zr(e?.sanitize);return e?.postprocessMessage&&r&&e?.sanitize===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{let a=s.text??"",i=s.message.rawContent??null;if(t){let c=t.process({text:a,raw:i??a,message:s.message,streaming:s.streaming});c!==null&&(a=c.text,c.persist||(s.message.__skipPersist=!0),c.resubmit&&!s.streaming&&n&&n())}let p=Nn()!==null,d;if(e?.postprocessMessage){let c=e.postprocessMessage({...s,text:a,raw:i??s.text??""});d=r?r(c):c}else if(o){let c=s.streaming?Jd(a):a,u=o(c);d=r&&p?r(u):u}else d=Fn(a);return d}};function Mg(e){let t=m("div","persona-attachment-drop-overlay");e?.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),e?.backdropBlur!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e?.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e?.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e?.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e?.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e?.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=e?.iconName??"upload",o=e?.iconSize??"48px",r=e?.iconColor??"rgba(59, 130, 246, 0.6)",s=e?.iconStrokeWidth??.5,a=te(n,o,r,s);if(a&&t.appendChild(a),e?.label){let i=m("span","persona-drop-overlay-label");i.textContent=e.label,t.appendChild(i)}return t}var wC=(e,t)=>{let n={...e};for(let[o,r]of Object.entries(t)){let s=n[o];n[o]=s?{...s,...r}:r}return n},AC=e=>e.reduce((t,n)=>({blocks:[...t.blocks,...n.blocks],contentParts:[...t.contentParts,...n.contentParts],context:wC(t.context,n.context)}),{blocks:[],contentParts:[],context:{}}),mc=(e,t,n)=>{if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let o=hs(t),r=ai.getForInstance(o.plugins),{plugin:s,teardown:a}=lg();o.components&&kn.registerAll(o.components);let i=wg(),d=o.persistState===!1?null:o.storageAdapter??lc(),c={},u=null,b=!1,g=l=>{if(o.onStateLoaded)try{let f=o.onStateLoaded(l);if(f&&typeof f=="object"&&"state"in f){let{state:h,open:x}=f;return x&&(b=!0),h}return f}catch(f){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",f)}return l};if(d?.load)try{let l=d.load();if(l&&typeof l.then=="function")u=l.then(f=>g(f??{messages:[],metadata:{}}));else{let h=g(l??{messages:[],metadata:{}});h.metadata&&(c=fc(h.metadata)),h.messages?.length&&(o={...o,initialMessages:h.messages}),h.artifacts?.length&&(o={...o,initialArtifacts:h.artifacts,initialSelectedArtifactId:h.selectedArtifactId??null})}}catch(l){typeof console<"u"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(o.onStateLoaded)try{let l=g({messages:[],metadata:{}});l.messages?.length&&(o={...o,initialMessages:l.messages})}catch(l){typeof console<"u"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let y=()=>c,C=l=>{c=l({...c})??{},Oi()},M=o.actionParsers&&o.actionParsers.length?o.actionParsers:[li],L=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Er.message,Er.messageAndClick],I=ci({parsers:M,handlers:L,getSessionMetadata:y,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null});I.syncFromMetadata();let S=o.launcher?.enabled??!0,R=o.launcher?.autoExpand??!1,$=o.autoFocusInput??!1,z=R,w=S,U=o.layout?.header?.layout,q=!1,Q=()=>ho(o),O=()=>S||Q(),D=Q()?!1:S?R:!0,ie=!1,me=null,we=()=>{ie=!0,me&&clearTimeout(me),me=setTimeout(()=>{ie&&(typeof console<"u"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),ie=!1)},1e4)},Ee=Eg(o,I,we),se=o.features?.showReasoning??!0,fe=o.features?.showToolCalls??!0,Y=o.features?.showEventStreamToggle??!1,ce=o.features?.scrollToBottom??{},Z=o.features?.scrollBehavior??{},he=`${(typeof o.persistState=="object"?o.persistState?.keyPrefix:void 0)??"persona-"}event-stream`,de=Y?new Is(he):null,Me=o.features?.eventStream?.maxEvents??2e3,De=Y?new Rs(Me,de):null,_e=Y?new Ws:null,He=null,Ue=!1,Ve=null,ke=0;de?.open().then(()=>De?.restore()).catch(l=>{o.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ne={onCopy:l=>{i.emit("message:copy",l),_?.isClientTokenMode()&&_.submitMessageFeedback(l.id,"copy").catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",f)}),o.messageActions?.onCopy?.(l)},onFeedback:l=>{i.emit("message:feedback",l),_?.isClientTokenMode()&&_.submitMessageFeedback(l.messageId,l.type).catch(f=>{o.debug&&console.error("[AgentWidget] Failed to submit feedback:",f)}),o.messageActions?.onFeedback?.(l)}},Be=o.statusIndicator??{},vt=l=>l==="idle"?Be.idleText??It.idle:l==="connecting"?Be.connectingText??It.connecting:l==="connected"?Be.connectedText??It.connected:l==="error"?Be.errorText??It.error:l==="paused"?Be.pausedText??It.paused:l==="resuming"?Be.resumingText??It.resuming:It[l];function mt(l,f,h,x){if(x==="idle"&&h.idleLink){l.textContent="";let A=document.createElement("a");A.href=h.idleLink,A.target="_blank",A.rel="noopener noreferrer",A.textContent=f,A.style.color="inherit",A.style.textDecoration="none",l.appendChild(A)}else l.textContent=f}let at=Vu({config:o,showClose:O()}),{wrapper:Oe,panel:ye,pillRoot:Xe}=at.shell,Le=at.panelElements,{container:ue,body:le,messagesWrapper:ve,suggestions:xt,textarea:xe,sendButton:pe,sendButtonWrapper:gn,composerForm:X,statusText:E,introTitle:F,introSubtitle:v,closeButton:T,iconHolder:k,headerTitle:H,headerSubtitle:V,header:B,footer:j,actionsRow:ae,rightActions:Ge}=Le,Te=Le.leftActions,rt=Le.setSendButtonMode,K=Le.micButton,ze=Le.micButtonWrapper,Ae=Le.attachmentButton,We=Le.attachmentButtonWrapper,Pe=Le.attachmentInput,Ye=Le.attachmentPreviewsContainer;ue.classList.add("persona-relative"),le.classList.add("persona-relative");let vo=12,xo=()=>ce.label??"",xi=()=>ce.iconName??"arrow-down",Ds=()=>ce.enabled!==!1,Jt=()=>Z.mode??"anchor-top",Un=()=>Jt()==="follow"||Jt()==="anchor-top"&&Or,Mc=()=>Z.anchorTopOffset??16,df=()=>Z.restorePosition??"bottom",kc=()=>Z.pauseOnInteraction===!0,Lc=()=>Z.showActivityWhilePinned!==!1,Pc=()=>Z.announce===!0,kt=m("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");kt.type="button",kt.style.display="none",kt.setAttribute("data-persona-scroll-to-bottom","true");let kr=m("span","persona-flex persona-items-center"),Ci=m("span",""),Co=m("span","");Co.setAttribute("data-persona-scroll-to-bottom-count",""),Co.style.display="none",kt.append(kr,Ci,Co),ue.appendChild(kt);let zn=m("div","persona-stream-anchor-spacer");zn.setAttribute("aria-hidden","true"),zn.setAttribute("data-persona-anchor-spacer",""),zn.style.flexShrink="0",zn.style.pointerEvents="none",zn.style.height="0px",le.appendChild(zn);let wo=m("div","persona-sr-only");wo.setAttribute("aria-live","polite"),wo.setAttribute("aria-atomic","true"),wo.setAttribute("role","status"),wo.setAttribute("data-persona-live-region",""),Object.assign(wo.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"}),ue.appendChild(wo);let Lr=null,Ns=null,Rc=l=>{!Pc()||!l||(Ns=l,Lr===null&&(Lr=setTimeout(()=>{Lr=null,Ns&&Pc()&&(wo.textContent=Ns),Ns=null},400)))},Jo=()=>{let f=j.style.display==="none"?0:j.offsetHeight;kt.style.bottom=`${f+vo}px`};Jo();let Ic=()=>{let l=!!xo();kt.setAttribute("aria-label",xo()||"Jump to latest"),kt.title=xo(),kt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),kr.innerHTML="";let f=te(xi(),"14px","currentColor",2);f?(kr.appendChild(f),kr.style.display=""):kr.style.display="none",Ci.textContent=xo(),Ci.style.display=l?"":"none"};Ic();let St=null,Yt=null,Wc=null,Hc=r.find(l=>l.renderHeader);if(Hc?.renderHeader){let l=Hc.renderHeader({config:o,defaultRenderer:()=>{let f=yo({config:o,showClose:O()});return Cr(ue,f,o),f.header},onClose:()=>pt(!1,"user")});if(l){let f=ue.querySelector(".persona-border-b-persona-divider");f&&(f.replaceWith(l),B=l,at.header.element=l)}}let wi=()=>{if(!De)return;if(Ue=!0,!He&&De&&(He=gg({buffer:De,getFullHistory:()=>De.getAllFromStore(),onClose:()=>Pr(),config:o,plugins:r,getThroughput:()=>_e?.getMetric()??{status:"idle"}})),He&&(le.style.display="none",j.parentNode?.insertBefore(He.element,j),He.update()),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${Kt.actionIconColor}`;let f=o.features?.eventStream?.classNames?.toggleButtonActive;f&&f.split(/\s+/).forEach(h=>h&&tt.classList.add(h))}let l=()=>{if(!Ue)return;let f=Date.now();f-ke>=200&&(He?.update(),ke=f),Ve=requestAnimationFrame(l)};ke=0,Ve=requestAnimationFrame(l),en(),i.emit("eventStream:opened",{timestamp:Date.now()})},Pr=()=>{if(Ue){if(Ue=!1,He&&He.element.remove(),le.style.display="",tt){tt.style.boxShadow="";let l=o.features?.eventStream?.classNames?.toggleButtonActive;l&&l.split(/\s+/).forEach(f=>f&&tt.classList.remove(f))}Ve!==null&&(cancelAnimationFrame(Ve),Ve=null),en(),i.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(Y){let l=o.features?.eventStream?.classNames,f="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l?.toggleButton?" "+l.toggleButton:"");tt=m("button",f),tt.style.width="28px",tt.style.height="28px",tt.style.color=Kt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let h=te("activity","18px","currentColor",1.5);h&&tt.appendChild(h);let x=Le.clearChatButtonWrapper,A=Le.closeButtonWrapper,P=x||A;P&&P.parentNode===B?B.insertBefore(tt,P):B.appendChild(tt),tt.addEventListener("click",()=>{Ue?Pr():wi()})}let pf=l=>{let f=o.attachments;if(!f?.enabled)return;let h=l.querySelector("[data-persona-composer-attachment-previews]")??l.querySelector(".persona-attachment-previews");if(!h){h=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let A=l.querySelector("[data-persona-composer-form]");A?.parentNode?A.parentNode.insertBefore(h,A):l.insertBefore(h,l.firstChild)}if(!(l.querySelector("[data-persona-composer-attachment-input]")??l.querySelector('input[type="file"]'))){let A=m("input");A.type="file",A.setAttribute("data-persona-composer-attachment-input",""),A.accept=(f.allowedTypes??$n).join(","),A.multiple=(f.maxFiles??4)>1,A.style.display="none",A.setAttribute("aria-label",f.buttonTooltipText??"Attach files"),l.appendChild(A)}},Bc=r.find(l=>l.renderComposer);if(Bc?.renderComposer){let l=o.composer,f=Bc.renderComposer({config:o,defaultRenderer:()=>Ls({config:o}).footer,onSubmit:h=>{if(!_||_.isStreaming())return;let x=h.trim(),A=St?.hasAttachments()??!1;if(!x&&!A)return;dd();let P;A&&(P=[],P.push(...St.getContentParts()),x&&P.push(Fo(x))),_.sendMessage(x,{contentParts:P}),A&&St.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Pe?.click()},models:l?.models,selectedModelId:l?.selectedModelId,onModelChange:h=>{o.composer={...o.composer,selectedModelId:h},o.agent&&(o.agent={...o.agent,model:h})},onVoiceToggle:o.voiceRecognition?.enabled===!0?()=>{Wc?.()}:void 0});f&&(at.replaceComposer(f),j=at.composer.footer)}let uf=l=>{let f=(...ge)=>{for(let oe of ge){let Ce=l.querySelector(oe);if(Ce)return Ce}return null},h=l.querySelector("[data-persona-composer-form]"),x=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),P=l.querySelector("[data-persona-composer-mic]"),J=l.querySelector("[data-persona-composer-status]");h&&(X=h),x&&(xe=x),A&&(pe=A),P&&(K=P,ze=P.parentElement),J&&(E=J);let N=f("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(xt=N);let G=f("[data-persona-composer-attachment-button]",".persona-attachment-button");G&&(Ae=G,We=G.parentElement),Pe=f("[data-persona-composer-attachment-input]",'input[type="file"]'),Ye=f("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let re=f("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");re&&(ae=re),Te=f(".persona-widget-composer__left-actions")};pf(j),uf(j);let qn=o.layout?.contentMaxWidth??(Q()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);if(qn&&(ve.style.maxWidth=qn,ve.style.marginLeft="auto",ve.style.marginRight="auto",ve.style.width="100%"),qn&&X&&!Q()&&(X.style.maxWidth=qn,X.style.marginLeft="auto",X.style.marginRight="auto"),qn&&xt&&!Q()&&(xt.style.maxWidth=qn,xt.style.marginLeft="auto",xt.style.marginRight="auto"),qn&&Ye&&!Q()&&(Ye.style.maxWidth=qn,Ye.style.marginLeft="auto",Ye.style.marginRight="auto"),o.attachments?.enabled&&Pe&&Ye){St=mr.fromConfig(o.attachments),St.setPreviewsContainer(Ye),Pe.addEventListener("change",h=>{let x=h.target;St?.handleFileSelect(x.files),x.value=""});let l=o.attachments.dropOverlay,f=Mg(l);ue.appendChild(f)}let gf=()=>Yt?.prefetch();if(o.contextMentions?.enabled&&xe&&(Yt=Zp({config:o,textarea:xe,anchor:X??xe,getMessages:()=>_.getMessages(),liveRegionHost:ue}),Yt)){let l=xe;l.parentElement?.insertBefore(Yt.contextRow,l);let f=Yt.affordanceButtons;for(let h=f.length-1;h>=0;h--){let x=f[h];Te?Te.insertBefore(x,Te.firstChild):X?.appendChild(x)}}(()=>{let l=o.layout?.slots??{},f=x=>{switch(x){case"body-top":return ue.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ve;case"footer-top":return xt;case"composer":return X;case"footer-bottom":return E;default:return null}},h=(x,A)=>{switch(x){case"header-left":case"header-center":case"header-right":if(x==="header-left")B.insertBefore(A,B.firstChild);else if(x==="header-right")B.appendChild(A);else{let P=B.querySelector(".persona-flex-col");P?P.parentNode?.insertBefore(A,P.nextSibling):B.appendChild(A)}break;case"body-top":{let P=le.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");P?P.replaceWith(A):le.insertBefore(A,le.firstChild);break}case"body-bottom":le.appendChild(A);break;case"footer-top":xt.replaceWith(A);break;case"footer-bottom":E.replaceWith(A);break;default:break}};for(let[x,A]of Object.entries(l))if(A)try{let P=A({config:o,defaultContent:()=>f(x)});P&&h(x,P)}catch(P){typeof console<"u"&&console.error(`[AgentWidget] Error rendering slot "${x}":`,P)}})();let Oc=l=>{let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let x=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let P=h.getAttribute("data-bubble-type");if(P==="reasoning")Ar.has(A)?Ar.delete(A):Ar.add(A),Zu(A,x);else if(P==="tool")Sr.has(A)?Sr.delete(A):Sr.add(A),eg(A,x,o);else if(P==="approval"){let N=((o.approval!==!1?o.approval:void 0)?.detailsDisplay??"collapsed")==="expanded",G=Vo.get(A)??N;Vo.set(A,!G),rg(A,x,o)}Eo.delete(A)};ve.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Oc(l))}),ve.addEventListener("keydown",l=>{let f=l.target;(l.key==="Enter"||l.key===" ")&&f.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Oc(l))}),ve.addEventListener("copy",l=>{let{clipboardData:f}=l;if(!f)return;let h=ve.getRootNode(),x=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let A=x.toString(),P=Eu(A);!P||P===A||(f.setData("text/plain",P),l.preventDefault())});let Ai=new Map,Dc=null,Nc="idle",ff={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},mf=(l,f)=>{let{icon:h,label:x}=ff[f];l.setAttribute("aria-label",x),l.title=x,l.setAttribute("aria-pressed",f==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",f!=="idle"),l.classList.toggle("persona-message-action-loading",f==="loading");let A=te(h,14,"currentColor",2);A&&(l.innerHTML="",l.appendChild(A))},Fc=()=>{ve.querySelectorAll('[data-action="read-aloud"]').forEach(f=>{let x=f.closest("[data-actions-for]")?.getAttribute("data-actions-for")??null;mf(f,x&&x===Dc?Nc:"idle")})};ve.addEventListener("click",l=>{let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest("[data-actions-for]");if(!x)return;let A=x.getAttribute("data-actions-for");if(!A)return;let P=h.getAttribute("data-action");if(P==="copy"){let N=_.getMessages().find(G=>G.id===A);if(N&&ne.onCopy){let G=N.content||"";navigator.clipboard.writeText(G).then(()=>{h.classList.add("persona-message-action-success");let re=te("check",14,"currentColor",2);re&&(h.innerHTML="",h.appendChild(re)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let ge=te("copy",14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge))},2e3)}).catch(re=>{typeof console<"u"&&console.error("[AgentWidget] Failed to copy message:",re)}),ne.onCopy(N)}}else if(P==="read-aloud")_.toggleReadAloud(A);else if(P==="upvote"||P==="downvote"){let N=(Ai.get(A)??null)===P,G=P==="upvote"?"thumbs-up":"thumbs-down";if(N){Ai.delete(A),h.classList.remove("persona-message-action-active");let re=te(G,14,"currentColor",2);re&&(h.innerHTML="",h.appendChild(re))}else{let re=P==="upvote"?"downvote":"upvote",ge=x.querySelector(`[data-action="${re}"]`);if(ge){ge.classList.remove("persona-message-action-active");let nt=te(re==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);nt&&(ge.innerHTML="",ge.appendChild(nt))}Ai.set(A,P),h.classList.add("persona-message-action-active");let oe=te(G,14,"currentColor",2);oe&&(oe.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(oe)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ke=_.getMessages().find(ut=>ut.id===A);Ke&&ne.onFeedback&&ne.onFeedback({type:P,messageId:Ke.id,message:Ke})}}}),ve.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest(".persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let P=h.getAttribute("data-approval-action");if(!P)return;let J=P==="approve"?"approved":"denied",G=_.getMessages().find(ge=>ge.id===A);if(!G?.approval)return;let re=x.querySelector("[data-approval-buttons]");re&&re.querySelectorAll("button").forEach(oe=>{oe.disabled=!0,oe.style.opacity="0.5",oe.style.cursor="not-allowed"}),G.approval.toolType==="webmcp"?_.resolveWebMcpApproval(A,J):_.resolveApproval(G.approval,J)});let Ze=null,Rr=null,Ir=()=>{},Wr="none",Fs=null,fn={artifacts:[],selectedId:null},Rn=!1,mn=!1,Hr=!1,Xo=!1,_c=()=>Xo||fn.artifacts.some(l=>Bo(o.features?.artifacts,l.artifactType)==="panel"),_s=()=>fn.artifacts.length>0&&!Rn&&_c(),lt={current:null},Si=(l,f)=>{let h=_.getArtifactById(f),x=h?.markdown,A=h?.title||"artifact",P=h?.file,J=h?.artifactType??"markdown";if(!x){let re=l.closest("[data-open-artifact], [data-artifact-inline]")?.closest("[data-message-id]")?.getAttribute("data-message-id");if(re){let oe=_.getMessages().find(Ce=>Ce.id===re);if(oe?.rawContent)try{let Ce=JSON.parse(oe.rawContent);x=Ce?.props?.markdown,A=Ce?.props?.title||A,Ce?.props?.file&&typeof Ce.props.file=="object"&&(P=Ce.props.file),!h&&typeof Ce?.props?.artifactType=="string"&&(J=Ce.props.artifactType)}catch{}}}return{markdown:x,title:A,file:P,artifactType:J}};ve.addEventListener("click",l=>{let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-download-artifact");if(!x||o.features?.artifacts?.onArtifactAction?.({type:"download",artifactId:x})===!0)return;let{markdown:P,title:J,file:N}=Si(h,x);if(!P)return;let{filename:G,mime:re,content:ge}=cu({title:J,markdown:P,file:N}),oe=new Blob([ge],{type:re}),Ce=URL.createObjectURL(oe),Ke=document.createElement("a");Ke.href=Ce,Ke.download=G,Ke.click(),URL.revokeObjectURL(Ce)}),ve.addEventListener("click",l=>{let h=l.target.closest("[data-artifact-custom-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-artifact-custom-action");if(!x)return;let A=h.closest("[data-artifact-inline]"),P=A?null:h.closest("[data-open-artifact]"),J=A?A.getAttribute("data-artifact-inline"):P?.getAttribute("data-open-artifact")??null,G=(A?o.features?.artifacts?.inlineActions:o.features?.artifacts?.cardActions)?.find(ut=>ut.id===x);if(!G)return;let{markdown:re,title:ge,file:oe,artifactType:Ce}=Si(h,J??""),Ke={artifactId:J,title:ge,artifactType:Ce,markdown:re,file:oe};try{Promise.resolve(G.onClick(Ke)).catch(()=>{})}catch{}}),ve.addEventListener("click",l=>{let h=l.target.closest("[data-copy-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-copy-artifact");if(!x)return;let A=_.getArtifactById(x),P="";if(A)P=Cs(A);else{let{markdown:J,file:N,artifactType:G}=Si(h,x);G==="markdown"&&(P=Cs({id:x,artifactType:"markdown",status:"complete",markdown:J??"",...N?{file:N}:{}}))}P&&navigator.clipboard.writeText(P).then(()=>{let J=te("check",16,"currentColor",2);J&&(h.replaceChildren(J),setTimeout(()=>{let N=te("copy",16,"currentColor",2);N&&h.replaceChildren(N)},1500))}).catch(()=>{})}),ve.addEventListener("click",l=>{let h=l.target.closest("[data-expand-artifact-inline]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-expand-artifact-inline");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(Rn=!1,Xo=!0,mn=!0,Hr=!0,_.selectArtifact(x),In())}),ve.addEventListener("click",l=>{let f=l.target;if(f.closest("[data-download-artifact]")||f.closest("[data-artifact-custom-action]"))return;let h=f.closest("[data-open-artifact]");if(!h)return;let x=h.getAttribute("data-open-artifact");!x||o.features?.artifacts?.onArtifactAction?.({type:"open",artifactId:x})===!0||(l.preventDefault(),l.stopPropagation(),Rn=!1,Xo=!0,_.selectArtifact(x),In())}),ve.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let f=l.target;!f.hasAttribute("data-open-artifact")&&!f.hasAttribute("data-expand-artifact-inline")||(l.preventDefault(),f.click())});let Qo=Le.composerOverlay,Yo=(l,f,h)=>{let x=f.trim();if(!x||!lt.current)return;let A=l.getAttribute("data-tool-call-id")??"",P=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:x,answers:h.structured,values:h.values??(h.source==="multi"?x.split(", "):[x]),isFreeText:P,source:h.source},bubbles:!0,composed:!0})),Do(Qo,A);let J=lt.current.getMessages().find(N=>N.toolCall?.id===A);J?.agentMetadata?.awaitingLocalTool?lt.current.resolveAskUserQuestion(J,h.structured??x):lt.current.sendMessage(x)},Ao=l=>{let f=lt.current;if(!f)return;let h=l.getAttribute("data-tool-call-id")??"",x=f.getMessages().find(A=>A.toolCall?.id===h);x&&f.persistAskUserQuestionProgress(x,{answers:ha(l,x),currentIndex:pn(l)})},$c=l=>Object.entries(l).map(([f,h])=>`${f}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Ti=l=>{if(o.features?.askUserQuestion?.groupedAutoAdvance===!1)return;let f=pn(l),h=pr(l);if(f>=h-1)return;let x=lt.current?.getMessages().find(A=>A.toolCall?.id===l.getAttribute("data-tool-call-id"));x&&(ya(l,x,o,f+1),Ao(l))};Qo.addEventListener("click",l=>{let h=l.target.closest("[data-ask-user-action]");if(!h)return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;let A=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),A==="dismiss"){let P=x.getAttribute("data-tool-call-id")??"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:P},bubbles:!0,composed:!0})),Do(Qo,P);let J=lt.current?.getMessages().find(N=>N.toolCall?.id===P);J?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(J),lt.current?.resolveAskUserQuestion(J,"(dismissed)"));return}if(A==="pick"){let P=h.getAttribute("data-option-label");if(!P)return;let J=x.getAttribute("data-multi-select")==="true",N=ro(x);if(N&&J){let G=Oo(x)[pn(x)],re=new Set(Array.isArray(G)?G:[]);re.has(P)?re.delete(P):re.add(P),so(x,Array.from(re)),Ao(x);return}if(N){so(x,P),Ao(x),Ti(x);return}if(J){let G=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",G?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!G);let re=x.querySelector('[data-ask-user-action="submit-multi"]');re&&(re.disabled=ll(x).length===0);return}Yo(x,P,{source:"pick",values:[P]});return}if(A==="submit-multi"){let P=ll(x);if(P.length===0)return;Yo(x,P.join(", "),{source:"multi",values:P});return}if(A==="open-free-text"){let P=x.querySelector('[data-ask-free-text-row="true"]');P&&(P.classList.remove("persona-hidden"),P.querySelector('[data-ask-free-text-input="true"]')?.focus());return}if(A==="focus-free-text"){x.querySelector('[data-ask-free-text-input="true"]')?.focus();return}if(A==="submit-free-text"){let J=x.querySelector('[data-ask-free-text-input="true"]')?.value??"";if(!J.trim())return;if(ro(x)){so(x,J.trim()),Ao(x),Ti(x);return}Yo(x,J,{source:"free-text"});return}if(A==="next"||A==="back"){if(!lt.current)return;let P=x.getAttribute("data-tool-call-id")??"",J=lt.current.getMessages().find(oe=>oe.toolCall?.id===P);if(!J)return;let G=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";if(G){let oe=Oo(x)[pn(x)];(typeof oe!="string"||oe!==G)&&so(x,G)}let re=A==="next"?1:-1,ge=pn(x)+re;ya(x,J,o,ge),Ao(x);return}if(A==="submit-all"){if(!lt.current)return;let P=x.getAttribute("data-tool-call-id")??"",J=lt.current.getMessages().find(oe=>oe.toolCall?.id===P);if(!J)return;let G=x.querySelector('[data-ask-free-text-input="true"]')?.value?.trim()??"";G&&so(x,G);let re=ha(x,J);lt.current.persistAskUserQuestionProgress(J,{answers:re,currentIndex:pn(x)});let ge=$c(re);Yo(x,ge||"(submitted)",{source:"submit-all",structured:re});return}if(A==="skip"){if(!lt.current)return;let P=x.getAttribute("data-tool-call-id")??"",J=lt.current.getMessages().find(Ce=>Ce.toolCall?.id===P);if(!J)return;let N=ro(x),G=pn(x),re=pr(x),ge=G>=re-1;if(!N){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:P},bubbles:!0,composed:!0})),Do(Qo,P),J.agentMetadata?.awaitingLocalTool&&(lt.current.markAskUserQuestionResolved(J),lt.current.resolveAskUserQuestion(J,"(dismissed)"));return}so(x,"");let oe=x.querySelector('[data-ask-free-text-input="true"]');if(oe&&(oe.value=""),ge){let Ce=ha(x,J),Ke=$c(Ce);Yo(x,Ke||"(skipped)",{source:"submit-all",structured:Ce});return}ya(x,J,o,G+1),Ao(x);return}}),Qo.addEventListener("keydown",l=>{if(l.key!=="Enter")return;let h=l.target;if(!h.matches?.('[data-ask-free-text-input="true"]'))return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;l.preventDefault();let A=h.value;if(A.trim()){if(ro(x)){so(x,A.trim()),Ao(x),Ti(x);return}Yo(x,A,{source:"free-text"})}});let jc=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let f=l.target;if(f?.tagName==="INPUT"||f?.tagName==="TEXTAREA"||f?.isContentEditable)return;let h=Qo.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let x=Number(l.key),P=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];P&&(l.preventDefault(),P.click())};document.addEventListener("keydown",jc);let Vn=null,Ct=null,Br=null,$s=null,Ei=()=>{},Uc=!1,js="",Us="";function Mi(){$s?.(),$s=null}let zc=()=>{if(!Vn||!Ct)return;let l=e.classList.contains("persona-artifact-welded-split"),f=e.ownerDocument.defaultView??window,h=f.innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){Ct.style.removeProperty("position"),Ct.style.removeProperty("left"),Ct.style.removeProperty("top"),Ct.style.removeProperty("bottom"),Ct.style.removeProperty("width"),Ct.style.removeProperty("z-index");return}let x=Vn.firstElementChild;if(!x||x===Ct)return;let A=10;Ct.style.position="absolute",Ct.style.top="0",Ct.style.bottom="0",Ct.style.width=`${A}px`,Ct.style.zIndex="5";let P=rc(Vn,f),J=x.offsetWidth+P/2-A/2;Ct.style.left=`${Math.max(0,J)}px`},zs=()=>{},hf=()=>{let l=e.ownerDocument.defaultView??window,f=o.launcher?.mobileFullscreen??!0,h=o.launcher?.mobileBreakpoint??640;return!f||l.innerWidth>h?!1:S||Wt(o)},qs=()=>!Gt(o)||!_s()||e.classList.contains("persona-artifact-narrow-host")||hf()||(e.ownerDocument.defaultView??window).innerWidth<yC?"none":oc(o)?"detached":"welded",In=()=>{if(!Ze||!Gt(o))return;Hs(e,o),Bs(e,o),zs();let l=o.features?.artifacts?.layout?.narrowHostMaxWidth??520,f=ye.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",f>0&&f<=l);let h=_s();Ze.setVisible(h),Ze.update(fn),Rn?(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),Ze.backdrop?.classList.add("persona-hidden"),mn=!1,Hr=!1):fn.artifacts.length>0&&_c()?(Ze.element.classList.remove("persona-hidden"),Ze.setMobileOpen(!0)):(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),Ze.backdrop?.classList.add("persona-hidden"),mn=!1,Hr=!1);let x=o.features?.artifacts?.layout?.showExpandToggle===!0;if(Ze.setExpandToggleVisible(x),Ze.setCopyButtonVisible(o.features?.artifacts?.layout?.showCopyButton===!0),Ze.setCustomActions(o.features?.artifacts?.toolbarActions??[]),Ze.setTabFade(o.features?.artifacts?.layout?.tabFade),Ze.setRenderTabBar(o.features?.artifacts?.renderTabBar),!x&&!Hr&&(mn=!1),mn!==Uc){let P=Ze.element;mn?(js=P.style.width,Us=P.style.maxWidth,P.style.removeProperty("width"),P.style.removeProperty("max-width")):(js&&(P.style.width=js),Us&&(P.style.maxWidth=Us),js="",Us=""),Uc=mn}e.classList.toggle("persona-artifact-expanded",mn),Ze.setExpanded(mn);let A=qs();A!==Wr&&(Wr=A,Ir()),Ei()};if(Gt(o)){ye.style.position="relative";let l=m("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),f=m("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(ue),Ze=fg(o,{onSelect:h=>lt.current?.selectArtifact(h),onDismiss:()=>{Rn=!0,In()},onToggleExpand:()=>{let h=!mn,x=fn.selectedId??fn.artifacts[fn.artifacts.length-1]?.id??null;o.features?.artifacts?.onArtifactAction?.({type:"expand",artifactId:x,expanded:h})!==!0&&(mn=h,h||(Hr=!1),In())}}),Ze.element.classList.add("persona-hidden"),Vn=f,f.appendChild(l),f.appendChild(Ze.element),Ze.backdrop&&ye.appendChild(Ze.backdrop),ye.appendChild(f),Ei=()=>{if(!Vn||!Ze)return;if(!(o.features?.artifacts?.layout?.resizable===!0)){Br?.(),Br=null,Mi(),Ct&&(Ct.remove(),Ct=null),Ze.element.style.removeProperty("width"),Ze.element.style.removeProperty("maxWidth");return}if(!Ct){let x=m("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");x.setAttribute("role","separator"),x.setAttribute("aria-orientation","vertical"),x.setAttribute("aria-label","Resize artifacts panel"),x.tabIndex=0;let A=e.ownerDocument,P=A.defaultView??window,J=N=>{if(!Ze||N.button!==0||e.classList.contains("persona-artifact-narrow-host")||e.classList.contains("persona-artifact-expanded")||P.innerWidth<=640)return;N.preventDefault(),Mi();let G=N.clientX,re=Ze.element.getBoundingClientRect().width,ge=o.features?.artifacts?.layout,oe=Ke=>{let ut=Vn.getBoundingClientRect().width,nt=e.classList.contains("persona-artifact-welded-split"),tn=rc(Vn,P),Tt=nt?0:x.getBoundingClientRect().width||6,Pt=re-(Ke.clientX-G),W=bg(Pt,ut,tn,Tt,ge?.resizableMinWidth,ge?.resizableMaxWidth);Ze.element.style.width=`${W}px`,Ze.element.style.maxWidth="none",zc()},Ce=()=>{A.removeEventListener("pointermove",oe),A.removeEventListener("pointerup",Ce),A.removeEventListener("pointercancel",Ce),$s=null;try{x.releasePointerCapture(N.pointerId)}catch{}};$s=Ce,A.addEventListener("pointermove",oe),A.addEventListener("pointerup",Ce),A.addEventListener("pointercancel",Ce);try{x.setPointerCapture(N.pointerId)}catch{}};x.addEventListener("pointerdown",J),Ct=x,Vn.insertBefore(x,Ze.element),Br=()=>{x.removeEventListener("pointerdown",J)}}if(Ct){let x=_s();Ct.classList.toggle("persona-hidden",!x),zc()}},zs=()=>{if(!S||!Ze||(o.launcher?.sidebarMode??!1)||Wt(o)&&on(o).reveal==="emerge")return;let x=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,P=o.launcher?.mobileBreakpoint??640;if(A&&x.innerWidth<=P||!yg(o,S))return;let J=o.launcher?.width??o.launcherWidth??un,N=o.features?.artifacts?.layout?.expandedPanelWidth??"min(720px, calc(100vw - 24px))";_s()?(ye.style.width=N,ye.style.maxWidth=N):(ye.style.width=J,ye.style.maxWidth=J)},typeof ResizeObserver<"u"&&(Rr=new ResizeObserver(()=>{In()}),Rr.observe(ye))}else ye.appendChild(ue);Q()&&Xe&&(Le.peekBanner&&Xe.appendChild(Le.peekBanner),Xe.appendChild(j)),e.appendChild(Oe),Xe&&e.appendChild(Xe);let Vs=()=>{if(Q()){ye.style.width="100%",ye.style.maxWidth="100%";let Mt=o.launcher?.composerBar??{},Qt=Oe.dataset.state==="expanded",aa=Mt.expandedSize??"anchored";if(!(Qt&&aa!=="fullscreen")){ue.style.background="",ue.style.border="",ue.style.borderRadius="",ue.style.overflow="",ue.style.boxShadow="";return}let Xr=o.theme?.components?.panel,ia=Uo(o),ar=(On,Wo)=>On==null||On===""?Wo:Vt(ia,On)??On,la="1px solid var(--persona-border)",Yi="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",Io="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";ue.style.background="var(--persona-surface, #ffffff)",ue.style.border=ar(Xr?.border,la),ue.style.borderRadius=ar(Xr?.borderRadius,Io),ue.style.boxShadow=ar(Xr?.shadow,Yi),ue.style.overflow="hidden";return}let l=Wt(o),f=o.launcher?.sidebarMode??!1,h=l||f||(o.launcher?.fullHeight??!1),x=o.launcher?.enabled===!1,A=o.launcher?.detachedPanel===!0,P=o.theme?.components?.panel,J=Uo(o),N=(Mt,Qt)=>Mt==null||Mt===""?Qt:Vt(J,Mt)??Mt,G=e.ownerDocument.defaultView??window,re=o.launcher?.mobileFullscreen??!0,ge=o.launcher?.mobileBreakpoint??640,oe=G.innerWidth<=ge,Ce=re&&oe&&S,Ke=l&&re&&oe,ut=o.launcher?.position??"bottom-left",nt=ut==="bottom-left"||ut==="top-left",tn=o.launcher?.zIndex??Ut,Tt="var(--persona-panel-border, 1px solid var(--persona-border))",Pt="var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))",W="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Re=A&&!Ce&&!Ke;Re?e.setAttribute("data-persona-panel-detached","true"):e.removeAttribute("data-persona-panel-detached");let $e=Re?Tt:f||Ce?"none":Tt,Se=Re?Pt:Ce?"none":f?nt?"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":Pt;l&&!Ce&&!Re&&(Se="none",$e="none");let Et=Re?W:f||Ce?"0":W,gt=N(P?.border,$e),qt=N(P?.shadow,Se),ft=N(P?.borderRadius,Et),Xt=qs(),Rt=Xt==="detached",Ie=Xt==="welded";e.classList.toggle("persona-artifact-detached-split",Rt),e.classList.toggle("persona-artifact-welded-split",Ie);let je="var(--persona-artifact-chat-shadow, var(--persona-artifact-pane-shadow, var(--persona-panel-shadow, var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25)))))",At=(o.features?.artifacts?.layout?.chatSurface==="flush"?"flush":"card")==="flush"&&Gt(o)&&oc(o)&&x&&!l;e.classList.toggle("persona-artifact-chat-flush",At);let ct=Rt||At?"none":qt,ht=Rt?Tt:Ie?"none":gt,et=Rt?W:ft;At&&(ht="none",et="0");let Ne=P?.borderRadius!=null&&P.borderRadius!=="",bt=At&&!Ne?"0":ft,_t=le.scrollTop;e.style.cssText="",Oe.style.cssText="",ye.style.cssText="",ue.style.cssText="",le.style.cssText="",j.style.cssText="",Ue&&(le.style.display="none"),(h||x)&&(e.style.minWidth="0");let dn=()=>{if(_t<=0)return;(le.ownerDocument.defaultView??window).requestAnimationFrame(()=>{if(le.scrollTop===_t)return;let Qt=le.scrollHeight-le.clientHeight;Qt<=0||(le.scrollTop=Math.min(_t,Qt))})};if(Ce){Oe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),Oe.style.cssText=`
49
49
  position: fixed !important;
50
50
  inset: 0 !important;
51
51
  width: 100% !important;
@@ -81,7 +81,7 @@ _Details: ${n.message}_`:o}var us=e=>({isError:!0,content:[{type:"text",text:e}]
81
81
  overflow: hidden !important;
82
82
  border-radius: 0 !important;
83
83
  border: none !important;
84
- `,le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",j.style.flexShrink="0",q=!0,dn();return}let sa=o?.launcher?.width??o?.launcherWidth??un;if(!f&&!l)x&&h?(ye.style.width="100%",ye.style.maxWidth="100%"):(ye.style.width=sa,ye.style.maxWidth=sa);else if(l)if(on(o).reveal==="emerge"&&!A){let Qt=on(o).width;ye.style.width=Qt,ye.style.maxWidth=Qt}else ye.style.width="100%",ye.style.maxWidth="100%";if(zs(),ye.style.boxShadow=ct,ye.style.borderRadius=bt,Rt?ye.style.border="none":Ie&&(ye.style.border=gt),ue.style.border=ht,ue.style.borderRadius=et,ue.style.boxShadow=Rt&&!At?je:"",At&&(ue.style.background="transparent",le.style.background="transparent",j.style.background="transparent",j.style.borderTop="none"),Ie){let Mt=o.features?.artifacts?.layout;Fs=Mt?.unifiedSplitOuterRadius?.trim()||Mt?.paneBorderRadius?.trim()||ft}else Fs=null;if(l&&!Ce&&!Re&&!Rt&&!Ie&&P?.border===void 0&&(ue.style.border="none",on(o).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),l&&!Ce&&Ie&&P?.border===void 0&&(on(o).side==="right"?ye.style.borderLeft="1px solid var(--persona-border)":ye.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",x&&(e.style.width="100%"),Oe.style.display="flex",Oe.style.flexDirection="column",Oe.style.flex="1 1 0%",Oe.style.minHeight="0",Oe.style.maxHeight="100%",Oe.style.height="100%",x&&(Oe.style.overflow="hidden"),ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1 1 0%",ye.style.minHeight="0",ye.style.maxHeight="100%",ye.style.height="100%",Rt||(ye.style.overflow="hidden"),ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",j.style.flexShrink="0"),x&&(Re||Rt||At)&&!l&&(At||(Oe.style.padding="var(--persona-panel-inset)"),Oe.style.background="var(--persona-panel-canvas-bg)"),Oe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!f&&!x&&!l&&(wn[ut]??wn["bottom-right"]).split(" ").forEach(Qt=>Oe.classList.add(Qt)),f){let Mt=o.launcher?.sidebarWidth??"420px";A?Oe.style.cssText=`
84
+ `,le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",j.style.flexShrink="0",q=!0,dn();return}let sa=o?.launcher?.width??o?.launcherWidth??un;if(!f&&!l)x&&h?(ye.style.width="100%",ye.style.maxWidth="100%"):(ye.style.width=sa,ye.style.maxWidth=sa);else if(l)if(on(o).reveal==="emerge"&&!A){let Qt=on(o).width;ye.style.width=Qt,ye.style.maxWidth=Qt}else ye.style.width="100%",ye.style.maxWidth="100%";if(zs(),ye.style.boxShadow=ct,ye.style.borderRadius=bt,Rt?ye.style.border="none":Ie&&(ye.style.border=gt),ue.style.border=ht,ue.style.borderRadius=et,ue.style.boxShadow=Rt&&!At?je:"",At&&(ue.style.background="transparent",le.style.background="transparent",j.style.background="transparent",j.style.borderTop="none"),Ie){let Mt=o.features?.artifacts?.layout;Fs=Mt?.unifiedSplitOuterRadius?.trim()||Mt?.paneBorderRadius?.trim()||ft}else Fs=null;if(l&&!Ce&&!Re&&!Rt&&!Ie&&P?.border===void 0&&(ue.style.border="none",on(o).side==="right"?ue.style.borderLeft="1px solid var(--persona-border)":ue.style.borderRight="1px solid var(--persona-border)"),l&&!Ce&&Ie&&P?.border===void 0&&(on(o).side==="right"?ye.style.borderLeft="1px solid var(--persona-border)":ye.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",x&&(e.style.width="100%"),Oe.style.display="flex",Oe.style.flexDirection="column",Oe.style.flex="1 1 0%",Oe.style.minHeight="0",Oe.style.maxHeight="100%",Oe.style.height="100%",x&&(Oe.style.overflow="hidden"),ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1 1 0%",ye.style.minHeight="0",ye.style.maxHeight="100%",ye.style.height="100%",Rt||(ye.style.overflow="hidden"),ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.overflow="hidden",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.overflowY="auto",j.style.flexShrink="0"),x&&(Re||Rt||At)&&!l&&(At||(Oe.style.padding="var(--persona-panel-inset)"),Oe.style.background="var(--persona-panel-canvas-bg)"),Oe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!f&&!x&&!l&&(Cn[ut]??Cn["bottom-right"]).split(" ").forEach(Qt=>Oe.classList.add(Qt)),f){let Mt=o.launcher?.sidebarWidth??"420px";A?Oe.style.cssText=`
85
85
  position: fixed !important;
86
86
  top: var(--persona-panel-inset) !important;
87
87
  bottom: var(--persona-panel-inset) !important;
@@ -139,9 +139,9 @@ _Details: ${n.message}_`:o}var us=e=>({isError:!0,content:[{type:"text",text:e}]
139
139
  border-top: none !important;
140
140
  padding: 8px 16px 12px 16px !important;
141
141
  ${At?"background: transparent !important;":""}
142
- `}if(!x&&!l){let Mt="max-height: -moz-available !important; max-height: stretch !important;",Qt=f?"":"padding-top: 1.25em !important;",aa=f?"":`z-index: ${o.launcher?.zIndex??Ut} !important;`;Oe.style.cssText+=Mt+Qt+aa}dn()};Vs(),hr(e,o),Hs(e,o),Bs(e,o),Ir=()=>{Vs(),hr(e,o),Hs(e,o),Bs(e,o),Fs?e.style.setProperty("--persona-artifact-welded-outer-radius",Fs):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let qe=[];qe.push(()=>{document.removeEventListener("keydown",$c)}),qe.push(()=>{Lr!==null&&clearTimeout(Lr)});let An=null,Sn=null;qe.push(()=>{An?.(),An=null,Sn?.(),Sn=null}),Rr&&qe.push(()=>{Rr?.disconnect(),Rr=null}),qe.push(()=>{Br?.(),Br=null,Mi(),Ct&&(Ct.remove(),Ct=null),Ze?.element.style.removeProperty("width"),Ze?.element.style.removeProperty("maxWidth")}),Y&&qe.push(()=>{Ve!==null&&(cancelAnimationFrame(Ve),Ve=null),He?.destroy(),He=null,De?.destroy(),De=null,de=null});let So=null,zc=()=>{So&&(So(),So=null),o.colorScheme==="auto"&&(So=ys(()=>{hr(e,o)}))};zc(),qe.push(()=>{So&&(So(),So=null)}),qe.push(a);let Ks=o.features?.streamAnimation;if(Ks?.type&&Ks.type!=="none"){let l=xr(Ks.type,Ks.plugins);l&&(Ga(l,e),qe.push(()=>Du(e)))}let Gs=lg(xt),To=null,_,ki=l=>{if(!_)return;let f=l??_.getMessages(),h=o.features?.suggestReplies?.enabled!==!1?pl(f):null;h?Gs.render(h,_,xe,f,o.suggestionChipsConfig,{agentPushed:!0}):f.some(x=>x.role==="user")?Gs.render([],_,xe,f):Gs.render(o.suggestionChips,_,xe,f,o.suggestionChipsConfig)},hn=!1,Eo=ku(),Zo=new Map,Mo=new Map,Gn=new Map,Li=0,hf=Fn()!==null,Zt=ja(),sn=0,Jn=null,an=!1,Js=!1,Xn=0,yn=null,ko=null,Pi=!1,Xs=!1,Ri=null,Or=!0,Ii=!1,Wi=null,yf=4,Qs=24,bf=80,Hi=new Map,Qe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},qc=o.voiceRecognition?.autoResume??!1,Hn=l=>{i.emit("voice:state",{active:Qe.active,source:l,timestamp:Date.now()})},bn=()=>{C(l=>({...l,voiceState:{active:Qe.active,timestamp:Date.now(),manuallyDeactivated:Qe.manuallyDeactivated}}))},vf=()=>{if(o.voiceRecognition?.enabled===!1)return;let l=fc(c.voiceState),f=!!l.active,h=Number(l.timestamp??0);Qe.manuallyDeactivated=!!l.manuallyDeactivated,f&&Date.now()-h<mC&&setTimeout(()=>{Qe.active||(Qe.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Qe.active=_.isVoiceActive(),Hn("restore"),_.isVoiceActive()&&rr()}):ta("restore"))},1e3)},xf=()=>_?Sg(_.getMessages()).filter(l=>!l.__skipPersist):[],Ys=null,Vc=(l,f)=>{typeof console<"u"&&console.error(l,f)},Bi=(l,f)=>{let h=()=>{try{let J=l();return!J||typeof J.then!="function"?null:Promise.resolve(J).catch(N=>{Vc(f,N)})}catch(J){return Vc(f,J),null}},x=Ys,A=x?x.then(()=>h()??void 0):h();if(!A)return;let P=A.finally(()=>{Ys===P&&(Ys=null)});Ys=P};function Oi(l){if(!d?.save)return;let h={messages:l?Sg(l):_?xf():[],metadata:c,artifacts:fn.artifacts,selectedArtifactId:fn.selectedId};Bi(()=>d.save(h),"[AgentWidget] Failed to persist state:")}let er=null,Kc=()=>Oe.querySelector("#persona-scroll-container")||le,Dr=()=>{er!==null&&(cancelAnimationFrame(er),er=null),an=!1},Gc=()=>{Jn!==null&&(cancelAnimationFrame(Jn),Jn=null),Js=!1,Dr()},Cf=()=>hn&&Ni()&&(Jt()!=="anchor-top"||kc()),Di=()=>{let l=xo()||"Jump to latest",f=Cf();kt.toggleAttribute("data-persona-scroll-to-bottom-streaming",f),Xn>0?(Co.textContent=String(Xn),Co.style.display="",kt.setAttribute("aria-label",`${l} (${Xn} new)`)):(Co.textContent="",Co.style.display="none",kt.setAttribute("aria-label",f?`${l} (response streaming below)`:l))},Jc=()=>{Xn!==0&&(Xn=0,Di())},Ni=()=>zn()?!Zt.isFollowing():!fo(le,Qs),en=()=>{if(!Ds()||Ue){kt.parentNode&&kt.remove(),kt.style.display="none";return}kt.parentNode!==ue&&ue.appendChild(kt),Jo();let f=Pn(le)>0&&Ni();f?Di():Jc(),kt.style.display=f?"":"none"},Nr=()=>{Zt.pause()&&(Gc(),en())},Qn=()=>{Zt.resume(),Jc(),en()},Yn=(l=!1)=>{zn()&&Zt.isFollowing()&&(!l&&!hn||(Jn!==null&&(cancelAnimationFrame(Jn),Jn=null),Js=!0,Jn=requestAnimationFrame(()=>{Jn=null,Js=!1,Zt.isFollowing()&&wf(Kc(),l?220:140)})))},Xc=(l,f,h,x=()=>!0)=>{let A=l.scrollTop,P=f(),J=P-A;if(Dr(),Math.abs(J)<1){an=!0,l.scrollTop=P,sn=l.scrollTop,an=!1;return}let N=performance.now();an=!0;let G=ge=>1-Math.pow(1-ge,3),re=ge=>{if(!x()){Dr();return}let oe=f();oe!==P&&(P=oe,J=P-A);let Ce=ge-N,Ke=Math.min(Ce/h,1),ut=G(Ke),nt=A+J*ut;l.scrollTop=nt,sn=l.scrollTop,Ke<1?er=requestAnimationFrame(re):(l.scrollTop=P,sn=l.scrollTop,er=null,an=!1)};er=requestAnimationFrame(re)},wf=(l,f=500)=>{let h=Pn(l)-l.scrollTop;if(Math.abs(h)<1){sn=l.scrollTop;return}if(Math.abs(h)>=bf){Dr(),an=!0,l.scrollTop=Pn(l),sn=l.scrollTop,an=!1;return}Xc(l,()=>Pn(l),f,()=>Zt.isFollowing())},Qc=()=>{let l=Kc();an=!0,l.scrollTop=Pn(l),sn=l.scrollTop,an=!1,en()},Yc=l=>{let f=0,h=l;for(;h&&h!==le;)f+=h.offsetTop,h=h.offsetParent;return f},Zc=()=>{if(cf()!=="last-user-turn")return!1;let l=_?.getMessages()??[];if(l.length<2)return!1;let f=[...l].reverse().find(P=>P.role==="user");if(!f)return!1;let h=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(f.id):f.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=le.querySelector(`[data-message-id="${h}"]`);if(!x)return!1;let A=Math.min(Math.max(0,Yc(x)-Ec()),Pn(le));return an=!0,le.scrollTop=A,sn=le.scrollTop,an=!1,Jt()==="follow"&&!fo(le,Qs)&&Zt.pause(),en(),!0},ed=l=>{qn.style.height=`${Math.max(0,Math.round(l))}px`,yn&&(yn.spacerHeight=Math.max(0,l))},Fr=()=>{ko!==null&&(cancelAnimationFrame(ko),ko=null),Dr(),yn=null,qn.style.height="0px"},Af=l=>{ko!==null&&cancelAnimationFrame(ko),ko=requestAnimationFrame(()=>{ko=null;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=le.querySelector(`[data-message-id="${f}"]`);if(!h)return;let x=Yc(h),A=yn?.spacerHeight??0,P=le.scrollHeight-A,{targetScrollTop:J,spacerHeight:N}=Wu({anchorOffsetTop:x,topOffset:Ec(),viewportHeight:le.clientHeight,contentHeight:P});yn={initialSpacerHeight:N,contentHeightAtAnchor:P,spacerHeight:N},ed(N),Xc(le,()=>J,220)})},Sf=()=>{if(zn()){if(!Zt.isFollowing()||fo(le,1))return;Yn(!hn);return}if(yn&&yn.initialSpacerHeight>0){let l=le.scrollHeight-yn.spacerHeight,f=Hu({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:l});f!==yn.spacerHeight&&ed(f)}en()},Tf=l=>{let f=Jt();f==="follow"?(Qn(),Yn(!0)):f==="anchor-top"&&(Or=!1,Ii=!0,Af(l))},Ef=()=>{if(Jt()==="anchor-top"){if(Ii){Or=!1;return}Or=!0,Fr(),Qn(),Yn(!0)}},Mf=l=>{let f=new Map;l.forEach(h=>{let x=Hi.get(h.id);f.set(h.id,{streaming:h.streaming,role:h.role}),!x&&h.role==="assistant"&&(i.emit("assistant:message",h),!Xs&&(Jt()!=="anchor-top"||kc())&&Ni()&&(Xn+=1,Di(),en(),Pc(Xn===1?"1 new message below.":`${Xn} new messages below.`))),h.role==="assistant"&&x?.streaming&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(x?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),Hi.clear(),f.forEach((h,x)=>{Hi.set(x,h)})},Zs=(l,f)=>{let h=f==="user"?"user":"assistant",x=o.layout?.messages?.[h],A=x?.width??"content",P=x?.maxWidth??(A==="full"?"100%":"85%");l.classList.add("persona-message-row"),l.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),l.classList.add(`persona-message-row-${f}`,`persona-message-width-${A}`),l.classList.toggle("persona-justify-end",f==="user"),l.setAttribute("data-message-role",f),l.setAttribute("data-message-width",A),l.style.setProperty("--persona-message-row-max-width",P)},Lo=(l,f)=>{let h=document.createElement("div");return h.className="persona-flex",h.id=`wrapper-${l}`,h.setAttribute("data-wrapper-id",l),Zs(h,f),h},kf=(l,f,h)=>{let x=document.createElement("div"),P=(()=>{let W=r.find(Re=>Re.renderLoadingIndicator);if(W?.renderLoadingIndicator)return W.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),J=(W,Re)=>Re==null?!1:typeof Re=="string"?(W.textContent=Re,!0):(W.appendChild(Re),!0),N=new Set,G=new Map,re=new Set,ge=r.some(W=>W.renderAskUserQuestion),oe=[],Ce=[],Ke=o.enableComponentStreaming!==!1,ut=o.approval!==!1,nt=[];if(f.forEach(W=>{N.add(W.id),G.set(W.id,W.role);let Re=ge&&oo(W),$e=ut&&W.variant==="approval"&&!!W.approval,Se=!Re&&W.role==="assistant"&&!W.variant&&Ke&&di(W);!$e&&Gn.has(W.id)&&(l.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Gn.delete(W.id)),!Se&&Mo.has(W.id)&&(l.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Mo.delete(W.id));let Et=oo(W)?`:${W.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${W.agentMetadata?.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",gt=Mu(W,Li)+Et,qt=Re||$e||Se?null:Lu(Eo,W.id,gt);if(qt){x.appendChild(qt.cloneNode(!0)),oo(W)&&W.toolCall?.id&&W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(re.add(W.toolCall.id),rs(W,o,Le.composerOverlay));return}let ft=null,Xt=r.find(je=>!!(W.variant==="reasoning"&&je.renderReasoning||W.variant==="tool"&&je.renderToolCall||!W.variant&&je.renderMessage)),Rt=o.layout?.messages;if(oo(W)&&W.agentMetadata?.askUserQuestionAnswered===!0){Zo.delete(W.id),l.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime");return}if(ba(W)&&o.features?.suggestReplies?.enabled!==!1)return;if(oo(W)&&o.features?.askUserQuestion?.enabled!==!1){let je=r.find(Nt=>typeof Nt.renderAskUserQuestion=="function");if(je&&lt.current){let Nt=Zo.get(W.id),Ft=Nt!==gt,At=null;if(Ft){let{payload:et,complete:Ne}=ro(W),bt=W.id,_t=()=>lt.current?.getMessages().find(dn=>dn.id===bt);At=je.renderAskUserQuestion({message:W,payload:et,complete:Ne,resolve:dn=>{let Jr=_t();Jr&&lt.current?.resolveAskUserQuestion(Jr,dn)},dismiss:()=>{let dn=_t();dn?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(dn),lt.current?.resolveAskUserQuestion(dn,"(dismissed)"))},config:o})}let ct=Nt!=null;if(Ft&&At===null&&!ct){W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(re.add(W.toolCall.id),rs(W,o,Le.composerOverlay));return}let ht=Lo(W.id,W.role);ht.setAttribute("data-ask-plugin-stub","true"),ht.setAttribute("data-preserve-runtime","true"),x.appendChild(ht),oe.push({messageId:W.id,fingerprint:gt,bubble:At});return}else{W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(re.add(W.toolCall.id),rs(W,o,Le.composerOverlay));return}}else if($e){let je=r.find(ct=>typeof ct.renderApproval=="function")??s,Ft=Gn.get(W.id)!==gt,At=null;if(Ft&&je?.renderApproval){let ct=W.id,ht=(et,Ne)=>{let bt=lt.current?.getMessages().find(_t=>_t.id===ct);bt?.approval&&(bt.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(bt.id,et):lt.current?.resolveApproval(bt.approval,et,Ne))};At=je.renderApproval({message:W,defaultRenderer:()=>ri(W,o),config:o,approve:et=>ht("approved",et),deny:et=>ht("denied",et)})}if(Ft&&At===null)l.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Gn.delete(W.id),ft=ri(W,o);else{let ct=Lo(W.id,W.role);ct.setAttribute("data-approval-plugin-stub","true"),ct.setAttribute("data-preserve-runtime","true"),x.appendChild(ct),nt.push({messageId:W.id,fingerprint:gt,bubble:At});return}}else if(Xt)if(W.variant==="reasoning"&&W.reasoning&&Xt.renderReasoning){if(!se)return;ft=Xt.renderReasoning({message:W,defaultRenderer:()=>Jl(W,o),config:o})}else if(W.variant==="tool"&&W.toolCall&&Xt.renderToolCall){if(!fe)return;ft=Xt.renderToolCall({message:W,defaultRenderer:()=>Ql(W,o),config:o})}else Xt.renderMessage&&(ft=Xt.renderMessage({message:W,defaultRenderer:()=>{let je=Ps(W,h,Rt,o.messageActions,ne,{loadingIndicatorRenderer:P,widgetConfig:o});return W.role!=="user"&&sc(je,W,o,_),je},config:o}));if(!ft&&Se){let je=pc(W);if(je){let Nt=Mo.get(W.id),Ft=Nt!==gt,At=o.wrapComponentDirectiveInBubble!==!1&&Ln.getOptions(je.component)?.bubbleChrome!==!1,ct=null;if(Ft){let ht=dc(je,{config:o,message:W,transform:h});if(ht&&je.component==="PersonaArtifactInline"){let et=ht.hasAttribute("data-artifact-inline")?ht:ht.querySelector("[data-artifact-inline]"),Ne=et?.getAttribute("data-artifact-inline")??"",bt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Ne):Ne,_t=Ne?l.querySelector(`#wrapper-${W.id}`)?.querySelector(`[data-artifact-inline="${bt}"]`)??null:null;et&&_t&&_t!==et&&wu(_t)&&(et===ht?ht=_t:et.replaceWith(_t))}if(ht)if(At){let et=document.createElement("div");if(et.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),et.id=`bubble-${W.id}`,et.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let Ne=document.createElement("div");Ne.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Ne.innerHTML=h({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),et.appendChild(Ne)}et.appendChild(ht),ct=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-${W.id}`,et.setAttribute("data-message-id",W.id),et.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let Ne=document.createElement("div");Ne.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Ne.innerHTML=h({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),et.appendChild(Ne)}et.appendChild(ht),ct=et}}if(ct||Nt!=null){let ht=Lo(W.id,W.role);ht.setAttribute("data-component-directive-stub","true"),ht.setAttribute("data-preserve-runtime","true"),x.appendChild(ht),Ce.push({messageId:W.id,fingerprint:gt,bubble:ct});return}}}if(!ft)if(W.variant==="reasoning"&&W.reasoning){if(!se)return;ft=Jl(W,o)}else if(W.variant==="tool"&&W.toolCall){if(!fe)return;ft=Ql(W,o)}else if(W.variant==="approval"&&W.approval){if(o.approval===!1)return;ft=ri(W,o)}else{let je=o.layout?.messages;je?.renderUserMessage&&W.role==="user"?ft=je.renderUserMessage({message:W,config:o,streaming:!!W.streaming}):je?.renderAssistantMessage&&W.role==="assistant"?ft=je.renderAssistantMessage({message:W,config:o,streaming:!!W.streaming}):ft=Ps(W,h,je,o.messageActions,ne,{loadingIndicatorRenderer:P,widgetConfig:o}),W.role!=="user"&&ft&&sc(ft,W,o,_)}let Ie=Lo(W.id,W.role);Ie.appendChild(ft),Pu(Eo,W.id,gt,Ie),x.appendChild(Ie)}),Le.composerOverlay&&Le.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let $e=Re.getAttribute("data-persona-ask-sheet-for");$e&&!re.has($e)&&Do(Le.composerOverlay,$e)}),o.features?.toolCallDisplay?.grouped){let W=[],Re=[],$e=o.features.toolCallDisplay.groupedMode==="summary";f.forEach(Se=>{if(Se.variant==="tool"&&Se.toolCall&&fe){Re.push(Se);return}Se.variant==="reasoning"&&!se||((Re.length>1||$e&&Re.length>0)&&W.push(Re),Re=[])}),(Re.length>1||$e&&Re.length>0)&&W.push(Re),W.forEach(Se=>{let Et=Se.map(je=>Array.from(x.children).find(Nt=>Nt instanceof HTMLElement&&Nt.getAttribute("data-wrapper-id")===je.id)).filter(je=>!!je);if(Et.length<($e?1:2))return;let gt=Lo(`tool-group-${Se[0].id}`,"assistant");gt.setAttribute("data-persona-tool-group-row","true");let qt=document.createElement("div");qt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",qt.setAttribute("data-persona-tool-group","true");let ft=document.createElement("div");ft.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",ft.id=`tool-group-summary-${Se[0].id}`;let Xt=`Called ${Se.length} ${Se.length===1?"tool":"tools"}`,Rt=o.toolCall?.renderGroupedSummary?.({messages:Se,toolCalls:Se.map(je=>je.toolCall).filter(je=>!!je),defaultSummary:Xt,config:o});J(ft,Rt)||(ft.textContent=Xt);let Ie=document.createElement("div");Ie.className="persona-tool-group-stack persona-flex persona-flex-col",Ie.id=`tool-group-stack-${Se[0].id}`,Ie.setAttribute("data-persona-tool-group-stack","true"),qt.appendChild(ft),$e||qt.appendChild(Ie),gt.appendChild(qt),Et[0].before(gt),Et.forEach((je,Nt)=>{if($e){je.remove();return}je.style.setProperty("--persona-message-row-max-width","100%");let Ft=document.createElement("div");Ft.className="persona-tool-group-item persona-relative",Ft.setAttribute("data-persona-tool-group-item","true"),Nt<Et.length-1&&Ft.setAttribute("data-persona-tool-group-connector","true"),Ft.appendChild(je),Ie.appendChild(Ft)})})}Ru(Eo,N);let tn=f.some(W=>W.role==="assistant"&&W.streaming),Tt=f[f.length-1],Pt=Tt?.role==="assistant"&&!Tt.streaming&&Tt.variant!=="approval";if(hn&&f.some(W=>W.role==="user")&&!tn&&!Pt){let W={config:o,streaming:!0,location:"standalone",defaultRenderer:wr},Re=r.find(Se=>Se.renderLoadingIndicator),$e=null;if(Re?.renderLoadingIndicator&&($e=Re.renderLoadingIndicator(W)),$e===null&&o.loadingIndicator?.render&&($e=o.loadingIndicator.render(W)),$e===null&&($e=wr()),$e){let Se=document.createElement("div"),Et=o.loadingIndicator?.showBubble!==!1;Se.className=Et?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Se.setAttribute("data-typing-indicator","true"),Se.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Se.appendChild($e);let gt=Lo("typing-indicator","assistant");gt.appendChild(Se),x.appendChild(gt)}}if(!hn&&f.length>0){let W=f[f.length-1],Re={config:o,lastMessage:W,messageCount:f.length},$e=r.find(Et=>Et.renderIdleIndicator),Se=null;if($e?.renderIdleIndicator&&(Se=$e.renderIdleIndicator(Re)),Se===null&&o.loadingIndicator?.renderIdle&&(Se=o.loadingIndicator.renderIdle(Re)),Se){let Et=document.createElement("div"),gt=o.loadingIndicator?.showBubble!==!1;Et.className=gt?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Et.setAttribute("data-idle-indicator","true"),Et.appendChild(Se);let qt=Lo("idle-indicator","assistant");qt.appendChild(Et),x.appendChild(qt)}}if(Yd(x),$a(l,x),tl(l),oe.length>0)for(let{messageId:W,fingerprint:Re,bubble:$e}of oe){let Se=l.querySelector(`#wrapper-${W}`);Se&&(Zs(Se,G.get(W)??"assistant"),$e!==null&&(Se.replaceChildren($e),Se.setAttribute("data-bubble-fp",Re),Zo.set(W,Re)))}if(Zo.size>0)for(let W of Zo.keys())N.has(W)||Zo.delete(W);if(Ce.length>0)for(let{messageId:W,fingerprint:Re,bubble:$e}of Ce){let Se=l.querySelector(`#wrapper-${W}`);Se&&(Zs(Se,G.get(W)??"assistant"),$e!==null&&(Se.replaceChildren($e),Se.setAttribute("data-bubble-fp",Re),Mo.set(W,Re)))}if(Mo.size>0)for(let W of Mo.keys())N.has(W)||Mo.delete(W);if(nt.length>0)for(let{messageId:W,fingerprint:Re,bubble:$e}of nt){let Se=l.querySelector(`#wrapper-${W}`);Se&&(Zs(Se,G.get(W)??"assistant"),$e!==null&&(Se.replaceChildren($e),Se.setAttribute("data-bubble-fp",Re),Gn.set(W,Re)))}if(Gn.size>0)for(let W of Gn.keys())N.has(W)||Gn.delete(W)},_r=(l,f,h)=>{kf(l,f,h),Nc()},$r=null,Lf=()=>{if($r)return;let l=h=>{let x=h.composedPath();x.includes(Oe)||Xe&&x.includes(Xe)||pt(!1,"user")};$r=l,(e.ownerDocument??document).addEventListener("pointerdown",l,!0)},td=()=>{if(!$r)return;(e.ownerDocument??document).removeEventListener("pointerdown",$r,!0),$r=null};qe.push(()=>td());let jr=null,Pf=()=>{if(jr)return;let l=h=>{h.key==="Escape"&&(h.isComposing||pt(!1,"user"))};jr=l,(e.ownerDocument??document).addEventListener("keydown",l,!0)},nd=()=>{if(!jr)return;(e.ownerDocument??document).removeEventListener("keydown",jr,!0),jr=null};qe.push(()=>nd());let Ur=!1,od=new Set,Rf=()=>{let l=o.launcher?.composerBar?.peek?.streamAnimation;return l||o.features?.streamAnimation},tr=()=>{if(!Q())return;let l=Le.peekBanner,f=Le.peekTextNode;if(!l||!f)return;if(D){l.classList.remove("persona-pill-peek--visible");return}let h=_?.getMessages()??[],x;for(let Tt=h.length-1;Tt>=0;Tt--){let Pt=h[Tt];if(Pt.role==="assistant"&&Pt.content){x=Pt;break}}if(!x){l.classList.remove("persona-pill-peek--visible");return}let A=x.content,P=!!x.streaming,J=Rf(),N=qa(J),G=N.type!=="none"?xr(N.type,J?.plugins):null,re=G?.isAnimating?.(x)===!0,ge=G!==null&&(P||re);ge&&G&&!od.has(G.name)&&(Ga(G,e),od.add(G.name));let oe=ge&&G?.containerClass?G.containerClass:null,Ce=f.dataset.personaPeekStreamClass??null;Ce&&Ce!==oe&&(f.classList.remove(Ce),delete f.dataset.personaPeekStreamClass),oe&&Ce!==oe&&(f.classList.add(oe),f.dataset.personaPeekStreamClass=oe),ge?(f.style.setProperty("--persona-stream-step",`${N.speed}ms`),f.style.setProperty("--persona-stream-duration",`${N.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let Ke=ge?Va(A,N.buffer,G,x,P):A;if(ge&&N.placeholder==="skeleton"&&P&&(!Ke||!Ke.trim())){let Tt=document.createElement("div"),Pt=Ts();Pt.classList.add("persona-pill-peek__skeleton"),Tt.appendChild(Pt),$a(f,Tt)}else{let Tt=Math.max(0,Ke.length-100),Pt=Ke.length>100?Ke.slice(-100):Ke,W=_n(Pt);if(!ge||!G){let Re=Ke.length>100?`\u2026${Pt}`:Pt;f.textContent!==Re&&(f.textContent=Re)}else{let Re=W;(G.wrap==="char"||G.wrap==="word")&&(Re=Ss(W,G.wrap,`peek-${x.id}`,{skipTags:G.skipTags,startIndex:Tt}));let $e=document.createElement("div");if($e.innerHTML=Re,G.useCaret&&Pt.length>0){let Se=Ka(),Et=$e.querySelectorAll(".persona-stream-char, .persona-stream-word"),gt=Et[Et.length-1];gt?.parentNode?gt.parentNode.insertBefore(Se,gt.nextSibling):$e.appendChild(Se)}$a(f,$e),G.onAfterRender?.({container:f,bubble:l,messageId:x.id,message:x,speed:N.speed,duration:N.duration})}}let tn=hn||Ur;l.classList.toggle("persona-pill-peek--visible",tn)};if(Q()){let l=Le.peekBanner;if(l){let x=A=>{A.preventDefault(),A.stopPropagation(),pt(!0,"user")};l.addEventListener("pointerdown",x),qe.push(()=>{l.removeEventListener("pointerdown",x)})}let f=()=>{Ur||(Ur=!0,tr())},h=()=>{Ur&&(Ur=!1,tr())};ye.addEventListener("pointerenter",f),ye.addEventListener("pointerleave",h),qe.push(()=>{ye.removeEventListener("pointerenter",f),ye.removeEventListener("pointerleave",h)}),Xe&&(Xe.addEventListener("pointerenter",f),Xe.addEventListener("pointerleave",h),qe.push(()=>{Xe.removeEventListener("pointerenter",f),Xe.removeEventListener("pointerleave",h)}))}let If=l=>{let f=o.launcher?.composerBar??{},h=f.expandedSize??"anchored",x=f.bottomOffset??"16px",A=f.collapsedMaxWidth,P=f.expandedMaxWidth??"880px",J=f.expandedTopOffset??"5vh",N=f.modalMaxWidth??"880px",G=f.modalMaxHeight??"min(90vh, 800px)",re="calc(100vw - 32px)",ge="var(--persona-pill-area-height, 80px)",oe=Oe.style;if(oe.left="",oe.right="",oe.top="",oe.bottom="",oe.transform="",oe.width="",oe.maxWidth="",oe.height="",oe.maxHeight="",Xe){let Ce=Xe.style;Ce.bottom=x,Ce.width=A??""}if(l&&h!=="fullscreen"){if(h==="modal"){oe.top="50%",oe.left="50%",oe.transform="translate(-50%, -50%)",oe.bottom="auto",oe.right="auto",oe.width=N,oe.maxWidth=re,oe.maxHeight=G,oe.height=G;return}oe.left="50%",oe.transform="translateX(-50%)",oe.bottom=`calc(${x} + ${ge})`,oe.top=J,oe.width=P,oe.maxWidth=re}},zr=()=>{if(!O())return;if(Q()){let re=(o.launcher?.composerBar??{}).expandedSize??"anchored",ge=D?"expanded":"collapsed";Oe.dataset.state=ge,Oe.dataset.expandedSize=re,Xe&&(Xe.dataset.state=ge,Xe.dataset.expandedSize=re),Oe.style.removeProperty("display"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),If(D),ue.style.display=D?"flex":"none",Vs(),D?(Lf(),Pf()):(td(),nd()),tr();return}let l=Wt(o),f=e.ownerDocument.defaultView??window,h=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,A=f.innerWidth<=h,P=x&&A&&S,J=on(o).reveal;D?(Oe.style.removeProperty("display"),Oe.style.display=l?"flex":"",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0"),ye.classList.add("persona-scale-100","persona-opacity-100"),Bt?Bt.element.style.display="none":zt&&(zt.style.display="none")):(l?l&&(J==="overlay"||J==="push")&&!P?(Oe.style.removeProperty("display"),Oe.style.display="flex",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Oe.style.setProperty("display","none","important"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Oe.style.display="",Oe.classList.add("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100"),ye.classList.add("persona-scale-95","persona-opacity-0")),Bt?Bt.element.style.display=l?"none":"":zt&&(zt.style.display=l?"none":""))},pt=(l,f="user")=>{if(!O()||D===l)return;let h=D;D=l,zr();let x=(()=>{let P=o.launcher?.sidebarMode??!1,J=e.ownerDocument.defaultView??window,N=o.launcher?.mobileFullscreen??!0,G=o.launcher?.mobileBreakpoint??640,re=J.innerWidth<=G,ge=Wt(o)&&N&&re,oe=Q()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return P||N&&re&&S||ge||oe})();if(D&&x){if(!An){let P=e.getRootNode(),J=P instanceof ShadowRoot?P.host:e.closest(".persona-host");J&&(An=jl(J,o.launcher?.zIndex??Ut))}Sn||(Sn=Ul(e.ownerDocument))}else D||(An?.(),An=null,Sn?.(),Sn=null);D&&(Kr(),Zc()||(Jt()==="follow"?Yn(!0):Qc()));let A={open:D,source:f,timestamp:Date.now()};D&&!h?i.emit("widget:opened",A):!D&&h&&i.emit("widget:closed",A),i.emit("widget:state",{open:D,launcherEnabled:S,voiceActive:Qe.active,streaming:_.isStreaming()})},Fi=l=>{rt(l?"stop":"send"),K&&(K.disabled=l),Gs.buttons.forEach(f=>{f.disabled=l}),j.dataset.personaComposerStreaming=l?"true":"false",j.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=l)})},_i=()=>{Qe.active||xe&&xe.focus()};i.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>_i(),200)});let rd=()=>{F.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",v.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",xe.placeholder=o.copy?.inputPlaceholder??"How can I help...";let l=le.querySelector("[data-persona-intro-card]");if(l){let h=o.copy?.showWelcomeCard!==!1;l.style.display=h?"":"none",h?(le.classList.remove("persona-gap-3"),le.classList.add("persona-gap-6")):(le.classList.remove("persona-gap-6"),le.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!_?.isStreaming()&&(pe.textContent=o.copy?.sendButtonLabel??"Send"),xe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',xe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=c.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{C(f=>({...f,sessionId:l}))}});let Po=null,Wf=()=>{Po==null&&(Po=setInterval(()=>{let l=ve.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Po),Po=null;return}let f=Date.now();l.forEach(h=>{let x=Number(h.getAttribute("data-tool-elapsed"));x&&(h.textContent=xa(f-x))})},100))},$i=(l,f)=>{if(Object.is(l,f))return!0;if(l===null||f===null||typeof l!="object"||typeof f!="object")return!1;if(Array.isArray(l)||Array.isArray(f))return!Array.isArray(l)||!Array.isArray(f)||l.length!==f.length?!1:l.every((J,N)=>$i(J,f[N]));let h=l,x=f,A=Object.keys(h),P=Object.keys(x);return A.length===P.length&&A.every(J=>Object.prototype.hasOwnProperty.call(x,J)&&$i(h[J],x[J]))},sd=l=>{let{content:f,rawContent:h,llmContent:x,...A}=l;return A},ji=l=>l.role==="assistant"&&l.streaming===!0&&!l.variant&&!l.toolCall&&!l.tools&&!l.approval&&!l.reasoning&&!l.contentParts&&!l.stopReason&&!di(l),Hf=(l,f,h)=>{if(l.length!==f.length)return!1;let x=l[h.index],A=f[h.index];return!x||!A||x.id!==h.id||A.id!==h.id?!1:(!Object.is(x.content,A.content)||!Object.is(x.rawContent,A.rawContent)||!Object.is(x.llmContent,A.llmContent))&&ji(x)&&ji(A)&&$i(sd(x),sd(A))},ad=null,nr=null,Ro=null,Bn=null,ea=l=>{ad=l;let f,h;nr=null;for(let A=l.length-1;A>=0;A-=1){let P=l[A];if(!f&&P.role==="user"&&(f=P),!h&&P.role==="assistant"&&(h=P),!nr&&ji(P)&&(nr={index:A,id:P.id}),f&&h&&nr)break}_r(ve,l,Ee),Ol(ve,fn.artifacts,{suppressTransition:hn}),Wf(),ki(l),Yn(!hn),Mf(l),l.length===0&&(Fr(),Or=!0,Ii=!1),!Pi||Xs?(Pi=!0,Ri=f?.id??null,Wi=h?.id??null):f&&f.id!==Ri?(Ri=f.id,Tf(f.id)):h&&h.id!==Wi&&Ef(),h&&(Wi=h.id);let x=Qe.lastUserMessageId;f&&f.id!==x&&(Qe.lastUserMessageId=f.id,i.emit("user:message",f)),Qe.lastUserMessageWasVoice=!!f?.viaVoice,Oi(l),tr()},Ui=()=>{Bn!==null&&(cancelAnimationFrame(Bn),Bn=null);let l=Ro;Ro=null,l&&ea(l)},id=()=>{Bn!==null&&cancelAnimationFrame(Bn),Bn=null,Ro=null},Bf=l=>{let f=Ro??ad;if(hn&&f&&nr&&Hf(f,l,nr)){Ro=l,Bn===null&&(Bn=requestAnimationFrame(()=>{Bn=null;let h=Ro;Ro=null,h&&ea(h)}));return}if(l.length===0){id(),ea(l);return}Ui(),ea(l)};_=new gs(o,{onMessagesChanged(l){Bf(l)},onStatusChanged(l){let f=o.statusIndicator??{};mt(E,(x=>x==="idle"?f.idleText??It.idle:x==="connecting"?f.connectingText??It.connecting:x==="connected"?f.connectedText??It.connected:x==="error"?f.errorText??It.error:x==="paused"?f.pausedText??It.paused:x==="resuming"?f.resumingText??It.resuming:It[x])(l),f,l)},onStreamingChanged(l){l||(_?.getMessages().length===0?id():Ui()),hn=l,Fi(l),_&&_r(ve,_.getMessages(),Ee),l||Yn(!0),en(),Pc(l?"Responding\u2026":"Response complete."),tr()},onVoiceStatusChanged(l){if(i.emit("voice:status",{status:l,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(l){case"listening":On(),rr();break;case"processing":On(),Vf();break;case"speaking":On(),Kf();break;default:l==="idle"&&_.isBargeInActive()?(On(),rr(),K?.setAttribute("aria-label","End voice session")):(Qe.active=!1,On(),Hn("system"),bn());break}},onArtifactsState(l){fn=l,l.artifacts.length===0&&(Xo=!1),Ol(ve,l.artifacts,{suppressTransition:hn}),Wn(),Oi()},onReconnect(l){let{executionId:f,lastEventId:h}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:f,after:h}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:f,after:h,attempt:l.attempt??1}):i.emit("stream:resumed",{executionId:f,after:h})}}),lt.current=_,qe.push(()=>_.cancel());let zi=null;if(_.onReadAloudChange((l,f)=>{Oc=l,Dc=f,Nc();let h=l??zi;l&&(zi=l);let x=h?_.getMessages().find(A=>A.id===h)??null:null;i.emit("message:read-aloud",{messageId:h,message:x,state:f,timestamp:Date.now()}),f==="idle"&&(zi=null)}),Pi=!0,o.voiceRecognition?.provider?.type==="runtype")try{_.setupVoice()}catch(l){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&_.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(De||o.onSSEEvent)&&_.setSSEEventCallback((l,f)=>{o.onSSEEvent?.(l,f),_e?.processEvent(l,f),De?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(f)})});let ld=()=>{o.resume&&typeof o.reconnectStream=="function"&&_.resumeFromHandle(o.resume)};u?u.then(l=>{if(l){if(l.metadata&&(c=fc(l.metadata),I.syncFromMetadata()),l.messages?.length){Xs=!0;try{_.hydrateMessages(l.messages)}finally{Xs=!1}}l.artifacts?.length&&_.hydrateArtifacts(l.artifacts,l.selectedArtifactId??null)}}).catch(l=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>ld()):ld();let cd=()=>{!Q()||D||!(o.launcher?.composerBar?.expandOnSubmit??!0)||pt(!0,"auto")},Of=(l,f)=>l?f?{refs:[...l.refs,...f.refs],finalize:async()=>{let[h,x]=await Promise.allSettled([l.finalize(),f.finalize()]),A=[];return h.status==="fulfilled"?A.push(h.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",h.reason),x.status==="fulfilled"?A.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),wC(A)}}:l:f,Df=()=>{let f=xe.getInlineMessageFields?.();return f&&f.contentSegments.some(x=>x.kind==="mention")?f.contentSegments:void 0},qr=!1,Nf=async l=>{let f=xe.value.trim(),h=St?.hasAttachments()??!1,x=f?await(Yt?.takeInlineCommand(f)??Promise.resolve(null)):null;if(x?.kind==="action"){xe.value="",xe.style.height="auto",Vr(),Yt?.clear();return}let A=Yt?.collectForSubmit()??null,P=x?.kind==="server"?x.mentions:null,J=Of(A,P),N=x?.kind==="prompt"?x.sendText:f,G=!!A&&A.refs.length>0;if(!N&&!h&&!G&&!P)return;cd();let re;h&&(re=[],re.push(...St.getContentParts()),N&&re.push(Fo(N)));let ge=x?.kind==="prompt"?void 0:Df();xe.value="",xe.style.height="auto",Vr(),_.sendMessage(N,{contentParts:re,mentions:J??void 0,contentSegments:ge,viaVoice:l?.viaVoice}),h&&St.clearAttachments(),A&&Yt?.clear()},qi=async l=>{if(!qr){qr=!0;try{await Nf(l)}finally{qr=!1}}},dd=l=>{if(l.preventDefault(),_.isStreaming()){_.cancel(),_e?.reset(),He?.update();return}qr||qi()},Ff=()=>o.features?.composerHistory!==!1,Vi={...Fl},Ki=!1,Vr=()=>{Vi={...Fl}},_f=()=>_.getMessages().filter(l=>l.role==="user").map(l=>l.content??"").filter(l=>l.length>0),$f=l=>{if(!xe)return;Ki=!0,xe.value=l,xe.dispatchEvent(new Event("input",{bubbles:!0})),Ki=!1;let f=xe.value.length;xe.setSelectionRange(f,f)},jf=l=>{Ki||(l.isComposing||Yt?.handleInput(l.inputType??void 0),Vr())},Uf=l=>{if(xe&&!(!l.isComposing&&Yt?.handleKeydown(l))){if(Ff()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let f=xe.selectionStart===0&&xe.selectionEnd===0,h=Eu({direction:l.key==="ArrowUp"?"up":"down",history:_f(),currentValue:xe.value,atStart:f,state:Vi});if(Vi=h.state,h.handled){l.preventDefault(),h.value!==void 0&&$f(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}if(qr){l.preventDefault();return}Vr(),l.preventDefault(),pe.click()}}},pd=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(ue)&&(_.cancel(),_e?.reset(),He?.update(),Vr(),l.preventDefault(),l.stopImmediatePropagation())},zf=async l=>{if(o.attachments?.enabled!==!0||!St)return;let f=bC(l.clipboardData);f.length!==0&&(l.preventDefault(),await St.handleFiles(f))},ln=null,Tn=!1,or=null,wt=null,ud=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ta=(l="user")=>{if(Tn||_.isStreaming())return;let f=ud();if(!f)return;ln=new f;let x=(o.voiceRecognition??{}).pauseDuration??2e3;ln.continuous=!0,ln.interimResults=!0,ln.lang="en-US";let A=xe.value;ln.onresult=P=>{let J="",N="";for(let re=0;re<P.results.length;re++){let ge=P.results[re],oe=ge[0].transcript;ge.isFinal?J+=oe+" ":N=oe}let G=A+J+N;xe.value=G,or&&clearTimeout(or),(J||N)&&(or=window.setTimeout(()=>{xe.value.trim()&&ln&&Tn&&(Zn(),qi({viaVoice:!0}))},x))},ln.onerror=P=>{P.error!=="no-speech"&&Zn()},ln.onend=()=>{if(Tn){let P=xe.value.trim();P&&P!==A.trim()&&qi({viaVoice:!0}),Zn()}};try{if(ln.start(),Tn=!0,Qe.active=!0,l!=="system"&&(Qe.manuallyDeactivated=!1),Hn(l),bn(),K){let P=o.voiceRecognition??{};wt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:P.iconName??"mic",iconSize:parseFloat(P.iconSize??o.sendButton?.size??"40")||24};let J=P.recordingBackgroundColor,N=P.recordingIconColor,G=P.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=J??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=N??"var(--persona-voice-recording-indicator, #ffffff)",N){let re=K.querySelector("svg");re&&re.setAttribute("stroke",N)}G&&(K.style.borderColor=G),K.setAttribute("aria-label","Stop voice recognition")}}catch{Zn("system")}},Zn=(l="user")=>{if(Tn){if(Tn=!1,or&&(clearTimeout(or),or=null),ln){try{ln.stop()}catch{}ln=null}if(Qe.active=!1,Hn(l),bn(),K){if(K.classList.remove("persona-voice-recording"),wt){K.style.backgroundColor=wt.backgroundColor,K.style.color=wt.color,K.style.borderColor=wt.borderColor;let f=K.querySelector("svg");f&&f.setAttribute("stroke",wt.color||"currentColor"),wt=null}K.setAttribute("aria-label","Start voice recognition")}}},qf=(l,f)=>{let h=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=l?.provider?.type==="runtype",A=l?.provider?.type==="custom";if(!(h||x||A))return null;let J=m("div","persona-send-button-wrapper"),N=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button";let G=l?.tooltipText??"Start voice recognition";N.setAttribute("aria-label",G);let re=l?.iconName??"mic",ge=f?.size??"40px",oe=l?.iconSize??ge,Ce=parseFloat(oe)||24,Ke=l?.backgroundColor??f?.backgroundColor,ut=l?.iconColor??f?.textColor;N.style.width=oe,N.style.height=oe,N.style.minWidth=oe,N.style.minHeight=oe,N.style.fontSize="18px",N.style.lineHeight="1",ut?N.style.color=ut:N.style.color="var(--persona-text, #111827)";let tn=te(re,Ce,ut||"currentColor",1.5);tn?N.appendChild(tn):N.textContent="\u{1F3A4}",Ke?N.style.backgroundColor=Ke:N.style.backgroundColor="",l?.borderWidth&&(N.style.borderWidth=l.borderWidth,N.style.borderStyle="solid"),l?.borderColor&&(N.style.borderColor=l.borderColor),l?.paddingX&&(N.style.paddingLeft=l.paddingX,N.style.paddingRight=l.paddingX),l?.paddingY&&(N.style.paddingTop=l.paddingY,N.style.paddingBottom=l.paddingY),J.appendChild(N);let Tt=l?.showTooltip??!1;return Dt({anchor:N,trigger:J,text:()=>N.getAttribute("aria-label")??G,enabled:Tt}),{micButton:N,micButtonWrapper:J}},Gi=()=>{if(!K||wt)return;let l=o.voiceRecognition??{};wt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:l.iconName??"mic",iconSize:parseFloat(l.iconSize??o.sendButton?.size??"40")||24}},Ji=(l,f)=>{if(!K)return;let h=K.querySelector("svg");h&&h.remove();let x=wt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),A=te(l,x,f,1.5);A&&K.appendChild(A)},na=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},rr=()=>{if(!K)return;Gi();let l=o.voiceRecognition??{},f=l.recordingBackgroundColor,h=l.recordingIconColor,x=l.recordingBorderColor;if(na(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=f??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=h??"var(--persona-voice-recording-indicator, #ffffff)",h){let A=K.querySelector("svg");A&&A.setAttribute("stroke",h)}x&&(K.style.borderColor=x),K.setAttribute("aria-label","Stop voice recognition")},Vf=()=>{if(!K)return;Gi();let l=o.voiceRecognition??{},f=_.getVoiceInterruptionMode(),h=l.processingIconName??"loader",x=l.processingIconColor??wt?.color??"",A=l.processingBackgroundColor??wt?.backgroundColor??"",P=l.processingBorderColor??wt?.borderColor??"";na(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=A,K.style.borderColor=P;let J=x||"currentColor";K.style.color=J,Ji(h,J),K.setAttribute("aria-label","Processing voice input"),f==="none"&&(K.style.cursor="default")},Kf=()=>{if(!K)return;Gi();let l=o.voiceRecognition??{},f=_.getVoiceInterruptionMode(),h=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",x=l.speakingIconName??h,A=l.speakingIconColor??(f==="barge-in"?l.recordingIconColor??wt?.color??"":wt?.color??""),P=l.speakingBackgroundColor??(f==="barge-in"?l.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":wt?.backgroundColor??""),J=l.speakingBorderColor??(f==="barge-in"?l.recordingBorderColor??"":wt?.borderColor??"");na(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=P,K.style.borderColor=J;let N=A||"currentColor";K.style.color=N,Ji(x,N);let G=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",G),f==="none"&&(K.style.cursor="default"),f==="barge-in"&&K.classList.add("persona-voice-recording")},On=()=>{K&&(na(),wt&&(K.style.backgroundColor=wt.backgroundColor??"",K.style.color=wt.color??"",K.style.borderColor=wt.borderColor??"",Ji(wt.iconName,wt.color||"currentColor"),wt=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},oa=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let l=_.getVoiceStatus(),f=_.getVoiceInterruptionMode();if(f==="none"&&(l==="processing"||l==="speaking"))return;if(f==="cancel"&&(l==="processing"||l==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,bn(),Hn("user"),On()});return}_.toggleVoice().then(()=>{Qe.active=_.isVoiceActive(),Qe.manuallyDeactivated=!_.isVoiceActive(),bn(),Hn("user"),_.isVoiceActive()?rr():On()});return}if(Tn){let l=xe.value.trim();Qe.manuallyDeactivated=!0,bn(),Zn("user"),l&&(xe.value="",xe.style.height="auto",_.sendMessage(l))}else Qe.manuallyDeactivated=!1,bn(),ta("user")};Ic=oa,K&&(K.addEventListener("click",oa),qe.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),On()):Zn("system"),K&&K.removeEventListener("click",oa)}));let Gf=i.on("assistant:complete",()=>{qc&&(Qe.active||Qe.manuallyDeactivated||qc==="assistant"&&!Qe.lastUserMessageWasVoice||setTimeout(()=>{!Qe.active&&!Qe.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Qe.active=_.isVoiceActive(),Hn("auto"),_.isVoiceActive()&&rr()}):ta("auto"))},600))});qe.push(Gf);let Jf=i.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});qe.push(Jf);let gd=()=>{pt(!D,"user")},Bt=null,zt=null;if(S&&!Q()){let{instance:l,element:f}=Vl({config:o,plugins:r,onToggle:gd});Bt=l,l||(zt=f)}Bt?e.appendChild(Bt.element):zt&&e.appendChild(zt),zr(),ki(),rd(),Fi(_.isStreaming()),Zc()||(Jt()==="follow"?Yn(!0):Qc()),vf(),$&&(!S||Q()?setTimeout(()=>_i(),0):D&&setTimeout(()=>_i(),200));let Kr=()=>{if(Q()){Jo(),zr();return}let l=Wt(o),f=o.launcher?.sidebarMode??!1,h=l||f||(o.launcher?.fullHeight??!1),x=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,P=o.launcher?.mobileBreakpoint??640,J=x.innerWidth<=P,N=A&&J&&S;try{if(N){Ir(),Wr=qs();return}let G=!1;q&&(q=!1,Ir(),G=!0);let re=qs();if(!G&&re!==Wr&&(Ir(),G=!0),Wr=re,G&&Ei(),!S&&!l){ye.style.height="",ye.style.width="";return}if(!f&&!l){let oe=o?.launcher?.width??o?.launcherWidth??un;ye.style.width=oe,ye.style.maxWidth=oe}if(zs(),!h){let ge=x.innerHeight,oe=64,Ce=o.launcher?.heightOffset??0,Ke=Math.max(200,ge-oe),ut=Math.min(640,Ke),nt=Math.max(200,ut-Ce);ye.style.height=`${nt}px`}}finally{if(Jo(),zr(),D&&S){let re=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ge=o.launcher?.sidebarMode??!1,oe=o.launcher?.mobileFullscreen??!0,Ce=Wt(o)&&oe&&re,Ke=ge||oe&&re&&S||Ce;if(Ke&&!Sn){let ut=e.getRootNode(),nt=ut instanceof ShadowRoot?ut.host:e.closest(".persona-host");nt&&!An&&(An=jl(nt,o.launcher?.zIndex??Ut)),Sn=Ul(e.ownerDocument)}else Ke||(An?.(),An=null,Sn?.(),Sn=null)}}};Kr();let fd=e.ownerDocument.defaultView??window;if(fd.addEventListener("resize",Kr),qe.push(()=>fd.removeEventListener("resize",Kr)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{Jo()});l.observe(j),qe.push(()=>l.disconnect())}sn=le.scrollTop;let md=Pn(le),Xf=()=>{let l=le.getRootNode();return(typeof l.getSelection=="function"?l.getSelection():null)??le.ownerDocument.getSelection()},Xi=()=>Iu(Xf(),le),hd=()=>{let l=le.scrollTop,f=Pn(le),h=f<md;if(md=f,!zn()){sn=l,en();return}let{action:x,nextLastScrollTop:A}=Ua({following:Zt.isFollowing(),currentScrollTop:l,lastScrollTop:sn,nearBottom:fo(le,Qs),userScrollThreshold:yf,isAutoScrolling:an||Js||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(sn=A,x==="resume"){Xi()||Qn();return}x==="pause"&&Nr()};if(le.addEventListener("scroll",hd,{passive:!0}),qe.push(()=>le.removeEventListener("scroll",hd)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{Sf(),tl(ve)});l.observe(ve),l.observe(le),qe.push(()=>l.disconnect())}let yd=()=>{zn()&&Zt.isFollowing()&&Xi()&&Nr()},bd=le.ownerDocument;bd.addEventListener("selectionchange",yd),qe.push(()=>{bd.removeEventListener("selectionchange",yd)});let Qf=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),vd=l=>{Mc()&&zn()&&Zt.isFollowing()&&Qf.has(l.key)&&Nr()},xd=l=>{if(!Mc()||!zn()||!Zt.isFollowing())return;let f=l.target;f&&f.closest("a, button, [tabindex], input, textarea, select")&&Nr()};le.addEventListener("keydown",vd),le.addEventListener("focusin",xd),qe.push(()=>{le.removeEventListener("keydown",vd),le.removeEventListener("focusin",xd)});let Cd=l=>{if(!zn())return;let f=za({following:Zt.isFollowing(),deltaY:l.deltaY,nearBottom:fo(le,Qs),resumeWhenNearBottom:!0});f==="pause"?Nr():f==="resume"&&!Xi()&&Qn()};le.addEventListener("wheel",Cd,{passive:!0}),qe.push(()=>le.removeEventListener("wheel",Cd)),kt.addEventListener("click",()=>{Fr(),le.scrollTop=le.scrollHeight,sn=le.scrollTop,Qn(),Yn(!0),en()}),qe.push(()=>kt.remove()),qe.push(()=>{Gc(),Fr()});let wd=()=>{T&&(To&&(T.removeEventListener("click",To),To=null),O()?(T.style.display="",To=()=>{pt(!1,"user")},T.addEventListener("click",To)):T.style.display="none")};wd(),(()=>{let{clearChatButton:l}=Le;l&&l.addEventListener("click",()=>{_.clearMessages(),Eo.clear(),Qn(),Do(Le.composerOverlay);try{localStorage.removeItem(Mr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Mr}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Mr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(f),d?.clear&&Bi(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},I.syncFromMetadata(),De?.clear(),_e?.reset(),He?.update()})})(),X&&X.addEventListener("submit",dd);let Ad=[["keydown",Uf],["input",jf],["paste",zf],["focus",uf]],Sd=l=>{if(l)for(let[f,h]of Ad)l.addEventListener(f,h)},Td=l=>{if(l)for(let[f,h]of Ad)l.removeEventListener(f,h)};Sd(xe),Yt?.onComposerSwap((l,f)=>{Td(f),xe=l,Sd(l)});let Ed=e.ownerDocument??document;Ed.addEventListener("keydown",pd,!0);let Md="persona-attachment-drop-active",Gr=0,Qi=()=>{Gr=0,ue.classList.remove(Md)},sr=()=>o.attachments?.enabled===!0&&St!==null,kd=l=>{!pi(l.dataTransfer)||!sr()||(Gr++,Gr===1&&ue.classList.add(Md))},Ld=l=>{!pi(l.dataTransfer)||!sr()||(Gr--,Gr<=0&&Qi())},Pd=l=>{!pi(l.dataTransfer)||!sr()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Rd=l=>{if(!pi(l.dataTransfer)||!sr())return;l.preventDefault(),l.stopPropagation(),Qi();let f=Array.from(l.dataTransfer.files??[]);f.length!==0&&St.handleFiles(f)},eo=!0;ue.addEventListener("dragenter",kd,eo),ue.addEventListener("dragleave",Ld,eo),e.addEventListener("dragover",Pd,eo),e.addEventListener("drop",Rd,eo);let ra=e.ownerDocument,Id=l=>{sr()&&l.preventDefault()},Wd=l=>{sr()&&l.preventDefault()};ra.addEventListener("dragover",Id),ra.addEventListener("drop",Wd),qe.push(()=>{X&&X.removeEventListener("submit",dd),Td(xe),Ed.removeEventListener("keydown",pd,!0),Yt?.destroy()}),qe.push(()=>{ue.removeEventListener("dragenter",kd,eo),ue.removeEventListener("dragleave",Ld,eo),e.removeEventListener("dragover",Pd,eo),e.removeEventListener("drop",Rd,eo),ra.removeEventListener("dragover",Id),ra.removeEventListener("drop",Wd),Qi()}),qe.push(()=>{_.cancel()}),Bt?qe.push(()=>{Bt?.destroy()}):zt&&qe.push(()=>{zt?.remove()});let Lt={update(l){let f=o.toolCall,h=o.messageActions,x=o.layout?.messages,A=o.colorScheme,P=o.loadingIndicator,J=o.iterationDisplay,N=o.features?.showReasoning,G=o.features?.showToolCalls,re=o.features?.toolCallDisplay,ge=o.features?.reasoningDisplay,oe=o.features?.streamAnimation?.type;o=ii(o,l),Vs(),hr(e,o),Hs(e,o),Bs(e,o),Wn(),o.colorScheme!==A&&zc();let Ce=ai.getForInstance(o.plugins);r.length=0,r.push(...Ce),S=o.launcher?.enabled??!0,R=o.launcher?.autoExpand??!1,se=o.features?.showReasoning??!0,fe=o.features?.showToolCalls??!0,ce=o.features?.scrollToBottom??{};let Ke=Jt();Z=o.features?.scrollBehavior??{},Ke!==Jt()&&(Fr(),Qn()),Rc(),en();let ut=Y;if(Y=o.features?.showEventStreamToggle??!1,Y&&!ut){if(De||(de=new Is(he),De=new Rs(Me,de),_e=_e??new Ws,de.open().then(()=>De?.restore()).catch(()=>{}),_.setSSEEventCallback((ee,Je)=>{o.onSSEEvent?.(ee,Je),_e?.processEvent(ee,Je),De.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(Je)})})),!tt&&B){let ee=o.features?.eventStream?.classNames,Je="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"+(ee?.toggleButton?" "+ee.toggleButton:"");tt=m("button",Je),tt.style.width="28px",tt.style.height="28px",tt.style.color=Kt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let yt=te("activity","18px","currentColor",1.5);yt&&tt.appendChild(yt);let ot=Le.clearChatButtonWrapper,st=Le.closeButtonWrapper,$t=ot||st;$t&&$t.parentNode===B?B.insertBefore(tt,$t):B.appendChild(tt),tt.addEventListener("click",()=>{Ue?Pr():wi()})}}else!Y&&ut&&(Pr(),tt&&(tt.remove(),tt=null),De?.clear(),de?.destroy(),De=null,de=null,_e?.reset(),_e=null);if(o.launcher?.enabled===!1&&Bt&&(Bt.destroy(),Bt=null),o.launcher?.enabled===!1&&zt&&(zt.remove(),zt=null),o.launcher?.enabled!==!1&&!Bt&&!zt){let{instance:ee,element:Je}=Vl({config:o,plugins:r,onToggle:gd});Bt=ee,ee||(zt=Je),e.appendChild(Je)}Bt&&Bt.update(o),H&&o.launcher?.title!==void 0&&(H.textContent=o.launcher.title),V&&o.launcher?.subtitle!==void 0&&(V.textContent=o.launcher.subtitle);let nt=o.layout?.header;if(nt?.layout!==U&&B){let ee=nt?ks(o,nt,{showClose:O(),onClose:()=>pt(!1,"user")}):yo({config:o,showClose:O(),onClose:()=>pt(!1,"user")});at.replaceHeader(ee),B=at.header.element,k=at.header.iconHolder,H=at.header.headerTitle,V=at.header.headerSubtitle,T=at.header.closeButton,U=nt?.layout}else if(nt){if(k&&(k.style.display=nt.showIcon===!1?"none":""),H&&(H.style.display=nt.showTitle===!1?"none":""),V&&(V.style.display=nt.showSubtitle===!1?"none":""),T){let ee=O()&&nt.showCloseButton!==!1;T.style.display=ee?"":"none"}if(Le.clearChatButtonWrapper){let ee=nt.showClearChat;if(ee!==void 0){Le.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Je}=Le;Je&&!Je.classList.contains("persona-absolute")&&(ee?Je.classList.remove("persona-ml-auto"):Je.classList.add("persona-ml-auto"))}}}let Tt=o.layout?.showHeader!==!1;B&&(B.style.display=Tt?"":"none");let Pt=o.layout?.showFooter!==!1;j&&(j.style.display=Pt?"":"none"),Jo(),en(),S!==w?S?pt(R,"auto"):(D=!0,zr()):R!==z&&pt(R,"auto"),z=R,w=S,Kr(),wd();let $e=JSON.stringify(o.toolCall)!==JSON.stringify(f),Se=JSON.stringify(o.messageActions)!==JSON.stringify(h),Et=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),gt=o.loadingIndicator?.render!==P?.render||o.loadingIndicator?.renderIdle!==P?.renderIdle||o.loadingIndicator?.showBubble!==P?.showBubble,qt=o.iterationDisplay!==J,ft=(o.features?.showReasoning??!0)!==(N??!0)||(o.features?.showToolCalls??!0)!==(G??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(re)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ge);($e||Se||Et||gt||qt||ft)&&_&&(Li++,_r(ve,_.getMessages(),Ee));let Rt=o.features?.streamAnimation?.type;if(Rt!==oe&&Rt&&Rt!=="none"){let ee=xr(Rt,o.features?.streamAnimation?.plugins);ee&&Ga(ee,e)}let Ie=o.launcher??{},je=Ie.headerIconHidden??!1,Nt=o.layout?.header?.showIcon,Ft=je||Nt===!1,At=Ie.headerIconName,ct=Ie.headerIconSize??"48px";if(k){let ee=ue.querySelector(".persona-border-b-persona-divider"),Je=ee?.querySelector(".persona-flex-col");if(Ft)k.style.display="none",ee&&Je&&!ee.contains(Je)&&ee.insertBefore(Je,ee.firstChild);else{if(k.style.display="",k.style.height=ct,k.style.width=ct,ee&&Je&&(ee.contains(k)?k.nextSibling!==Je&&(k.remove(),ee.insertBefore(k,Je)):ee.insertBefore(k,Je)),At){let ot=parseFloat(ct)||24,st=te(At,ot*.6,"currentColor",1);st?k.replaceChildren(st):k.textContent=Ie.agentIconText??"\u{1F4AC}"}else if(Ie.iconUrl){let ot=k.querySelector("img");if(ot)ot.src=Ie.iconUrl,ot.style.height=ct,ot.style.width=ct;else{let st=document.createElement("img");st.src=Ie.iconUrl,st.alt="",st.className="persona-rounded-xl persona-object-cover",st.style.height=ct,st.style.width=ct,k.replaceChildren(st)}}else{let ot=k.querySelector("svg"),st=k.querySelector("img");(ot||st)&&k.replaceChildren(),k.textContent=Ie.agentIconText??"\u{1F4AC}"}let yt=k.querySelector("img");yt&&(yt.style.height=ct,yt.style.width=ct)}}let ht=o.layout?.header?.showTitle,et=o.layout?.header?.showSubtitle;if(H&&(H.style.display=ht===!1?"none":""),V&&(V.style.display=et===!1?"none":""),T){let ee=O()&&o.layout?.header?.showCloseButton!==!1;T.style.display=ee?"":"none";let Je=Ie.closeButtonSize??"32px",yt=Ie.closeButtonPlacement??"inline";T.style.height=Je,T.style.width=Je;let{closeButtonWrapper:ot}=Le,st=yt==="top-right",$t=ot?.classList.contains("persona-absolute");if(ot&&st!==$t)if(ot.remove(),st)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ue.style.position="relative",ue.appendChild(ot);else{let no=Ie.clearChat?.placement??"inline",Qr=Ie.clearChat?.enabled??!0;ot.className=Qr&&no==="inline"?"":"persona-ml-auto";let Hd=ue.querySelector(".persona-border-b-persona-divider");Hd&&Hd.appendChild(ot)}if(T.style.color=Ie.closeButtonColor||Kt.actionIconColor,Ie.closeButtonBackgroundColor?(T.style.backgroundColor=Ie.closeButtonBackgroundColor,T.classList.remove("hover:persona-bg-gray-100")):(T.style.backgroundColor="",T.classList.add("hover:persona-bg-gray-100")),Ie.closeButtonBorderWidth||Ie.closeButtonBorderColor){let no=Ie.closeButtonBorderWidth||"0px",Qr=Ie.closeButtonBorderColor||"transparent";T.style.border=`${no} solid ${Qr}`,T.classList.remove("persona-border-none")}else T.style.border="",T.classList.add("persona-border-none");Ie.closeButtonBorderRadius?(T.style.borderRadius=Ie.closeButtonBorderRadius,T.classList.remove("persona-rounded-full")):(T.style.borderRadius="",T.classList.add("persona-rounded-full")),Ie.closeButtonPaddingX?(T.style.paddingLeft=Ie.closeButtonPaddingX,T.style.paddingRight=Ie.closeButtonPaddingX):(T.style.paddingLeft="",T.style.paddingRight=""),Ie.closeButtonPaddingY?(T.style.paddingTop=Ie.closeButtonPaddingY,T.style.paddingBottom=Ie.closeButtonPaddingY):(T.style.paddingTop="",T.style.paddingBottom="");let nn=Ie.closeButtonIconName??"x",vn=Ie.closeButtonIconText??"\xD7";T.innerHTML="";let Ot=te(nn,"28px","currentColor",1);Ot?(Ot.style.display="block",T.appendChild(Ot)):T.textContent=vn;let jt=Ie.closeButtonTooltipText??"Close chat",Nn=Ie.closeButtonShowTooltip??!0;T.setAttribute("aria-label",jt),ot&&Dt({anchor:T,trigger:ot,text:()=>T?.getAttribute("aria-label")??jt,enabled:Nn})}let{clearChatButton:Ne,clearChatButtonWrapper:bt}=Le;if(Ne){let ee=Ie.clearChat??{},Je=ee.enabled??!0,yt=o.layout?.header?.showClearChat,ot=yt!==void 0?yt:Je,st=ee.placement??"inline";if(bt){bt.style.display=ot?"":"none";let{closeButtonWrapper:$t}=Le;!Q()&&$t&&!$t.classList.contains("persona-absolute")&&(ot?$t.classList.remove("persona-ml-auto"):$t.classList.add("persona-ml-auto"));let nn=st==="top-right",vn=bt.classList.contains("persona-absolute");if(!Q()&&nn!==vn&&ot){if(bt.remove(),nn)bt.className="persona-absolute persona-top-4 persona-z-50",bt.style.right="48px",ue.style.position="relative",ue.appendChild(bt);else{bt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",bt.style.right="";let jt=ue.querySelector(".persona-border-b-persona-divider"),Nn=Le.closeButtonWrapper;jt&&Nn&&Nn.parentElement===jt?jt.insertBefore(bt,Nn):jt&&jt.appendChild(bt)}let Ot=Le.closeButtonWrapper;Ot&&!Ot.classList.contains("persona-absolute")&&(nn?Ot.classList.add("persona-ml-auto"):Ot.classList.remove("persona-ml-auto"))}}if(ot){if(!Q()){let no=ee.size??"32px";Ne.style.height=no,Ne.style.width=no}let $t=ee.iconName??"refresh-cw",nn=ee.iconColor??"";Ne.style.color=nn||Kt.actionIconColor,Ne.innerHTML="";let vn=Q()?"14px":"20px",Ot=te($t,vn,"currentColor",1);if(Ot&&(Ot.style.display="block",Ne.appendChild(Ot)),ee.backgroundColor?(Ne.style.backgroundColor=ee.backgroundColor,Ne.classList.remove("hover:persona-bg-gray-100")):(Ne.style.backgroundColor="",Ne.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let no=ee.borderWidth||"0px",Qr=ee.borderColor||"transparent";Ne.style.border=`${no} solid ${Qr}`,Ne.classList.remove("persona-border-none")}else Ne.style.border="",Ne.classList.add("persona-border-none");ee.borderRadius?(Ne.style.borderRadius=ee.borderRadius,Ne.classList.remove("persona-rounded-full")):(Ne.style.borderRadius="",Ne.classList.add("persona-rounded-full")),ee.paddingX?(Ne.style.paddingLeft=ee.paddingX,Ne.style.paddingRight=ee.paddingX):(Ne.style.paddingLeft="",Ne.style.paddingRight=""),ee.paddingY?(Ne.style.paddingTop=ee.paddingY,Ne.style.paddingBottom=ee.paddingY):(Ne.style.paddingTop="",Ne.style.paddingBottom="");let jt=ee.tooltipText??"Clear chat",Nn=ee.showTooltip??!0;Ne.setAttribute("aria-label",jt),bt&&Dt({anchor:Ne,trigger:bt,text:()=>Ne?.getAttribute("aria-label")??jt,enabled:Nn})}}let _t=o.actionParsers&&o.actionParsers.length?o.actionParsers:[li],dn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Er.message,Er.messageAndClick];I=ci({parsers:_t,handlers:dn,getSessionMetadata:y,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null}),Ee=Tg(o,I,we),_.updateConfig(o),_r(ve,_.getMessages(),Ee),ki(),rd(),Fi(_.isStreaming());let Jr=o.voiceRecognition?.enabled===!0,sa=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Mt=o.voiceRecognition?.provider?.type==="runtype";if(Jr&&(sa||Mt))if(!K||!ze){let ee=qf(o.voiceRecognition,o.sendButton);ee&&(K=ee.micButton,ze=ee.micButtonWrapper,Ge.insertBefore(ze,gn),K.addEventListener("click",oa),K.disabled=_.isStreaming())}else{let ee=o.voiceRecognition??{},Je=o.sendButton??{},yt=ee.iconName??"mic",ot=Je.size??"40px",st=ee.iconSize??ot,$t=parseFloat(st)||24;K.style.width=st,K.style.height=st,K.style.minWidth=st,K.style.minHeight=st;let nn=ee.iconColor??Je.textColor;K.innerHTML="";let vn=te(yt,$t,nn||"currentColor",1.5);vn?K.appendChild(vn):K.textContent="\u{1F3A4}";let Ot=ee.backgroundColor??Je.backgroundColor;Ot?K.style.backgroundColor=Ot:K.style.backgroundColor="",nn?K.style.color=nn:K.style.color="var(--persona-text, #111827)",ee.borderWidth?(K.style.borderWidth=ee.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),ee.borderColor?K.style.borderColor=ee.borderColor:K.style.borderColor="",ee.paddingX?(K.style.paddingLeft=ee.paddingX,K.style.paddingRight=ee.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),ee.paddingY?(K.style.paddingTop=ee.paddingY,K.style.paddingBottom=ee.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let jt=ee.tooltipText??"Start voice recognition",Nn=ee.showTooltip??!1;K.setAttribute("aria-label",jt),ze&&Dt({anchor:K,trigger:ze,text:()=>K?.getAttribute("aria-label")??jt,enabled:Nn}),ze.style.display="",K.disabled=_.isStreaming()}else K&&ze&&(ze.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()&&_.toggleVoice():Tn&&Zn());if(o.attachments?.enabled===!0){if(!We||!Ae){let ee=o.attachments??{},yt=(o.sendButton??{}).size??"40px";Ye||(Ye=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ye.style.display="none",X.insertBefore(Ye,xe)),Pe||(Pe=document.createElement("input"),Pe.type="file",Pe.accept=(ee.allowedTypes??jn).join(","),Pe.multiple=(ee.maxFiles??4)>1,Pe.style.display="none",Pe.setAttribute("aria-label","Attach files"),X.insertBefore(Pe,xe)),We=m("div","persona-send-button-wrapper"),Ae=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ae.type="button",Ae.setAttribute("aria-label",ee.buttonTooltipText??"Attach file");let ot=ee.buttonIconName??"paperclip",st=yt,$t=parseFloat(st)||40,nn=Math.round($t*.6);Ae.style.width=st,Ae.style.height=st,Ae.style.minWidth=st,Ae.style.minHeight=st,Ae.style.fontSize="18px",Ae.style.lineHeight="1";let vn=te(ot,nn,"currentColor",1.5);vn?Ae.appendChild(vn):Ae.textContent="\u{1F4CE}",Ae.addEventListener("click",jt=>{jt.preventDefault(),Pe?.click()}),We.appendChild(Ae);let Ot=ee.buttonTooltipText??"Attach file";Dt({anchor:Ae,trigger:We,text:()=>Ae?.getAttribute("aria-label")??Ot}),Te?Te.append(We):X.appendChild(We),!St&&Pe&&Ye&&(St=mr.fromConfig(ee),St.setPreviewsContainer(Ye),Pe.addEventListener("change",async()=>{St&&Pe?.files&&(await St.handleFileSelect(Pe.files),Pe.value="")}))}else{We.style.display="";let ee=o.attachments??{};Pe&&(Pe.accept=(ee.allowedTypes??jn).join(","),Pe.multiple=(ee.maxFiles??4)>1),St&&St.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}if(ue.querySelector(".persona-attachment-drop-overlay")?.remove(),ue.appendChild(Eg(o.attachments?.dropOverlay)),Ae){let ee=o.attachments??{},Je=ee.buttonTooltipText??"Attach file";Ae.setAttribute("aria-label",Je),Ae.textContent="";let yt=parseFloat(o.sendButton?.size??"40px")||40,ot=te(ee.buttonIconName??"paperclip",Math.round(yt*.6),"currentColor",1.5);ot?Ae.appendChild(ot):Ae.textContent="\u{1F4CE}",We&&Dt({anchor:Ae,trigger:We,text:()=>Ae?.getAttribute("aria-label")??Je})}}else We&&(We.style.display="none"),St&&St.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let Ht=o.sendButton??{},Xr=Ht.useIcon??!1,ia=Ht.iconText??"\u2191",ar=Ht.iconName,la=Ht.tooltipText??"Send message",Yi=Ht.showTooltip??!1,Io=Ht.size??"40px",Dn=Ht.backgroundColor,Wo=Ht.textColor;if(Xr){if(pe.style.width=Io,pe.style.height=Io,pe.style.minWidth=Io,pe.style.minHeight=Io,pe.style.fontSize="18px",pe.style.lineHeight="1",Wo?pe.style.color=Wo:pe.style.color="var(--persona-button-primary-fg, #ffffff)",!_.isStreaming())if(pe.innerHTML="",ar){let ee=parseFloat(Io)||24,Je=Wo?.trim()||"currentColor",yt=te(ar,ee,Je,2);yt?pe.appendChild(yt):pe.textContent=ia}else pe.textContent=ia;pe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Dn?(pe.style.backgroundColor=Dn,pe.classList.remove("persona-bg-persona-primary")):(pe.style.backgroundColor="",pe.classList.add("persona-bg-persona-primary"))}else pe.textContent=o.copy?.sendButtonLabel??"Send",pe.style.width="",pe.style.height="",pe.style.minWidth="",pe.style.minHeight="",pe.style.fontSize="",pe.style.lineHeight="",pe.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Dn?(pe.style.backgroundColor=Dn,pe.classList.remove("persona-bg-persona-accent")):pe.classList.add("persona-bg-persona-accent"),Wo?pe.style.color=Wo:pe.classList.add("persona-text-white");Ht.borderWidth?(pe.style.borderWidth=Ht.borderWidth,pe.style.borderStyle="solid"):(pe.style.borderWidth="",pe.style.borderStyle=""),Ht.borderColor?pe.style.borderColor=Ht.borderColor:pe.style.borderColor="",Ht.paddingX?(pe.style.paddingLeft=Ht.paddingX,pe.style.paddingRight=Ht.paddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),Ht.paddingY?(pe.style.paddingTop=Ht.paddingY,pe.style.paddingBottom=Ht.paddingY):(pe.style.paddingTop="",pe.style.paddingBottom=""),_.isStreaming()||pe.setAttribute("aria-label",la),gn&&Dt({anchor:pe,trigger:gn,text:()=>pe.getAttribute("aria-label")??la,enabled:Yi});let ca=o.layout?.contentMaxWidth??(Q()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);ca?(ve.style.maxWidth=ca,ve.style.marginLeft="auto",ve.style.marginRight="auto",ve.style.width="100%",X&&(X.style.maxWidth=ca,X.style.marginLeft="auto",X.style.marginRight="auto"),xt&&(xt.style.maxWidth=ca,xt.style.marginLeft="auto",xt.style.marginRight="auto")):(ve.style.maxWidth="",ve.style.marginLeft="",ve.style.marginRight="",ve.style.width="",X&&(X.style.maxWidth="",X.style.marginLeft="",X.style.marginRight=""),xt&&(xt.style.maxWidth="",xt.style.marginLeft="",xt.style.marginRight=""));let to=o.statusIndicator??{},Yf=to.visible??!0;if(E.style.display=Yf?"":"none",_){let ee=_.getStatus();mt(E,(yt=>yt==="idle"?to.idleText??It.idle:yt==="connecting"?to.connectingText??It.connecting:yt==="connected"?to.connectedText??It.connected:yt==="error"?to.errorText??It.error:It[yt])(ee),to,ee)}E.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Zf=to.align==="left"?"persona-text-left":to.align==="center"?"persona-text-center":"persona-text-right";E.classList.add(Zf)},open(){O()&&pt(!0,"api")},close(){O()&&pt(!1,"api")},toggle(){O()&&pt(!D,"api")},reconnect(){_.reconnectNow()},clearChat(){In=!1,_.clearMessages(),Eo.clear(),Qn();try{localStorage.removeItem(Mr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Mr}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Mr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),d?.clear&&Bi(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},I.syncFromMetadata(),De?.clear(),_e?.reset(),He?.update()},setMessage(l){return!xe||_.isStreaming()?!1:(!D&&O()&&pt(!0,"system"),xe.value=l,xe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let f=l?.trim()||xe.value.trim();return f?(!D&&O()&&pt(!0,"system"),xe.value="",xe.style.height="auto",_.sendMessage(f),!0):!1},startVoiceRecognition(){return _.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()||(!D&&O()&&pt(!0,"system"),Qe.manuallyDeactivated=!1,bn(),_.toggleVoice().then(()=>{Qe.active=_.isVoiceActive(),Hn("user"),_.isVoiceActive()&&rr()})),!0):Tn?!0:ud()?(!D&&O()&&pt(!0,"system"),Qe.manuallyDeactivated=!1,bn(),ta("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,bn(),Hn("user"),On()}),!0):!1:Tn?(Qe.manuallyDeactivated=!0,bn(),Zn("user"),!0):!1},injectMessage(l){return!D&&O()&&pt(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!D&&O()&&pt(!0,"system");let f=_.injectAssistantMessage(l);return ie&&(ie=!1,me&&(clearTimeout(me),me=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),f},injectUserMessage(l){return!D&&O()&&pt(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!D&&O()&&pt(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!D&&O()&&pt(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!D&&O()&&pt(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!D&&O()&&pt(!0,"system"),_.injectTestEvent(l)},async connectStream(l,f){return _.connectStream(l,f)},__pushEventStreamEvent(l){De&&(_e?.processEvent(l.type,l.payload),De.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Y||!De||wi()},hideEventStream(){Ue&&Pr()},isEventStreamVisible(){return Ue},showArtifacts(){Gt(o)&&(In=!1,Xo=!0,Wn(),Ze?.setMobileOpen(!0))},hideArtifacts(){Gt(o)&&(In=!0,Wn())},upsertArtifact(l){return Gt(o)?(Bo(o.features?.artifacts,l.artifactType)==="panel"&&(In=!1,Xo=!0),_.upsertArtifact(l)):null},selectArtifact(l){Gt(o)&&_.selectArtifact(l)},clearArtifacts(){Gt(o)&&_.clearArtifacts()},getArtifacts(){return _?.getArtifacts()??[]},getSelectedArtifactId(){return _?.getSelectedArtifactId()??null},focusInput(){return S&&!D&&!Q()||!xe?!1:(xe.focus(),!0)},async resolveApproval(l,f,h){let A=_.getMessages().find(P=>P.variant==="approval"&&P.approval?.id===l);if(!A?.approval)throw new Error(`Approval not found: ${l}`);if(A.approval.toolType==="webmcp"){_.resolveWebMcpApproval(A.id,f);return}return _.resolveApproval(A.approval,f,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(l){C(l)},on(l,f){return i.on(l,f)},off(l,f){i.off(l,f)},isOpen(){return O()&&D},isVoiceActive(){return Qe.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:O()&&D,launcherEnabled:S,voiceActive:Qe.active,streaming:_.isStreaming()}},showCSATFeedback(l){!D&&O()&&pt(!0,"system");let f=ve.querySelector(".persona-feedback-container");f&&f.remove();let h=uc({onSubmit:async(x,A)=>{_.isClientTokenMode()&&await _.submitCSATFeedback(x,A),l?.onSubmit?.(x,A)},onDismiss:l?.onDismiss,...l});ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!D&&O()&&pt(!0,"system");let f=ve.querySelector(".persona-feedback-container");f&&f.remove();let h=gc({onSubmit:async(x,A)=>{_.isClientTokenMode()&&await _.submitNPSFeedback(x,A),l?.onSubmit?.(x,A)},onDismiss:l?.onDismiss,...l});ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,f){return _.submitCSATFeedback(l,f)},async submitNPSFeedback(l,f){return _.submitNPSFeedback(l,f)},destroy(){Ui(),Po!=null&&(clearInterval(Po),Po=null),qe.forEach(l=>l()),Oe.remove(),Xe?.remove(),Bt?.destroy(),zt?.remove(),To&&T.removeEventListener("click",To)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let l=window.AgentWidgetBrowser,f={controller:Lt,getMessages:Lt.getMessages,getStatus:Lt.getStatus,getMetadata:Lt.getPersistentMetadata,updateMetadata:Lt.updatePersistentMetadata,clearHistory:()=>Lt.clearChat(),setVoiceActive:h=>h?Lt.startVoiceRecognition():Lt.stopVoiceRecognition()};window.AgentWidgetBrowser=f,qe.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=l)})}if(typeof window<"u"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===l)&&Lt.focusInput()};if(window.addEventListener("persona:focusInput",f),qe.push(()=>{window.removeEventListener("persona:focusInput",f)}),Y){let N=re=>{let ge=re.detail;(!ge?.instanceId||ge.instanceId===l)&&Lt.showEventStream()},G=re=>{let ge=re.detail;(!ge?.instanceId||ge.instanceId===l)&&Lt.hideEventStream()};window.addEventListener("persona:showEventStream",N),window.addEventListener("persona:hideEventStream",G),qe.push(()=>{window.removeEventListener("persona:showEventStream",N),window.removeEventListener("persona:hideEventStream",G)})}let h=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===l)&&Lt.showArtifacts()},x=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===l)&&Lt.hideArtifacts()},A=N=>{let G=N.detail;G?.instanceId&&G.instanceId!==l||G?.artifact&&Lt.upsertArtifact(G.artifact)},P=N=>{let G=N.detail;G?.instanceId&&G.instanceId!==l||typeof G?.id=="string"&&Lt.selectArtifact(G.id)},J=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===l)&&Lt.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",P),window.addEventListener("persona:clearArtifacts",J),qe.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",P),window.removeEventListener("persona:clearArtifacts",J)})}let cn=vC(o.persistState);if(cn&&O()){let l=xC(cn.storage),f=`${cn.keyPrefix}widget-open`,h=`${cn.keyPrefix}widget-voice`,x=`${cn.keyPrefix}widget-voice-mode`;if(l){let A=cn.persist?.openState&&l.getItem(f)==="true",P=cn.persist?.voiceState&&l.getItem(h)==="true",J=cn.persist?.voiceState&&l.getItem(x)==="true";if(A&&setTimeout(()=>{Lt.open(),setTimeout(()=>{if(P||J)Lt.startVoiceRecognition();else if(cn.persist?.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),cn.persist?.openState&&(i.on("widget:opened",()=>{l.setItem(f,"true")}),i.on("widget:closed",()=>{l.setItem(f,"false")})),cn.persist?.voiceState&&(i.on("voice:state",N=>{l.setItem(h,N.active?"true":"false")}),i.on("user:message",N=>{l.setItem(x,N.viaVoice?"true":"false")})),cn.clearOnChatClear){let N=()=>{l.removeItem(f),l.removeItem(h),l.removeItem(x)},G=()=>N();window.addEventListener("persona:clear-chat",G),qe.push(()=>{window.removeEventListener("persona:clear-chat",G)})}}}if(b&&O()&&setTimeout(()=>{Lt.open()},0),tr(),!hf){let l=Yr(()=>{_&&(Li++,Eo.clear(),_r(ve,_.getMessages(),Ee))});qe.push(l)}return Lt};var Mg=(e,t)=>{let n=e.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,t*parseFloat(r[1])/100):420},AC=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},SC=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},TC=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.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."+(t.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 ${t.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.")},kg=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},vc=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Lg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",vc(e)},hc=e=>{e.style.transition=""},yc=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},bc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ui=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},EC=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},MC=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},kC=e=>{let t=Uo(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:Vt(t,r)??r;return{inset:o(n?.inset,Ra),canvasBackground:o(n?.canvasBackground,Ia)}},Pg=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},LC=(e,t,n,o,r,s,a,i)=>{let p=on(s),d=p.reveal==="push",c=i!=null,u=i?.inset??"",b=i?.canvasBackground??"";EC(e,t,n,o,d),MC(e,t,n,o,p.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let g=e.ownerDocument.defaultView,y=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,M=g!=null?g.innerWidth<=C:!1;if(y&&M&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),yc(t),hc(o),Lg(o),bc(n),ui(r,o),Pg(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Ut),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Lg(o),AC(o,p.maxHeight),Pg(o,c&&a,u,b),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",yc(t),hc(o),bc(n),ui(r,o);let I=p.animate?"transform 180ms ease":"none",S=p.side==="right"?"translateX(100%)":"translateX(-100%)",R=a?"translateX(0)":S;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=I,o.style.transform=R,o.style.pointerEvents=a?"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"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",hc(o),vc(o),ui(r,o);let I=Mg(p.width,e.clientWidth),S=Math.max(0,e.clientWidth),R=p.animate?"margin-left 180ms ease":"none",$=p.side==="right"?a?-I:0:a?0:-I;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${S+I}px`,t.style.transition=R,t.style.marginLeft=`${$}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${S}px`,n.style.maxWidth=`${S}px`,n.style.minWidth=`${S}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=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",yc(t),vc(o),bc(n),ui(r,o);let I=p.reveal==="emerge";I?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let S=a?p.width:"0px",R=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",$=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${S}`,o.style.width=S,o.style.maxWidth=S,o.style.minWidth=S,o.style.minHeight="0",SC(o,p.maxHeight),o.style.overflow=I||$?"hidden":"visible",o.style.transition=R,I){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let z=c?`calc(${Mg(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=z,r.style.minWidth=z,r.style.maxWidth=z,r.style.boxSizing="border-box"}}},PC=(e,t)=>{let n=e.ownerDocument.createElement("div");return kg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){kg(n,o)},destroy(){n.remove()}}},RC=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.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=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;i.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,e),p.appendChild(e);let b=null,g=()=>{b?.disconnect(),b=null},y=null,C=()=>{y=t?.launcher?.detachedPanel===!0?kC(t):null};C();let M=()=>{LC(a,i,p,d,c,t,u,y)},L=null,I=()=>{L?.(),L=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(L=ys(()=>{C(),M()}))},S=()=>{g(),on(t).reveal==="push"&&(typeof ResizeObserver>"u"||(b=new ResizeObserver(()=>{M()}),b.observe(a)))},R=!1,$=()=>{M(),S(),u&&!R&&a.dataset.personaDockMobileFullscreen!=="true"&&(R=!0,TC(a,on(t)))},z=a.ownerDocument.defaultView,w=()=>{$()};return z?.addEventListener("resize",w),on(t).reveal==="push"?(i.appendChild(p),i.appendChild(d),a.appendChild(i)):(a.appendChild(p),a.appendChild(d)),$(),I(),{mode:"docked",host:c,shell:a,syncWidgetState(U){let q=U.launcherEnabled?U.open:!0;u!==q&&(u=q,$())},updateConfig(U){t=U,(t?.launcher?.enabled??!0)===!1&&(u=!0),C(),$(),I()},destroy(){z?.removeEventListener("resize",w),L?.(),L=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},gi=(e,t)=>Wt(t)?RC(e,t):PC(e,t);var IC=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Rg=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},Ig=e=>{let t=IC(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=gi(t,r),a,i=[],p=(M,L)=>{let S=!(L?.launcher?.enabled??!0)||Wt(L),R=o.createElement("div");if(R.setAttribute("data-persona-root","true"),S&&(R.style.height="100%",R.style.display="flex",R.style.flexDirection="column",R.style.flex="1",R.style.minHeight="0",R.style.minWidth="0"),n){let $=M.attachShadow({mode:"open"});$.appendChild(R),Rg($,o)}else M.appendChild(R),Rg(M,o);return t.id&&R.setAttribute("data-persona-instance",t.id),R},d=()=>{s.syncWidgetState(a.getState())},c=()=>{i.forEach(M=>M()),i=[a.on("widget:opened",d),a.on("widget:closed",d)],d()},u=()=>{let M=p(s.host,r);a=mc(M,r,{debugTools:e.debugTools}),c()},b=()=>{i.forEach(M=>M()),i=[],a.destroy()};u(),e.onChatReady?.();let g=M=>{b(),s.destroy(),s=gi(t,M),r=M,u()},y={update(M){let L=ii(r??{},M),I=Wt(r),S=Wt(L),R=ho(r),$=ho(L);if(I!==S||R!==$){g(L);return}r=L,s.updateConfig(r),a.update(M),d()},destroy(){b(),s.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(y,{get(M,L,I){if(L==="host")return s.host;if(L in M)return Reflect.get(M,L,I);let S=a[L];return typeof S=="function"?S.bind(a):S}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};function WC(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function HC(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(s=>s.toLowerCase().startsWith(o))?1:WC(o,n)?2:3}function Wg(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function xc(e,t){let n=t.trim();if(!n)return[...e].sort(Wg);let o=[];for(let r of e){let s=HC(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:Wg(r.item,s.item)),o.map(r=>r.item)}function BC(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function OC(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>xc(e.items,t),resolve:e.resolve}}function DC(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>xc(t,BC(r).name),resolve:(r,s)=>{let a=n.get(r.id);return a?a.kind==="server"?{context:(typeof a.data=="function"?a.data(s.args):a.data)??{}}:{insertText:typeof a.prompt=="function"?a.prompt(s.args):a.prompt??""}:{}}}}var Ng=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),NC=new Set(["button","a","input","select","textarea","details","summary"]),FC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Cc=/\b(product|card|item|listing|result)\b/i,Ac=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,_C=3e3,$C=100;function Fg(e){let t=typeof e.className=="string"?e.className:"";if(Cc.test(t)||e.id&&Cc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Cc.test(o.value))return!0}return!1}function _g(e){return Ac.test((e.textContent??"").trim())}function $g(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function jC(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Hg(e){let t=e.match(Ac);return t?t[0]:null}function Bg(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function UC(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var zC="commerce-card",qC="result-card";function Og(e){return!Fg(e)||!_g(e)||!$g(e)&&!jC(e)?0:5200}function Dg(e){return!Fg(e)||_g(e)||!$g(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var jg=[{id:zC,scoreElement(e){return Og(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||Ac.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(Og(e)===0)return null;let{title:n,href:o}=Bg(e),r=Hg((e.textContent??"").trim())??Hg(t.text)??"",s=UC(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
143
- `)}},{id:qC,scoreElement(e){return Dg(e)},formatSummary(e,t){if(Dg(e)===0)return null;let{title:n,href:o}=Bg(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
144
- `)}}];function VC(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function KC(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,s=t.visibleOnly??e.visibleOnly??!0,a=t.root??e.root,i=t.mode??"structured",p=t.maxCandidates??Math.max(500,n*10),d=e.rules??jg;return i==="simple"&&e.rules&&e.rules.length>0?(VC(),d=[]):i==="simple"&&(d=[]),{mode:i,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:a,rules:d}}function wc(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var GC=["data-testid","data-product","data-action","data-id","data-name","data-type"];function JC(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||NC.has(t)||n&&FC.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Ug(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function XC(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let s=e.getAttribute("type");s&&(t.type=s);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let p=e.getAttribute("role");p&&(t.role=p);for(let d=0;d<e.attributes.length;d++){let c=e.attributes[d];c.name.startsWith("data-")&&(t[c.name]=c.value)}return t}function zg(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${wc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of GC){let s=e.getAttribute(r);if(s){let a=`${t}[${r}="${wc(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(n.length>0){let r=`${t}.${n.map(a=>wc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let p=`${r}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}catch{}}}}let o=e.parentElement;if(o){let s=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function QC(e){return e==="static"?$C:_C}function qg(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:zg(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:JC(e),attributes:XC(e)}}function YC(e,t,n,o){let r=QC(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,o);i>0&&(r+=i,a.formatSummary&&!s&&(s=a))}return{score:r,formattingRule:s}}function ZC(e,t){for(let n of e)if(t.el!==n.el&&n.formattingRule?.shouldSuppressDescendant&&n.el.contains(t.el)&&n.formattingRule.shouldSuppressDescendant(n.el,t.el,t.enriched))return!0;return!1}function ew(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&r.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let d=i,c=d.tagName.toLowerCase();if(Ng.has(c)){i=a.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Ug(d)){i=a.nextNode();continue}let u=qg(d,e.maxTextLength),b=u.text.length>0,g=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(M=>M==="role");if(!b&&!g){i=a.nextNode();continue}if(o.has(u.selector)){i=a.nextNode();continue}o.add(u.selector);let{score:y,formattingRule:C}=YC(d,u,e.rules,n);r.push({el:d,domIndex:s,enriched:u,score:y,formattingRule:C}),s+=1}i=a.nextNode()}r.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,b=c.enriched.interactivity==="static"?1:0;return u!==b?u-b:c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex});let p=[];for(let d of r){if(p.length>=e.maxElements)break;ZC(p,d)||p.push(d)}return p.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,b=c.enriched.interactivity==="static"?1:0;return u!==b?u-b:u===1&&c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex}),p.map(d=>{let c;if(d.formattingRule?.formatSummary){let b=d.formattingRule.formatSummary(d.el,d.enriched,n);b&&(c=b)}let u={...d.enriched};return c&&(u.formattedSummary=c),u})}function tw(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=r.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let p=s,d=p.tagName.toLowerCase();if(Ng.has(d)){s=r.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!Ug(p)){s=r.nextNode();continue}let c=qg(p,e.maxTextLength),u=c.text.length>0,b=Object.keys(c.attributes).length>0&&!Object.keys(c.attributes).every(g=>g==="role");if(!u&&!b){s=r.nextNode();continue}o.has(c.selector)||(o.add(c.selector),n.push(c))}s=r.nextNode()}let a=[],i=[];for(let p of n)p.interactivity!=="static"?a.push(p):i.push(p);return[...a,...i].slice(0,e.maxElements)}function nw(e={}){let t=KC(e),n=t.root??document.body;return n?t.mode==="simple"?tw(t,n):ew(t,n):[]}var fi=100;function ow(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let s=e.map(a=>a.formattedSummary).filter(a=>!!a&&a.length>0);s.length>0&&o.push(`Structured summaries:
142
+ `}if(!x&&!l){let Mt="max-height: -moz-available !important; max-height: stretch !important;",Qt=f?"":"padding-top: 1.25em !important;",aa=f?"":`z-index: ${o.launcher?.zIndex??Ut} !important;`;Oe.style.cssText+=Mt+Qt+aa}dn()};Vs(),hr(e,o),Hs(e,o),Bs(e,o),Ir=()=>{Vs(),hr(e,o),Hs(e,o),Bs(e,o),Fs?e.style.setProperty("--persona-artifact-welded-outer-radius",Fs):e.style.removeProperty("--persona-artifact-welded-outer-radius")};let qe=[];qe.push(()=>{document.removeEventListener("keydown",jc)}),qe.push(()=>{Lr!==null&&clearTimeout(Lr)});let wn=null,An=null;qe.push(()=>{wn?.(),wn=null,An?.(),An=null}),Rr&&qe.push(()=>{Rr?.disconnect(),Rr=null}),qe.push(()=>{Br?.(),Br=null,Mi(),Ct&&(Ct.remove(),Ct=null),Ze?.element.style.removeProperty("width"),Ze?.element.style.removeProperty("maxWidth")}),Y&&qe.push(()=>{Ve!==null&&(cancelAnimationFrame(Ve),Ve=null),He?.destroy(),He=null,De?.destroy(),De=null,de=null});let So=null,qc=()=>{So&&(So(),So=null),o.colorScheme==="auto"&&(So=ys(()=>{hr(e,o)}))};qc(),qe.push(()=>{So&&(So(),So=null)}),qe.push(a);let Ks=o.features?.streamAnimation;if(Ks?.type&&Ks.type!=="none"){let l=xr(Ks.type,Ks.plugins);l&&(Ga(l,e),qe.push(()=>Nu(e)))}let Gs=cg(xt),To=null,_,ki=l=>{if(!_)return;let f=l??_.getMessages(),h=o.features?.suggestReplies?.enabled!==!1?pl(f):null;h?Gs.render(h,_,xe,f,o.suggestionChipsConfig,{agentPushed:!0}):f.some(x=>x.role==="user")?Gs.render([],_,xe,f):Gs.render(o.suggestionChips,_,xe,f,o.suggestionChipsConfig)},hn=!1,Eo=Lu(),Zo=new Map,Mo=new Map,Kn=new Map,Li=0,yf=Nn()!==null,Zt=ja(),sn=0,Gn=null,an=!1,Js=!1,Jn=0,yn=null,ko=null,Pi=!1,Xs=!1,Ri=null,Or=!0,Ii=!1,Wi=null,bf=4,Qs=24,vf=80,Hi=new Map,Qe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Vc=o.voiceRecognition?.autoResume??!1,Wn=l=>{i.emit("voice:state",{active:Qe.active,source:l,timestamp:Date.now()})},bn=()=>{C(l=>({...l,voiceState:{active:Qe.active,timestamp:Date.now(),manuallyDeactivated:Qe.manuallyDeactivated}}))},xf=()=>{if(o.voiceRecognition?.enabled===!1)return;let l=fc(c.voiceState),f=!!l.active,h=Number(l.timestamp??0);Qe.manuallyDeactivated=!!l.manuallyDeactivated,f&&Date.now()-h<hC&&setTimeout(()=>{Qe.active||(Qe.manuallyDeactivated=!1,o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Qe.active=_.isVoiceActive(),Wn("restore"),_.isVoiceActive()&&rr()}):ta("restore"))},1e3)},Cf=()=>_?Tg(_.getMessages()).filter(l=>!l.__skipPersist):[],Ys=null,Kc=(l,f)=>{typeof console<"u"&&console.error(l,f)},Bi=(l,f)=>{let h=()=>{try{let J=l();return!J||typeof J.then!="function"?null:Promise.resolve(J).catch(N=>{Kc(f,N)})}catch(J){return Kc(f,J),null}},x=Ys,A=x?x.then(()=>h()??void 0):h();if(!A)return;let P=A.finally(()=>{Ys===P&&(Ys=null)});Ys=P};function Oi(l){if(!d?.save)return;let h={messages:l?Tg(l):_?Cf():[],metadata:c,artifacts:fn.artifacts,selectedArtifactId:fn.selectedId};Bi(()=>d.save(h),"[AgentWidget] Failed to persist state:")}let er=null,Gc=()=>Oe.querySelector("#persona-scroll-container")||le,Dr=()=>{er!==null&&(cancelAnimationFrame(er),er=null),an=!1},Jc=()=>{Gn!==null&&(cancelAnimationFrame(Gn),Gn=null),Js=!1,Dr()},wf=()=>hn&&Ni()&&(Jt()!=="anchor-top"||Lc()),Di=()=>{let l=xo()||"Jump to latest",f=wf();kt.toggleAttribute("data-persona-scroll-to-bottom-streaming",f),Jn>0?(Co.textContent=String(Jn),Co.style.display="",kt.setAttribute("aria-label",`${l} (${Jn} new)`)):(Co.textContent="",Co.style.display="none",kt.setAttribute("aria-label",f?`${l} (response streaming below)`:l))},Xc=()=>{Jn!==0&&(Jn=0,Di())},Ni=()=>Un()?!Zt.isFollowing():!fo(le,Qs),en=()=>{if(!Ds()||Ue){kt.parentNode&&kt.remove(),kt.style.display="none";return}kt.parentNode!==ue&&ue.appendChild(kt),Jo();let f=Ln(le)>0&&Ni();f?Di():Xc(),kt.style.display=f?"":"none"},Nr=()=>{Zt.pause()&&(Jc(),en())},Xn=()=>{Zt.resume(),Xc(),en()},Qn=(l=!1)=>{Un()&&Zt.isFollowing()&&(!l&&!hn||(Gn!==null&&(cancelAnimationFrame(Gn),Gn=null),Js=!0,Gn=requestAnimationFrame(()=>{Gn=null,Js=!1,Zt.isFollowing()&&Af(Gc(),l?220:140)})))},Qc=(l,f,h,x=()=>!0)=>{let A=l.scrollTop,P=f(),J=P-A;if(Dr(),Math.abs(J)<1){an=!0,l.scrollTop=P,sn=l.scrollTop,an=!1;return}let N=performance.now();an=!0;let G=ge=>1-Math.pow(1-ge,3),re=ge=>{if(!x()){Dr();return}let oe=f();oe!==P&&(P=oe,J=P-A);let Ce=ge-N,Ke=Math.min(Ce/h,1),ut=G(Ke),nt=A+J*ut;l.scrollTop=nt,sn=l.scrollTop,Ke<1?er=requestAnimationFrame(re):(l.scrollTop=P,sn=l.scrollTop,er=null,an=!1)};er=requestAnimationFrame(re)},Af=(l,f=500)=>{let h=Ln(l)-l.scrollTop;if(Math.abs(h)<1){sn=l.scrollTop;return}if(Math.abs(h)>=vf){Dr(),an=!0,l.scrollTop=Ln(l),sn=l.scrollTop,an=!1;return}Qc(l,()=>Ln(l),f,()=>Zt.isFollowing())},Yc=()=>{let l=Gc();an=!0,l.scrollTop=Ln(l),sn=l.scrollTop,an=!1,en()},Zc=l=>{let f=0,h=l;for(;h&&h!==le;)f+=h.offsetTop,h=h.offsetParent;return f},ed=()=>{if(df()!=="last-user-turn")return!1;let l=_?.getMessages()??[];if(l.length<2)return!1;let f=[...l].reverse().find(P=>P.role==="user");if(!f)return!1;let h=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(f.id):f.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=le.querySelector(`[data-message-id="${h}"]`);if(!x)return!1;let A=Math.min(Math.max(0,Zc(x)-Mc()),Ln(le));return an=!0,le.scrollTop=A,sn=le.scrollTop,an=!1,Jt()==="follow"&&!fo(le,Qs)&&Zt.pause(),en(),!0},td=l=>{zn.style.height=`${Math.max(0,Math.round(l))}px`,yn&&(yn.spacerHeight=Math.max(0,l))},Fr=()=>{ko!==null&&(cancelAnimationFrame(ko),ko=null),Dr(),yn=null,zn.style.height="0px"},Sf=l=>{ko!==null&&cancelAnimationFrame(ko),ko=requestAnimationFrame(()=>{ko=null;let f=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=le.querySelector(`[data-message-id="${f}"]`);if(!h)return;let x=Zc(h),A=yn?.spacerHeight??0,P=le.scrollHeight-A,{targetScrollTop:J,spacerHeight:N}=Hu({anchorOffsetTop:x,topOffset:Mc(),viewportHeight:le.clientHeight,contentHeight:P});yn={initialSpacerHeight:N,contentHeightAtAnchor:P,spacerHeight:N},td(N),Qc(le,()=>J,220)})},Tf=()=>{if(Un()){if(!Zt.isFollowing()||fo(le,1))return;Qn(!hn);return}if(yn&&yn.initialSpacerHeight>0){let l=le.scrollHeight-yn.spacerHeight,f=Bu({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:l});f!==yn.spacerHeight&&td(f)}en()},Ef=l=>{let f=Jt();f==="follow"?(Xn(),Qn(!0)):f==="anchor-top"&&(Or=!1,Ii=!0,Sf(l))},Mf=()=>{if(Jt()==="anchor-top"){if(Ii){Or=!1;return}Or=!0,Fr(),Xn(),Qn(!0)}},kf=l=>{let f=new Map;l.forEach(h=>{let x=Hi.get(h.id);f.set(h.id,{streaming:h.streaming,role:h.role}),!x&&h.role==="assistant"&&(i.emit("assistant:message",h),!Xs&&(Jt()!=="anchor-top"||Lc())&&Ni()&&(Jn+=1,Di(),en(),Rc(Jn===1?"1 new message below.":`${Jn} new messages below.`))),h.role==="assistant"&&x?.streaming&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(x?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),Hi.clear(),f.forEach((h,x)=>{Hi.set(x,h)})},Zs=(l,f)=>{let h=f==="user"?"user":"assistant",x=o.layout?.messages?.[h],A=x?.width??"content",P=x?.maxWidth??(A==="full"?"100%":"85%");l.classList.add("persona-message-row"),l.classList.remove("persona-message-row-user","persona-message-row-assistant","persona-message-row-system","persona-message-width-content","persona-message-width-full"),l.classList.add(`persona-message-row-${f}`,`persona-message-width-${A}`),l.classList.toggle("persona-justify-end",f==="user"),l.setAttribute("data-message-role",f),l.setAttribute("data-message-width",A),l.style.setProperty("--persona-message-row-max-width",P)},Lo=(l,f)=>{let h=document.createElement("div");return h.className="persona-flex",h.id=`wrapper-${l}`,h.setAttribute("data-wrapper-id",l),Zs(h,f),h},Lf=(l,f,h)=>{let x=document.createElement("div"),P=(()=>{let W=r.find(Re=>Re.renderLoadingIndicator);if(W?.renderLoadingIndicator)return W.renderLoadingIndicator;if(o.loadingIndicator?.render)return o.loadingIndicator.render})(),J=(W,Re)=>Re==null?!1:typeof Re=="string"?(W.textContent=Re,!0):(W.appendChild(Re),!0),N=new Set,G=new Map,re=new Set,ge=r.some(W=>W.renderAskUserQuestion),oe=[],Ce=[],Ke=o.enableComponentStreaming!==!1,ut=o.approval!==!1,nt=[];if(f.forEach(W=>{N.add(W.id),G.set(W.id,W.role);let Re=ge&&no(W),$e=ut&&W.variant==="approval"&&!!W.approval,Se=!Re&&W.role==="assistant"&&!W.variant&&Ke&&di(W);!$e&&Kn.has(W.id)&&(l.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Kn.delete(W.id)),!Se&&Mo.has(W.id)&&(l.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Mo.delete(W.id));let Et=no(W)?`:${W.agentMetadata?.askUserQuestionAnswered?"a":"u"}:${W.agentMetadata?.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",gt=ku(W,Li)+Et,qt=Re||$e||Se?null:Pu(Eo,W.id,gt);if(qt){x.appendChild(qt.cloneNode(!0)),no(W)&&W.toolCall?.id&&W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(re.add(W.toolCall.id),rs(W,o,Le.composerOverlay));return}let ft=null,Xt=r.find(je=>!!(W.variant==="reasoning"&&je.renderReasoning||W.variant==="tool"&&je.renderToolCall||!W.variant&&je.renderMessage)),Rt=o.layout?.messages;if(no(W)&&W.agentMetadata?.askUserQuestionAnswered===!0){Zo.delete(W.id),l.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime");return}if(ba(W)&&o.features?.suggestReplies?.enabled!==!1)return;if(no(W)&&o.features?.askUserQuestion?.enabled!==!1){let je=r.find(Nt=>typeof Nt.renderAskUserQuestion=="function");if(je&&lt.current){let Nt=Zo.get(W.id),Ft=Nt!==gt,At=null;if(Ft){let{payload:et,complete:Ne}=oo(W),bt=W.id,_t=()=>lt.current?.getMessages().find(dn=>dn.id===bt);At=je.renderAskUserQuestion({message:W,payload:et,complete:Ne,resolve:dn=>{let Jr=_t();Jr&&lt.current?.resolveAskUserQuestion(Jr,dn)},dismiss:()=>{let dn=_t();dn?.agentMetadata?.awaitingLocalTool&&(lt.current?.markAskUserQuestionResolved(dn),lt.current?.resolveAskUserQuestion(dn,"(dismissed)"))},config:o})}let ct=Nt!=null;if(Ft&&At===null&&!ct){W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(re.add(W.toolCall.id),rs(W,o,Le.composerOverlay));return}let ht=Lo(W.id,W.role);ht.setAttribute("data-ask-plugin-stub","true"),ht.setAttribute("data-preserve-runtime","true"),x.appendChild(ht),oe.push({messageId:W.id,fingerprint:gt,bubble:At});return}else{W.agentMetadata?.awaitingLocalTool===!0&&!W.agentMetadata?.askUserQuestionAnswered&&(re.add(W.toolCall.id),rs(W,o,Le.composerOverlay));return}}else if($e){let je=r.find(ct=>typeof ct.renderApproval=="function")??s,Ft=Kn.get(W.id)!==gt,At=null;if(Ft&&je?.renderApproval){let ct=W.id,ht=(et,Ne)=>{let bt=lt.current?.getMessages().find(_t=>_t.id===ct);bt?.approval&&(bt.approval.toolType==="webmcp"?lt.current?.resolveWebMcpApproval(bt.id,et):lt.current?.resolveApproval(bt.approval,et,Ne))};At=je.renderApproval({message:W,defaultRenderer:()=>ri(W,o),config:o,approve:et=>ht("approved",et),deny:et=>ht("denied",et)})}if(Ft&&At===null)l.querySelector(`#wrapper-${W.id}`)?.removeAttribute("data-preserve-runtime"),Kn.delete(W.id),ft=ri(W,o);else{let ct=Lo(W.id,W.role);ct.setAttribute("data-approval-plugin-stub","true"),ct.setAttribute("data-preserve-runtime","true"),x.appendChild(ct),nt.push({messageId:W.id,fingerprint:gt,bubble:At});return}}else if(Xt)if(W.variant==="reasoning"&&W.reasoning&&Xt.renderReasoning){if(!se)return;ft=Xt.renderReasoning({message:W,defaultRenderer:()=>Jl(W,o),config:o})}else if(W.variant==="tool"&&W.toolCall&&Xt.renderToolCall){if(!fe)return;ft=Xt.renderToolCall({message:W,defaultRenderer:()=>Ql(W,o),config:o})}else Xt.renderMessage&&(ft=Xt.renderMessage({message:W,defaultRenderer:()=>{let je=Ps(W,h,Rt,o.messageActions,ne,{loadingIndicatorRenderer:P,widgetConfig:o});return W.role!=="user"&&sc(je,W,o,_),je},config:o}));if(!ft&&Se){let je=pc(W);if(je){let Nt=Mo.get(W.id),Ft=Nt!==gt,At=o.wrapComponentDirectiveInBubble!==!1&&kn.getOptions(je.component)?.bubbleChrome!==!1,ct=null;if(Ft){let ht=dc(je,{config:o,message:W,transform:h});if(ht&&je.component==="PersonaArtifactInline"){let et=ht.hasAttribute("data-artifact-inline")?ht:ht.querySelector("[data-artifact-inline]"),Ne=et?.getAttribute("data-artifact-inline")??"",bt=typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(Ne):Ne,_t=Ne?l.querySelector(`#wrapper-${W.id}`)?.querySelector(`[data-artifact-inline="${bt}"]`)??null:null;et&&_t&&_t!==et&&Au(_t)&&(et===ht?ht=_t:et.replaceWith(_t))}if(ht)if(At){let et=document.createElement("div");if(et.className=["persona-message-bubble","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),et.id=`bubble-${W.id}`,et.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let Ne=document.createElement("div");Ne.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Ne.innerHTML=h({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),et.appendChild(Ne)}et.appendChild(ht),ct=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-${W.id}`,et.setAttribute("data-message-id",W.id),et.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let Ne=document.createElement("div");Ne.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Ne.innerHTML=h({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),et.appendChild(Ne)}et.appendChild(ht),ct=et}}if(ct||Nt!=null){let ht=Lo(W.id,W.role);ht.setAttribute("data-component-directive-stub","true"),ht.setAttribute("data-preserve-runtime","true"),x.appendChild(ht),Ce.push({messageId:W.id,fingerprint:gt,bubble:ct});return}}}if(!ft)if(W.variant==="reasoning"&&W.reasoning){if(!se)return;ft=Jl(W,o)}else if(W.variant==="tool"&&W.toolCall){if(!fe)return;ft=Ql(W,o)}else if(W.variant==="approval"&&W.approval){if(o.approval===!1)return;ft=ri(W,o)}else{let je=o.layout?.messages;je?.renderUserMessage&&W.role==="user"?ft=je.renderUserMessage({message:W,config:o,streaming:!!W.streaming}):je?.renderAssistantMessage&&W.role==="assistant"?ft=je.renderAssistantMessage({message:W,config:o,streaming:!!W.streaming}):ft=Ps(W,h,je,o.messageActions,ne,{loadingIndicatorRenderer:P,widgetConfig:o}),W.role!=="user"&&ft&&sc(ft,W,o,_)}let Ie=Lo(W.id,W.role);Ie.appendChild(ft),Ru(Eo,W.id,gt,Ie),x.appendChild(Ie)}),Le.composerOverlay&&Le.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Re=>{let $e=Re.getAttribute("data-persona-ask-sheet-for");$e&&!re.has($e)&&Do(Le.composerOverlay,$e)}),o.features?.toolCallDisplay?.grouped){let W=[],Re=[],$e=o.features.toolCallDisplay.groupedMode==="summary";f.forEach(Se=>{if(Se.variant==="tool"&&Se.toolCall&&fe){Re.push(Se);return}Se.variant==="reasoning"&&!se||((Re.length>1||$e&&Re.length>0)&&W.push(Re),Re=[])}),(Re.length>1||$e&&Re.length>0)&&W.push(Re),W.forEach(Se=>{let Et=Se.map(je=>Array.from(x.children).find(Nt=>Nt instanceof HTMLElement&&Nt.getAttribute("data-wrapper-id")===je.id)).filter(je=>!!je);if(Et.length<($e?1:2))return;let gt=Lo(`tool-group-${Se[0].id}`,"assistant");gt.setAttribute("data-persona-tool-group-row","true");let qt=document.createElement("div");qt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",qt.setAttribute("data-persona-tool-group","true");let ft=document.createElement("div");ft.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted",ft.id=`tool-group-summary-${Se[0].id}`;let Xt=`Called ${Se.length} ${Se.length===1?"tool":"tools"}`,Rt=o.toolCall?.renderGroupedSummary?.({messages:Se,toolCalls:Se.map(je=>je.toolCall).filter(je=>!!je),defaultSummary:Xt,config:o});J(ft,Rt)||(ft.textContent=Xt);let Ie=document.createElement("div");Ie.className="persona-tool-group-stack persona-flex persona-flex-col",Ie.id=`tool-group-stack-${Se[0].id}`,Ie.setAttribute("data-persona-tool-group-stack","true"),qt.appendChild(ft),$e||qt.appendChild(Ie),gt.appendChild(qt),Et[0].before(gt),Et.forEach((je,Nt)=>{if($e){je.remove();return}je.style.setProperty("--persona-message-row-max-width","100%");let Ft=document.createElement("div");Ft.className="persona-tool-group-item persona-relative",Ft.setAttribute("data-persona-tool-group-item","true"),Nt<Et.length-1&&Ft.setAttribute("data-persona-tool-group-connector","true"),Ft.appendChild(je),Ie.appendChild(Ft)})})}Iu(Eo,N);let tn=f.some(W=>W.role==="assistant"&&W.streaming),Tt=f[f.length-1],Pt=Tt?.role==="assistant"&&!Tt.streaming&&Tt.variant!=="approval";if(hn&&f.some(W=>W.role==="user")&&!tn&&!Pt){let W={config:o,streaming:!0,location:"standalone",defaultRenderer:wr},Re=r.find(Se=>Se.renderLoadingIndicator),$e=null;if(Re?.renderLoadingIndicator&&($e=Re.renderLoadingIndicator(W)),$e===null&&o.loadingIndicator?.render&&($e=o.loadingIndicator.render(W)),$e===null&&($e=wr()),$e){let Se=document.createElement("div"),Et=o.loadingIndicator?.showBubble!==!1;Se.className=Et?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Se.setAttribute("data-typing-indicator","true"),Se.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Se.appendChild($e);let gt=Lo("typing-indicator","assistant");gt.appendChild(Se),x.appendChild(gt)}}if(!hn&&f.length>0){let W=f[f.length-1],Re={config:o,lastMessage:W,messageCount:f.length},$e=r.find(Et=>Et.renderIdleIndicator),Se=null;if($e?.renderIdleIndicator&&(Se=$e.renderIdleIndicator(Re)),Se===null&&o.loadingIndicator?.renderIdle&&(Se=o.loadingIndicator.renderIdle(Re)),Se){let Et=document.createElement("div"),gt=o.loadingIndicator?.showBubble!==!1;Et.className=gt?["persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Et.setAttribute("data-idle-indicator","true"),Et.appendChild(Se);let qt=Lo("idle-indicator","assistant");qt.appendChild(Et),x.appendChild(qt)}}if(Zd(x),$a(l,x),tl(l),oe.length>0)for(let{messageId:W,fingerprint:Re,bubble:$e}of oe){let Se=l.querySelector(`#wrapper-${W}`);Se&&(Zs(Se,G.get(W)??"assistant"),$e!==null&&(Se.replaceChildren($e),Se.setAttribute("data-bubble-fp",Re),Zo.set(W,Re)))}if(Zo.size>0)for(let W of Zo.keys())N.has(W)||Zo.delete(W);if(Ce.length>0)for(let{messageId:W,fingerprint:Re,bubble:$e}of Ce){let Se=l.querySelector(`#wrapper-${W}`);Se&&(Zs(Se,G.get(W)??"assistant"),$e!==null&&(Se.replaceChildren($e),Se.setAttribute("data-bubble-fp",Re),Mo.set(W,Re)))}if(Mo.size>0)for(let W of Mo.keys())N.has(W)||Mo.delete(W);if(nt.length>0)for(let{messageId:W,fingerprint:Re,bubble:$e}of nt){let Se=l.querySelector(`#wrapper-${W}`);Se&&(Zs(Se,G.get(W)??"assistant"),$e!==null&&(Se.replaceChildren($e),Se.setAttribute("data-bubble-fp",Re),Kn.set(W,Re)))}if(Kn.size>0)for(let W of Kn.keys())N.has(W)||Kn.delete(W)},_r=(l,f,h)=>{Lf(l,f,h),Fc()},$r=null,Pf=()=>{if($r)return;let l=h=>{let x=h.composedPath();x.includes(Oe)||Xe&&x.includes(Xe)||pt(!1,"user")};$r=l,(e.ownerDocument??document).addEventListener("pointerdown",l,!0)},nd=()=>{if(!$r)return;(e.ownerDocument??document).removeEventListener("pointerdown",$r,!0),$r=null};qe.push(()=>nd());let jr=null,Rf=()=>{if(jr)return;let l=h=>{h.key==="Escape"&&(h.isComposing||pt(!1,"user"))};jr=l,(e.ownerDocument??document).addEventListener("keydown",l,!0)},od=()=>{if(!jr)return;(e.ownerDocument??document).removeEventListener("keydown",jr,!0),jr=null};qe.push(()=>od());let Ur=!1,rd=new Set,If=()=>{let l=o.launcher?.composerBar?.peek?.streamAnimation;return l||o.features?.streamAnimation},tr=()=>{if(!Q())return;let l=Le.peekBanner,f=Le.peekTextNode;if(!l||!f)return;if(D){l.classList.remove("persona-pill-peek--visible");return}let h=_?.getMessages()??[],x;for(let Tt=h.length-1;Tt>=0;Tt--){let Pt=h[Tt];if(Pt.role==="assistant"&&Pt.content){x=Pt;break}}if(!x){l.classList.remove("persona-pill-peek--visible");return}let A=x.content,P=!!x.streaming,J=If(),N=qa(J),G=N.type!=="none"?xr(N.type,J?.plugins):null,re=G?.isAnimating?.(x)===!0,ge=G!==null&&(P||re);ge&&G&&!rd.has(G.name)&&(Ga(G,e),rd.add(G.name));let oe=ge&&G?.containerClass?G.containerClass:null,Ce=f.dataset.personaPeekStreamClass??null;Ce&&Ce!==oe&&(f.classList.remove(Ce),delete f.dataset.personaPeekStreamClass),oe&&Ce!==oe&&(f.classList.add(oe),f.dataset.personaPeekStreamClass=oe),ge?(f.style.setProperty("--persona-stream-step",`${N.speed}ms`),f.style.setProperty("--persona-stream-duration",`${N.duration}ms`)):(f.style.removeProperty("--persona-stream-step"),f.style.removeProperty("--persona-stream-duration"));let Ke=ge?Va(A,N.buffer,G,x,P):A;if(ge&&N.placeholder==="skeleton"&&P&&(!Ke||!Ke.trim())){let Tt=document.createElement("div"),Pt=Ts();Pt.classList.add("persona-pill-peek__skeleton"),Tt.appendChild(Pt),$a(f,Tt)}else{let Tt=Math.max(0,Ke.length-100),Pt=Ke.length>100?Ke.slice(-100):Ke,W=Fn(Pt);if(!ge||!G){let Re=Ke.length>100?`\u2026${Pt}`:Pt;f.textContent!==Re&&(f.textContent=Re)}else{let Re=W;(G.wrap==="char"||G.wrap==="word")&&(Re=Ss(W,G.wrap,`peek-${x.id}`,{skipTags:G.skipTags,startIndex:Tt}));let $e=document.createElement("div");if($e.innerHTML=Re,G.useCaret&&Pt.length>0){let Se=Ka(),Et=$e.querySelectorAll(".persona-stream-char, .persona-stream-word"),gt=Et[Et.length-1];gt?.parentNode?gt.parentNode.insertBefore(Se,gt.nextSibling):$e.appendChild(Se)}$a(f,$e),G.onAfterRender?.({container:f,bubble:l,messageId:x.id,message:x,speed:N.speed,duration:N.duration})}}let tn=hn||Ur;l.classList.toggle("persona-pill-peek--visible",tn)};if(Q()){let l=Le.peekBanner;if(l){let x=A=>{A.preventDefault(),A.stopPropagation(),pt(!0,"user")};l.addEventListener("pointerdown",x),qe.push(()=>{l.removeEventListener("pointerdown",x)})}let f=()=>{Ur||(Ur=!0,tr())},h=()=>{Ur&&(Ur=!1,tr())};ye.addEventListener("pointerenter",f),ye.addEventListener("pointerleave",h),qe.push(()=>{ye.removeEventListener("pointerenter",f),ye.removeEventListener("pointerleave",h)}),Xe&&(Xe.addEventListener("pointerenter",f),Xe.addEventListener("pointerleave",h),qe.push(()=>{Xe.removeEventListener("pointerenter",f),Xe.removeEventListener("pointerleave",h)}))}let Wf=l=>{let f=o.launcher?.composerBar??{},h=f.expandedSize??"anchored",x=f.bottomOffset??"16px",A=f.collapsedMaxWidth,P=f.expandedMaxWidth??"880px",J=f.expandedTopOffset??"5vh",N=f.modalMaxWidth??"880px",G=f.modalMaxHeight??"min(90vh, 800px)",re="calc(100vw - 32px)",ge="var(--persona-pill-area-height, 80px)",oe=Oe.style;if(oe.left="",oe.right="",oe.top="",oe.bottom="",oe.transform="",oe.width="",oe.maxWidth="",oe.height="",oe.maxHeight="",Xe){let Ce=Xe.style;Ce.bottom=x,Ce.width=A??""}if(l&&h!=="fullscreen"){if(h==="modal"){oe.top="50%",oe.left="50%",oe.transform="translate(-50%, -50%)",oe.bottom="auto",oe.right="auto",oe.width=N,oe.maxWidth=re,oe.maxHeight=G,oe.height=G;return}oe.left="50%",oe.transform="translateX(-50%)",oe.bottom=`calc(${x} + ${ge})`,oe.top=J,oe.width=P,oe.maxWidth=re}},zr=()=>{if(!O())return;if(Q()){let re=(o.launcher?.composerBar??{}).expandedSize??"anchored",ge=D?"expanded":"collapsed";Oe.dataset.state=ge,Oe.dataset.expandedSize=re,Xe&&(Xe.dataset.state=ge,Xe.dataset.expandedSize=re),Oe.style.removeProperty("display"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Wf(D),ue.style.display=D?"flex":"none",Vs(),D?(Pf(),Rf()):(nd(),od()),tr();return}let l=Wt(o),f=e.ownerDocument.defaultView??window,h=o.launcher?.mobileBreakpoint??640,x=o.launcher?.mobileFullscreen??!0,A=f.innerWidth<=h,P=x&&A&&S,J=on(o).reveal;D?(Oe.style.removeProperty("display"),Oe.style.display=l?"flex":"",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-95","persona-opacity-0"),ye.classList.add("persona-scale-100","persona-opacity-100"),Bt?Bt.element.style.display="none":zt&&(zt.style.display="none")):(l?l&&(J==="overlay"||J==="push")&&!P?(Oe.style.removeProperty("display"),Oe.style.display="flex",Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Oe.style.setProperty("display","none","important"),Oe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Oe.style.display="",Oe.classList.add("persona-pointer-events-none","persona-opacity-0"),ye.classList.remove("persona-scale-100","persona-opacity-100"),ye.classList.add("persona-scale-95","persona-opacity-0")),Bt?Bt.element.style.display=l?"none":"":zt&&(zt.style.display=l?"none":""))},pt=(l,f="user")=>{if(!O()||D===l)return;let h=D;D=l,zr();let x=(()=>{let P=o.launcher?.sidebarMode??!1,J=e.ownerDocument.defaultView??window,N=o.launcher?.mobileFullscreen??!0,G=o.launcher?.mobileBreakpoint??640,re=J.innerWidth<=G,ge=Wt(o)&&N&&re,oe=Q()&&(o.launcher?.composerBar?.expandedSize??"fullscreen")==="fullscreen";return P||N&&re&&S||ge||oe})();if(D&&x){if(!wn){let P=e.getRootNode(),J=P instanceof ShadowRoot?P.host:e.closest(".persona-host");J&&(wn=jl(J,o.launcher?.zIndex??Ut))}An||(An=Ul(e.ownerDocument))}else D||(wn?.(),wn=null,An?.(),An=null);D&&(Kr(),ed()||(Jt()==="follow"?Qn(!0):Yc()));let A={open:D,source:f,timestamp:Date.now()};D&&!h?i.emit("widget:opened",A):!D&&h&&i.emit("widget:closed",A),i.emit("widget:state",{open:D,launcherEnabled:S,voiceActive:Qe.active,streaming:_.isStreaming()})},Fi=l=>{rt(l?"stop":"send"),K&&(K.disabled=l),Gs.buttons.forEach(f=>{f.disabled=l}),j.dataset.personaComposerStreaming=l?"true":"false",j.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(f=>{(f instanceof HTMLButtonElement||f instanceof HTMLInputElement||f instanceof HTMLTextAreaElement||f instanceof HTMLSelectElement)&&(f.disabled=l)})},_i=()=>{Qe.active||xe&&xe.focus()};i.on("widget:opened",()=>{o.autoFocusInput&&setTimeout(()=>_i(),200)});let sd=()=>{F.textContent=o.copy?.welcomeTitle??"Hello \u{1F44B}",v.textContent=o.copy?.welcomeSubtitle??"Ask anything about your account or products.",xe.placeholder=o.copy?.inputPlaceholder??"How can I help...";let l=le.querySelector("[data-persona-intro-card]");if(l){let h=o.copy?.showWelcomeCard!==!1;l.style.display=h?"":"none",h?(le.classList.remove("persona-gap-3"),le.classList.add("persona-gap-6")):(le.classList.remove("persona-gap-6"),le.classList.add("persona-gap-3"))}!(o.sendButton?.useIcon??!1)&&!_?.isStreaming()&&(pe.textContent=o.copy?.sendButtonLabel??"Send"),xe.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',xe.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};o.clientToken&&(o={...o,getStoredSessionId:()=>{let l=c.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{C(f=>({...f,sessionId:l}))}});let Po=null,Hf=()=>{Po==null&&(Po=setInterval(()=>{let l=ve.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Po),Po=null;return}let f=Date.now();l.forEach(h=>{let x=Number(h.getAttribute("data-tool-elapsed"));x&&(h.textContent=xa(f-x))})},100))},$i=(l,f)=>{if(Object.is(l,f))return!0;if(l===null||f===null||typeof l!="object"||typeof f!="object")return!1;if(Array.isArray(l)||Array.isArray(f))return!Array.isArray(l)||!Array.isArray(f)||l.length!==f.length?!1:l.every((J,N)=>$i(J,f[N]));let h=l,x=f,A=Object.keys(h),P=Object.keys(x);return A.length===P.length&&A.every(J=>Object.prototype.hasOwnProperty.call(x,J)&&$i(h[J],x[J]))},ad=l=>{let{content:f,rawContent:h,llmContent:x,...A}=l;return A},ji=l=>l.role==="assistant"&&l.streaming===!0&&!l.variant&&!l.toolCall&&!l.tools&&!l.approval&&!l.reasoning&&!l.contentParts&&!l.stopReason&&!di(l),Bf=(l,f,h)=>{if(l.length!==f.length)return!1;let x=l[h.index],A=f[h.index];return!x||!A||x.id!==h.id||A.id!==h.id?!1:(!Object.is(x.content,A.content)||!Object.is(x.rawContent,A.rawContent)||!Object.is(x.llmContent,A.llmContent))&&ji(x)&&ji(A)&&$i(ad(x),ad(A))},id=null,nr=null,Ro=null,Hn=null,ea=l=>{id=l;let f,h;nr=null;for(let A=l.length-1;A>=0;A-=1){let P=l[A];if(!f&&P.role==="user"&&(f=P),!h&&P.role==="assistant"&&(h=P),!nr&&ji(P)&&(nr={index:A,id:P.id}),f&&h&&nr)break}_r(ve,l,Ee),Ol(ve,fn.artifacts,{suppressTransition:hn}),Hf(),ki(l),Qn(!hn),kf(l),l.length===0&&(Fr(),Or=!0,Ii=!1),!Pi||Xs?(Pi=!0,Ri=f?.id??null,Wi=h?.id??null):f&&f.id!==Ri?(Ri=f.id,Ef(f.id)):h&&h.id!==Wi&&Mf(),h&&(Wi=h.id);let x=Qe.lastUserMessageId;f&&f.id!==x&&(Qe.lastUserMessageId=f.id,i.emit("user:message",f)),Qe.lastUserMessageWasVoice=!!f?.viaVoice,Oi(l),tr()},Ui=()=>{Hn!==null&&(cancelAnimationFrame(Hn),Hn=null);let l=Ro;Ro=null,l&&ea(l)},ld=()=>{Hn!==null&&cancelAnimationFrame(Hn),Hn=null,Ro=null},Of=l=>{let f=Ro??id;if(hn&&f&&nr&&Bf(f,l,nr)){Ro=l,Hn===null&&(Hn=requestAnimationFrame(()=>{Hn=null;let h=Ro;Ro=null,h&&ea(h)}));return}if(l.length===0){ld(),ea(l);return}Ui(),ea(l)};_=new gs(o,{onMessagesChanged(l){Of(l)},onStatusChanged(l){let f=o.statusIndicator??{};mt(E,(x=>x==="idle"?f.idleText??It.idle:x==="connecting"?f.connectingText??It.connecting:x==="connected"?f.connectedText??It.connected:x==="error"?f.errorText??It.error:x==="paused"?f.pausedText??It.paused:x==="resuming"?f.resumingText??It.resuming:It[x])(l),f,l)},onStreamingChanged(l){l||(_?.getMessages().length===0?ld():Ui()),hn=l,Fi(l),_&&_r(ve,_.getMessages(),Ee),l||Qn(!0),en(),Rc(l?"Responding\u2026":"Response complete."),tr()},onVoiceStatusChanged(l){if(i.emit("voice:status",{status:l,timestamp:Date.now()}),o.voiceRecognition?.provider?.type==="runtype")switch(l){case"listening":Bn(),rr();break;case"processing":Bn(),Kf();break;case"speaking":Bn(),Gf();break;default:l==="idle"&&_.isBargeInActive()?(Bn(),rr(),K?.setAttribute("aria-label","End voice session")):(Qe.active=!1,Bn(),Wn("system"),bn());break}},onArtifactsState(l){fn=l,l.artifacts.length===0&&(Xo=!1),Ol(ve,l.artifacts,{suppressTransition:hn}),In(),Oi()},onReconnect(l){let{executionId:f,lastEventId:h}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:f,after:h}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:f,after:h,attempt:l.attempt??1}):i.emit("stream:resumed",{executionId:f,after:h})}}),lt.current=_,qe.push(()=>_.cancel());let zi=null;if(_.onReadAloudChange((l,f)=>{Dc=l,Nc=f,Fc();let h=l??zi;l&&(zi=l);let x=h?_.getMessages().find(A=>A.id===h)??null:null;i.emit("message:read-aloud",{messageId:h,message:x,state:f,timestamp:Date.now()}),f==="idle"&&(zi=null)}),Pi=!0,o.voiceRecognition?.provider?.type==="runtype")try{_.setupVoice()}catch(l){typeof console<"u"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}o.clientToken&&_.initClientSession().catch(l=>{o.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(De||o.onSSEEvent)&&_.setSSEEventCallback((l,f)=>{o.onSSEEvent?.(l,f),_e?.processEvent(l,f),De?.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(f)})});let cd=()=>{o.resume&&typeof o.reconnectStream=="function"&&_.resumeFromHandle(o.resume)};u?u.then(l=>{if(l){if(l.metadata&&(c=fc(l.metadata),I.syncFromMetadata()),l.messages?.length){Xs=!0;try{_.hydrateMessages(l.messages)}finally{Xs=!1}}l.artifacts?.length&&_.hydrateArtifacts(l.artifacts,l.selectedArtifactId??null)}}).catch(l=>{typeof console<"u"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>cd()):cd();let dd=()=>{!Q()||D||!(o.launcher?.composerBar?.expandOnSubmit??!0)||pt(!0,"auto")},Df=(l,f)=>l?f?{refs:[...l.refs,...f.refs],finalize:async()=>{let[h,x]=await Promise.allSettled([l.finalize(),f.finalize()]),A=[];return h.status==="fulfilled"?A.push(h.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",h.reason),x.status==="fulfilled"?A.push(x.value):console.warn("[Persona] a mention bundle failed to finalize; sending without it",x.reason),AC(A)}}:l:f,Nf=()=>{let f=xe.getInlineMessageFields?.();return f&&f.contentSegments.some(x=>x.kind==="mention")?f.contentSegments:void 0},qr=!1,Ff=async l=>{let f=xe.value.trim(),h=St?.hasAttachments()??!1,x=f?await(Yt?.takeInlineCommand(f)??Promise.resolve(null)):null;if(x?.kind==="action"){xe.value="",xe.style.height="auto",Vr(),Yt?.clear();return}let A=Yt?.collectForSubmit()??null,P=x?.kind==="server"?x.mentions:null,J=Df(A,P),N=x?.kind==="prompt"?x.sendText:f,G=!!A&&A.refs.length>0;if(!N&&!h&&!G&&!P)return;dd();let re;h&&(re=[],re.push(...St.getContentParts()),N&&re.push(Fo(N)));let ge=x?.kind==="prompt"?void 0:Nf();xe.value="",xe.style.height="auto",Vr(),_.sendMessage(N,{contentParts:re,mentions:J??void 0,contentSegments:ge,viaVoice:l?.viaVoice}),h&&St.clearAttachments(),A&&Yt?.clear()},qi=async l=>{if(!qr){qr=!0;try{await Ff(l)}finally{qr=!1}}},pd=l=>{if(l.preventDefault(),_.isStreaming()){_.cancel(),_e?.reset(),He?.update();return}qr||qi()},_f=()=>o.features?.composerHistory!==!1,Vi={...Fl},Ki=!1,Vr=()=>{Vi={...Fl}},$f=()=>_.getMessages().filter(l=>l.role==="user").map(l=>l.content??"").filter(l=>l.length>0),jf=l=>{if(!xe)return;Ki=!0,xe.value=l,xe.dispatchEvent(new Event("input",{bubbles:!0})),Ki=!1;let f=xe.value.length;xe.setSelectionRange(f,f)},Uf=l=>{Ki||(l.isComposing||Yt?.handleInput(l.inputType??void 0),Vr())},zf=l=>{if(xe&&!(!l.isComposing&&Yt?.handleKeydown(l))){if(_f()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let f=xe.selectionStart===0&&xe.selectionEnd===0,h=Mu({direction:l.key==="ArrowUp"?"up":"down",history:$f(),currentValue:xe.value,atStart:f,state:Vi});if(Vi=h.state,h.handled){l.preventDefault(),h.value!==void 0&&jf(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}if(qr){l.preventDefault();return}Vr(),l.preventDefault(),pe.click()}}},ud=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(ue)&&(_.cancel(),_e?.reset(),He?.update(),Vr(),l.preventDefault(),l.stopImmediatePropagation())},qf=async l=>{if(o.attachments?.enabled!==!0||!St)return;let f=vC(l.clipboardData);f.length!==0&&(l.preventDefault(),await St.handleFiles(f))},ln=null,Sn=!1,or=null,wt=null,gd=()=>typeof window>"u"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ta=(l="user")=>{if(Sn||_.isStreaming())return;let f=gd();if(!f)return;ln=new f;let x=(o.voiceRecognition??{}).pauseDuration??2e3;ln.continuous=!0,ln.interimResults=!0,ln.lang="en-US";let A=xe.value;ln.onresult=P=>{let J="",N="";for(let re=0;re<P.results.length;re++){let ge=P.results[re],oe=ge[0].transcript;ge.isFinal?J+=oe+" ":N=oe}let G=A+J+N;xe.value=G,or&&clearTimeout(or),(J||N)&&(or=window.setTimeout(()=>{xe.value.trim()&&ln&&Sn&&(Yn(),qi({viaVoice:!0}))},x))},ln.onerror=P=>{P.error!=="no-speech"&&Yn()},ln.onend=()=>{if(Sn){let P=xe.value.trim();P&&P!==A.trim()&&qi({viaVoice:!0}),Yn()}};try{if(ln.start(),Sn=!0,Qe.active=!0,l!=="system"&&(Qe.manuallyDeactivated=!1),Wn(l),bn(),K){let P=o.voiceRecognition??{};wt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:P.iconName??"mic",iconSize:parseFloat(P.iconSize??o.sendButton?.size??"40")||24};let J=P.recordingBackgroundColor,N=P.recordingIconColor,G=P.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=J??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=N??"var(--persona-voice-recording-indicator, #ffffff)",N){let re=K.querySelector("svg");re&&re.setAttribute("stroke",N)}G&&(K.style.borderColor=G),K.setAttribute("aria-label","Stop voice recognition")}}catch{Yn("system")}},Yn=(l="user")=>{if(Sn){if(Sn=!1,or&&(clearTimeout(or),or=null),ln){try{ln.stop()}catch{}ln=null}if(Qe.active=!1,Wn(l),bn(),K){if(K.classList.remove("persona-voice-recording"),wt){K.style.backgroundColor=wt.backgroundColor,K.style.color=wt.color,K.style.borderColor=wt.borderColor;let f=K.querySelector("svg");f&&f.setAttribute("stroke",wt.color||"currentColor"),wt=null}K.setAttribute("aria-label","Start voice recognition")}}},Vf=(l,f)=>{let h=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),x=l?.provider?.type==="runtype",A=l?.provider?.type==="custom";if(!(h||x||A))return null;let J=m("div","persona-send-button-wrapper"),N=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button";let G=l?.tooltipText??"Start voice recognition";N.setAttribute("aria-label",G);let re=l?.iconName??"mic",ge=f?.size??"40px",oe=l?.iconSize??ge,Ce=parseFloat(oe)||24,Ke=l?.backgroundColor??f?.backgroundColor,ut=l?.iconColor??f?.textColor;N.style.width=oe,N.style.height=oe,N.style.minWidth=oe,N.style.minHeight=oe,N.style.fontSize="18px",N.style.lineHeight="1",ut?N.style.color=ut:N.style.color="var(--persona-text, #111827)";let tn=te(re,Ce,ut||"currentColor",1.5);tn?N.appendChild(tn):N.textContent="\u{1F3A4}",Ke?N.style.backgroundColor=Ke:N.style.backgroundColor="",l?.borderWidth&&(N.style.borderWidth=l.borderWidth,N.style.borderStyle="solid"),l?.borderColor&&(N.style.borderColor=l.borderColor),l?.paddingX&&(N.style.paddingLeft=l.paddingX,N.style.paddingRight=l.paddingX),l?.paddingY&&(N.style.paddingTop=l.paddingY,N.style.paddingBottom=l.paddingY),J.appendChild(N);let Tt=l?.showTooltip??!1;return Dt({anchor:N,trigger:J,text:()=>N.getAttribute("aria-label")??G,enabled:Tt}),{micButton:N,micButtonWrapper:J}},Gi=()=>{if(!K||wt)return;let l=o.voiceRecognition??{};wt={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:l.iconName??"mic",iconSize:parseFloat(l.iconSize??o.sendButton?.size??"40")||24}},Ji=(l,f)=>{if(!K)return;let h=K.querySelector("svg");h&&h.remove();let x=wt?.iconSize??(parseFloat(o.voiceRecognition?.iconSize??o.sendButton?.size??"40")||24),A=te(l,x,f,1.5);A&&K.appendChild(A)},na=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},rr=()=>{if(!K)return;Gi();let l=o.voiceRecognition??{},f=l.recordingBackgroundColor,h=l.recordingIconColor,x=l.recordingBorderColor;if(na(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=f??"var(--persona-voice-recording-bg, #ef4444)",K.style.color=h??"var(--persona-voice-recording-indicator, #ffffff)",h){let A=K.querySelector("svg");A&&A.setAttribute("stroke",h)}x&&(K.style.borderColor=x),K.setAttribute("aria-label","Stop voice recognition")},Kf=()=>{if(!K)return;Gi();let l=o.voiceRecognition??{},f=_.getVoiceInterruptionMode(),h=l.processingIconName??"loader",x=l.processingIconColor??wt?.color??"",A=l.processingBackgroundColor??wt?.backgroundColor??"",P=l.processingBorderColor??wt?.borderColor??"";na(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=A,K.style.borderColor=P;let J=x||"currentColor";K.style.color=J,Ji(h,J),K.setAttribute("aria-label","Processing voice input"),f==="none"&&(K.style.cursor="default")},Gf=()=>{if(!K)return;Gi();let l=o.voiceRecognition??{},f=_.getVoiceInterruptionMode(),h=f==="cancel"?"square":f==="barge-in"?"mic":"volume-2",x=l.speakingIconName??h,A=l.speakingIconColor??(f==="barge-in"?l.recordingIconColor??wt?.color??"":wt?.color??""),P=l.speakingBackgroundColor??(f==="barge-in"?l.recordingBackgroundColor??"var(--persona-voice-recording-bg, #ef4444)":wt?.backgroundColor??""),J=l.speakingBorderColor??(f==="barge-in"?l.recordingBorderColor??"":wt?.borderColor??"");na(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=P,K.style.borderColor=J;let N=A||"currentColor";K.style.color=N,Ji(x,N);let G=f==="cancel"?"Stop playback and re-record":f==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",G),f==="none"&&(K.style.cursor="default"),f==="barge-in"&&K.classList.add("persona-voice-recording")},Bn=()=>{K&&(na(),wt&&(K.style.backgroundColor=wt.backgroundColor??"",K.style.color=wt.color??"",K.style.borderColor=wt.borderColor??"",Ji(wt.iconName,wt.color||"currentColor"),wt=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},oa=()=>{if(o.voiceRecognition?.provider?.type==="runtype"){let l=_.getVoiceStatus(),f=_.getVoiceInterruptionMode();if(f==="none"&&(l==="processing"||l==="speaking"))return;if(f==="cancel"&&(l==="processing"||l==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,bn(),Wn("user"),Bn()});return}_.toggleVoice().then(()=>{Qe.active=_.isVoiceActive(),Qe.manuallyDeactivated=!_.isVoiceActive(),bn(),Wn("user"),_.isVoiceActive()?rr():Bn()});return}if(Sn){let l=xe.value.trim();Qe.manuallyDeactivated=!0,bn(),Yn("user"),l&&(xe.value="",xe.style.height="auto",_.sendMessage(l))}else Qe.manuallyDeactivated=!1,bn(),ta("user")};Wc=oa,K&&(K.addEventListener("click",oa),qe.push(()=>{o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Bn()):Yn("system"),K&&K.removeEventListener("click",oa)}));let Jf=i.on("assistant:complete",()=>{Vc&&(Qe.active||Qe.manuallyDeactivated||Vc==="assistant"&&!Qe.lastUserMessageWasVoice||setTimeout(()=>{!Qe.active&&!Qe.manuallyDeactivated&&(o.voiceRecognition?.provider?.type==="runtype"?_.toggleVoice().then(()=>{Qe.active=_.isVoiceActive(),Wn("auto"),_.isVoiceActive()&&rr()}):ta("auto"))},600))});qe.push(Jf);let Xf=i.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});qe.push(Xf);let fd=()=>{pt(!D,"user")},Bt=null,zt=null;if(S&&!Q()){let{instance:l,element:f}=Vl({config:o,plugins:r,onToggle:fd});Bt=l,l||(zt=f)}Bt?e.appendChild(Bt.element):zt&&e.appendChild(zt),zr(),ki(),sd(),Fi(_.isStreaming()),ed()||(Jt()==="follow"?Qn(!0):Yc()),xf(),$&&(!S||Q()?setTimeout(()=>_i(),0):D&&setTimeout(()=>_i(),200));let Kr=()=>{if(Q()){Jo(),zr();return}let l=Wt(o),f=o.launcher?.sidebarMode??!1,h=l||f||(o.launcher?.fullHeight??!1),x=e.ownerDocument.defaultView??window,A=o.launcher?.mobileFullscreen??!0,P=o.launcher?.mobileBreakpoint??640,J=x.innerWidth<=P,N=A&&J&&S;try{if(N){Ir(),Wr=qs();return}let G=!1;q&&(q=!1,Ir(),G=!0);let re=qs();if(!G&&re!==Wr&&(Ir(),G=!0),Wr=re,G&&Ei(),!S&&!l){ye.style.height="",ye.style.width="";return}if(!f&&!l){let oe=o?.launcher?.width??o?.launcherWidth??un;ye.style.width=oe,ye.style.maxWidth=oe}if(zs(),!h){let ge=x.innerHeight,oe=64,Ce=o.launcher?.heightOffset??0,Ke=Math.max(200,ge-oe),ut=Math.min(640,Ke),nt=Math.max(200,ut-Ce);ye.style.height=`${nt}px`}}finally{if(Jo(),zr(),D&&S){let re=(e.ownerDocument.defaultView??window).innerWidth<=(o.launcher?.mobileBreakpoint??640),ge=o.launcher?.sidebarMode??!1,oe=o.launcher?.mobileFullscreen??!0,Ce=Wt(o)&&oe&&re,Ke=ge||oe&&re&&S||Ce;if(Ke&&!An){let ut=e.getRootNode(),nt=ut instanceof ShadowRoot?ut.host:e.closest(".persona-host");nt&&!wn&&(wn=jl(nt,o.launcher?.zIndex??Ut)),An=Ul(e.ownerDocument)}else Ke||(wn?.(),wn=null,An?.(),An=null)}}};Kr();let md=e.ownerDocument.defaultView??window;if(md.addEventListener("resize",Kr),qe.push(()=>md.removeEventListener("resize",Kr)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{Jo()});l.observe(j),qe.push(()=>l.disconnect())}sn=le.scrollTop;let hd=Ln(le),Qf=()=>{let l=le.getRootNode();return(typeof l.getSelection=="function"?l.getSelection():null)??le.ownerDocument.getSelection()},Xi=()=>Wu(Qf(),le),yd=()=>{let l=le.scrollTop,f=Ln(le),h=f<hd;if(hd=f,!Un()){sn=l,en();return}let{action:x,nextLastScrollTop:A}=Ua({following:Zt.isFollowing(),currentScrollTop:l,lastScrollTop:sn,nearBottom:fo(le,Qs),userScrollThreshold:bf,isAutoScrolling:an||Js||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(sn=A,x==="resume"){Xi()||Xn();return}x==="pause"&&Nr()};if(le.addEventListener("scroll",yd,{passive:!0}),qe.push(()=>le.removeEventListener("scroll",yd)),typeof ResizeObserver<"u"){let l=new ResizeObserver(()=>{Tf(),tl(ve)});l.observe(ve),l.observe(le),qe.push(()=>l.disconnect())}let bd=()=>{Un()&&Zt.isFollowing()&&Xi()&&Nr()},vd=le.ownerDocument;vd.addEventListener("selectionchange",bd),qe.push(()=>{vd.removeEventListener("selectionchange",bd)});let Yf=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),xd=l=>{kc()&&Un()&&Zt.isFollowing()&&Yf.has(l.key)&&Nr()},Cd=l=>{if(!kc()||!Un()||!Zt.isFollowing())return;let f=l.target;f&&f.closest("a, button, [tabindex], input, textarea, select")&&Nr()};le.addEventListener("keydown",xd),le.addEventListener("focusin",Cd),qe.push(()=>{le.removeEventListener("keydown",xd),le.removeEventListener("focusin",Cd)});let wd=l=>{if(!Un())return;let f=za({following:Zt.isFollowing(),deltaY:l.deltaY,nearBottom:fo(le,Qs),resumeWhenNearBottom:!0});f==="pause"?Nr():f==="resume"&&!Xi()&&Xn()};le.addEventListener("wheel",wd,{passive:!0}),qe.push(()=>le.removeEventListener("wheel",wd)),kt.addEventListener("click",()=>{Fr(),le.scrollTop=le.scrollHeight,sn=le.scrollTop,Xn(),Qn(!0),en()}),qe.push(()=>kt.remove()),qe.push(()=>{Jc(),Fr()});let Ad=()=>{T&&(To&&(T.removeEventListener("click",To),To=null),O()?(T.style.display="",To=()=>{pt(!1,"user")},T.addEventListener("click",To)):T.style.display="none")};Ad(),(()=>{let{clearChatButton:l}=Le;l&&l.addEventListener("click",()=>{_.clearMessages(),Eo.clear(),Xn(),Do(Le.composerOverlay);try{localStorage.removeItem(Mr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Mr}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Mr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let f=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(f),d?.clear&&Bi(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},I.syncFromMetadata(),De?.clear(),_e?.reset(),He?.update()})})(),X&&X.addEventListener("submit",pd);let Sd=[["keydown",zf],["input",Uf],["paste",qf],["focus",gf]],Td=l=>{if(l)for(let[f,h]of Sd)l.addEventListener(f,h)},Ed=l=>{if(l)for(let[f,h]of Sd)l.removeEventListener(f,h)};Td(xe),Yt?.onComposerSwap((l,f)=>{Ed(f),xe=l,Td(l)});let Md=e.ownerDocument??document;Md.addEventListener("keydown",ud,!0);let kd="persona-attachment-drop-active",Gr=0,Qi=()=>{Gr=0,ue.classList.remove(kd)},sr=()=>o.attachments?.enabled===!0&&St!==null,Ld=l=>{!pi(l.dataTransfer)||!sr()||(Gr++,Gr===1&&ue.classList.add(kd))},Pd=l=>{!pi(l.dataTransfer)||!sr()||(Gr--,Gr<=0&&Qi())},Rd=l=>{!pi(l.dataTransfer)||!sr()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Id=l=>{if(!pi(l.dataTransfer)||!sr())return;l.preventDefault(),l.stopPropagation(),Qi();let f=Array.from(l.dataTransfer.files??[]);f.length!==0&&St.handleFiles(f)},Zn=!0;ue.addEventListener("dragenter",Ld,Zn),ue.addEventListener("dragleave",Pd,Zn),e.addEventListener("dragover",Rd,Zn),e.addEventListener("drop",Id,Zn);let ra=e.ownerDocument,Wd=l=>{sr()&&l.preventDefault()},Hd=l=>{sr()&&l.preventDefault()};ra.addEventListener("dragover",Wd),ra.addEventListener("drop",Hd),qe.push(()=>{X&&X.removeEventListener("submit",pd),Ed(xe),Md.removeEventListener("keydown",ud,!0),Yt?.destroy()}),qe.push(()=>{ue.removeEventListener("dragenter",Ld,Zn),ue.removeEventListener("dragleave",Pd,Zn),e.removeEventListener("dragover",Rd,Zn),e.removeEventListener("drop",Id,Zn),ra.removeEventListener("dragover",Wd),ra.removeEventListener("drop",Hd),Qi()}),qe.push(()=>{_.cancel()}),Bt?qe.push(()=>{Bt?.destroy()}):zt&&qe.push(()=>{zt?.remove()});let Lt={update(l){let f=o.toolCall,h=o.messageActions,x=o.layout?.messages,A=o.colorScheme,P=o.loadingIndicator,J=o.iterationDisplay,N=o.features?.showReasoning,G=o.features?.showToolCalls,re=o.features?.toolCallDisplay,ge=o.features?.reasoningDisplay,oe=o.features?.streamAnimation?.type;o=ii(o,l),Vs(),hr(e,o),Hs(e,o),Bs(e,o),In(),o.colorScheme!==A&&qc();let Ce=ai.getForInstance(o.plugins);r.length=0,r.push(...Ce),S=o.launcher?.enabled??!0,R=o.launcher?.autoExpand??!1,se=o.features?.showReasoning??!0,fe=o.features?.showToolCalls??!0,ce=o.features?.scrollToBottom??{};let Ke=Jt();Z=o.features?.scrollBehavior??{},Ke!==Jt()&&(Fr(),Xn()),Ic(),en();let ut=Y;if(Y=o.features?.showEventStreamToggle??!1,Y&&!ut){if(De||(de=new Is(he),De=new Rs(Me,de),_e=_e??new Ws,de.open().then(()=>De?.restore()).catch(()=>{}),_.setSSEEventCallback((ee,Je)=>{o.onSSEEvent?.(ee,Je),_e?.processEvent(ee,Je),De.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ee,timestamp:Date.now(),payload:JSON.stringify(Je)})})),!tt&&B){let ee=o.features?.eventStream?.classNames,Je="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"+(ee?.toggleButton?" "+ee.toggleButton:"");tt=m("button",Je),tt.style.width="28px",tt.style.height="28px",tt.style.color=Kt.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let yt=te("activity","18px","currentColor",1.5);yt&&tt.appendChild(yt);let ot=Le.clearChatButtonWrapper,st=Le.closeButtonWrapper,$t=ot||st;$t&&$t.parentNode===B?B.insertBefore(tt,$t):B.appendChild(tt),tt.addEventListener("click",()=>{Ue?Pr():wi()})}}else!Y&&ut&&(Pr(),tt&&(tt.remove(),tt=null),De?.clear(),de?.destroy(),De=null,de=null,_e?.reset(),_e=null);if(o.launcher?.enabled===!1&&Bt&&(Bt.destroy(),Bt=null),o.launcher?.enabled===!1&&zt&&(zt.remove(),zt=null),o.launcher?.enabled!==!1&&!Bt&&!zt){let{instance:ee,element:Je}=Vl({config:o,plugins:r,onToggle:fd});Bt=ee,ee||(zt=Je),e.appendChild(Je)}Bt&&Bt.update(o),H&&o.launcher?.title!==void 0&&(H.textContent=o.launcher.title),V&&o.launcher?.subtitle!==void 0&&(V.textContent=o.launcher.subtitle);let nt=o.layout?.header;if(nt?.layout!==U&&B){let ee=nt?ks(o,nt,{showClose:O(),onClose:()=>pt(!1,"user")}):yo({config:o,showClose:O(),onClose:()=>pt(!1,"user")});at.replaceHeader(ee),B=at.header.element,k=at.header.iconHolder,H=at.header.headerTitle,V=at.header.headerSubtitle,T=at.header.closeButton,U=nt?.layout}else if(nt){if(k&&(k.style.display=nt.showIcon===!1?"none":""),H&&(H.style.display=nt.showTitle===!1?"none":""),V&&(V.style.display=nt.showSubtitle===!1?"none":""),T){let ee=O()&&nt.showCloseButton!==!1;T.style.display=ee?"":"none"}if(Le.clearChatButtonWrapper){let ee=nt.showClearChat;if(ee!==void 0){Le.clearChatButtonWrapper.style.display=ee?"":"none";let{closeButtonWrapper:Je}=Le;Je&&!Je.classList.contains("persona-absolute")&&(ee?Je.classList.remove("persona-ml-auto"):Je.classList.add("persona-ml-auto"))}}}let Tt=o.layout?.showHeader!==!1;B&&(B.style.display=Tt?"":"none");let Pt=o.layout?.showFooter!==!1;j&&(j.style.display=Pt?"":"none"),Jo(),en(),S!==w?S?pt(R,"auto"):(D=!0,zr()):R!==z&&pt(R,"auto"),z=R,w=S,Kr(),Ad();let $e=JSON.stringify(o.toolCall)!==JSON.stringify(f),Se=JSON.stringify(o.messageActions)!==JSON.stringify(h),Et=JSON.stringify(o.layout?.messages)!==JSON.stringify(x),gt=o.loadingIndicator?.render!==P?.render||o.loadingIndicator?.renderIdle!==P?.renderIdle||o.loadingIndicator?.showBubble!==P?.showBubble,qt=o.iterationDisplay!==J,ft=(o.features?.showReasoning??!0)!==(N??!0)||(o.features?.showToolCalls??!0)!==(G??!0)||JSON.stringify(o.features?.toolCallDisplay)!==JSON.stringify(re)||JSON.stringify(o.features?.reasoningDisplay)!==JSON.stringify(ge);($e||Se||Et||gt||qt||ft)&&_&&(Li++,_r(ve,_.getMessages(),Ee));let Rt=o.features?.streamAnimation?.type;if(Rt!==oe&&Rt&&Rt!=="none"){let ee=xr(Rt,o.features?.streamAnimation?.plugins);ee&&Ga(ee,e)}let Ie=o.launcher??{},je=Ie.headerIconHidden??!1,Nt=o.layout?.header?.showIcon,Ft=je||Nt===!1,At=Ie.headerIconName,ct=Ie.headerIconSize??"48px";if(k){let ee=ue.querySelector(".persona-border-b-persona-divider"),Je=ee?.querySelector(".persona-flex-col");if(Ft)k.style.display="none",ee&&Je&&!ee.contains(Je)&&ee.insertBefore(Je,ee.firstChild);else{if(k.style.display="",k.style.height=ct,k.style.width=ct,ee&&Je&&(ee.contains(k)?k.nextSibling!==Je&&(k.remove(),ee.insertBefore(k,Je)):ee.insertBefore(k,Je)),At){let ot=parseFloat(ct)||24,st=te(At,ot*.6,"currentColor",1);st?k.replaceChildren(st):k.textContent=Ie.agentIconText??"\u{1F4AC}"}else if(Ie.iconUrl){let ot=k.querySelector("img");if(ot)ot.src=Ie.iconUrl,ot.style.height=ct,ot.style.width=ct;else{let st=document.createElement("img");st.src=Ie.iconUrl,st.alt="",st.className="persona-rounded-xl persona-object-cover",st.style.height=ct,st.style.width=ct,k.replaceChildren(st)}}else{let ot=k.querySelector("svg"),st=k.querySelector("img");(ot||st)&&k.replaceChildren(),k.textContent=Ie.agentIconText??"\u{1F4AC}"}let yt=k.querySelector("img");yt&&(yt.style.height=ct,yt.style.width=ct)}}let ht=o.layout?.header?.showTitle,et=o.layout?.header?.showSubtitle;if(H&&(H.style.display=ht===!1?"none":""),V&&(V.style.display=et===!1?"none":""),T){let ee=O()&&o.layout?.header?.showCloseButton!==!1;T.style.display=ee?"":"none";let Je=Ie.closeButtonSize??"32px",yt=Ie.closeButtonPlacement??"inline";T.style.height=Je,T.style.width=Je;let{closeButtonWrapper:ot}=Le,st=yt==="top-right",$t=ot?.classList.contains("persona-absolute");if(ot&&st!==$t)if(ot.remove(),st)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ue.style.position="relative",ue.appendChild(ot);else{let to=Ie.clearChat?.placement??"inline",Qr=Ie.clearChat?.enabled??!0;ot.className=Qr&&to==="inline"?"":"persona-ml-auto";let Bd=ue.querySelector(".persona-border-b-persona-divider");Bd&&Bd.appendChild(ot)}if(T.style.color=Ie.closeButtonColor||Kt.actionIconColor,Ie.closeButtonBackgroundColor?(T.style.backgroundColor=Ie.closeButtonBackgroundColor,T.classList.remove("hover:persona-bg-gray-100")):(T.style.backgroundColor="",T.classList.add("hover:persona-bg-gray-100")),Ie.closeButtonBorderWidth||Ie.closeButtonBorderColor){let to=Ie.closeButtonBorderWidth||"0px",Qr=Ie.closeButtonBorderColor||"transparent";T.style.border=`${to} solid ${Qr}`,T.classList.remove("persona-border-none")}else T.style.border="",T.classList.add("persona-border-none");Ie.closeButtonBorderRadius?(T.style.borderRadius=Ie.closeButtonBorderRadius,T.classList.remove("persona-rounded-full")):(T.style.borderRadius="",T.classList.add("persona-rounded-full")),Ie.closeButtonPaddingX?(T.style.paddingLeft=Ie.closeButtonPaddingX,T.style.paddingRight=Ie.closeButtonPaddingX):(T.style.paddingLeft="",T.style.paddingRight=""),Ie.closeButtonPaddingY?(T.style.paddingTop=Ie.closeButtonPaddingY,T.style.paddingBottom=Ie.closeButtonPaddingY):(T.style.paddingTop="",T.style.paddingBottom="");let nn=Ie.closeButtonIconName??"x",vn=Ie.closeButtonIconText??"\xD7";T.innerHTML="";let Ot=te(nn,"28px","currentColor",1);Ot?(Ot.style.display="block",T.appendChild(Ot)):T.textContent=vn;let jt=Ie.closeButtonTooltipText??"Close chat",Dn=Ie.closeButtonShowTooltip??!0;T.setAttribute("aria-label",jt),ot&&Dt({anchor:T,trigger:ot,text:()=>T?.getAttribute("aria-label")??jt,enabled:Dn})}let{clearChatButton:Ne,clearChatButtonWrapper:bt}=Le;if(Ne){let ee=Ie.clearChat??{},Je=ee.enabled??!0,yt=o.layout?.header?.showClearChat,ot=yt!==void 0?yt:Je,st=ee.placement??"inline";if(bt){bt.style.display=ot?"":"none";let{closeButtonWrapper:$t}=Le;!Q()&&$t&&!$t.classList.contains("persona-absolute")&&(ot?$t.classList.remove("persona-ml-auto"):$t.classList.add("persona-ml-auto"));let nn=st==="top-right",vn=bt.classList.contains("persona-absolute");if(!Q()&&nn!==vn&&ot){if(bt.remove(),nn)bt.className="persona-absolute persona-top-4 persona-z-50",bt.style.right="48px",ue.style.position="relative",ue.appendChild(bt);else{bt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",bt.style.right="";let jt=ue.querySelector(".persona-border-b-persona-divider"),Dn=Le.closeButtonWrapper;jt&&Dn&&Dn.parentElement===jt?jt.insertBefore(bt,Dn):jt&&jt.appendChild(bt)}let Ot=Le.closeButtonWrapper;Ot&&!Ot.classList.contains("persona-absolute")&&(nn?Ot.classList.add("persona-ml-auto"):Ot.classList.remove("persona-ml-auto"))}}if(ot){if(!Q()){let to=ee.size??"32px";Ne.style.height=to,Ne.style.width=to}let $t=ee.iconName??"refresh-cw",nn=ee.iconColor??"";Ne.style.color=nn||Kt.actionIconColor,Ne.innerHTML="";let vn=Q()?"14px":"20px",Ot=te($t,vn,"currentColor",1);if(Ot&&(Ot.style.display="block",Ne.appendChild(Ot)),ee.backgroundColor?(Ne.style.backgroundColor=ee.backgroundColor,Ne.classList.remove("hover:persona-bg-gray-100")):(Ne.style.backgroundColor="",Ne.classList.add("hover:persona-bg-gray-100")),ee.borderWidth||ee.borderColor){let to=ee.borderWidth||"0px",Qr=ee.borderColor||"transparent";Ne.style.border=`${to} solid ${Qr}`,Ne.classList.remove("persona-border-none")}else Ne.style.border="",Ne.classList.add("persona-border-none");ee.borderRadius?(Ne.style.borderRadius=ee.borderRadius,Ne.classList.remove("persona-rounded-full")):(Ne.style.borderRadius="",Ne.classList.add("persona-rounded-full")),ee.paddingX?(Ne.style.paddingLeft=ee.paddingX,Ne.style.paddingRight=ee.paddingX):(Ne.style.paddingLeft="",Ne.style.paddingRight=""),ee.paddingY?(Ne.style.paddingTop=ee.paddingY,Ne.style.paddingBottom=ee.paddingY):(Ne.style.paddingTop="",Ne.style.paddingBottom="");let jt=ee.tooltipText??"Clear chat",Dn=ee.showTooltip??!0;Ne.setAttribute("aria-label",jt),bt&&Dt({anchor:Ne,trigger:bt,text:()=>Ne?.getAttribute("aria-label")??jt,enabled:Dn})}}let _t=o.actionParsers&&o.actionParsers.length?o.actionParsers:[li],dn=o.actionHandlers&&o.actionHandlers.length?o.actionHandlers:[Er.message,Er.messageAndClick];I=ci({parsers:_t,handlers:dn,getSessionMetadata:y,updateSessionMetadata:C,emit:i.emit,documentRef:typeof document<"u"?document:null}),Ee=Eg(o,I,we),_.updateConfig(o),_r(ve,_.getMessages(),Ee),ki(),sd(),Fi(_.isStreaming());let Jr=o.voiceRecognition?.enabled===!0,sa=typeof window<"u"&&(typeof window.webkitSpeechRecognition<"u"||typeof window.SpeechRecognition<"u"),Mt=o.voiceRecognition?.provider?.type==="runtype";if(Jr&&(sa||Mt))if(!K||!ze){let ee=Vf(o.voiceRecognition,o.sendButton);ee&&(K=ee.micButton,ze=ee.micButtonWrapper,Ge.insertBefore(ze,gn),K.addEventListener("click",oa),K.disabled=_.isStreaming())}else{let ee=o.voiceRecognition??{},Je=o.sendButton??{},yt=ee.iconName??"mic",ot=Je.size??"40px",st=ee.iconSize??ot,$t=parseFloat(st)||24;K.style.width=st,K.style.height=st,K.style.minWidth=st,K.style.minHeight=st;let nn=ee.iconColor??Je.textColor;K.innerHTML="";let vn=te(yt,$t,nn||"currentColor",1.5);vn?K.appendChild(vn):K.textContent="\u{1F3A4}";let Ot=ee.backgroundColor??Je.backgroundColor;Ot?K.style.backgroundColor=Ot:K.style.backgroundColor="",nn?K.style.color=nn:K.style.color="var(--persona-text, #111827)",ee.borderWidth?(K.style.borderWidth=ee.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),ee.borderColor?K.style.borderColor=ee.borderColor:K.style.borderColor="",ee.paddingX?(K.style.paddingLeft=ee.paddingX,K.style.paddingRight=ee.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),ee.paddingY?(K.style.paddingTop=ee.paddingY,K.style.paddingBottom=ee.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let jt=ee.tooltipText??"Start voice recognition",Dn=ee.showTooltip??!1;K.setAttribute("aria-label",jt),ze&&Dt({anchor:K,trigger:ze,text:()=>K?.getAttribute("aria-label")??jt,enabled:Dn}),ze.style.display="",K.disabled=_.isStreaming()}else K&&ze&&(ze.style.display="none",o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()&&_.toggleVoice():Sn&&Yn());if(o.attachments?.enabled===!0){if(!We||!Ae){let ee=o.attachments??{},yt=(o.sendButton??{}).size??"40px";Ye||(Ye=m("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ye.style.display="none",X.insertBefore(Ye,xe)),Pe||(Pe=document.createElement("input"),Pe.type="file",Pe.accept=(ee.allowedTypes??$n).join(","),Pe.multiple=(ee.maxFiles??4)>1,Pe.style.display="none",Pe.setAttribute("aria-label","Attach files"),X.insertBefore(Pe,xe)),We=m("div","persona-send-button-wrapper"),Ae=m("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Ae.type="button",Ae.setAttribute("aria-label",ee.buttonTooltipText??"Attach file");let ot=ee.buttonIconName??"paperclip",st=yt,$t=parseFloat(st)||40,nn=Math.round($t*.6);Ae.style.width=st,Ae.style.height=st,Ae.style.minWidth=st,Ae.style.minHeight=st,Ae.style.fontSize="18px",Ae.style.lineHeight="1";let vn=te(ot,nn,"currentColor",1.5);vn?Ae.appendChild(vn):Ae.textContent="\u{1F4CE}",Ae.addEventListener("click",jt=>{jt.preventDefault(),Pe?.click()}),We.appendChild(Ae);let Ot=ee.buttonTooltipText??"Attach file";Dt({anchor:Ae,trigger:We,text:()=>Ae?.getAttribute("aria-label")??Ot}),Te?Te.append(We):X.appendChild(We),!St&&Pe&&Ye&&(St=mr.fromConfig(ee),St.setPreviewsContainer(Ye),Pe.addEventListener("change",async()=>{St&&Pe?.files&&(await St.handleFileSelect(Pe.files),Pe.value="")}))}else{We.style.display="";let ee=o.attachments??{};Pe&&(Pe.accept=(ee.allowedTypes??$n).join(","),Pe.multiple=(ee.maxFiles??4)>1),St&&St.updateConfig({allowedTypes:ee.allowedTypes,maxFileSize:ee.maxFileSize,maxFiles:ee.maxFiles})}if(ue.querySelector(".persona-attachment-drop-overlay")?.remove(),ue.appendChild(Mg(o.attachments?.dropOverlay)),Ae){let ee=o.attachments??{},Je=ee.buttonTooltipText??"Attach file";Ae.setAttribute("aria-label",Je),Ae.textContent="";let yt=parseFloat(o.sendButton?.size??"40px")||40,ot=te(ee.buttonIconName??"paperclip",Math.round(yt*.6),"currentColor",1.5);ot?Ae.appendChild(ot):Ae.textContent="\u{1F4CE}",We&&Dt({anchor:Ae,trigger:We,text:()=>Ae?.getAttribute("aria-label")??Je})}}else We&&(We.style.display="none"),St&&St.clearAttachments(),ue.querySelector(".persona-attachment-drop-overlay")?.remove();let Ht=o.sendButton??{},Xr=Ht.useIcon??!1,ia=Ht.iconText??"\u2191",ar=Ht.iconName,la=Ht.tooltipText??"Send message",Yi=Ht.showTooltip??!1,Io=Ht.size??"40px",On=Ht.backgroundColor,Wo=Ht.textColor;if(Xr){if(pe.style.width=Io,pe.style.height=Io,pe.style.minWidth=Io,pe.style.minHeight=Io,pe.style.fontSize="18px",pe.style.lineHeight="1",Wo?pe.style.color=Wo:pe.style.color="var(--persona-button-primary-fg, #ffffff)",!_.isStreaming())if(pe.innerHTML="",ar){let ee=parseFloat(Io)||24,Je=Wo?.trim()||"currentColor",yt=te(ar,ee,Je,2);yt?pe.appendChild(yt):pe.textContent=ia}else pe.textContent=ia;pe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",On?(pe.style.backgroundColor=On,pe.classList.remove("persona-bg-persona-primary")):(pe.style.backgroundColor="",pe.classList.add("persona-bg-persona-primary"))}else pe.textContent=o.copy?.sendButtonLabel??"Send",pe.style.width="",pe.style.height="",pe.style.minWidth="",pe.style.minHeight="",pe.style.fontSize="",pe.style.lineHeight="",pe.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",On?(pe.style.backgroundColor=On,pe.classList.remove("persona-bg-persona-accent")):pe.classList.add("persona-bg-persona-accent"),Wo?pe.style.color=Wo:pe.classList.add("persona-text-white");Ht.borderWidth?(pe.style.borderWidth=Ht.borderWidth,pe.style.borderStyle="solid"):(pe.style.borderWidth="",pe.style.borderStyle=""),Ht.borderColor?pe.style.borderColor=Ht.borderColor:pe.style.borderColor="",Ht.paddingX?(pe.style.paddingLeft=Ht.paddingX,pe.style.paddingRight=Ht.paddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),Ht.paddingY?(pe.style.paddingTop=Ht.paddingY,pe.style.paddingBottom=Ht.paddingY):(pe.style.paddingTop="",pe.style.paddingBottom=""),_.isStreaming()||pe.setAttribute("aria-label",la),gn&&Dt({anchor:pe,trigger:gn,text:()=>pe.getAttribute("aria-label")??la,enabled:Yi});let ca=o.layout?.contentMaxWidth??(Q()?o.launcher?.composerBar?.contentMaxWidth??"720px":void 0);ca?(ve.style.maxWidth=ca,ve.style.marginLeft="auto",ve.style.marginRight="auto",ve.style.width="100%",X&&(X.style.maxWidth=ca,X.style.marginLeft="auto",X.style.marginRight="auto"),xt&&(xt.style.maxWidth=ca,xt.style.marginLeft="auto",xt.style.marginRight="auto")):(ve.style.maxWidth="",ve.style.marginLeft="",ve.style.marginRight="",ve.style.width="",X&&(X.style.maxWidth="",X.style.marginLeft="",X.style.marginRight=""),xt&&(xt.style.maxWidth="",xt.style.marginLeft="",xt.style.marginRight=""));let eo=o.statusIndicator??{},Zf=eo.visible??!0;if(E.style.display=Zf?"":"none",_){let ee=_.getStatus();mt(E,(yt=>yt==="idle"?eo.idleText??It.idle:yt==="connecting"?eo.connectingText??It.connecting:yt==="connected"?eo.connectedText??It.connected:yt==="error"?eo.errorText??It.error:It[yt])(ee),eo,ee)}E.classList.remove("persona-text-left","persona-text-center","persona-text-right");let em=eo.align==="left"?"persona-text-left":eo.align==="center"?"persona-text-center":"persona-text-right";E.classList.add(em)},open(){O()&&pt(!0,"api")},close(){O()&&pt(!1,"api")},toggle(){O()&&pt(!D,"api")},reconnect(){_.reconnectNow()},clearChat(){Rn=!1,_.clearMessages(),Eo.clear(),Xn();try{localStorage.removeItem(Mr),o.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Mr}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(o.clearChatHistoryStorageKey&&o.clearChatHistoryStorageKey!==Mr)try{localStorage.removeItem(o.clearChatHistoryStorageKey),o.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${o.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),d?.clear&&Bi(()=>d.clear(),"[AgentWidget] Failed to clear storage adapter:"),c={},I.syncFromMetadata(),De?.clear(),_e?.reset(),He?.update()},setMessage(l){return!xe||_.isStreaming()?!1:(!D&&O()&&pt(!0,"system"),xe.value=l,xe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let f=l?.trim()||xe.value.trim();return f?(!D&&O()&&pt(!0,"system"),xe.value="",xe.style.height="auto",_.sendMessage(f),!0):!1},startVoiceRecognition(){return _.isStreaming()?!1:o.voiceRecognition?.provider?.type==="runtype"?(_.isVoiceActive()||(!D&&O()&&pt(!0,"system"),Qe.manuallyDeactivated=!1,bn(),_.toggleVoice().then(()=>{Qe.active=_.isVoiceActive(),Wn("user"),_.isVoiceActive()&&rr()})),!0):Sn?!0:gd()?(!D&&O()&&pt(!0,"system"),Qe.manuallyDeactivated=!1,bn(),ta("user"),!0):!1},stopVoiceRecognition(){return o.voiceRecognition?.provider?.type==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,bn(),Wn("user"),Bn()}),!0):!1:Sn?(Qe.manuallyDeactivated=!0,bn(),Yn("user"),!0):!1},injectMessage(l){return!D&&O()&&pt(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!D&&O()&&pt(!0,"system");let f=_.injectAssistantMessage(l);return ie&&(ie=!1,me&&(clearTimeout(me),me=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),f},injectUserMessage(l){return!D&&O()&&pt(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!D&&O()&&pt(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!D&&O()&&pt(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!D&&O()&&pt(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!D&&O()&&pt(!0,"system"),_.injectTestEvent(l)},async connectStream(l,f){return _.connectStream(l,f)},__pushEventStreamEvent(l){De&&(_e?.processEvent(l.type,l.payload),De.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!Y||!De||wi()},hideEventStream(){Ue&&Pr()},isEventStreamVisible(){return Ue},showArtifacts(){Gt(o)&&(Rn=!1,Xo=!0,In(),Ze?.setMobileOpen(!0))},hideArtifacts(){Gt(o)&&(Rn=!0,In())},upsertArtifact(l){return Gt(o)?(Bo(o.features?.artifacts,l.artifactType)==="panel"&&(Rn=!1,Xo=!0),_.upsertArtifact(l)):null},selectArtifact(l){Gt(o)&&_.selectArtifact(l)},clearArtifacts(){Gt(o)&&_.clearArtifacts()},getArtifacts(){return _?.getArtifacts()??[]},getSelectedArtifactId(){return _?.getSelectedArtifactId()??null},focusInput(){return S&&!D&&!Q()||!xe?!1:(xe.focus(),!0)},async resolveApproval(l,f,h){let A=_.getMessages().find(P=>P.variant==="approval"&&P.approval?.id===l);if(!A?.approval)throw new Error(`Approval not found: ${l}`);if(A.approval.toolType==="webmcp"){_.resolveWebMcpApproval(A.id,f);return}return _.resolveApproval(A.approval,f,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...c}},updatePersistentMetadata(l){C(l)},on(l,f){return i.on(l,f)},off(l,f){i.off(l,f)},isOpen(){return O()&&D},isVoiceActive(){return Qe.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:O()&&D,launcherEnabled:S,voiceActive:Qe.active,streaming:_.isStreaming()}},showCSATFeedback(l){!D&&O()&&pt(!0,"system");let f=ve.querySelector(".persona-feedback-container");f&&f.remove();let h=uc({onSubmit:async(x,A)=>{_.isClientTokenMode()&&await _.submitCSATFeedback(x,A),l?.onSubmit?.(x,A)},onDismiss:l?.onDismiss,...l});ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!D&&O()&&pt(!0,"system");let f=ve.querySelector(".persona-feedback-container");f&&f.remove();let h=gc({onSubmit:async(x,A)=>{_.isClientTokenMode()&&await _.submitNPSFeedback(x,A),l?.onSubmit?.(x,A)},onDismiss:l?.onDismiss,...l});ve.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,f){return _.submitCSATFeedback(l,f)},async submitNPSFeedback(l,f){return _.submitNPSFeedback(l,f)},destroy(){Ui(),Po!=null&&(clearInterval(Po),Po=null),qe.forEach(l=>l()),Oe.remove(),Xe?.remove(),Bt?.destroy(),zt?.remove(),To&&T.removeEventListener("click",To)}};if(((n?.debugTools??!1)||!!o.debug)&&typeof window<"u"){let l=window.AgentWidgetBrowser,f={controller:Lt,getMessages:Lt.getMessages,getStatus:Lt.getStatus,getMetadata:Lt.getPersistentMetadata,updateMetadata:Lt.updatePersistentMetadata,clearHistory:()=>Lt.clearChat(),setVoiceActive:h=>h?Lt.startVoiceRecognition():Lt.stopVoiceRecognition()};window.AgentWidgetBrowser=f,qe.push(()=>{window.AgentWidgetBrowser===f&&(window.AgentWidgetBrowser=l)})}if(typeof window<"u"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),f=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===l)&&Lt.focusInput()};if(window.addEventListener("persona:focusInput",f),qe.push(()=>{window.removeEventListener("persona:focusInput",f)}),Y){let N=re=>{let ge=re.detail;(!ge?.instanceId||ge.instanceId===l)&&Lt.showEventStream()},G=re=>{let ge=re.detail;(!ge?.instanceId||ge.instanceId===l)&&Lt.hideEventStream()};window.addEventListener("persona:showEventStream",N),window.addEventListener("persona:hideEventStream",G),qe.push(()=>{window.removeEventListener("persona:showEventStream",N),window.removeEventListener("persona:hideEventStream",G)})}let h=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===l)&&Lt.showArtifacts()},x=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===l)&&Lt.hideArtifacts()},A=N=>{let G=N.detail;G?.instanceId&&G.instanceId!==l||G?.artifact&&Lt.upsertArtifact(G.artifact)},P=N=>{let G=N.detail;G?.instanceId&&G.instanceId!==l||typeof G?.id=="string"&&Lt.selectArtifact(G.id)},J=N=>{let G=N.detail;(!G?.instanceId||G.instanceId===l)&&Lt.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",P),window.addEventListener("persona:clearArtifacts",J),qe.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",P),window.removeEventListener("persona:clearArtifacts",J)})}let cn=xC(o.persistState);if(cn&&O()){let l=CC(cn.storage),f=`${cn.keyPrefix}widget-open`,h=`${cn.keyPrefix}widget-voice`,x=`${cn.keyPrefix}widget-voice-mode`;if(l){let A=cn.persist?.openState&&l.getItem(f)==="true",P=cn.persist?.voiceState&&l.getItem(h)==="true",J=cn.persist?.voiceState&&l.getItem(x)==="true";if(A&&setTimeout(()=>{Lt.open(),setTimeout(()=>{if(P||J)Lt.startVoiceRecognition();else if(cn.persist?.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),cn.persist?.openState&&(i.on("widget:opened",()=>{l.setItem(f,"true")}),i.on("widget:closed",()=>{l.setItem(f,"false")})),cn.persist?.voiceState&&(i.on("voice:state",N=>{l.setItem(h,N.active?"true":"false")}),i.on("user:message",N=>{l.setItem(x,N.viaVoice?"true":"false")})),cn.clearOnChatClear){let N=()=>{l.removeItem(f),l.removeItem(h),l.removeItem(x)},G=()=>N();window.addEventListener("persona:clear-chat",G),qe.push(()=>{window.removeEventListener("persona:clear-chat",G)})}}}if(b&&O()&&setTimeout(()=>{Lt.open()},0),tr(),!yf){let l=Yr(()=>{_&&(Li++,Eo.clear(),_r(ve,_.getMessages(),Ee))});qe.push(l)}return Lt};var kg=(e,t)=>{let n=e.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,t*parseFloat(r[1])/100):420},SC=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},TC=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},EC=(e,t)=>{let n=e.parentElement;if(!n)return;let o=e.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."+(t.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 ${t.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.")},Lg=(e,t)=>{let n=t?.launcher?.enabled??!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0",e.style.minWidth=n?"":"0"},vc=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Pg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",vc(e)},hc=e=>{e.style.transition=""},yc=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},bc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ui=(e,t)=>{e.style.width="",e.style.minWidth="0",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},MC=(e,t,n,o,r)=>{r?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,o),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(o))},kC=(e,t,n,o,r,s)=>{let a=s?t:e;r==="left"?a.firstElementChild!==o&&a.replaceChildren(o,n):a.lastElementChild!==o&&a.replaceChildren(n,o)},LC=e=>{let t=Uo(e),n=t.components?.panel,o=(r,s)=>r==null||r===""?s:Vt(t,r)??r;return{inset:o(n?.inset,Ra),canvasBackground:o(n?.canvasBackground,Ia)}},Rg=(e,t,n,o)=>{if(!t){e.style.padding="",e.style.background="",e.style.boxSizing="";return}e.style.boxSizing="border-box",e.style.padding=n,e.style.background=o},PC=(e,t,n,o,r,s,a,i)=>{let p=on(s),d=p.reveal==="push",c=i!=null,u=i?.inset??"",b=i?.canvasBackground??"";MC(e,t,n,o,d),kC(e,t,n,o,p.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=p.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto";let g=e.ownerDocument.defaultView,y=s?.launcher?.mobileFullscreen??!0,C=s?.launcher?.mobileBreakpoint??640,M=g!=null?g.innerWidth<=C:!1;if(y&&M&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),yc(t),hc(o),Pg(o),bc(n),ui(r,o),Rg(o,!1,"",""),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",o.style.display="flex",o.style.flexDirection="column",o.style.position="fixed",o.style.inset="0",o.style.width="100%",o.style.height="100%",o.style.maxWidth="100%",o.style.minWidth="0",o.style.minHeight="0",o.style.overflow="hidden",o.style.zIndex=String(s?.launcher?.zIndex??Ut),o.style.transform="none",o.style.transition="none",o.style.pointerEvents="auto",o.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Pg(o),SC(o,p.maxHeight),Rg(o,c&&a,u,b),p.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",yc(t),hc(o),bc(n),ui(r,o);let I=p.animate?"transform 180ms ease":"none",S=p.side==="right"?"translateX(100%)":"translateX(-100%)",R=a?"translateX(0)":S;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=I,o.style.transform=R,o.style.pointerEvents=a?"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"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",hc(o),vc(o),ui(r,o);let I=kg(p.width,e.clientWidth),S=Math.max(0,e.clientWidth),R=p.animate?"margin-left 180ms ease":"none",$=p.side==="right"?a?-I:0:a?0:-I;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${S+I}px`,t.style.transition=R,t.style.marginLeft=`${$}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${S}px`,n.style.maxWidth=`${S}px`,n.style.minWidth=`${S}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=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",yc(t),vc(o),bc(n),ui(r,o);let I=p.reveal==="emerge";I?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let S=a?p.width:"0px",R=p.animate?`width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease${c?", padding 180ms ease":""}`:"none",$=!a;if(o.style.display="flex",o.style.flexDirection="column",o.style.flex=`0 0 ${S}`,o.style.width=S,o.style.maxWidth=S,o.style.minWidth=S,o.style.minHeight="0",TC(o,p.maxHeight),o.style.overflow=I||$?"hidden":"visible",o.style.transition=R,I){o.style.alignItems=p.side==="right"?"flex-start":"flex-end";let z=c?`calc(${kg(p.width,e.clientWidth)}px - (2 * ${u}))`:p.width;r.style.width=z,r.style.minWidth=z,r.style.maxWidth=z,r.style.boxSizing="border-box"}}},RC=(e,t)=>{let n=e.ownerDocument.createElement("div");return Lg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(o){Lg(n,o)},destroy(){n.remove()}}},IC=(e,t)=>{let{ownerDocument:n}=e,o=e.parentElement;if(!o)throw new Error("Docked widget target must be attached to the DOM");let r=e.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=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),p=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),u=t?.launcher?.enabled??!0?t?.launcher?.autoExpand??!1:!0;i.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),o.insertBefore(a,e),p.appendChild(e);let b=null,g=()=>{b?.disconnect(),b=null},y=null,C=()=>{y=t?.launcher?.detachedPanel===!0?LC(t):null};C();let M=()=>{PC(a,i,p,d,c,t,u,y)},L=null,I=()=>{L?.(),L=null,!(t?.launcher?.detachedPanel!==!0||t?.colorScheme!=="auto")&&(L=ys(()=>{C(),M()}))},S=()=>{g(),on(t).reveal==="push"&&(typeof ResizeObserver>"u"||(b=new ResizeObserver(()=>{M()}),b.observe(a)))},R=!1,$=()=>{M(),S(),u&&!R&&a.dataset.personaDockMobileFullscreen!=="true"&&(R=!0,EC(a,on(t)))},z=a.ownerDocument.defaultView,w=()=>{$()};return z?.addEventListener("resize",w),on(t).reveal==="push"?(i.appendChild(p),i.appendChild(d),a.appendChild(i)):(a.appendChild(p),a.appendChild(d)),$(),I(),{mode:"docked",host:c,shell:a,syncWidgetState(U){let q=U.launcherEnabled?U.open:!0;u!==q&&(u=q,$())},updateConfig(U){t=U,(t?.launcher?.enabled??!0)===!1&&(u=!0),C(),$(),I()},destroy(){z?.removeEventListener("resize",w),L?.(),L=null,g(),o.isConnected&&(s&&s.parentNode===o?o.insertBefore(e,s):o.appendChild(e)),a.remove()}}},gi=(e,t)=>Wt(t)?IC(e,t):RC(e,t);var WC=e=>{if(typeof window>"u"||typeof document>"u")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Ig=(e,t)=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let n=t.head.querySelector("link[data-persona]");if(!n)return;let o=n.cloneNode(!0);e.insertBefore(o,e.firstChild)},Wg=e=>{let t=WC(e.target),n=e.useShadowDom===!0,o=t.ownerDocument,r=e.config,s=gi(t,r),a,i=[],p=(M,L)=>{let S=!(L?.launcher?.enabled??!0)||Wt(L),R=o.createElement("div");if(R.setAttribute("data-persona-root","true"),S&&(R.style.height="100%",R.style.display="flex",R.style.flexDirection="column",R.style.flex="1",R.style.minHeight="0",R.style.minWidth="0"),n){let $=M.attachShadow({mode:"open"});$.appendChild(R),Ig($,o)}else M.appendChild(R),Ig(M,o);return t.id&&R.setAttribute("data-persona-instance",t.id),R},d=()=>{s.syncWidgetState(a.getState())},c=()=>{i.forEach(M=>M()),i=[a.on("widget:opened",d),a.on("widget:closed",d)],d()},u=()=>{let M=p(s.host,r);a=mc(M,r,{debugTools:e.debugTools}),c()},b=()=>{i.forEach(M=>M()),i=[],a.destroy()};u(),e.onChatReady?.();let g=M=>{b(),s.destroy(),s=gi(t,M),r=M,u()},y={update(M){let L=ii(r??{},M),I=Wt(r),S=Wt(L),R=ho(r),$=ho(L);if(I!==S||R!==$){g(L);return}r=L,s.updateConfig(r),a.update(M),d()},destroy(){b(),s.destroy(),e.windowKey&&typeof window<"u"&&delete window[e.windowKey]}},C=new Proxy(y,{get(M,L,I){if(L==="host")return s.host;if(L in M)return Reflect.get(M,L,I);let S=a[L];return typeof S=="function"?S.bind(a):S}});return e.windowKey&&typeof window<"u"&&(window[e.windowKey]=C),C};function HC(e,t){if(!e)return!0;let n=0;for(let o=0;o<t.length&&n<e.length;o++)t[o]===e[n]&&n++;return n===e.length}function BC(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return n.startsWith(o)?0:e.replace(/([a-z])([A-Z])/g,"$1 $2").split(/[\s\-_/.]+/).some(s=>s.toLowerCase().startsWith(o))?1:HC(o,n)?2:3}function Hg(e,t){let n=e.recencyScore??0,o=t.recencyScore??0;return o!==n?o-n:e.label.localeCompare(t.label)}function xc(e,t){let n=t.trim();if(!n)return[...e].sort(Hg);let o=[];for(let r of e){let s=BC(r.label,n);s!==3&&o.push({item:r,tier:s})}return o.sort((r,s)=>r.tier!==s.tier?r.tier-s.tier:Hg(r.item,s.item)),o.map(r=>r.item)}function OC(e){let t=e.replace(/^\s+/,""),n=t.search(/\s/);return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}function DC(e){return{id:e.id,label:e.label,resolveOn:e.resolveOn,search:t=>xc(e.items,t),resolve:e.resolve}}function NC(e){let t=e.commands.map(r=>({id:r.name,label:r.name,description:r.description,iconName:r.iconName,command:r.kind??"prompt",insertMode:r.insertMode,submitOnSelect:r.submitOnSelect,action:r.action,commandArgsPlaceholder:r.argsPlaceholder})),n=new Map(e.commands.map(r=>[r.name,r])),o=new Map(t.map(r=>[r.id,r]));return{id:e.id,label:e.label,matchCommand:r=>o.get(r),resolveOn:"submit",search:r=>xc(t,OC(r).name),resolve:(r,s)=>{let a=n.get(r.id);return a?a.kind==="server"?{context:(typeof a.data=="function"?a.data(s.args):a.data)??{}}:{insertText:typeof a.prompt=="function"?a.prompt(s.args):a.prompt??""}:{}}}}var Fg=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),FC=new Set(["button","a","input","select","textarea","details","summary"]),_C=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Cc=/\b(product|card|item|listing|result)\b/i,Ac=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,$C=3e3,jC=100;function _g(e){let t=typeof e.className=="string"?e.className:"";if(Cc.test(t)||e.id&&Cc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let o=e.attributes[n];if(o.name.startsWith("data-")&&Cc.test(o.value))return!0}return!1}function $g(e){return Ac.test((e.textContent??"").trim())}function jg(e){let t=e.querySelectorAll("a[href]");for(let n=0;n<t.length;n++){let o=t[n].getAttribute("href")??"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function UC(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Bg(e){let t=e.match(Ac);return t?t[0]:null}function Og(e){let t=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]")??e.querySelector("a[href]");if(t&&t.textContent?.trim()){let o=t.getAttribute("href");return{title:t.textContent.trim(),href:o&&o!=="#"?o:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return n?.textContent?.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function zC(e){let t=[],n=o=>{let r=o.trim();r&&!t.includes(r)&&t.push(r)};return e.querySelectorAll("button").forEach(o=>n(o.textContent??"")),e.querySelectorAll('[role="button"]').forEach(o=>n(o.textContent??"")),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(o=>{n(o.value??"")}),t.slice(0,6)}var qC="commerce-card",VC="result-card";function Dg(e){return!_g(e)||!$g(e)||!jg(e)&&!UC(e)?0:5200}function Ng(e){return!_g(e)||$g(e)||!jg(e)||(e.textContent??"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Ug=[{id:qC,scoreElement(e){return Dg(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let o=n.text.trim();return!!(o.length===0||Ac.test(o)&&o.length<32)}return!0},formatSummary(e,t){if(Dg(e)===0)return null;let{title:n,href:o}=Og(e),r=Bg((e.textContent??"").trim())??Bg(t.text)??"",s=zC(e);return[o&&n?`[${n}](${o})${r?`: ${r}`:""}`:n?`${n}${r?`: ${r}`:""}`:r||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
143
+ `)}},{id:VC,scoreElement(e){return Ng(e)},formatSummary(e,t){if(Ng(e)===0)return null;let{title:n,href:o}=Og(e);return[o&&n?`[${n}](${o})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
144
+ `)}}];function KC(){typeof console<"u"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function GC(e){let t=e.options??{},n=t.maxElements??e.maxElements??80,o=t.excludeSelector??e.excludeSelector??".persona-host",r=t.maxTextLength??e.maxTextLength??200,s=t.visibleOnly??e.visibleOnly??!0,a=t.root??e.root,i=t.mode??"structured",p=t.maxCandidates??Math.max(500,n*10),d=e.rules??Ug;return i==="simple"&&e.rules&&e.rules.length>0?(KC(),d=[]):i==="simple"&&(d=[]),{mode:i,maxElements:n,maxCandidates:p,excludeSelector:o,maxTextLength:r,visibleOnly:s,root:a,rules:d}}function wc(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var JC=["data-testid","data-product","data-action","data-id","data-name","data-type"];function XC(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||FC.has(t)||n&&_C.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function zg(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function QC(e){let t={},n=e.id;n&&(t.id=n);let o=e.getAttribute("href");o&&(t.href=o);let r=e.getAttribute("aria-label");r&&(t["aria-label"]=r);let s=e.getAttribute("type");s&&(t.type=s);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let p=e.getAttribute("role");p&&(t.role=p);for(let d=0;d<e.attributes.length;d++){let c=e.attributes[d];c.name.startsWith("data-")&&(t[c.name]=c.value)}return t}function qg(e){let t=e.tagName.toLowerCase();if(e.id){let r=`#${wc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}}for(let r of JC){let s=e.getAttribute(r);if(s){let a=`${t}[${r}="${wc(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(r=>r&&!r.startsWith("persona-")).slice(0,3);if(n.length>0){let r=`${t}.${n.map(a=>wc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(r).length===1)return r}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let p=`${r}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}catch{}}}}let o=e.parentElement;if(o){let s=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function YC(e){return e==="static"?jC:$C}function Vg(e,t){let n=e.tagName.toLowerCase(),o=(e.textContent??"").trim().substring(0,t);return{selector:qg(e),tagName:n,text:o,role:e.getAttribute("role"),interactivity:XC(e),attributes:QC(e)}}function ZC(e,t,n,o){let r=YC(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,o);i>0&&(r+=i,a.formatSummary&&!s&&(s=a))}return{score:r,formattingRule:s}}function ew(e,t){for(let n of e)if(t.el!==n.el&&n.formattingRule?.shouldSuppressDescendant&&n.el.contains(t.el)&&n.formattingRule.shouldSuppressDescendant(n.el,t.el,t.enriched))return!0;return!1}function tw(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},o=new Set,r=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&r.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let d=i,c=d.tagName.toLowerCase();if(Fg.has(c)){i=a.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!zg(d)){i=a.nextNode();continue}let u=Vg(d,e.maxTextLength),b=u.text.length>0,g=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(M=>M==="role");if(!b&&!g){i=a.nextNode();continue}if(o.has(u.selector)){i=a.nextNode();continue}o.add(u.selector);let{score:y,formattingRule:C}=ZC(d,u,e.rules,n);r.push({el:d,domIndex:s,enriched:u,score:y,formattingRule:C}),s+=1}i=a.nextNode()}r.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,b=c.enriched.interactivity==="static"?1:0;return u!==b?u-b:c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex});let p=[];for(let d of r){if(p.length>=e.maxElements)break;ew(p,d)||p.push(d)}return p.sort((d,c)=>{let u=d.enriched.interactivity==="static"?1:0,b=c.enriched.interactivity==="static"?1:0;return u!==b?u-b:u===1&&c.score!==d.score?c.score-d.score:d.domIndex-c.domIndex}),p.map(d=>{let c;if(d.formattingRule?.formatSummary){let b=d.formattingRule.formatSummary(d.el,d.enriched,n);b&&(c=b)}let u={...d.enriched};return c&&(u.formattedSummary=c),u})}function nw(e,t){let n=[],o=new Set,r=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=r.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let p=s,d=p.tagName.toLowerCase();if(Fg.has(d)){s=r.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){s=r.nextNode();continue}}catch{}if(e.visibleOnly&&!zg(p)){s=r.nextNode();continue}let c=Vg(p,e.maxTextLength),u=c.text.length>0,b=Object.keys(c.attributes).length>0&&!Object.keys(c.attributes).every(g=>g==="role");if(!u&&!b){s=r.nextNode();continue}o.has(c.selector)||(o.add(c.selector),n.push(c))}s=r.nextNode()}let a=[],i=[];for(let p of n)p.interactivity!=="static"?a.push(p):i.push(p);return[...a,...i].slice(0,e.maxElements)}function ow(e={}){let t=GC(e),n=t.root??document.body;return n?t.mode==="simple"?nw(t,n):tw(t,n):[]}var fi=100;function rw(e,t={}){if(e.length===0)return"No page elements found.";let n=t.mode??"structured",o=[];if(n==="structured"){let s=e.map(a=>a.formattedSummary).filter(a=>!!a&&a.length>0);s.length>0&&o.push(`Structured summaries:
145
145
  ${s.map(a=>`- ${a.split(`
146
146
  `).join(`
147
147
  `)}`).join(`
@@ -155,7 +155,7 @@ ${s.join(`
155
155
  ${s.join(`
156
156
  `)}`)}return o.join(`
157
157
 
158
- `)}function rw(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function sw(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function aw(e){return{name:"@persona/brand",version:"1.0.0",transform(t){let n={...t.palette};return e.colors?.primary&&(n.colors={...n.colors,primary:{50:Rn(e.colors.primary,.95),100:Rn(e.colors.primary,.9),200:Rn(e.colors.primary,.8),300:Rn(e.colors.primary,.7),400:Rn(e.colors.primary,.6),500:e.colors.primary,600:Rn(e.colors.primary,.8),700:Rn(e.colors.primary,.7),800:Rn(e.colors.primary,.6),900:Rn(e.colors.primary,.5),950:Rn(e.colors.primary,.45)}}),{...t,palette:n}}}}function iw(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function lw(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Rn(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(o+(255-o)*(1-t)),i=Math.round(r+(255-r)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function cw(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var dw={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Vg={components:{panel:{borderRadius:"0",shadow:"none"}}},Kg={id:"shop",label:"Shopping Assistant",config:{theme:dw,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:un},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Gg={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Vg}},Jg={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Vg}},Xg={shop:Kg,minimal:Gg,fullscreen:Jg};function pw(e){return Xg[e]}var uw=Ig;function Un(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function gw(e){if(e)return{getHeaders:Un(e.getHeaders),onFeedback:Un(e.onFeedback),onCopy:Un(e.onCopy),requestMiddleware:Un(e.requestMiddleware),actionHandlers:Un(e.actionHandlers),actionParsers:Un(e.actionParsers),postprocessMessage:Un(e.postprocessMessage),contextProviders:Un(e.contextProviders),streamParser:Un(e.streamParser)}}var Qg=`({ text, message }: any) => {
158
+ `)}function sw(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function aw(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function iw(e){return{name:"@persona/brand",version:"1.0.0",transform(t){let n={...t.palette};return e.colors?.primary&&(n.colors={...n.colors,primary:{50:Pn(e.colors.primary,.95),100:Pn(e.colors.primary,.9),200:Pn(e.colors.primary,.8),300:Pn(e.colors.primary,.7),400:Pn(e.colors.primary,.6),500:e.colors.primary,600:Pn(e.colors.primary,.8),700:Pn(e.colors.primary,.7),800:Pn(e.colors.primary,.6),900:Pn(e.colors.primary,.5),950:Pn(e.colors.primary,.45)}}),{...t,palette:n}}}}function lw(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function cw(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Pn(e,t){let n=parseInt(e.slice(1,3),16),o=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(o+(255-o)*(1-t)),i=Math.round(r+(255-r)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function dw(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var pw={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Kg={components:{panel:{borderRadius:"0",shadow:"none"}}},Gg={id:"shop",label:"Shopping Assistant",config:{theme:pw,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:un},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Jg={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Kg}},Xg={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Kg}},Qg={shop:Gg,minimal:Jg,fullscreen:Xg};function uw(e){return Qg[e]}var gw=Wg;function Sc(e){return e?.cdnBase?.trim().replace(/\/+$/,"").replace(/[\\'"<>`]/g,n=>`%${n.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)||`https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${io}/dist`}function jn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function fw(e){if(e)return{getHeaders:jn(e.getHeaders),onFeedback:jn(e.onFeedback),onCopy:jn(e.onCopy),requestMiddleware:jn(e.requestMiddleware),actionHandlers:jn(e.actionHandlers),actionParsers:jn(e.actionParsers),postprocessMessage:jn(e.postprocessMessage),contextProviders:jn(e.contextProviders),streamParser:jn(e.streamParser)}}var Yg=`({ text, message }: any) => {
159
159
  const jsonSource = (message as any).rawContent || text || message.content;
160
160
  if (!jsonSource || typeof jsonSource !== 'string') return null;
161
161
  let cleanJson = jsonSource
@@ -168,7 +168,7 @@ ${s.join(`
168
168
  if (parsed.action) return { type: parsed.action, payload: parsed };
169
169
  } catch (e) { return null; }
170
170
  return null;
171
- }`,Yg=`function(ctx) {
171
+ }`,Zg=`function(ctx) {
172
172
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
173
173
  if (!jsonSource || typeof jsonSource !== 'string') return null;
174
174
  var cleanJson = jsonSource
@@ -181,7 +181,7 @@ ${s.join(`
181
181
  if (parsed.action) return { type: parsed.action, payload: parsed };
182
182
  } catch (e) { return null; }
183
183
  return null;
184
- }`,Zg=`(action: any, context: any) => {
184
+ }`,ef=`(action: any, context: any) => {
185
185
  if (action.type !== 'nav_then_click') return;
186
186
  const payload = action.payload || action.raw || {};
187
187
  const url = payload?.page;
@@ -198,7 +198,7 @@ ${s.join(`
198
198
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
199
199
  window.location.href = targetUrl;
200
200
  return { handled: true, displayText: text };
201
- }`,ef=`function(action, context) {
201
+ }`,tf=`function(action, context) {
202
202
  if (action.type !== 'nav_then_click') return;
203
203
  var payload = action.payload || action.raw || {};
204
204
  var url = payload.page;
@@ -215,26 +215,26 @@ ${s.join(`
215
215
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
216
216
  window.location.href = targetUrl;
217
217
  return { handled: true, displayText: text };
218
- }`,fw=`(parsed: any) => {
218
+ }`,mw=`(parsed: any) => {
219
219
  if (!parsed || typeof parsed !== 'object') return null;
220
220
  if (parsed.action === 'nav_then_click') return 'Navigating...';
221
221
  if (parsed.action === 'message') return parsed.text || '';
222
222
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
223
223
  return parsed.text || null;
224
- }`,mw=`function(parsed) {
224
+ }`,hw=`function(parsed) {
225
225
  if (!parsed || typeof parsed !== 'object') return null;
226
226
  if (parsed.action === 'nav_then_click') return 'Navigating...';
227
227
  if (parsed.action === 'message') return parsed.text || '';
228
228
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
229
229
  return parsed.text || null;
230
- }`;function hw(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function mi(e){return e.parserType??hw(e.streamParser)??"plain"}function hi(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([o,r])=>{typeof r=="string"&&n.push(`${t} ${o}: "${r}",`)}),n.push(`${t}},`)),n}function yi(e,t,n){let o=[],r=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=n?.onFeedback||n?.onCopy;return(r||s)&&(o.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?o.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&o.push(`${t} ${a}: ${i},`))}),n?.onFeedback&&o.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&o.push(`${t} onCopy: ${n.onCopy},`),o.push(`${t}},`)),o}function bi(e,t){let n=[];if(e.markdown){let o=e.markdown.options&&Object.keys(e.markdown.options).length>0,r=e.markdown.disableDefaultStyles!==void 0;(o||r)&&(n.push(`${t}markdown: {`),o&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`)}),n.push(`${t} },`)),r&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function vi(e,t){let n=[];if(e.layout){let o=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(o||r)&&(n.push(`${t}layout: {`),o&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),r&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,p])=>{typeof p=="string"?n.push(`${t} ${i}: "${p}",`):typeof p=="boolean"&&n.push(`${t} ${i}: ${p},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([p])=>p!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"?n.push(`${t} ${p}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${p}: ${d},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Sc(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function tf(e,t,n){Object.entries(t).forEach(([o,r])=>{if(!(r===void 0||typeof r=="function")){if(Array.isArray(r)){e.push(`${n}${o}: ${JSON.stringify(r)},`);return}if(r&&typeof r=="object"){e.push(`${n}${o}: {`),tf(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function bo(e,t,n,o){n&&(e.push(`${o}${t}: {`),tf(e,n,`${o} `),e.push(`${o}},`))}function Os(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function yw(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:gw(n.hooks)}:void 0;return t==="esm"?bw(o,r):t==="script-installer"?Cw(o,r):t==="script-advanced"?Aw(o,r):t==="react-component"?vw(o,r):t==="react-advanced"?xw(o,r):ww(o,r)}function bw(e,t){let n=t?.hooks,o=mi(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Os(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&bo(s,"theme",e.theme," "),e.launcher&&bo(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...hi(e," ")),s.push(...yi(e," ",n)),s.push(...bi(e," ")),s.push(...vi(e," ")),s.push(...Sc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
231
- `)}function vw(e,t){let n=t?.hooks,o=mi(e),r=o!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${Os(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&bo(s,"theme",e.theme," "),e.launcher&&bo(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...hi(e," ")),s.push(...yi(e," ",n)),s.push(...bi(e," ")),s.push(...vi(e," ")),s.push(...Sc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
232
- `)}function xw(e,t){let n=t?.hooks,o=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${Os(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.agentId&&o.push(` agentId: "${e.agentId}",`),e.target&&o.push(` target: "${e.target}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&bo(o,"theme",e.theme," "),e.launcher&&bo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{o.push(` ${r}: "${s}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"?o.push(` ${r}: ${s},`):typeof s=="number"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{o.push(` ${r}: ${s},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{o.push(` "${r}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...hi(e," ")),o.push(...yi(e," ",n)),o.push(...bi(e," ")),o.push(...vi(e," ")),n?.getHeaders&&o.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&o.push(` contextProviders: ${n.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?o.push(` streamParser: ${n.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${fw}),`)),n?.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),o.push(" // Built-in parser for markdown-wrapped JSON"),o.push(` ${Qg}`),o.push(" ],")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" actionParsers: ["),o.push(" defaultJsonActionParser,"),o.push(" // Parser for markdown-wrapped JSON"),o.push(` ${Qg}`),o.push(" ],")),n?.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` actionHandlers: [...(${n.actionHandlers}),`),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Built-in handler for nav_then_click action"),o.push(` ${Zg}`),o.push(" ],")):(o.push(" // Action handlers for navigation and other actions"),o.push(" actionHandlers: ["),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Handler for nav_then_click action"),o.push(` ${Zg}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
233
- `)}function nf(e){let t=mi(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let r={};Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&(r[s]=a)}),Object.keys(r).length>0&&(o.toolCall=r)}if(e.messageActions){let r={};Object.entries(e.messageActions).forEach(([s,a])=>{s!=="onFeedback"&&s!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(r[s]=a)}),Object.keys(r).length>0&&(o.messageActions=r)}if(e.markdown){let r={};e.markdown.options&&(r.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(r.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(r).length>0&&(o.markdown=r)}if(e.layout){let r={};if(e.layout.header){let s={};Object.entries(e.layout.header).forEach(([a,i])=>{a!=="render"&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.header=s)}if(e.layout.messages){let s={};Object.entries(e.layout.messages).forEach(([a,i])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof i=="object"&&i!==null)s.avatar=i;else if(a==="timestamp"&&typeof i=="object"&&i!==null){let p={};Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"||typeof c=="boolean")&&(p[d]=c)}),Object.keys(p).length>0&&(s.timestamp=p)}else(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messages=s)}Object.keys(r).length>0&&(o.layout=r)}return o}function Cw(e,t){let n=nf(e),r=!!(t?.windowKey||t?.target)?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,s=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Cn}/dist/install.global.js" data-config='${s}'></script>`}function ww(e,t){let n=t?.hooks,o=mi(e),r=o!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Cn}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Cn}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Os(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&bo(s,"theme",e.theme," "),e.launcher&&bo(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...hi(e," ")),s.push(...yi(e," ",n)),s.push(...bi(e," ")),s.push(...vi(e," ")),s.push(...Sc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
234
- `)}function Aw(e,t){let n=t?.hooks,o=nf(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
230
+ }`;function yw(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function mi(e){return e.parserType??yw(e.streamParser)??"plain"}function hi(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([o,r])=>{typeof r=="string"&&n.push(`${t} ${o}: "${r}",`)}),n.push(`${t}},`)),n}function yi(e,t,n){let o=[],r=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=n?.onFeedback||n?.onCopy;return(r||s)&&(o.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?o.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&o.push(`${t} ${a}: ${i},`))}),n?.onFeedback&&o.push(`${t} onFeedback: ${n.onFeedback},`),n?.onCopy&&o.push(`${t} onCopy: ${n.onCopy},`),o.push(`${t}},`)),o}function bi(e,t){let n=[];if(e.markdown){let o=e.markdown.options&&Object.keys(e.markdown.options).length>0,r=e.markdown.disableDefaultStyles!==void 0;(o||r)&&(n.push(`${t}markdown: {`),o&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`)}),n.push(`${t} },`)),r&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function vi(e,t){let n=[];if(e.layout){let o=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(o||r)&&(n.push(`${t}layout: {`),o&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),r&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,p])=>{typeof p=="string"?n.push(`${t} ${i}: "${p}",`):typeof p=="boolean"&&n.push(`${t} ${i}: ${p},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([p])=>p!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"?n.push(`${t} ${p}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${p}: ${d},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function Tc(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function nf(e,t,n){Object.entries(t).forEach(([o,r])=>{if(!(r===void 0||typeof r=="function")){if(Array.isArray(r)){e.push(`${n}${o}: ${JSON.stringify(r)},`);return}if(r&&typeof r=="object"){e.push(`${n}${o}: {`),nf(e,r,`${n} `),e.push(`${n}},`);return}e.push(`${n}${o}: ${JSON.stringify(r)},`)}})}function bo(e,t,n,o){n&&(e.push(`${o}${t}: {`),nf(e,n,`${o} `),e.push(`${o}},`))}function Os(e){return(e?.target??"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function bw(e,t="esm",n){let o={...e};delete o.postprocessMessage,delete o.initialMessages;let r=n?{...n,hooks:fw(n.hooks)}:void 0;return t==="esm"?vw(o,r):t==="script-installer"?ww(o,r):t==="script-advanced"?Sw(o,r):t==="react-component"?xw(o,r):t==="react-advanced"?Cw(o,r):Aw(o,r)}function vw(e,t){let n=t?.hooks,o=mi(e),r=o!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Os(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&bo(s,"theme",e.theme," "),e.launcher&&bo(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...hi(e," ")),s.push(...yi(e," ",n)),s.push(...bi(e," ")),s.push(...vi(e," ")),s.push(...Tc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
231
+ `)}function xw(e,t){let n=t?.hooks,o=mi(e),r=o!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${Os(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),r&&s.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&bo(s,"theme",e.theme," "),e.launcher&&bo(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...hi(e," ")),s.push(...yi(e," ",n)),s.push(...bi(e," ")),s.push(...vi(e," ")),s.push(...Tc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n?.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
232
+ `)}function Cw(e,t){let n=t?.hooks,o=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${Os(t)}',`," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.agentId&&o.push(` agentId: "${e.agentId}",`),e.target&&o.push(` target: "${e.target}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&bo(o,"theme",e.theme," "),e.launcher&&bo(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([r,s])=>{o.push(` ${r}: "${s}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"?o.push(` ${r}: ${s},`):typeof s=="number"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([r,s])=>{typeof s=="string"?o.push(` ${r}: "${s}",`):typeof s=="boolean"&&o.push(` ${r}: ${s},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([r,s])=>{o.push(` ${r}: ${s},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(r=>{o.push(` "${r}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...hi(e," ")),o.push(...yi(e," ",n)),o.push(...bi(e," ")),o.push(...vi(e," ")),n?.getHeaders&&o.push(` getHeaders: ${n.getHeaders},`),n?.contextProviders&&o.push(` contextProviders: ${n.contextProviders},`),e.debug&&o.push(` debug: ${e.debug},`),o.push(" initialMessages: loadSavedMessages(),"),n?.streamParser?o.push(` streamParser: ${n.streamParser},`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(` streamParser: () => createFlexibleJsonStreamParser(${mw}),`)),n?.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),o.push(" // Built-in parser for markdown-wrapped JSON"),o.push(` ${Yg}`),o.push(" ],")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" actionParsers: ["),o.push(" defaultJsonActionParser,"),o.push(" // Parser for markdown-wrapped JSON"),o.push(` ${Yg}`),o.push(" ],")),n?.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` actionHandlers: [...(${n.actionHandlers}),`),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Built-in handler for nav_then_click action"),o.push(` ${ef}`),o.push(" ],")):(o.push(" // Action handlers for navigation and other actions"),o.push(" actionHandlers: ["),o.push(" defaultActionHandlers.message,"),o.push(" defaultActionHandlers.messageAndClick,"),o.push(" // Handler for nav_then_click action"),o.push(` ${ef}`),o.push(" ],")),n?.postprocessMessage?o.push(` postprocessMessage: ${n.postprocessMessage},`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n?.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" requestMiddleware: ({ payload, config }) => {"),o.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),o.push(" const merged = customResult || payload;"),o.push(" return {"),o.push(" ...merged,"),o.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),o.push(" };"),o.push(" }")):(o.push(" requestMiddleware: ({ payload }) => {"),o.push(" return {"),o.push(" ...payload,"),o.push(" metadata: collectDOMContext()"),o.push(" };"),o.push(" }")),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Save state on message events"),o.push(" const handleMessage = () => {"),o.push(" const session = handle?.getSession?.();"),o.push(" if (session) {"),o.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),o.push(" messages: session.messages,"),o.push(" timestamp: new Date().toISOString()"),o.push(" }));"),o.push(" }"),o.push(" };"),o.push(""),o.push(" // Clear state on clear chat"),o.push(" const handleClearChat = () => {"),o.push(" localStorage.removeItem(STORAGE_KEY);"),o.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),o.push(" };"),o.push(""),o.push(" window.addEventListener('persona:message', handleMessage);"),o.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" window.removeEventListener('persona:message', handleMessage);"),o.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage: Collects DOM context for AI-powered navigation"),o.push("// Features:"),o.push("// - Extracts page elements (products, buttons, links)"),o.push("// - Persists chat history across page loads"),o.push("// - Handles navigation actions (nav_then_click)"),o.push("// - Processes structured JSON actions from AI"),o.push("//"),o.push("// Example usage in Next.js:"),o.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),o.push("//"),o.push("// export default function RootLayout({ children }) {"),o.push("// return ("),o.push('// <html lang="en">'),o.push("// <body>"),o.push("// {children}"),o.push("// <ChatWidgetAdvanced />"),o.push("// </body>"),o.push("// </html>"),o.push("// );"),o.push("// }"),o.join(`
233
+ `)}function of(e){let t=mi(e),n=t!=="plain",o={};if(e.apiUrl&&(o.apiUrl=e.apiUrl),e.clientToken&&(o.clientToken=e.clientToken),e.agentId&&(o.agentId=e.agentId),e.target&&(o.target=e.target),e.flowId&&(o.flowId=e.flowId),n&&(o.parserType=t),e.theme&&(o.theme=e.theme),e.launcher&&(o.launcher=e.launcher),e.copy&&(o.copy=e.copy),e.sendButton&&(o.sendButton=e.sendButton),e.voiceRecognition&&(o.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(o.statusIndicator=e.statusIndicator),e.features&&(o.features=e.features),e.suggestionChips?.length>0&&(o.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(o.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(o.debug=e.debug),e.toolCall){let r={};Object.entries(e.toolCall).forEach(([s,a])=>{typeof a=="string"&&(r[s]=a)}),Object.keys(r).length>0&&(o.toolCall=r)}if(e.messageActions){let r={};Object.entries(e.messageActions).forEach(([s,a])=>{s!=="onFeedback"&&s!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(r[s]=a)}),Object.keys(r).length>0&&(o.messageActions=r)}if(e.markdown){let r={};e.markdown.options&&(r.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(r.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(r).length>0&&(o.markdown=r)}if(e.layout){let r={};if(e.layout.header){let s={};Object.entries(e.layout.header).forEach(([a,i])=>{a!=="render"&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.header=s)}if(e.layout.messages){let s={};Object.entries(e.layout.messages).forEach(([a,i])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof i=="object"&&i!==null)s.avatar=i;else if(a==="timestamp"&&typeof i=="object"&&i!==null){let p={};Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"||typeof c=="boolean")&&(p[d]=c)}),Object.keys(p).length>0&&(s.timestamp=p)}else(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messages=s)}Object.keys(r).length>0&&(o.layout=r)}return o}function ww(e,t){let n=of(e),r=!!(t?.windowKey||t?.target)?{config:n,...t?.windowKey?{windowKey:t.windowKey}:{},...t?.target?{target:t.target}:{}}:n,s=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="${Sc(t)}/install.global.js" data-config='${s}'></script>`}function Aw(e,t){let n=t?.hooks,o=mi(e),r=o!=="plain",s=Sc(t),a=["<!-- Load CSS -->",`<link rel="stylesheet" href="${s}/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="${s}/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Os(t)}',`,...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&a.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&a.push(` clientToken: "${e.clientToken}",`),e.agentId&&a.push(` agentId: "${e.agentId}",`),e.target&&a.push(` target: "${e.target}",`),e.flowId&&a.push(` flowId: "${e.flowId}",`),r&&a.push(` parserType: "${o}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&bo(a,"theme",e.theme," "),e.launcher&&bo(a,"launcher",e.launcher," "),e.copy&&(a.push(" copy: {"),Object.entries(e.copy).forEach(([i,p])=>{a.push(` ${i}: "${p}",`)}),a.push(" },")),e.sendButton&&(a.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([i,p])=>{typeof p=="string"?a.push(` ${i}: "${p}",`):typeof p=="boolean"&&a.push(` ${i}: ${p},`)}),a.push(" },")),e.voiceRecognition&&(a.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([i,p])=>{typeof p=="string"?a.push(` ${i}: "${p}",`):typeof p=="boolean"?a.push(` ${i}: ${p},`):typeof p=="number"&&a.push(` ${i}: ${p},`)}),a.push(" },")),e.statusIndicator&&(a.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([i,p])=>{typeof p=="string"?a.push(` ${i}: "${p}",`):typeof p=="boolean"&&a.push(` ${i}: ${p},`)}),a.push(" },")),e.features&&(a.push(" features: {"),Object.entries(e.features).forEach(([i,p])=>{a.push(` ${i}: ${p},`)}),a.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(a.push(" suggestionChips: ["),e.suggestionChips.forEach(i=>{a.push(` "${i}",`)}),a.push(" ],")),e.suggestionChipsConfig&&(a.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&a.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&a.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&a.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&a.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),a.push(" },")),a.push(...hi(e," ")),a.push(...yi(e," ",n)),a.push(...bi(e," ")),a.push(...vi(e," ")),a.push(...Tc(n," ")),e.debug&&a.push(` debug: ${e.debug},`),n?.postprocessMessage?a.push(` postprocessMessage: ${n.postprocessMessage}`):a.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),a.push(" }"),a.push(" });"),a.push("</script>"),a.join(`
234
+ `)}function Sw(e,t){let n=t?.hooks,o=of(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(o,null,2).split(`
235
235
  `).map((a,i)=>i===0?a:" "+a).join(`
236
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Cn}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n?.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n?.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n?.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${mw});`),s.push(" };")),s.push(""),n?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Yg}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Yg}`),s.push(" ];")),s.push(""),n?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${ef}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${ef}`),s.push(" ];")),s.push(""),n?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n?.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n?.onFeedback||n?.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${Os(t)}',`," useShadowDom: false,",...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
237
- `)}var of={desktop:{w:1280,h:800},mobile:{w:390,h:844}},rf=.1,sf=.15,af=1.5,Tc=24,lf=40,Sw=`
236
+ `)};`,""," // Constants",` var CDN_BASE = '${Sc(t)}';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n?.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n?.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n?.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${hw});`),s.push(" };")),s.push(""),n?.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Zg}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Zg}`),s.push(" ];")),s.push(""),n?.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${tf}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${tf}`),s.push(" ];")),s.push(""),n?.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n?.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n?.onFeedback||n?.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n?.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n?.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${Os(t)}',`," useShadowDom: false,",...t?.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
237
+ `)}var rf={desktop:{w:1280,h:800},mobile:{w:390,h:844}},sf=.1,af=.15,lf=1.5,Ec=24,cf=40,Tw=`
238
238
  /* \u2500\u2500 Root \u2500\u2500 */
239
239
  .persona-dc-root {
240
240
  display: flex;
@@ -385,7 +385,7 @@ ${s.join(`
385
385
  .persona-dc-stage {
386
386
  height: 550px;
387
387
  min-height: 400px;
388
- padding: ${Tc}px;
388
+ padding: ${Ec}px;
389
389
  overflow: auto;
390
390
  background: #f0f1f3;
391
391
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -475,5 +475,5 @@ ${s.join(`
475
475
  min-height: 300px;
476
476
  }
477
477
  }
478
- `;function Tw(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Sw,document.head.appendChild(e)}function Ew(e,t){let n=e.clientWidth-Tc*2-lf,o=e.clientHeight-Tc*2-lf;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function Mw(e,t,n,o,r){e.style.width=`${n.w*o}px`,e.style.height=`${n.h*o}px`,e.style.borderRadius=r==="mobile"?`${32*o}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${o})`}function kw(e,t){let{items:n,initialIndex:o=0,initialDevice:r="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:p=!0,onChange:d}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");Tw();let c=Math.max(0,Math.min(o,n.length-1)),u=r,b=s,g=null,y=1,C=!1,M=m("div","persona-dc-root"),L=m("div","persona-dc-toolbar"),I=m("div","persona-dc-toolbar-lead"),S=m("div","persona-dc-toolbar-trail"),R=dt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>_e(-1)}),$=m("div");$.style.position="relative";let z=m("button","persona-dc-title-btn");z.type="button",z.setAttribute("aria-expanded","false"),z.setAttribute("aria-haspopup","listbox");let w=m("span","persona-dc-title-text"),U=m("span","persona-dc-title-chevron"),q=te("chevron-down",12,"currentColor",2);q&&U.appendChild(q),z.append(w,U);let Q=m("div","persona-dc-dropdown");Q.setAttribute("role","listbox"),Q.style.display="none";let O=!1;function D(){Q.innerHTML="";for(let ne=0;ne<n.length;ne++){let Be=n[ne],vt=m("button","persona-dc-dropdown-item");vt.type="button",vt.setAttribute("role","option"),vt.setAttribute("aria-current",ne===c?"true":"false");let mt=m("span");if(mt.textContent=Be.title,vt.appendChild(mt),Be.description){let at=m("span","persona-dc-dropdown-desc");at.textContent=Be.description,vt.appendChild(at)}vt.addEventListener("click",()=>{me(),He(ne)}),Q.appendChild(vt)}}function ie(){O=!O,Q.style.display=O?"":"none",z.setAttribute("aria-expanded",O?"true":"false"),O&&D()}function me(){O&&(O=!1,Q.style.display="none",z.setAttribute("aria-expanded","false"))}z.addEventListener("click",ne=>{ne.stopPropagation(),ie()});let we=()=>me();document.addEventListener("click",we),$.append(z,Q);let Ee=dt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>_e(1)}),se=m("span","persona-dc-counter");I.append(R,$,Ee,se);let fe=null;i&&(fe=uo({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:ne=>{u=ne,he.dataset.device=u,g=null,Ue()}}),S.appendChild(fe.element));let Y=null;if(a){let ne=m("div","persona-dc-zoom-controls"),Be=dt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{g=Math.max(sf,(g??y)-rf),Ue()}});Y=m("span","persona-dc-zoom-level"),Y.title="Reset to 100%",Y.style.cursor="pointer",Y.addEventListener("click",()=>{g=1,Ue()});let vt=dt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{g=Math.min(af,(g??y)+rf),Ue()}}),mt=dt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,Ue()}});ne.append(Be,Y,vt,mt),S.appendChild(ne)}if(p){let ne=m("div","persona-dc-separator");S.appendChild(ne);let Be=uo({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:b,onSelect:vt=>{b=vt,he.dataset.colorScheme=b,Me()}});S.appendChild(Be.element)}let ce=m("div","persona-dc-separator");S.appendChild(ce);let Z=dt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[c].url,"_blank")}});S.appendChild(Z),L.append(I,S);let be=m("div","persona-dc-stage"),he=m("div","persona-dc-iframe-wrapper");he.dataset.device=u,he.dataset.colorScheme=b;let de=m("iframe","persona-dc-iframe");de.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),de.setAttribute("loading","lazy"),de.title=n[c].title,he.appendChild(de),be.appendChild(he),M.append(L,be),e.appendChild(M);function Me(){try{let ne=de.contentDocument?.body;if(!ne)return;b==="dark"?ne.classList.add("theme-dark"):ne.classList.remove("theme-dark")}catch{}}de.addEventListener("load",()=>Me());function De(){let ne=n[c];w.textContent=ne.title,se.textContent=`${c+1} / ${n.length}`,de.title=ne.title}function _e(ne){let Be=((c+ne)%n.length+n.length)%n.length;He(Be)}function He(ne){ne<0||ne>=n.length||(c=ne,de.src=n[c].url,De(),d?.(c,n[c]))}function Ue(){if(C)return;let ne=of[u]??of.desktop;y=Ew(be,ne);let Be=Math.max(sf,Math.min(af,g??y));Mw(he,de,ne,Be,u),Y&&(Y.textContent=`${Math.round(Be*100)}%`)}let Ve=new ResizeObserver(()=>Ue());Ve.observe(be),De(),de.src=n[c].url,requestAnimationFrame(()=>Ue());function ke(){C||(C=!0,Ve.disconnect(),document.removeEventListener("click",we),M.remove())}return{element:M,goTo:He,next:()=>_e(1),prev:()=>_e(-1),getIndex:()=>c,setDevice(ne){u=ne,he.dataset.device=ne,fe?.setSelected(ne),g=null,Ue()},setColorScheme(ne){b=ne,he.dataset.colorScheme=ne},setZoom(ne){g=ne,Ue()},destroy:ke}}export{wp as ASK_USER_QUESTION_CLIENT_TOOL,Cp as ASK_USER_QUESTION_PARAMETERS_SCHEMA,fa as ASK_USER_QUESTION_TOOL_NAME,ur as AgentWidgetClient,gs as AgentWidgetSession,mr as AttachmentManager,jo as BrowserSpeechEngine,ou as DEFAULT_COMPONENTS,kl as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,un as DEFAULT_FLOATING_LAUNCHER_WIDTH,tu as DEFAULT_PALETTE,nu as DEFAULT_SEMANTIC,it as DEFAULT_WIDGET_CONFIG,Xg as PRESETS,Jg as PRESET_FULLSCREEN,Gg as PRESET_MINIMAL,Kg as PRESET_SHOP,fr as ReadAloudController,cl as SUGGEST_REPLIES_CLIENT_TOOL,bp as SUGGEST_REPLIES_PARAMETERS_SCHEMA,Mn as SUGGEST_REPLIES_TOOL_NAME,Gb as THEME_ZONES,Cn as VERSION,En as WEBMCP_TOOL_PREFIX,es as WebMcpBridge,rw as accessibilityPlugin,sw as animationsPlugin,hr as applyThemeVariables,Cr as attachHeaderToContainer,aw as brandPlugin,Ls as buildComposer,Nu as buildDefaultHeader,yo as buildHeader,ks as buildHeaderWithLayout,Fu as buildMinimalHeader,ss as builtInClientToolsForDispatch,nw as collectEnrichedPageContext,Ln as componentRegistry,ci as createActionManager,mc as createAgentExperience,Qm as createAskUserQuestionBubble,xl as createBestAvailableVoiceProvider,fx as createBubbleWithLayout,uc as createCSATFeedback,Bl as createComboButton,gC as createComponentMiddleware,cc as createComponentStreamParser,zd as createDefaultSanitizer,kw as createDemoCarousel,cm as createDirectivePostprocessor,qo as createDropdownMenu,th as createFlexibleJsonStreamParser,dt as createIconButton,ph as createImagePart,ml as createJsonStreamParser,po as createLabelButton,lc as createLocalStorageAdapter,pa as createMarkdownProcessor,cr as createMarkdownProcessorFromConfig,Qu as createMessageActions,gc as createNPSFeedback,gl as createPlainTextParser,cw as createPlugin,fl as createRegexJsonParser,tc as createRovingTablist,DC as createSlashCommandsSource,Ps as createStandardBubble,OC as createStaticMentionSource,Fo as createTextPart,Wa as createTheme,ys as createThemeObserver,uo as createToggleGroup,wr as createTypingIndicator,$o as createVoiceProvider,gi as createWidgetHostLayout,hl as createXmlParser,uw as default,Er as defaultActionHandlers,li as defaultJsonActionParser,xc as defaultMentionFilter,jg as defaultParseRules,Ha as detectColorScheme,dm as directivePostprocessor,rs as ensureAskUserQuestionSheet,_n as escapeHtml,pc as extractComponentDirectiveFromMessage,uh as fileToImagePart,ow as formatEnrichedContext,No as generateAssistantMessageId,yw as generateCodeSnippet,ih as generateMessageId,zg as generateStableSelector,cs as generateUserMessageId,Uo as getActiveTheme,Rl as getColorScheme,ch as getDisplayText,_u as getHeaderLayout,dh as getImageParts,pw as getPreset,di as hasComponentDirective,bl as hasImages,zl as headerLayouts,lw as highContrastPlugin,Ig as initAgentWidget,oo as isAskUserQuestionMessage,uC as isComponentDirectiveType,Wt as isDockedMountMode,ba as isSuggestRepliesMessage,Ea as isVoiceSupported,Ho as isWebMcpToolName,pl as latestAgentSuggestions,Fv as listRegisteredStreamAnimations,Nd as loadMarkdownParsers,$d as markdownPostprocessor,hs as mergeWithDefaults,lh as normalizeContent,Yr as onMarkdownParsersReady,ro as parseAskUserQuestionPayload,vp as parseSuggestRepliesPayload,ps as pickBestVoice,ai as pluginRegistry,iw as reducedMotionPlugin,Dv as registerStreamAnimationPlugin,Do as removeAskUserQuestionSheet,dc as renderComponentDirective,Xu as renderLoadingIndicatorWithFallback,te as renderLucideIcon,on as resolveDockConfig,Zr as resolveSanitizer,Ll as resolveTokens,ol as stripWebMcpPrefix,Pl as themeToCssVariables,Nv as unregisterStreamAnimationPlugin,gh as validateImageFile,ru as validateTheme};
478
+ `;function Ew(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Tw,document.head.appendChild(e)}function Mw(e,t){let n=e.clientWidth-Ec*2-cf,o=e.clientHeight-Ec*2-cf;return n<=0||o<=0?1:Math.min(n/t.w,o/t.h,1)}function kw(e,t,n,o,r){e.style.width=`${n.w*o}px`,e.style.height=`${n.h*o}px`,e.style.borderRadius=r==="mobile"?`${32*o}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${o})`}function Lw(e,t){let{items:n,initialIndex:o=0,initialDevice:r="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:p=!0,onChange:d}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");Ew();let c=Math.max(0,Math.min(o,n.length-1)),u=r,b=s,g=null,y=1,C=!1,M=m("div","persona-dc-root"),L=m("div","persona-dc-toolbar"),I=m("div","persona-dc-toolbar-lead"),S=m("div","persona-dc-toolbar-trail"),R=dt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>_e(-1)}),$=m("div");$.style.position="relative";let z=m("button","persona-dc-title-btn");z.type="button",z.setAttribute("aria-expanded","false"),z.setAttribute("aria-haspopup","listbox");let w=m("span","persona-dc-title-text"),U=m("span","persona-dc-title-chevron"),q=te("chevron-down",12,"currentColor",2);q&&U.appendChild(q),z.append(w,U);let Q=m("div","persona-dc-dropdown");Q.setAttribute("role","listbox"),Q.style.display="none";let O=!1;function D(){Q.innerHTML="";for(let ne=0;ne<n.length;ne++){let Be=n[ne],vt=m("button","persona-dc-dropdown-item");vt.type="button",vt.setAttribute("role","option"),vt.setAttribute("aria-current",ne===c?"true":"false");let mt=m("span");if(mt.textContent=Be.title,vt.appendChild(mt),Be.description){let at=m("span","persona-dc-dropdown-desc");at.textContent=Be.description,vt.appendChild(at)}vt.addEventListener("click",()=>{me(),He(ne)}),Q.appendChild(vt)}}function ie(){O=!O,Q.style.display=O?"":"none",z.setAttribute("aria-expanded",O?"true":"false"),O&&D()}function me(){O&&(O=!1,Q.style.display="none",z.setAttribute("aria-expanded","false"))}z.addEventListener("click",ne=>{ne.stopPropagation(),ie()});let we=()=>me();document.addEventListener("click",we),$.append(z,Q);let Ee=dt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>_e(1)}),se=m("span","persona-dc-counter");I.append(R,$,Ee,se);let fe=null;i&&(fe=uo({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:ne=>{u=ne,he.dataset.device=u,g=null,Ue()}}),S.appendChild(fe.element));let Y=null;if(a){let ne=m("div","persona-dc-zoom-controls"),Be=dt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{g=Math.max(af,(g??y)-sf),Ue()}});Y=m("span","persona-dc-zoom-level"),Y.title="Reset to 100%",Y.style.cursor="pointer",Y.addEventListener("click",()=>{g=1,Ue()});let vt=dt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{g=Math.min(lf,(g??y)+sf),Ue()}}),mt=dt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,Ue()}});ne.append(Be,Y,vt,mt),S.appendChild(ne)}if(p){let ne=m("div","persona-dc-separator");S.appendChild(ne);let Be=uo({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:b,onSelect:vt=>{b=vt,he.dataset.colorScheme=b,Me()}});S.appendChild(Be.element)}let ce=m("div","persona-dc-separator");S.appendChild(ce);let Z=dt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[c].url,"_blank")}});S.appendChild(Z),L.append(I,S);let be=m("div","persona-dc-stage"),he=m("div","persona-dc-iframe-wrapper");he.dataset.device=u,he.dataset.colorScheme=b;let de=m("iframe","persona-dc-iframe");de.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),de.setAttribute("loading","lazy"),de.title=n[c].title,he.appendChild(de),be.appendChild(he),M.append(L,be),e.appendChild(M);function Me(){try{let ne=de.contentDocument?.body;if(!ne)return;b==="dark"?ne.classList.add("theme-dark"):ne.classList.remove("theme-dark")}catch{}}de.addEventListener("load",()=>Me());function De(){let ne=n[c];w.textContent=ne.title,se.textContent=`${c+1} / ${n.length}`,de.title=ne.title}function _e(ne){let Be=((c+ne)%n.length+n.length)%n.length;He(Be)}function He(ne){ne<0||ne>=n.length||(c=ne,de.src=n[c].url,De(),d?.(c,n[c]))}function Ue(){if(C)return;let ne=rf[u]??rf.desktop;y=Mw(be,ne);let Be=Math.max(af,Math.min(lf,g??y));kw(he,de,ne,Be,u),Y&&(Y.textContent=`${Math.round(Be*100)}%`)}let Ve=new ResizeObserver(()=>Ue());Ve.observe(be),De(),de.src=n[c].url,requestAnimationFrame(()=>Ue());function ke(){C||(C=!0,Ve.disconnect(),document.removeEventListener("click",we),M.remove())}return{element:M,goTo:He,next:()=>_e(1),prev:()=>_e(-1),getIndex:()=>c,setDevice(ne){u=ne,he.dataset.device=ne,fe?.setSelected(ne),g=null,Ue()},setColorScheme(ne){b=ne,he.dataset.colorScheme=ne},setZoom(ne){g=ne,Ue()},destroy:ke}}export{Ap as ASK_USER_QUESTION_CLIENT_TOOL,wp as ASK_USER_QUESTION_PARAMETERS_SCHEMA,fa as ASK_USER_QUESTION_TOOL_NAME,ur as AgentWidgetClient,gs as AgentWidgetSession,mr as AttachmentManager,jo as BrowserSpeechEngine,ru as DEFAULT_COMPONENTS,kl as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,un as DEFAULT_FLOATING_LAUNCHER_WIDTH,nu as DEFAULT_PALETTE,ou as DEFAULT_SEMANTIC,it as DEFAULT_WIDGET_CONFIG,Qg as PRESETS,Xg as PRESET_FULLSCREEN,Jg as PRESET_MINIMAL,Gg as PRESET_SHOP,fr as ReadAloudController,cl as SUGGEST_REPLIES_CLIENT_TOOL,vp as SUGGEST_REPLIES_PARAMETERS_SCHEMA,En as SUGGEST_REPLIES_TOOL_NAME,Jb as THEME_ZONES,io as VERSION,Tn as WEBMCP_TOOL_PREFIX,es as WebMcpBridge,sw as accessibilityPlugin,aw as animationsPlugin,hr as applyThemeVariables,Cr as attachHeaderToContainer,iw as brandPlugin,Ls as buildComposer,Fu as buildDefaultHeader,yo as buildHeader,ks as buildHeaderWithLayout,_u as buildMinimalHeader,ss as builtInClientToolsForDispatch,ow as collectEnrichedPageContext,kn as componentRegistry,ci as createActionManager,mc as createAgentExperience,Ym as createAskUserQuestionBubble,xl as createBestAvailableVoiceProvider,mx as createBubbleWithLayout,uc as createCSATFeedback,Bl as createComboButton,fC as createComponentMiddleware,cc as createComponentStreamParser,qd as createDefaultSanitizer,Lw as createDemoCarousel,dm as createDirectivePostprocessor,qo as createDropdownMenu,nh as createFlexibleJsonStreamParser,dt as createIconButton,uh as createImagePart,ml as createJsonStreamParser,po as createLabelButton,lc as createLocalStorageAdapter,pa as createMarkdownProcessor,cr as createMarkdownProcessorFromConfig,Yu as createMessageActions,gc as createNPSFeedback,gl as createPlainTextParser,dw as createPlugin,fl as createRegexJsonParser,tc as createRovingTablist,NC as createSlashCommandsSource,Ps as createStandardBubble,DC as createStaticMentionSource,Fo as createTextPart,Wa as createTheme,ys as createThemeObserver,uo as createToggleGroup,wr as createTypingIndicator,$o as createVoiceProvider,gi as createWidgetHostLayout,hl as createXmlParser,gw as default,Er as defaultActionHandlers,li as defaultJsonActionParser,xc as defaultMentionFilter,Ug as defaultParseRules,Ha as detectColorScheme,pm as directivePostprocessor,rs as ensureAskUserQuestionSheet,Fn as escapeHtml,pc as extractComponentDirectiveFromMessage,gh as fileToImagePart,rw as formatEnrichedContext,No as generateAssistantMessageId,bw as generateCodeSnippet,lh as generateMessageId,qg as generateStableSelector,cs as generateUserMessageId,Uo as getActiveTheme,Rl as getColorScheme,dh as getDisplayText,$u as getHeaderLayout,ph as getImageParts,uw as getPreset,di as hasComponentDirective,bl as hasImages,zl as headerLayouts,cw as highContrastPlugin,Wg as initAgentWidget,no as isAskUserQuestionMessage,gC as isComponentDirectiveType,Wt as isDockedMountMode,ba as isSuggestRepliesMessage,Ea as isVoiceSupported,Ho as isWebMcpToolName,pl as latestAgentSuggestions,_v as listRegisteredStreamAnimations,Fd as loadMarkdownParsers,jd as markdownPostprocessor,hs as mergeWithDefaults,ch as normalizeContent,Yr as onMarkdownParsersReady,oo as parseAskUserQuestionPayload,xp as parseSuggestRepliesPayload,ps as pickBestVoice,ai as pluginRegistry,lw as reducedMotionPlugin,Nv as registerStreamAnimationPlugin,Do as removeAskUserQuestionSheet,dc as renderComponentDirective,Qu as renderLoadingIndicatorWithFallback,te as renderLucideIcon,on as resolveDockConfig,Zr as resolveSanitizer,Ll as resolveTokens,ol as stripWebMcpPrefix,Pl as themeToCssVariables,Fv as unregisterStreamAnimationPlugin,fh as validateImageFile,su as validateTheme};
479
479
  //# sourceMappingURL=index.js.map