@runtypelabs/persona 4.6.0 → 4.7.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/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-8RICZWQe.d.cts → types-CSmiKRVa.d.cts} +5 -0
- package/dist/animations/{types-8RICZWQe.d.ts → types-CSmiKRVa.d.ts} +5 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/codegen.cjs +4 -4
- package/dist/codegen.js +4 -4
- package/dist/index.cjs +39 -39
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +51 -3
- package/dist/index.d.ts +51 -3
- package/dist/index.global.js +29 -29
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +39 -39
- package/dist/index.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +5 -0
- package/dist/smart-dom-reader.d.ts +5 -0
- package/dist/theme-editor-preview.cjs +30 -30
- package/dist/theme-editor-preview.d.cts +5 -0
- package/dist/theme-editor-preview.d.ts +5 -0
- package/dist/theme-editor-preview.js +30 -30
- package/dist/theme-editor.d.cts +5 -0
- package/dist/theme-editor.d.ts +5 -0
- package/package.json +4 -2
- package/src/client.test.ts +314 -0
- package/src/client.ts +200 -86
- package/src/generated/runtype-openapi-contract.ts +10 -1
- package/src/runtime/persist-state.test.ts +118 -0
- package/src/ui.scroll-additive.test.ts +1 -1
- package/src/ui.streaming-coalescing.test.ts +312 -0
- package/src/ui.ts +235 -105
- package/src/utils/morph.test.ts +47 -0
- package/src/utils/morph.ts +18 -0
package/dist/index.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
var ih=Object.defineProperty;var ys=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ki=(e,t)=>{for(var n in t)ih(e,n,{get:t[n],enumerable:!0})};var qu={};Ki(qu,{DOMPurify:()=>ch,Marked:()=>lh});import{Marked as lh}from"marked";import ch from"dompurify";var zu=ys(()=>{"use strict"});var Ss,dl=ys(()=>{"use strict";Ss=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;var o;this.sampleRate=t;let r=Math.max(0,(o=n.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(t*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({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 o=new Uint8Array(this.remainder.length+t.length);o.set(this.remainder),o.set(t,this.remainder.length),n=o,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 r=this.pcmToFloat32(n);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let 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(),r=n.createBuffer(1,t.length,this.sampleRate);r.getChannelData(0).set(t);let o=n.createBufferSource();o.buffer=r,o.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)),o.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(o),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}o.onended=()=>{let a=this.activeSources.indexOf(o);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function Ly(e){return e.replace(/\/+$/,"")}async function Py(e){var t,n;try{let r=await e.json();return r.detail?`${(t=r.error)!=null?t:`Runtype TTS ${e.status}`}: ${r.detail}`:(n=r.error)!=null?n:`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Xa,_m=ys(()=>{"use strict";dl();Xa=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var t,n;return(n=this.playerPromise)!=null?n:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new Ss(24e3,{prebufferMs:(t=this.opts.prebufferMs)!=null?t:200})).then(r=>this.player=r)}speak(t,n){let r=++this.generation;this.run(r,t,n)}async run(t,n,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(t!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var f;t===this.generation&&((f=r.onStart)==null||f.call(r))}),d.onFinished(()=>{var f;t===this.generation&&((f=r.onEnd)==null||f.call(r))});let c=`${Ly(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,p=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:(o=n.voice)!=null?o:this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!p.ok||!p.body)throw new Error(await Py(p));let u=p.body.getReader();for(;;){let{done:f,value:g}=await u.read();if(t!==this.generation){await u.cancel().catch(()=>{});return}if(f)break;g&&g.byteLength>0&&d.enqueue(g)}d.markStreamEnd()}catch(d){if(t!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,c),(i=r.onError)==null||i.call(r,c)}}pause(){var t;(t=this.player)==null||t.pause()}resume(){var t;(t=this.player)==null||t.resume()}stop(){var t;this.generation++,(t=this.player)==null||t.flush()}destroy(){var t;this.generation++,(t=this.player)==null||t.destroy(),this.player=null,this.playerPromise=null}}});var Qa,$m=ys(()=>{"use strict";Qa=class{constructor(t,n,r={}){this.primary=t;this.fallback=n;this.options=r;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let r=!1;this.primary.speak(t,{onStart:()=>{var o;r=!0,(o=n.onStart)==null||o.call(n)},onEnd:()=>{var o;return(o=n.onEnd)==null?void 0:o.call(n)},onError:o=>{var s,a,i;if(r){(s=n.onError)==null||s.call(n,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var t,n,r,o;(n=(t=this.primary).destroy)==null||n.call(t),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var jm={};Ki(jm,{FallbackSpeechEngine:()=>Qa,RuntypeSpeechEngine:()=>Xa});var Um=ys(()=>{"use strict";_m();$m()});var zm={};Ki(zm,{createReconnectController:()=>Ry});function Ry(e){let t=0,n=null,r=null,o=!1,s=()=>{if(r&&(clearTimeout(r),r=null),n){let b=n;n=null,b()}},a=()=>{let b=e.getStatus();b!=="resuming"&&b!=="paused"||s()},i=()=>{typeof document!="undefined"&&document.visibilityState==="hidden"||a()},d=()=>{a()},c=()=>{o||(typeof document!="undefined"&&document.addEventListener("visibilitychange",i),typeof window!="undefined"&&window.addEventListener("online",d),o=!0)},p=()=>{o&&(typeof document!="undefined"&&document.removeEventListener("visibilitychange",i),typeof window!="undefined"&&window.removeEventListener("online",d),o=!1)},u=b=>new Promise(v=>{n=v,r=setTimeout(()=>{r=null,n=null,v()},b)}),f=()=>{var T;let b=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,p(),e.setAbortController(null);let v=!1;for(let L of e.getMessages())L.streaming&&(L.streaming=!1,v=!0);let S=e.buildErrorContent("Connection lost and the response could not be resumed.");S?e.appendMessage({id:`reconnect-failed-${(T=b==null?void 0:b.executionId)!=null?T:e.nextSequence()}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):v&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},g=async()=>{var T,L,P,E,k,C;let b=(L=(T=e.config.reconnect)==null?void 0:T.backoffMs)!=null?L:Iy,v=(E=(P=e.config.reconnect)==null?void 0:P.maxAttempts)!=null?E:b.length,S=e.config.reconnectStream;if(!S){e.setReconnecting(!1);return}for(;e.getResumable()&&t<v;){t+=1,e.setStatus("resuming");let I=e.getResumable(),j=I.lastEventId,$=new AbortController;e.setAbortController($),e.emitReconnect({phase:"resuming",handle:I,attempt:t});let R=null;try{let N=await S({executionId:I.executionId,after:I.lastEventId,signal:$.signal});N&&N.ok&&N.body&&(R=N.body)}catch{R=null}if($.signal.aborted)return;if(R){let N=(k=e.getMessages().find(Z=>Z.id===I.assistantMessageId))==null?void 0:k.content,O=typeof N=="string"?N:"";try{await e.resumeConnect(R,I.assistantMessageId,O)}catch{}if($.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,p(),e.emitReconnect({phase:"resumed",handle:I});return}e.getResumable().lastEventId!==j&&(t=0)}if(e.getResumable()&&t<v&&(e.setStatus("paused"),await u((C=b[Math.min(t-1,b.length-1)])!=null?C:1e3),$.signal.aborted))return}e.getResumable()&&f()};return{begin(){t=0,c(),g()},teardown(){r&&(clearTimeout(r),r=null),n=null,t=0,p()},wake:s}}var Iy,Vm=ys(()=>{"use strict";Iy=[1e3,2e3,4e3,8e3,8e3]});import{Marked as dh}from"marked";import ph from"dompurify";var Vu=null,xs=null,bs=null;var Ku=e=>{xs=e},Gu=()=>xs?Promise.resolve(xs):bs||(Vu?(bs=Vu().then(e=>(xs=e,e)),bs):(bs=Promise.resolve().then(()=>(zu(),qu)).then(e=>(xs=e,e)),bs)),Vo=()=>xs;Ku({Marked:dh,DOMPurify:ph});var uh=e=>{if(e)return e},Wa=e=>{let t=null;return n=>{var o,s;let r=Vo();if(!r)return Kr(n);if(!t){let{Marked:a}=r,i=e==null?void 0:e.markedOptions;t=new a({gfm:(o=i==null?void 0:i.gfm)!=null?o:!0,breaks:(s=i==null?void 0:i.breaks)!=null?s:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=uh(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},vs=e=>e?Wa({markedOptions:e.options,renderer:e.renderer}):Wa(),mh=Wa(),Xu=e=>mh(e),Kr=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Qu=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Ju=e=>`%%FORM_PLACEHOLDER_${e}%%`,Yu=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Ju(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=Ju(t.length);return t.push({token:s,type:o}),s}),n},gh=e=>{let t=vs(e);return n=>{let r=[],o=Yu(n,r),s=t(o);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Qu(i)}"></div>`;s=s.replace(d,p)}),s}},fh=e=>{let t=[],n=Yu(e,t),r=Xu(n);return t.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Qu(s)}"></div>`;r=r.replace(a,d)}),r};var hh={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"]},yh=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Zu=()=>{let e=null;return t=>{let n=Vo();if(!n)return Kr(t);if(!e){let{DOMPurify:r}=n;e=r(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!yh.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,hh)}},Xs=e=>e===!1?null:typeof e=="function"?e:Zu();var em=/^\s*\|?[\s:|-]*-[\s:|-]*$/,tm=e=>e.includes("|"),nm=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())},bh=e=>`| ${e.join(" | ")} |`,xh=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,vh=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),rm=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
2
|
-
`),n=!1;for(let r=0;r<t.length-1;r++){let o=t[r],s=t[r+1];if(!
|
|
3
|
-
`):e};var Rr="webmcp:",
|
|
1
|
+
var Ch=Object.defineProperty;var vs=(e,t)=>()=>(e&&(t=e(e=0)),t);var nl=(e,t)=>{for(var n in t)Ch(e,n,{get:t[n],enumerable:!0})};var nm={};nl(nm,{DOMPurify:()=>Sh,Marked:()=>Ah});import{Marked as Ah}from"marked";import Sh from"dompurify";var rm=vs(()=>{"use strict"});var Ms,xl=vs(()=>{"use strict";Ms=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;var o;this.sampleRate=t;let r=Math.max(0,(o=n.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(t*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({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 o=new Uint8Array(this.remainder.length+t.length);o.set(this.remainder),o.set(t,this.remainder.length),n=o,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 r=this.pcmToFloat32(n);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let 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(),r=n.createBuffer(1,t.length,this.sampleRate);r.getChannelData(0).set(t);let o=n.createBufferSource();o.buffer=r,o.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)),o.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(o),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}o.onended=()=>{let a=this.activeSources.indexOf(o);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function qy(e){return e.replace(/\/+$/,"")}async function zy(e){var t,n;try{let r=await e.json();return r.detail?`${(t=r.error)!=null?t:`Runtype TTS ${e.status}`}: ${r.detail}`:(n=r.error)!=null?n:`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var ei,Ym=vs(()=>{"use strict";xl();ei=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var t,n;return(n=this.playerPromise)!=null?n:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new Ms(24e3,{prebufferMs:(t=this.opts.prebufferMs)!=null?t:200})).then(r=>this.player=r)}speak(t,n){let r=++this.generation;this.run(r,t,n)}async run(t,n,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(t!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var f;t===this.generation&&((f=r.onStart)==null||f.call(r))}),d.onFinished(()=>{var f;t===this.generation&&((f=r.onEnd)==null||f.call(r))});let c=`${qy(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,p=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:(o=n.voice)!=null?o:this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!p.ok||!p.body)throw new Error(await zy(p));let u=p.body.getReader();for(;;){let{done:f,value:g}=await u.read();if(t!==this.generation){await u.cancel().catch(()=>{});return}if(f)break;g&&g.byteLength>0&&d.enqueue(g)}d.markStreamEnd()}catch(d){if(t!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,c),(i=r.onError)==null||i.call(r,c)}}pause(){var t;(t=this.player)==null||t.pause()}resume(){var t;(t=this.player)==null||t.resume()}stop(){var t;this.generation++,(t=this.player)==null||t.flush()}destroy(){var t;this.generation++,(t=this.player)==null||t.destroy(),this.player=null,this.playerPromise=null}}});var ti,Zm=vs(()=>{"use strict";ti=class{constructor(t,n,r={}){this.primary=t;this.fallback=n;this.options=r;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let r=!1;this.primary.speak(t,{onStart:()=>{var o;r=!0,(o=n.onStart)==null||o.call(n)},onEnd:()=>{var o;return(o=n.onEnd)==null?void 0:o.call(n)},onError:o=>{var s,a,i;if(r){(s=n.onError)==null||s.call(n,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var t,n,r,o;(n=(t=this.primary).destroy)==null||n.call(t),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var eg={};nl(eg,{FallbackSpeechEngine:()=>ti,RuntypeSpeechEngine:()=>ei});var tg=vs(()=>{"use strict";Ym();Zm()});var rg={};nl(rg,{createReconnectController:()=>Ky});function Ky(e){let t=0,n=null,r=null,o=!1,s=()=>{if(r&&(clearTimeout(r),r=null),n){let y=n;n=null,y()}},a=()=>{let y=e.getStatus();y!=="resuming"&&y!=="paused"||s()},i=()=>{typeof document!="undefined"&&document.visibilityState==="hidden"||a()},d=()=>{a()},c=()=>{o||(typeof document!="undefined"&&document.addEventListener("visibilitychange",i),typeof window!="undefined"&&window.addEventListener("online",d),o=!0)},p=()=>{o&&(typeof document!="undefined"&&document.removeEventListener("visibilitychange",i),typeof window!="undefined"&&window.removeEventListener("online",d),o=!1)},u=y=>new Promise(v=>{n=v,r=setTimeout(()=>{r=null,n=null,v()},y)}),f=()=>{var T;let y=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,p(),e.setAbortController(null);let v=!1;for(let L of e.getMessages())L.streaming&&(L.streaming=!1,v=!0);let A=e.buildErrorContent("Connection lost and the response could not be resumed.");A?e.appendMessage({id:`reconnect-failed-${(T=y==null?void 0:y.executionId)!=null?T:e.nextSequence()}`,role:"assistant",content:A,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):v&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},g=async()=>{var T,L,W,R,P,S;let y=(L=(T=e.config.reconnect)==null?void 0:T.backoffMs)!=null?L:Vy,v=(R=(W=e.config.reconnect)==null?void 0:W.maxAttempts)!=null?R:y.length,A=e.config.reconnectStream;if(!A){e.setReconnecting(!1);return}for(;e.getResumable()&&t<v;){t+=1,e.setStatus("resuming");let H=e.getResumable(),U=H.lastEventId,j=new AbortController;e.setAbortController(j),e.emitReconnect({phase:"resuming",handle:H,attempt:t});let k=null;try{let O=await A({executionId:H.executionId,after:H.lastEventId,signal:j.signal});O&&O.ok&&O.body&&(k=O.body)}catch{k=null}if(j.signal.aborted)return;if(k){let O=(P=e.getMessages().find(Z=>Z.id===H.assistantMessageId))==null?void 0:P.content,F=typeof O=="string"?O:"";try{await e.resumeConnect(k,H.assistantMessageId,F)}catch{}if(j.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,p(),e.emitReconnect({phase:"resumed",handle:H});return}e.getResumable().lastEventId!==U&&(t=0)}if(e.getResumable()&&t<v&&(e.setStatus("paused"),await u((S=y[Math.min(t-1,y.length-1)])!=null?S:1e3),j.signal.aborted))return}e.getResumable()&&f()};return{begin(){t=0,c(),g()},teardown(){r&&(clearTimeout(r),r=null),n=null,t=0,p()},wake:s}}var Vy,og=vs(()=>{"use strict";Vy=[1e3,2e3,4e3,8e3,8e3]});import{Marked as Th}from"marked";import Eh from"dompurify";var om=null,Cs=null,ws=null;var sm=e=>{Cs=e},am=()=>Cs?Promise.resolve(Cs):ws||(om?(ws=om().then(e=>(Cs=e,e)),ws):(ws=Promise.resolve().then(()=>(rm(),nm)).then(e=>(Cs=e,e)),ws)),Go=()=>Cs;sm({Marked:Th,DOMPurify:Eh});var Mh=e=>{if(e)return e},Oa=e=>{let t=null;return n=>{var o,s;let r=Go();if(!r)return Xr(n);if(!t){let{Marked:a}=r,i=e==null?void 0:e.markedOptions;t=new a({gfm:(o=i==null?void 0:i.gfm)!=null?o:!0,breaks:(s=i==null?void 0:i.breaks)!=null?s:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=Mh(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},As=e=>e?Oa({markedOptions:e.options,renderer:e.renderer}):Oa(),kh=Oa(),lm=e=>kh(e),Xr=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),cm=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),im=e=>`%%FORM_PLACEHOLDER_${e}%%`,dm=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=im(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=im(t.length);return t.push({token:s,type:o}),s}),n},Lh=e=>{let t=As(e);return n=>{let r=[],o=dm(n,r),s=t(o);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${cm(i)}"></div>`;s=s.replace(d,p)}),s}},Ph=e=>{let t=[],n=dm(e,t),r=lm(n);return t.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${cm(s)}"></div>`;r=r.replace(a,d)}),r};var Ih={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"]},Rh=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,pm=()=>{let e=null;return t=>{let n=Go();if(!n)return Xr(t);if(!e){let{DOMPurify:r}=n;e=r(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!Rh.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,Ih)}},Zs=e=>e===!1?null:typeof e=="function"?e:pm();var um=/^\s*\|?[\s:|-]*-[\s:|-]*$/,mm=e=>e.includes("|"),gm=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())},Wh=e=>`| ${e.join(" | ")} |`,Hh=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,Bh=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),fm=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
|
|
2
|
+
`),n=!1;for(let r=0;r<t.length-1;r++){let o=t[r],s=t[r+1];if(!mm(o)||um.test(o)||!um.test(s))continue;let a=gm(o).length;if(a<1)continue;let i=Hh(a);t[r+1]!==i&&(t[r+1]=i,n=!0);let d=r+2;for(;d<t.length;d++){let c=t[d];if(c.trim()===""||!mm(c))break;let p=Wh(Bh(gm(c),a));t[d]!==p&&(t[d]=p,n=!0)}r=d-1}return n?t.join(`
|
|
3
|
+
`):e};var Rr="webmcp:",rl=new Map,hm=e=>{var t;rl.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&rl.set(n.name,r)}},ta=e=>rl.get(ol(e)),Fa={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},ym=null;function xm(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,o;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(o=n.origin)!=null?o:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${Dh(t.join(""))}`}function bm(e,t){let n=3735928559^t,r=1103547991^t;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);n=Math.imul(n^s,2654435761),r=Math.imul(r^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function Dh(e){let t=bm(e,0).toString(36),n=bm(e,2654435761).toString(36);return`${t}.${n}`}var ea=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n: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(o){return Fa.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}hm(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Oh(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return mr("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let y=typeof document!="undefined"&&!!document.modelContext;return mr(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 o.getTools()}catch(y){let v=y instanceof Error?y.message:String(y);return mr(`Failed to read WebMCP registry: ${v}`)}hm(a);let i=a.find(y=>y.name===s);if(!i)return mr(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return mr(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return mr("Aborted by cancel()");let d=ta(s),c={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return mr("User declined the tool call.");if(r!=null&&r.aborted)return mr("Aborted by cancel()");let p=new AbortController,u=!1,f=setTimeout(()=>{u=!0,p.abort()},this.timeoutMs),g=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",g,{once:!0}));try{let y=await o.executeTool(i,jh(n),{signal:p.signal});return Fh(y)}catch(y){if(u)return mr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return mr("Aborted by cancel()");let v=y instanceof Error?y.message:String(y);return mr(v)}finally{clearTimeout(f),r&&r.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}(ym?await ym():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Fa.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")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,Fa.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){var r;let n=(r=this.confirmHandler)!=null?r:_h;try{return await n(t)}catch(o){return Fa.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(r=>Nh(t,r))}},ol=e=>e.startsWith(Rr)?e.slice(Rr.length):e,Jo=e=>e.startsWith(Rr),Nh=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Oh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Fh=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:Uh(t)}]}},mr=e=>({isError:!0,content:[{type:"text",text:e}]}),_h=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=$h(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)},Eh=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)}},Mh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},kh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Lh="agent_",Ph="flow_";function lm(e){return e.startsWith(Lh)?{kind:"agentId",agentId:e}:e.startsWith(Ph)?{kind:"flowId",flowId:e}:null}function cm(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let r=n.indexOf(":");if(r>0){let a=n.slice(0,r),i=n.slice(r+1);if(a==="runtype"){let c=lm(i);if(c)return c;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=t==null?void 0:t[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(i).payload}}let o=lm(n);if(o)return o;let s=t==null?void 0: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 Ih,ARR as Rh,OBJ as Wh,STR as Hh}from"partial-json";var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Wr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var Et=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))r.setAttribute(s,a);if(t.style){let s=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=n.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Zs=(...e)=>e.filter(Boolean).join(" ");var Ba="ask_user_question",ea=8,ws="data-persona-ask-sheet-for",Bh="Other",Dh="Other\u2026",pm="Type your own answer here",um="Send",Nh="Next",Oh="Back",Fh="Submit all",_h="Skip",$h=3,Xi="data-ask-current-index",Qi="data-ask-question-count",mm="data-ask-answers",Yi="data-ask-grouped",gm="data-ask-layout",jh=e=>e.layout==="pills"?"pills":"rows",Uh=e=>e.getAttribute(gm)==="pills"?"pills":"rows",dm=!1,fm=e=>e.replace(/["\\]/g,"\\$&"),yo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ba,Da=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},bo=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 r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=Ih(o,Hh|Wh|Rh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ta=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>ea&&!dm&&(dm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ea}.`)),t.slice(0,ea)},qh=e=>{var t;return(t=ta(e)[0])!=null?t:null},zh=(e,t)=>{var n;return(n=ta(e)[t])!=null?n:null},hm=(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))},ym=(e,t,n)=>{if(e!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let o=y("span","persona-ask-row-check");r.appendChild(o)}else{let o=y("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},Vh=(e,t,n,r)=>{let s=y("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",r?"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=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let c=y("span","persona-ask-row-description");c.textContent=e.description,a.appendChild(c)}s.appendChild(a);let d=ym(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Kh=e=>{let n=y("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},Gh=(e,t,n,r)=>{var p,u,f;let s=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<$h;g++)s.appendChild(Kh(r));return s}if(d.forEach((g,b)=>{s.appendChild(Vh(g,b,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?Bh:Dh;if(r==="rows"){let b=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");b.setAttribute("data-ask-user-action","focus-free-text"),b.setAttribute("data-option-index",String(d.length)),b.setAttribute("data-ask-other-row","true");let v=y("span","persona-ask-row-content"),S=document.createElement("input");S.type="text",S.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",S.placeholder=(p=t.freeTextPlaceholder)!=null?p:pm,S.setAttribute("data-ask-free-text-input","true"),S.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:g),v.appendChild(S),b.appendChild(v);let T=ym(r,a,d.length);T&&b.appendChild(T),s.appendChild(b)}else{let b=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");b.type="button",b.setAttribute("data-ask-user-action","open-free-text"),b.textContent=(f=t.freeTextLabel)!=null?f:g,s.appendChild(b)}}return s},bm=(e,t)=>{var s,a;let r=y("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");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:pm,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:um,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Jh=e=>{var r;let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:um,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Xh=(e,t,n)=>{var c,p,u,f;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=n.backLabel)!=null?c:Oh,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:_h,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:Fh:(f=n.nextLabel)!=null?f:Nh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Go=e=>{let t=e.getAttribute(mm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},xm=(e,t)=>{e.setAttribute(mm,JSON.stringify(t))},er=e=>{var n;let t=Number((n=e.getAttribute(Xi))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Qh=(e,t)=>{e.setAttribute(Xi,String(Math.max(0,Math.floor(t))))},Cs=e=>{var n;let t=Number((n=e.getAttribute(Qi))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},xo=e=>e.getAttribute(Yi)==="true",Yh=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Zh=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Na=(e,t)=>{let{payload:n}=bo(t),r=ta(n),o=Go(e),s={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},vm=e=>{let t=Go(e),n=er(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let c=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(c);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},wm=e=>{if(!xo(e))return;let t=Go(e),n=er(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);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}},Zi=(e,t,n)=>{let r=Da(n),o=Uh(e),{payload:s,complete:a}=bo(t),i=xo(e),d=er(e),c=Cs(e),p=i?zh(s,d):qh(s),u=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${c}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let b=e.querySelector('[data-ask-question="true"]');if(b){let L=typeof(p==null?void 0:p.question)=="string"?p.question:"";b.textContent=L,b.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let L=Gh(p,r,a,o);v.replaceWith(L)}if(o!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(bm(r,o))}let S=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!S?e.appendChild(Jh(r)):(!u||i)&&S&&S.remove(),e.setAttribute("data-multi-select",u?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=Xh(d,c,r);T?T.replaceWith(L):e.appendChild(L)}else T&&T.remove();vm(e),wm(e)},ey=(e,t,n)=>{let r=Da(t),o=jh(r),s=e.toolCall.id,a=ta(n),i=Math.max(1,a.length),d=i>1,c=Yh(e,a),p=d?Zh(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(ws,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Qi,String(i)),u.setAttribute(Xi,String(p)),u.setAttribute(Yi,d?"true":"false"),u.setAttribute(gm,o),xm(u,c),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),hm(u,r);let f=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=y("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let b=y("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",f.appendChild(b),u.appendChild(f);let S=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),u.appendChild(S),o!=="rows"&&u.appendChild(bm(r,o)),Zi(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},ty=(e,t,n)=>{let{payload:r}=bo(t),o=Math.max(1,ta(r).length);o>Cs(e)&&(e.setAttribute(Qi,String(o)),o>1&&!xo(e)&&e.setAttribute(Yi,"true")),Zi(e,t,n)},ny=(e,t)=>{let n=y("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 r=Da(t);hm(n,r);let o=y("span","persona-ask-stub-label"),{complete:s}=bo(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},na=(e,t,n)=>{if(!n||!yo(e)||Da(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${ws}]`).forEach(c=>{c.getAttribute(ws)!==o&&c.remove()});let a=n.querySelector(`[${ws}="${fm(o)}"]`);if(a){ty(a,e,t);return}let{payload:i}=bo(e),d=ey(e,t,i);n.appendChild(d)},Jo=(e,t)=>{if(!e)return;let n=t?`[${ws}="${fm(t)}"]`:`[${ws}]`;e.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},el=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),vo=(e,t)=>{let n=Go(e),r=er(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,xm(e,n),vm(e),wm(e)},Oa=(e,t,n,r)=>{let o=Cs(e),s=Math.max(0,Math.min(o-1,r));Qh(e,s),Zi(e,t,n)};var Hr="suggest_replies";var Cm={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},tl={name:Hr,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:Cm,origin:"sdk",annotations:{readOnlyHint:!0}},nl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Fa=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Hr},Am=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},rl=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!Fa(r))continue;let o=Am((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},Sm=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var Tm={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ea,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},Em={name:Ba,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:Tm,origin:"sdk",annotations:{readOnlyHint:!0}},_a=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(Em),Sm(e)&&t.push(tl),t};import{parse as Mm,STR as km,OBJ as Lm}from"partial-json";var $a=e=>e.replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
8
|
+
${e.description}`:"");return window.confirm(n)},$h=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)}},jh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Uh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var qh="agent_",zh="flow_";function vm(e){return e.startsWith(qh)?{kind:"agentId",agentId:e}:e.startsWith(zh)?{kind:"flowId",flowId:e}:null}function wm(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let r=n.indexOf(":");if(r>0){let a=n.slice(0,r),i=n.slice(r+1);if(a==="runtype"){let c=vm(i);if(c)return c;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=t==null?void 0:t[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(i).payload}}let o=vm(n);if(o)return o;let s=t==null?void 0: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 Vh,ARR as Kh,OBJ as Gh,STR as Jh}from"partial-json";var b=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Wr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var Et=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))r.setAttribute(s,a);if(t.style){let s=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=n.filter(s=>s!=null);return o.length>0&&r.append(...o),r},na=(...e)=>e.filter(Boolean).join(" ");var _a="ask_user_question",ra=8,Ss="data-persona-ask-sheet-for",Xh="Other",Qh="Other\u2026",Am="Type your own answer here",Sm="Send",Yh="Next",Zh="Back",ey="Submit all",ty="Skip",ny=3,sl="data-ask-current-index",al="data-ask-question-count",Tm="data-ask-answers",il="data-ask-grouped",Em="data-ask-layout",ry=e=>e.layout==="pills"?"pills":"rows",oy=e=>e.getAttribute(Em)==="pills"?"pills":"rows",Cm=!1,Mm=e=>e.replace(/["\\]/g,"\\$&"),xo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===_a,$a=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},vo=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 r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=Vh(o,Jh|Gh|Kh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},oa=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>ra&&!Cm&&(Cm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ra}.`)),t.slice(0,ra)},sy=e=>{var t;return(t=oa(e)[0])!=null?t:null},ay=(e,t)=>{var n;return(n=oa(e)[t])!=null?n:null},km=(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))},Lm=(e,t,n)=>{if(e!=="rows")return null;let r=b("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let o=b("span","persona-ask-row-check");r.appendChild(o)}else{let o=b("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},iy=(e,t,n,r)=>{let s=b("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",r?"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=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let c=b("span","persona-ask-row-description");c.textContent=e.description,a.appendChild(c)}s.appendChild(a);let d=Lm(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},ly=e=>{let n=b("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},cy=(e,t,n,r)=>{var p,u,f;let s=b("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<ny;g++)s.appendChild(ly(r));return s}if(d.forEach((g,y)=>{s.appendChild(iy(g,y,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?Xh:Qh;if(r==="rows"){let y=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");y.setAttribute("data-ask-user-action","focus-free-text"),y.setAttribute("data-option-index",String(d.length)),y.setAttribute("data-ask-other-row","true");let v=b("span","persona-ask-row-content"),A=document.createElement("input");A.type="text",A.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",A.placeholder=(p=t.freeTextPlaceholder)!=null?p:Am,A.setAttribute("data-ask-free-text-input","true"),A.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:g),v.appendChild(A),y.appendChild(v);let T=Lm(r,a,d.length);T&&y.appendChild(T),s.appendChild(y)}else{let y=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");y.type="button",y.setAttribute("data-ask-user-action","open-free-text"),y.textContent=(f=t.freeTextLabel)!=null?f:g,s.appendChild(y)}}return s},Pm=(e,t)=>{var s,a;let r=b("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");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:Am,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),t!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Sm,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},dy=e=>{var r;let t=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=b("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:Sm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},py=(e,t,n)=>{var c,p,u,f;let r=b("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=b("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=n.backLabel)!=null?c:Zh,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:ty,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:ey:(f=n.nextLabel)!=null?f:Yh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Xo=e=>{let t=e.getAttribute(Tm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Im=(e,t)=>{e.setAttribute(Tm,JSON.stringify(t))},er=e=>{var n;let t=Number((n=e.getAttribute(sl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},uy=(e,t)=>{e.setAttribute(sl,String(Math.max(0,Math.floor(t))))},Ts=e=>{var n;let t=Number((n=e.getAttribute(al))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},wo=e=>e.getAttribute(il)==="true",my=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},gy=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},ja=(e,t)=>{let{payload:n}=vo(t),r=oa(n),o=Xo(e),s={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},Rm=e=>{let t=Xo(e),n=er(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let c=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(c);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Wm=e=>{if(!wo(e))return;let t=Xo(e),n=er(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);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}},ll=(e,t,n)=>{let r=$a(n),o=oy(e),{payload:s,complete:a}=vo(t),i=wo(e),d=er(e),c=Ts(e),p=i?ay(s,d):sy(s),u=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${c}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let y=e.querySelector('[data-ask-question="true"]');if(y){let L=typeof(p==null?void 0:p.question)=="string"?p.question:"";y.textContent=L,y.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let L=cy(p,r,a,o);v.replaceWith(L)}if(o!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Pm(r,o))}let A=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!A?e.appendChild(dy(r)):(!u||i)&&A&&A.remove(),e.setAttribute("data-multi-select",u?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=py(d,c,r);T?T.replaceWith(L):e.appendChild(L)}else T&&T.remove();Rm(e),Wm(e)},fy=(e,t,n)=>{let r=$a(t),o=ry(r),s=e.toolCall.id,a=oa(n),i=Math.max(1,a.length),d=i>1,c=my(e,a),p=d?gy(e,i):0,u=b("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Ss,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(al,String(i)),u.setAttribute(sl,String(p)),u.setAttribute(il,d?"true":"false"),u.setAttribute(Em,o),Im(u,c),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),km(u,r);let f=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=b("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let y=b("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",f.appendChild(y),u.appendChild(f);let A=b("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return A.setAttribute("data-ask-pill-list","true"),A.setAttribute("role","group"),u.appendChild(A),o!=="rows"&&u.appendChild(Pm(r,o)),ll(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},hy=(e,t,n)=>{let{payload:r}=vo(t),o=Math.max(1,oa(r).length);o>Ts(e)&&(e.setAttribute(al,String(o)),o>1&&!wo(e)&&e.setAttribute(il,"true")),ll(e,t,n)},yy=(e,t)=>{let n=b("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 r=$a(t);km(n,r);let o=b("span","persona-ask-stub-label"),{complete:s}=vo(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},sa=(e,t,n)=>{if(!n||!xo(e)||$a(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${Ss}]`).forEach(c=>{c.getAttribute(Ss)!==o&&c.remove()});let a=n.querySelector(`[${Ss}="${Mm(o)}"]`);if(a){hy(a,e,t);return}let{payload:i}=vo(e),d=fy(e,t,i);n.appendChild(d)},Qo=(e,t)=>{if(!e)return;let n=t?`[${Ss}="${Mm(t)}"]`:`[${Ss}]`;e.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},cl=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),Co=(e,t)=>{let n=Xo(e),r=er(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Im(e,n),Rm(e),Wm(e)},Ua=(e,t,n,r)=>{let o=Ts(e),s=Math.max(0,Math.min(o-1,r));uy(e,s),ll(e,t,n)};var Hr="suggest_replies";var Hm={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},dl={name:Hr,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:Hm,origin:"sdk",annotations:{readOnlyHint:!0}},pl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),qa=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Hr},Bm=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},ul=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!qa(r))continue;let o=Bm((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},Dm=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var Nm={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ra,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},Om={name:_a,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:Nm,origin:"sdk",annotations:{readOnlyHint:!0}},aa=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(Om),Dm(e)&&t.push(dl),t};import{parse as Fm,STR as _m,OBJ as $m}from"partial-json";var za=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)}},by=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},jm=e=>e.status==="complete"?by(e):e.status==="pending"?"Waiting":"",xy=e=>{var o,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a: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 Um=e=>e.status==="complete"?xy(e):"Using tool...",Va=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},la=e=>{var n,r,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return Va(t)},Ka=e=>{var n,r,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return Va(t)},ml=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=la(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Ga=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&ia(r,n.slice(s,a.index),[]),a[1]!==void 0?ia(r,a[1],["bold"]):a[2]!==void 0?ia(r,a[2],["italic"]):a[3]!==void 0&&ia(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&ia(r,n.slice(s),[]),r},ia=(e,t,n)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:n}),o<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},vy=()=>{let e=null,t=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);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=r.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 r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},sa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},sl=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},al=()=>{var t;let e=sy();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},il=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=Mm(n,km|Lm);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?$a(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=$a(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},ay=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?$a(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?$a(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=Mm(s,km|Lm),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ll=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Rm="4.6.0";var fr=Rm;var ly="https://api.runtype.com/v1/dispatch",za="https://api.runtype.com";function cy(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var cl=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 dy(e){switch(e){case"json":return il;case"regex-json":return al;case"xml":return ll;default:return sl}}var Wm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function py(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=Wm(n);if(!Wm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=sa(e);return sa(t)!==null&&a===null?t:e}var As=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;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=(n=t.apiUrl)!=null?n:ly,this.headers={"Content-Type":"application/json","X-Persona-Version":fr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:dy(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Qs(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=cm(r,o);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){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(c=n.agentId)!=null?c:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.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}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(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 o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let E=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:E}),E}let c=await this.buildPayload(t.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(cl).map(E=>{var k,C,I;return{id:E.id,role:E.role,content:(I=(C=(k=E.contentParts)!=null?k:E.llmContent)!=null?C:E.rawContent)!=null?I:E.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},f=c.clientTools,g=!!(f&&f.length>0),b=g?im(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,S=g&&v&&this.lastSentClientToolsFingerprint===b,T=!1,L=null,P;for(let E=0;;E++){let C={...u,...g&&(T||!S)&&f?{clientTools:f}:{},...b?{clientToolsFingerprint:b}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(C),signal:r.signal}),P.status===409&&E===0&&g){let I=await P.json().catch(()=>null);if((I==null?void 0:I.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}L=I!=null?I:{error:"Chat request failed"}}break}if(!P.ok){let E=L!=null?L:await P.json().catch(()=>({error:"Chat request failed"}));if(P.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(P.status===429){let C=new Error(E.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let k=new Error(E.error||"Failed to send message");throw n({type:"error",error:k}),k}if(!P.body){let E=new Error("No response body received");throw n({type:"error",error:E}),E}this.lastSentClientToolsFingerprint=b!=null?b:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(P.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&n({type:"error",error:c}),c}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var c,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||za}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(cl).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,p)=>{let u=new Date(c.createdAt).getTime(),f=new Date(p.createdAt).getTime();return u-f}).map(c=>{var p,u,f;return{role:c.role,content:(f=(u=(p=c.contentParts)!=null?p:c.llmContent)!=null?u:c.rawContent)!=null?f:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[..._a(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(c,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(cl).sort((d,c)=>{let p=new Date(d.createdAt).getTime(),u=new Date(c.createdAt).getTime();return p-u}).map(d=>{var c,p,u;return{role:d.role,content:(u=(p=(c=d.contentParts)!=null?c:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,c]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=c);let s=[..._a(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async c=>{try{let p=await c({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let c=d;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{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(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},c=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.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!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r,o){var fn,yr,br,Ue;let s=t.getReader(),a=new TextDecoder,i="",d=Date.now(),c=0,p=()=>d+c++,u=M=>{let ue=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,Te=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,ke=M.tools?M.tools.map(He=>({...He,chunks:He.chunks?[...He.chunks]:void 0})):void 0;return{...M,reasoning:ue,toolCall:Te,tools:ke}},f=M=>{if(M.role!=="assistant"||M.variant)return!0;let ue=Array.isArray(M.contentParts)&&M.contentParts.length>0,Te=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||ue||Te||!!M.stopReason},g=M=>{f(M)&&n({type:"message",message:u(M)})},b=null,v=null,S={current:null},T={current:null},L=null,P="",E=new Map,k=new Map,C=new Map,I=new Map,j=new Map,$={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},N=M=>{if(M==null)return null;try{return String(M)}catch{return null}},O=M=>{var ue,Te,ke,He,nt;return N((nt=(He=(ke=(Te=(ue=M.stepId)!=null?ue:M.step_id)!=null?Te:M.step)!=null?ke:M.parentId)!=null?He:M.flowStepId)!=null?nt:M.flow_step_id)},Z=M=>{var ue,Te,ke,He,nt,Qe,ht;return N((ht=(Qe=(nt=(He=(ke=(Te=(ue=M.callId)!=null?ue:M.call_id)!=null?Te:M.requestId)!=null?ke:M.request_id)!=null?He:M.toolCallId)!=null?nt:M.tool_call_id)!=null?Qe:M.stepId)!=null?ht:M.step_id)},Ee=r,de=!1,ee=()=>{if(b)return b;let M,ue="",Te=L;return!de&&Ee?(M=Ee,de=!0,ue=o!=null?o:""):Ee&&Te?M=`${Ee}_${Te}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:M,role:"assistant",content:ue,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},g(b),b},Le=(M,ue)=>{$.lastId=ue,M&&$.byStep.set(M,ue)},Pe=(M,ue)=>{var nt;let Te=(nt=M.reasoningId)!=null?nt:M.id,ke=O(M);if(Te){let Qe=String(Te);return Le(ke,Qe),Qe}if(ke){let Qe=$.byStep.get(ke);if(Qe)return $.lastId=Qe,Qe}if($.lastId&&!ue)return $.lastId;if(!ue)return null;let He=`reason-${p()}`;return Le(ke,He),He},ne=M=>{let ue=I.get(M);if(ue)return ue;let Te={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:M,status:"streaming",chunks:[]}};return I.set(M,Te),g(Te),Te},Ae=(M,ue)=>{R.lastId=ue,M&&R.byCall.set(M,ue)},re=new Set,se=new Map,ae=new Set,fe=new Map,$e=M=>{if(!M)return!1;let ue=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return ue==="emit_artifact_markdown"||ue==="emit_artifact_component"},V=(M,ue)=>{var nt;let Te=(nt=M.toolId)!=null?nt:M.id,ke=Z(M);if(Te){let Qe=String(Te);return Ae(ke,Qe),Qe}if(ke){let Qe=R.byCall.get(ke);if(Qe)return R.lastId=Qe,Qe}if(R.lastId&&!ue)return R.lastId;if(!ue)return null;let He=`tool-${p()}`;return Ae(ke,He),He},Q=M=>{let ue=j.get(M);if(ue)return ue;let Te={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:M,status:"pending"}};return j.set(M,Te),g(Te),Te},Me=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let ue=Number(M);if(!Number.isNaN(ue)&&Number.isFinite(ue))return ue;let Te=Date.parse(M);if(!Number.isNaN(Te))return Te}return Date.now()},J=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},le=new Map,Ie=new Map,he=new Map,Ke=(M,ue,Te)=>{var ht;let ke=he.get(M);ke||(ke=[],he.set(M,ke));let He=0,nt=ke.length;for(;He<nt;){let me=He+nt>>>1;ke[me].seq<ue?He=me+1:nt=me}((ht=ke[He])==null?void 0:ht.seq)===ue?ke[He]={seq:ue,text:Te}:ke.splice(He,0,{seq:ue,text:Te});let Qe="";for(let me=0;me<ke.length;me++)Qe+=ke[me].text;return Qe},gt=(M,ue)=>{let Te=J(ue),ke=Ie.get(M.id),He=py(ke,Te);M.rawContent=He;let nt=le.get(M.id),Qe=ce=>{var Je;let ft=(Je=M.content)!=null?Je:"";ce.trim()!==""&&(ft.trim().length===0||ce.startsWith(ft)||ce.trimStart().startsWith(ft.trim()))&&(M.content=ce)},ht=()=>{var ce;if(nt){let ft=(ce=nt.close)==null?void 0:ce.call(nt);ft instanceof Promise&&ft.catch(()=>{})}le.delete(M.id),Ie.delete(M.id),M.streaming=!1,g(M)};if(!nt){Qe(Te),ht();return}let me=sa(He);if(me!==null&&me.trim()!==""){Qe(me),ht();return}let B=ce=>{var Lt;let ft=typeof ce=="string"?ce:(Lt=ce==null?void 0:ce.text)!=null?Lt:null;if(ft!==null&&ft.trim()!=="")return ft;let Je=nt.getExtractedText();return Je!==null&&Je.trim()!==""?Je:Te},xe;try{xe=nt.processChunk(He)}catch{Qe(Te),ht();return}if(xe instanceof Promise){xe.then(ce=>{Qe(B(ce)),ht()}).catch(()=>{Qe(Te),ht()});return}Qe(B(xe)),ht()},Wt=null,tt=(M,ue,Te,ke)=>{var me;M.rawContent=ue,le.has(M.id)||le.set(M.id,this.createStreamParser());let He=le.get(M.id),nt=ue.trim().startsWith("{")||ue.trim().startsWith("[");if(nt&&Ie.set(M.id,ue),He.__isPlainTextParser===!0){M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M);return}let ht=He.processChunk(ue);if(ht instanceof Promise)ht.then(B=>{var ce;let xe=typeof B=="string"?B:(ce=B==null?void 0:B.text)!=null?ce:null;xe!==null&&xe.trim()!==""?(M.content=xe,g(M)):!nt&&!ue.trim().startsWith("<")&&(M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M))}).catch(()=>{M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M)});else{let B=typeof ht=="string"?ht:(me=ht==null?void 0:ht.text)!=null?me:null;B!==null&&B.trim()!==""?(M.content=B,g(M)):!nt&&!ue.trim().startsWith("<")&&(M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M))}},ge=(M,ue)=>{var me,B;let Te=ue!=null?ue:M.content;if(Te==null||Te===""){M.streaming=!1,g(M);return}let ke=Ie.get(M.id),He=ke!=null?ke:J(Te);M.rawContent=He;let nt=le.get(M.id),Qe=null,ht=!1;if(nt&&(Qe=nt.getExtractedText(),Qe===null&&(Qe=sa(He)),Qe===null)){let xe=nt.processChunk(He);xe instanceof Promise?(ht=!0,xe.then(ce=>{var Je;let ft=typeof ce=="string"?ce:(Je=ce==null?void 0:ce.text)!=null?Je:null;ft!==null&&(M.content=ft,M.streaming=!1,le.delete(M.id),Ie.delete(M.id),g(M))}).catch(()=>{})):Qe=typeof xe=="string"?xe:(me=xe==null?void 0:xe.text)!=null?me:null}if(!ht){Qe!==null&&Qe.trim()!==""?M.content=Qe:Ie.has(M.id)||(M.content=J(Te));let xe=le.get(M.id);if(xe){let ce=(B=xe.close)==null?void 0:B.call(xe);ce instanceof Promise&&ce.catch(()=>{}),le.delete(M.id)}Ie.delete(M.id),M.streaming=!1,g(M)}},X=(M,ue,Te)=>{let ke=k.get(M);if(ke)return ke;let He={id:`nested-${ue}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Te?{variant:Te}:{},...Te==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ue}};return k.set(M,He),g(He),He},it=[],Ve,Se=new Map,we=0,Ze="agent",qt=!1,be=null,pe=null,vn=new Map,Ct=(fn=this.config.iterationDisplay)!=null?fn:"separate";for(Ve=()=>{var M,ue,Te,ke,He,nt,Qe,ht,me,B,xe,ce,ft,Je,Lt,Mt,xt,Rt,Xt,Ot,en,xr,Nr,or,sr,Xr,zt,ar,Or,Hn,kn,Bn,ir,vr,Qr,zn,Yr,At,wr,Cr,Fr,lr,yt,Lo,Ar,Po,Ln,ss,Zr,_r,eo,to,Io,Ro,no,vt,Dn,Nn,wn,St,Vn,Kn,On,ro,Ce,$r,Gn,Ft,Jn,jr,Ds,as,Ns,Wo,Sr,oo,lt,rn,on,Tr,Os,Ur,Ho,Er,F,is,cr,Mr,qr,kr,dr,ls,Ma,hn,Cn,pr,An,Bo,ur,yn,Lr,cs,Do,ds,so;for(let ao=0;ao<it.length;ao++){let ot=it[ao].payloadType,w=it[ao].payload;if(!qt&&Ze!=="flow"&&typeof w.stepType=="string"&&(Ze="flow"),ot==="reasoning_start"){let z=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&q){E.set(z,q),X(z,q,"reasoning");continue}let G=(M=Pe(w,!0))!=null?M:`reason-${p()}`,K=ne(G);K.reasoning=(ue=K.reasoning)!=null?ue:{id:G,status:"streaming",chunks:[]},K.reasoning.startedAt=(ke=K.reasoning.startedAt)!=null?ke:Me((Te=w.startedAt)!=null?Te:w.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(K.reasoning.scope=w.scope),K.streaming=!0,K.reasoning.status="streaming",g(K)}else if(ot==="reasoning_delta"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)&&k.has(z)){let Ne=k.get(z),rt=(Qe=(nt=(He=w.reasoningText)!=null?He:w.text)!=null?nt:w.delta)!=null?Qe:"";rt&&w.hidden!==!0&&Ne.reasoning&&(Ne.reasoning.chunks.push(String(rt)),g(Ne));continue}let q=(me=(ht=Pe(w,!1))!=null?ht:Pe(w,!0))!=null?me:`reason-${p()}`,G=ne(q);G.reasoning=(B=G.reasoning)!=null?B:{id:q,status:"streaming",chunks:[]},G.reasoning.startedAt=(ce=G.reasoning.startedAt)!=null?ce:Me((xe=w.startedAt)!=null?xe:w.timestamp);let K=(Lt=(Je=(ft=w.reasoningText)!=null?ft:w.text)!=null?Je:w.delta)!=null?Lt:"";if(K&&w.hidden!==!0){let Ne=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Ne!==void 0){let rt=Ke(q,Ne,String(K));G.reasoning.chunks=[rt]}else G.reasoning.chunks.push(String(K))}if(G.reasoning.status=w.done?"complete":"streaming",w.done){G.reasoning.completedAt=Me((Mt=w.completedAt)!=null?Mt:w.timestamp);let Ne=(xt=G.reasoning.startedAt)!=null?xt:Date.now();G.reasoning.durationMs=Math.max(0,((Rt=G.reasoning.completedAt)!=null?Rt:Date.now())-Ne)}G.streaming=G.reasoning.status!=="complete",g(G)}else if(ot==="reasoning_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)&&k.has(z)){let rt=k.get(z);if(rt.reasoning){let ct=typeof w.text=="string"?w.text:"";ct&&rt.reasoning.chunks.length===0&&rt.reasoning.chunks.push(ct),rt.reasoning.status="complete",rt.streaming=!1,g(rt)}E.delete(z),k.delete(z);continue}let q=(Ot=(Xt=Pe(w,!1))!=null?Xt:Pe(w,!0))!=null?Ot:`reason-${p()}`,G=typeof w.text=="string"?w.text:"";!I.get(q)&&(G||w.scope==="loop")&&ne(q);let K=I.get(q);if(K!=null&&K.reasoning){(w.scope==="loop"||w.scope==="turn")&&(K.reasoning.scope=w.scope),G&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(G),K.reasoning.status="complete",K.reasoning.completedAt=Me((en=w.completedAt)!=null?en:w.timestamp);let rt=(xr=K.reasoning.startedAt)!=null?xr:Date.now();K.reasoning.durationMs=Math.max(0,((Nr=K.reasoning.completedAt)!=null?Nr:Date.now())-rt),K.streaming=!1,g(K)}let Ne=O(w);Ne&&$.byStep.delete(Ne)}else if(ot==="tool_start"){b&&(b.streaming=!1,g(b),b=null),typeof w.iteration=="number"&&(we=w.iteration);let z=(sr=(or=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?or:V(w,!0))!=null?sr:`tool-${p()}`,q=(Xr=w.toolName)!=null?Xr:w.name;if($e(q)){re.add(z);continue}Ae(Z(w),z);let G=Q(z),K=(zt=G.toolCall)!=null?zt:{id:z,status:"pending"};K.name=q!=null?q:K.name,K.status="running",w.parameters!==void 0?K.args=w.parameters:w.args!==void 0&&(K.args=w.args),K.startedAt=(Or=K.startedAt)!=null?Or:Me((ar=w.startedAt)!=null?ar:w.timestamp),K.completedAt=void 0,K.durationMs=void 0,G.toolCall=K,G.streaming=!0,w.executionId&&(G.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(G)}else if(ot==="tool_output_delta"){let z=(kn=(Hn=V(w,!1))!=null?Hn:V(w,!0))!=null?kn:`tool-${p()}`;if(re.has(z))continue;let q=Q(z),G=(Bn=q.toolCall)!=null?Bn:{id:z,status:"running"};G.startedAt=(vr=G.startedAt)!=null?vr:Me((ir=w.startedAt)!=null?ir:w.timestamp);let K=(Yr=(zn=(Qr=w.text)!=null?Qr:w.delta)!=null?zn:w.message)!=null?Yr:"";K&&(G.chunks=(At=G.chunks)!=null?At:[],G.chunks.push(String(K))),G.status="running",q.toolCall=G,q.streaming=!0;let Ne=w.agentContext;(Ne||w.executionId)&&(q.agentMetadata=(Fr=q.agentMetadata)!=null?Fr:{executionId:(wr=Ne==null?void 0:Ne.executionId)!=null?wr:w.executionId,iteration:(Cr=Ne==null?void 0:Ne.iteration)!=null?Cr:w.iteration}),g(q)}else if(ot==="tool_complete"){let z=(yt=(lr=V(w,!1))!=null?lr:V(w,!0))!=null?yt:`tool-${p()}`;if(re.has(z)){re.delete(z);continue}let q=Q(z),G=(Lo=q.toolCall)!=null?Lo:{id:z,status:"running"};G.status="complete",w.result!==void 0&&(G.result=w.result),typeof w.duration=="number"&&(G.duration=w.duration),G.completedAt=Me((Ar=w.completedAt)!=null?Ar:w.timestamp);let K=(Po=w.duration)!=null?Po:w.executionTime;if(typeof K=="number")G.durationMs=K;else{let ct=(Ln=G.startedAt)!=null?Ln:Date.now();G.durationMs=Math.max(0,((ss=G.completedAt)!=null?ss:Date.now())-ct)}q.toolCall=G,q.streaming=!1;let Ne=w.agentContext;(Ne||w.executionId)&&(q.agentMetadata=(eo=q.agentMetadata)!=null?eo:{executionId:(Zr=Ne==null?void 0:Ne.executionId)!=null?Zr:w.executionId,iteration:(_r=Ne==null?void 0:Ne.iteration)!=null?_r:w.iteration}),g(q);let rt=Z(w);rt&&R.byCall.delete(rt)}else if(ot==="await"&&w.toolName){let z=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,q=(to=z!=null?z:w.toolId)!=null?to:`local-${p()}`,G=Q(q),K=w.toolName,Ne=w.origin==="webmcp"&&!Ko(K)?`webmcp:${K}`:K,rt=Ko(Ne),ct=(Io=G.toolCall)!=null?Io:{id:q,status:"pending"};ct.name=Ne,ct.args=w.parameters,ct.status=rt?"running":"complete",ct.chunks=(Ro=ct.chunks)!=null?Ro:[],ct.startedAt=(Dn=ct.startedAt)!=null?Dn:Me((vt=(no=w.startedAt)!=null?no:w.timestamp)!=null?vt:w.awaitedAt),rt?(ct.completedAt=void 0,ct.duration=void 0,ct.durationMs=void 0):ct.completedAt=(Nn=ct.completedAt)!=null?Nn:ct.startedAt,G.toolCall=ct,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(St=w.executionId)!=null?St:(wn=G.agentMetadata)==null?void 0:wn.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},g(G)}else if(ot==="text_start"){let z=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&q){E.set(z,q);continue}let G=b;G&&(Ze==="flow"?(ge(G),Wt=G):(G.streaming=!1,g(G)),b=null),L=typeof w.id=="string"?w.id:L,P=""}else if(ot==="text_delta"){let z=typeof w.id=="string"?w.id:null,q=z?E.get(z):void 0;if(z&&q){let K=typeof w.delta=="string"?w.delta:"",Ne=((Vn=C.get(z))!=null?Vn:"")+K;if(C.set(z,Ne),Ne.trim()==="")continue;let rt=X(z,q);rt.agentMetadata={...rt.agentMetadata,executionId:w.executionId,parentToolId:q},tt(rt,Ne,K,void 0);continue}if(L=typeof w.id=="string"?w.id:L,Ze==="flow"){let K=typeof w.delta=="string"?w.delta:"";if(P+=K,P.trim()==="")continue;let Ne=ee();Ne.agentMetadata={executionId:w.executionId,iteration:w.iteration},tt(Ne,P,K,void 0),v=Ne;continue}let G=ee();G.content+=(Kn=w.delta)!=null?Kn:"",G.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:be!=null?be:void 0,agentName:pe==null?void 0:pe.agentName},v=G,g(G)}else if(ot==="text_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)){let G=k.get(z);G&&ge(G),E.delete(z),C.delete(z),k.delete(z);continue}let q=b;q&&(Ze==="flow"?(ge(q),Wt=q):(((On=q.content)!=null?On:"")===""&&typeof w.text=="string"&&(q.content=w.text),q.streaming=!1,g(q)),b=null),L=null,P=""}else if(ot==="step_complete"){let z=w.stepType,q=w.executionType;if(z==="tool"||q==="context")continue;if(w.success===!1){let G=w.error,K=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&"message"in G?String((ro=G.message)!=null?ro:"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let Ne=b;Ne&&Ne.streaming&&(Ne.streaming=!1,g(Ne)),n({type:"status",status:"idle"});continue}{let G=Wt;Wt=null;let K=w.stopReason,Ne=(Ce=w.result)==null?void 0:Ce.response;if(G)K&&(G.stopReason=K),Ne!=null?gt(G,Ne):G.streaming!==!1&&(le.delete(G.id),Ie.delete(G.id),G.streaming=!1,g(G));else{let rt=Ne!=null&&Ne!=="";if(rt||K){let ct=ee();K&&(ct.stopReason=K),rt?ge(ct,Ne):(ct.streaming=!1,g(ct))}}continue}}else if(ot==="execution_start")Ze=w.kind==="flow"?"flow":"agent",qt=!0,Ze==="agent"&&(pe={executionId:w.executionId,agentId:($r=w.agentId)!=null?$r:"virtual",agentName:(Gn=w.agentName)!=null?Gn:"",status:"running",currentIteration:0,maxTurns:(Ft=w.maxTurns)!=null?Ft:1,startedAt:Me(w.startedAt)});else if(ot==="turn_start"){let z=typeof w.iteration=="number"?w.iteration:we;if(z!==we){if(pe&&(pe.currentIteration=z),Ct==="separate"&&z>1){let q=b;q&&(q.streaming=!1,g(q),vn.set(z-1,q),b=null)}we=z}be=typeof w.id=="string"?w.id:null,v=null}else if(ot==="tool_input_delta"){let z=(Jn=w.toolCallId)!=null?Jn:R.lastId;if(z){let q=j.get(z);q!=null&&q.toolCall&&(q.toolCall.chunks=(jr=q.toolCall.chunks)!=null?jr:[],q.toolCall.chunks.push((Ds=w.delta)!=null?Ds:""),g(q))}}else{if(ot==="tool_input_complete")continue;if(ot==="turn_complete"){let z=w.stopReason,q=b!=null?b:v;if(z&&q!==null){let G=w.id;(!G||((as=q.agentMetadata)==null?void 0:as.turnId)===G)&&(q.stopReason=z,g(q))}be===w.id&&(be=null)}else if(ot==="media_start"){let z=String(w.id);Se.set(z,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(ot==="media_delta"){let z=Se.get(String(w.id));z&&typeof w.delta=="string"&&z.parts.push(w.delta)}else if(ot==="media_complete"){let z=String(w.id),q=Se.get(z);Se.delete(z);let G=(Wo=(Ns=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Ns:q==null?void 0:q.mediaType)!=null?Wo:"application/octet-stream",K=typeof w.data=="string"?w.data:void 0,Ne=typeof w.url=="string"?w.url:q&&q.parts.length>0?q.parts.join(""):void 0,rt=null;if(K)rt={type:"media",data:K,mediaType:G};else if(Ne){let Pn=G.toLowerCase();rt={type:Pn==="image"||Pn.startsWith("image/")?"image-url":"file-url",url:Ne,mediaType:G}}let ct=(Sr=w.toolCallId)!=null?Sr:q==null?void 0:q.toolCallId,Di=rt?[rt]:[],io=[];for(let Pn of Di){if(!Pn||typeof Pn!="object")continue;let Qt=Pn,lo=typeof Qt.type=="string"?Qt.type:void 0,Xn=typeof Qt.mediaType=="string"?Qt.mediaType.toLowerCase():"",Sn=null,In="";if(lo==="media"){let Tn=typeof Qt.data=="string"?Qt.data:void 0;if(!Tn)continue;In=Xn.length>0?Xn:"application/octet-stream",Sn=`data:${In};base64,${Tn}`}else if(lo==="image-url"){let Tn=typeof Qt.url=="string"?Qt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else if(lo==="file-url"){let Tn=typeof Qt.url=="string"?Qt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else continue;if(Sn)if(lo==="image-url"||In.startsWith("image/"))io.push({type:"image",image:Sn,...In.includes("/")?{mimeType:In}:{}});else if(In.startsWith("audio/"))io.push({type:"audio",audio:Sn,mimeType:In});else if(In.startsWith("video/"))io.push({type:"video",video:Sn,mimeType:In});else{let Tn=In||"application/octet-stream";io.push({type:"file",data:Sn,mimeType:Tn,filename:cy(Tn)})}}if(io.length>0){let Pn=p(),Qt=ct,Xn={id:`agent-media-${typeof Qt=="string"&&Qt.length>0?`${Qt}-${Pn}`:String(Pn)}`,role:"assistant",content:"",contentParts:io,createdAt:new Date().toISOString(),streaming:!1,sequence:Pn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:we}};g(Xn);let Sn=b;Sn&&(Sn.streaming=!1,g(Sn)),b=null,S.current=null}}else if(ot==="execution_complete"){let z=(oo=w.kind)!=null?oo:Ze;z==="agent"&&pe&&(pe.status=w.success?"complete":"error",pe.completedAt=Me(w.completedAt),pe.stopReason=w.stopReason);let q=b;q&&(z==="flow"&&q.streaming!==!1?ge(q):(q.streaming=!1,g(q)),b=null),L=null,P="",Wt=null,n({type:"status",status:"idle",terminal:!0})}else if(ot==="execution_error"){let z=typeof w.error=="string"?w.error:(rn=(lt=w.error)==null?void 0:lt.message)!=null?rn:"Execution error";n({type:"error",error:new Error(z)})}else if(ot!=="ping"){if(ot==="approval_start"){let z=(on=w.approvalId)!=null?on:`approval-${p()}`,q={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:"pending",agentId:(Tr=pe==null?void 0:pe.agentId)!=null?Tr:"virtual",executionId:(Ur=(Os=w.executionId)!=null?Os:pe==null?void 0:pe.executionId)!=null?Ur:"",toolName:(Ho=w.toolName)!=null?Ho:"",toolType:w.toolType,description:(F=w.description)!=null?F:`Execute ${(Er=w.toolName)!=null?Er:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(ot==="step_await"&&w.awaitReason==="approval_required"){let z=(is=w.approvalId)!=null?is:`approval-${p()}`,q={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:"pending",agentId:(cr=pe==null?void 0:pe.agentId)!=null?cr:"virtual",executionId:(qr=(Mr=w.executionId)!=null?Mr:pe==null?void 0:pe.executionId)!=null?qr:"",toolName:(kr=w.toolName)!=null?kr:"",toolType:w.toolType,description:(ls=w.description)!=null?ls:`Execute ${(dr=w.toolName)!=null?dr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(ot==="approval_complete"){let z=w.approvalId;if(z){let G={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:(Ma=w.decision)!=null?Ma:"approved",agentId:(hn=pe==null?void 0:pe.agentId)!=null?hn:"virtual",executionId:(pr=(Cn=w.executionId)!=null?Cn:pe==null?void 0:pe.executionId)!=null?pr:"",toolName:(An=w.toolName)!=null?An:"",description:(Bo=w.description)!=null?Bo:"",resolvedAt:Date.now()}};g(G)}}else if(ot==="artifact_start"||ot==="artifact_delta"||ot==="artifact_update"||ot==="artifact_complete"){if(ot==="artifact_start"){let z=w.artifactType,q=String(w.id),G=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:q,artifactType:z,title:G,component:typeof w.component=="string"?w.component:void 0}),fe.set(q,{markdown:"",title:G}),!ae.has(q)){ae.add(q);let K={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:G,artifactType:z,status:"streaming"}})};se.set(q,K),g(K)}}else if(ot==="artifact_delta"){let z=String(w.id),q=typeof w.delta=="string"?w.delta:String((ur=w.delta)!=null?ur:"");n({type:"artifact_delta",id:z,artDelta:q});let G=fe.get(z);G&&(G.markdown+=q)}else if(ot==="artifact_update"){let z=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:z,component:typeof w.component=="string"?w.component:void 0})}else if(ot==="artifact_complete"){let z=String(w.id);n({type:"artifact_complete",id:z});let q=se.get(z);if(q){q.streaming=!1;try{let G=JSON.parse((yn=q.rawContent)!=null?yn:"{}");if(G.props){G.props.status="complete";let K=fe.get(z);K!=null&&K.markdown&&(G.props.markdown=K.markdown)}q.rawContent=JSON.stringify(G)}catch{}fe.delete(z),g(q),se.delete(z)}}}else if(ot==="transcript_insert"){let z=w.message;if(!z||typeof z!="object")continue;let q=String((Lr=z.id)!=null?Lr:`msg-${p()}`),G=z.role,Ne={id:q,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:p()};if(g(Ne),Ne.rawContent)try{let rt=JSON.parse(Ne.rawContent),ct=(cs=rt==null?void 0:rt.props)==null?void 0:cs.artifactId;typeof ct=="string"&&ae.add(ct)}catch{}b=null,S.current=null,le.delete(q),Ie.delete(q)}else if(ot==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let z=typeof w.error=="string"?w.error:((Do=w.error)==null?void 0:Do.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(z)});let q=b;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}else if(ot==="step_error"||ot==="dispatch_error"||ot==="flow_error"){let z=null;if(w.error instanceof Error)z=w.error;else if(ot==="dispatch_error"){let q=(ds=w.message)!=null?ds:w.error;q!=null&&q!==""&&(z=new Error(String(q)))}else{let q=w.error;typeof q=="string"&&q!==""?z=new Error(q):q!=null&&typeof q=="object"&&"message"in q&&(z=new Error(String((so=q.message)!=null?so:q)))}if(z){n({type:"error",error:z});let q=b;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}}}}it.length=0};;){let{done:M,value:ue}=await s.read();if(M)break;i+=a.decode(ue,{stream:!0});let Te=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 r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},ca=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=()=>{var t;let e=vy();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},hl=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=Fm(n,_m|$m);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?za(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=za(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},wy=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?za(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?za(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=Fm(s,_m|$m),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},yl=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var qm="4.7.0";var gr=qm;var Ay="https://api.runtype.com/v1/dispatch",Ja="https://api.runtype.com";function Sy(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var bl=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 Ty(e){switch(e){case"json":return hl;case"regex-json":return fl;case"xml":return yl;default:return gl}}var zm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Ey(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=zm(n);if(!zm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=ca(e);return ca(t)!==null&&a===null?t:e}var Es=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;this.sentNonEmptyClientToolsSessionId=null;var n,r,o,s;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=(n=t.apiUrl)!=null?n:Ay,this.headers={"Content-Type":"application/json","X-Persona-Version":gr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Ty(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new ea(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=wm(r,o);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){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ja}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(c=n.agentId)!=null?c:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":gr},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.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(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ja}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(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 o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":gr},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){var r;return(r=t.signal)==null||r.throwIfAborted(),this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var r,o,s,a;n({type:"status",status:"connecting"});try{let i=await this.initSession();if(new Date>=new Date(i.expiresAt.getTime()-6e4)){this.clearClientSession(),(o=(r=this.config).onSessionExpired)==null||o.call(r);let g=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:g}),g}let d=await this.buildPayload(t.messages),c=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([g])=>g!=="sessionId"&&g!=="session_id")):void 0,p={sessionId:i.sessionId,messages:t.messages.filter(bl).map(g=>{var y,v,A;return{id:g.id,role:g.role,content:(A=(v=(y=g.contentParts)!=null?y:g.llmContent)!=null?v:g.rawContent)!=null?A:g.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...c&&Object.keys(c).length>0&&{metadata:c},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context}},{response:u,commit:f}=await this.sendWithClientToolsDiff(i.sessionId,d.clientTools,g=>{let y={...p,...g};return this.debug&&console.debug("[AgentWidgetClient] client token dispatch",y),fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":gr},body:JSON.stringify(y),signal:t.signal})});if(!u.ok){let g=await u.json().catch(()=>({error:"Chat request failed"}));if(u.status===401){this.clearClientSession(),(a=(s=this.config).onSessionExpired)==null||a.call(s);let v=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:v}),v}if(u.status===429){let v=new Error(g.hint||"Message limit reached for this session.");throw n({type:"error",error:v}),v}let y=new Error(g.error||"Failed to send message");throw n({type:"error",error:y}),y}if(!u.body){let g=new Error("No response body received");throw n({type:"error",error:g}),g}f(),n({type:"status",status:"connected"});try{await this.streamResponse(u.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(i){let d=i instanceof Error?i:new Error(String(i));throw!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&n({type:"error",error:d}),d}}async dispatchProxy(t,n){n({type:"status",status:"connecting"});let r=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let o={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();o={...o,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:t.signal},r)}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:o,body:JSON.stringify(r),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 r=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",r);let o={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();o={...o,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(r),signal:t.signal},r)}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:o,body:JSON.stringify(r),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,r,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ja}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async sendWithClientToolsDiff(t,n,r,o){let s=!!(n&&n.length>0),a=s?xm(n):void 0,i=this.clientToolsFingerprintSessionId===t,d=s&&i&&this.lastSentClientToolsFingerprint===a,c=!s&&(o==null?void 0:o.emptyMeansReplace)===!0&&this.sentNonEmptyClientToolsSessionId===t,p=!1,u;for(let f=0;;f++){if(u=await r({...s&&(p||!d)&&n?{clientTools:n}:{},...c?{clientTools:[]}:{},...a?{clientToolsFingerprint:a}:{}}),u.status===409&&f===0&&s){let y=await u.clone().json().catch(()=>null);if((y==null?void 0:y.error)==="client_tools_resend_required"){p=!0,this.lastSentClientToolsFingerprint=null;continue}}break}return{response:u,commit:()=>{this.lastSentClientToolsFingerprint=a!=null?a:null,this.clientToolsFingerprintSessionId=t,s?this.sentNonEmptyClientToolsSessionId=t:c&&(this.sentNonEmptyClientToolsSessionId=null)}}}async resumeFlow(t,n,r){var c,p,u,f;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Ja}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};if(a&&(d.sessionId=a),o&&a){let g=[...aa(this.config),...(f=await((u=this.webMcpBridge)==null?void 0:u.snapshotForDispatch()))!=null?f:[]],{response:y,commit:v}=await this.sendWithClientToolsDiff(a,g,A=>{let T={...d,...A};return this.debug&&console.debug("[AgentWidgetClient] client token resume",T),fetch(s,{method:"POST",headers:i,body:JSON.stringify(T),signal:r==null?void 0:r.signal})},{emptyMeansReplace:!0});return y.ok&&v(),y}return fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(bl).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,p)=>{let u=new Date(c.createdAt).getTime(),f=new Date(p.createdAt).getTime();return u-f}).map(c=>{var p,u,f;return{role:c.role,content:(f=(u=(p=c.contentParts)!=null?p:c.llmContent)!=null?u:c.rawContent)!=null?f:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...aa(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(c,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(bl).sort((d,c)=>{let p=new Date(d.createdAt).getTime(),u=new Date(c.createdAt).getTime();return p-u}).map(d=>{var c,p,u;return{role:d.role,content:(u=(p=(c=d.contentParts)!=null?c:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,c]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=c);let s=[...aa(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async c=>{try{let p=await c({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let c=d;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{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(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},c=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.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!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r,o){var yn,hr,yr,Ue;let s=t.getReader(),a=new TextDecoder,i="",d=Date.now(),c=0,p=()=>d+c++,u=E=>{let ue=E.reasoning?{...E.reasoning,chunks:[...E.reasoning.chunks]}:void 0,Te=E.toolCall?{...E.toolCall,chunks:E.toolCall.chunks?[...E.toolCall.chunks]:void 0}:void 0,ke=E.tools?E.tools.map(He=>({...He,chunks:He.chunks?[...He.chunks]:void 0})):void 0;return{...E,reasoning:ue,toolCall:Te,tools:ke}},f=E=>{if(E.role!=="assistant"||E.variant)return!0;let ue=Array.isArray(E.contentParts)&&E.contentParts.length>0,Te=typeof E.rawContent=="string"&&E.rawContent.trim()!=="";return typeof E.content=="string"&&E.content.trim()!==""||ue||Te||!!E.stopReason},g=E=>{f(E)&&n({type:"message",message:u(E)})},y=null,v=null,A={current:null},T={current:null},L=null,W="",R=new Map,P=new Map,S=new Map,H=new Map,U=new Map,j={lastId:null,byStep:new Map},k={lastId:null,byCall:new Map},O=E=>{if(E==null)return null;try{return String(E)}catch{return null}},F=E=>{var ue,Te,ke,He,nt;return O((nt=(He=(ke=(Te=(ue=E.stepId)!=null?ue:E.step_id)!=null?Te:E.step)!=null?ke:E.parentId)!=null?He:E.flowStepId)!=null?nt:E.flow_step_id)},Z=E=>{var ue,Te,ke,He,nt,Qe,ht;return O((ht=(Qe=(nt=(He=(ke=(Te=(ue=E.callId)!=null?ue:E.call_id)!=null?Te:E.requestId)!=null?ke:E.request_id)!=null?He:E.toolCallId)!=null?nt:E.tool_call_id)!=null?Qe:E.stepId)!=null?ht:E.step_id)},Ee=r,de=!1,ee=()=>{if(y)return y;let E,ue="",Te=L;return!de&&Ee?(E=Ee,de=!0,ue=o!=null?o:""):Ee&&Te?E=`${Ee}_${Te}`:E=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:E,role:"assistant",content:ue,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},g(y),y},Le=(E,ue)=>{j.lastId=ue,E&&j.byStep.set(E,ue)},Pe=(E,ue)=>{var nt;let Te=(nt=E.reasoningId)!=null?nt:E.id,ke=F(E);if(Te){let Qe=String(Te);return Le(ke,Qe),Qe}if(ke){let Qe=j.byStep.get(ke);if(Qe)return j.lastId=Qe,Qe}if(j.lastId&&!ue)return j.lastId;if(!ue)return null;let He=`reason-${p()}`;return Le(ke,He),He},ne=E=>{let ue=H.get(E);if(ue)return ue;let Te={id:`reason-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:E,status:"streaming",chunks:[]}};return H.set(E,Te),g(Te),Te},Ae=(E,ue)=>{k.lastId=ue,E&&k.byCall.set(E,ue)},re=new Set,se=new Map,ae=new Set,fe=new Map,$e=E=>{if(!E)return!1;let ue=E.replace(/_+/g,"_").replace(/^_|_$/g,"");return ue==="emit_artifact_markdown"||ue==="emit_artifact_component"},V=(E,ue)=>{var nt;let Te=(nt=E.toolId)!=null?nt:E.id,ke=Z(E);if(Te){let Qe=String(Te);return Ae(ke,Qe),Qe}if(ke){let Qe=k.byCall.get(ke);if(Qe)return k.lastId=Qe,Qe}if(k.lastId&&!ue)return k.lastId;if(!ue)return null;let He=`tool-${p()}`;return Ae(ke,He),He},Q=E=>{let ue=U.get(E);if(ue)return ue;let Te={id:`tool-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:E,status:"pending"}};return U.set(E,Te),g(Te),Te},Me=E=>{if(typeof E=="number"&&Number.isFinite(E))return E;if(typeof E=="string"){let ue=Number(E);if(!Number.isNaN(ue)&&Number.isFinite(ue))return ue;let Te=Date.parse(E);if(!Number.isNaN(Te))return Te}return Date.now()},J=E=>{if(typeof E=="string")return E;if(E==null)return"";try{return JSON.stringify(E)}catch{return String(E)}},le=new Map,Ie=new Map,he=new Map,Ke=(E,ue,Te)=>{var ht;let ke=he.get(E);ke||(ke=[],he.set(E,ke));let He=0,nt=ke.length;for(;He<nt;){let me=He+nt>>>1;ke[me].seq<ue?He=me+1:nt=me}((ht=ke[He])==null?void 0:ht.seq)===ue?ke[He]={seq:ue,text:Te}:ke.splice(He,0,{seq:ue,text:Te});let Qe="";for(let me=0;me<ke.length;me++)Qe+=ke[me].text;return Qe},gt=(E,ue)=>{let Te=J(ue),ke=Ie.get(E.id),He=Ey(ke,Te);E.rawContent=He;let nt=le.get(E.id),Qe=ce=>{var Je;let ft=(Je=E.content)!=null?Je:"";ce.trim()!==""&&(ft.trim().length===0||ce.startsWith(ft)||ce.trimStart().startsWith(ft.trim()))&&(E.content=ce)},ht=()=>{var ce;if(nt){let ft=(ce=nt.close)==null?void 0:ce.call(nt);ft instanceof Promise&&ft.catch(()=>{})}le.delete(E.id),Ie.delete(E.id),E.streaming=!1,g(E)};if(!nt){Qe(Te),ht();return}let me=ca(He);if(me!==null&&me.trim()!==""){Qe(me),ht();return}let B=ce=>{var Lt;let ft=typeof ce=="string"?ce:(Lt=ce==null?void 0:ce.text)!=null?Lt:null;if(ft!==null&&ft.trim()!=="")return ft;let Je=nt.getExtractedText();return Je!==null&&Je.trim()!==""?Je:Te},xe;try{xe=nt.processChunk(He)}catch{Qe(Te),ht();return}if(xe instanceof Promise){xe.then(ce=>{Qe(B(ce)),ht()}).catch(()=>{Qe(Te),ht()});return}Qe(B(xe)),ht()},Wt=null,tt=(E,ue,Te,ke)=>{var me;E.rawContent=ue,le.has(E.id)||le.set(E.id,this.createStreamParser());let He=le.get(E.id),nt=ue.trim().startsWith("{")||ue.trim().startsWith("[");if(nt&&Ie.set(E.id,ue),He.__isPlainTextParser===!0){E.content=ke!==void 0?ue:E.content+Te,Ie.delete(E.id),le.delete(E.id),E.rawContent=void 0,g(E);return}let ht=He.processChunk(ue);if(ht instanceof Promise)ht.then(B=>{var ce;let xe=typeof B=="string"?B:(ce=B==null?void 0:B.text)!=null?ce:null;xe!==null&&xe.trim()!==""?(E.content=xe,g(E)):!nt&&!ue.trim().startsWith("<")&&(E.content=ke!==void 0?ue:E.content+Te,Ie.delete(E.id),le.delete(E.id),E.rawContent=void 0,g(E))}).catch(()=>{E.content=ke!==void 0?ue:E.content+Te,Ie.delete(E.id),le.delete(E.id),E.rawContent=void 0,g(E)});else{let B=typeof ht=="string"?ht:(me=ht==null?void 0:ht.text)!=null?me:null;B!==null&&B.trim()!==""?(E.content=B,g(E)):!nt&&!ue.trim().startsWith("<")&&(E.content=ke!==void 0?ue:E.content+Te,Ie.delete(E.id),le.delete(E.id),E.rawContent=void 0,g(E))}},ge=(E,ue)=>{var me,B;let Te=ue!=null?ue:E.content;if(Te==null||Te===""){E.streaming=!1,g(E);return}let ke=Ie.get(E.id),He=ke!=null?ke:J(Te);E.rawContent=He;let nt=le.get(E.id),Qe=null,ht=!1;if(nt&&(Qe=nt.getExtractedText(),Qe===null&&(Qe=ca(He)),Qe===null)){let xe=nt.processChunk(He);xe instanceof Promise?(ht=!0,xe.then(ce=>{var Je;let ft=typeof ce=="string"?ce:(Je=ce==null?void 0:ce.text)!=null?Je:null;ft!==null&&(E.content=ft,E.streaming=!1,le.delete(E.id),Ie.delete(E.id),g(E))}).catch(()=>{})):Qe=typeof xe=="string"?xe:(me=xe==null?void 0:xe.text)!=null?me:null}if(!ht){Qe!==null&&Qe.trim()!==""?E.content=Qe:Ie.has(E.id)||(E.content=J(Te));let xe=le.get(E.id);if(xe){let ce=(B=xe.close)==null?void 0:B.call(xe);ce instanceof Promise&&ce.catch(()=>{}),le.delete(E.id)}Ie.delete(E.id),E.streaming=!1,g(E)}},X=(E,ue,Te)=>{let ke=P.get(E);if(ke)return ke;let He={id:`nested-${ue}-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Te?{variant:Te}:{},...Te==="reasoning"?{reasoning:{id:E,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ue}};return P.set(E,He),g(He),He},it=[],Ve,Se=new Map,we=0,Ze="agent",qt=!1,be=null,pe=null,Cn=new Map,Ct=(yn=this.config.iterationDisplay)!=null?yn:"separate";for(Ve=()=>{var E,ue,Te,ke,He,nt,Qe,ht,me,B,xe,ce,ft,Je,Lt,Mt,xt,Rt,Xt,Ot,Zt,br,Nr,or,sr,Zr,zt,ar,Or,Hn,Pn,Bn,ir,xr,eo,zn,to,At,vr,wr,Fr,lr,yt,Io,Cr,Ro,In,is,no,_r,ro,oo,Wo,Ho,so,vt,Dn,Nn,An,St,Vn,Kn,On,ao,Ce,$r,Gn,Ft,Jn,jr,Fs,ls,_s,Bo,Ar,io,lt,nn,rn,Sr,$s,Ur,Do,Tr,_,cs,Xn,Er,qr,Mr,cr,ds,Ia,bn,Sn,dr,Tn,No,pr,xn,kr,ps,Oo,us,lo;for(let co=0;co<it.length;co++){let ot=it[co].payloadType,w=it[co].payload;if(!qt&&Ze!=="flow"&&typeof w.stepType=="string"&&(Ze="flow"),ot==="reasoning_start"){let z=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&q){R.set(z,q),X(z,q,"reasoning");continue}let G=(E=Pe(w,!0))!=null?E:`reason-${p()}`,K=ne(G);K.reasoning=(ue=K.reasoning)!=null?ue:{id:G,status:"streaming",chunks:[]},K.reasoning.startedAt=(ke=K.reasoning.startedAt)!=null?ke:Me((Te=w.startedAt)!=null?Te:w.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(K.reasoning.scope=w.scope),K.streaming=!0,K.reasoning.status="streaming",g(K)}else if(ot==="reasoning_delta"){let z=typeof w.id=="string"?w.id:null;if(z&&R.has(z)&&P.has(z)){let Ne=P.get(z),rt=(Qe=(nt=(He=w.reasoningText)!=null?He:w.text)!=null?nt:w.delta)!=null?Qe:"";rt&&w.hidden!==!0&&Ne.reasoning&&(Ne.reasoning.chunks.push(String(rt)),g(Ne));continue}let q=(me=(ht=Pe(w,!1))!=null?ht:Pe(w,!0))!=null?me:`reason-${p()}`,G=ne(q);G.reasoning=(B=G.reasoning)!=null?B:{id:q,status:"streaming",chunks:[]},G.reasoning.startedAt=(ce=G.reasoning.startedAt)!=null?ce:Me((xe=w.startedAt)!=null?xe:w.timestamp);let K=(Lt=(Je=(ft=w.reasoningText)!=null?ft:w.text)!=null?Je:w.delta)!=null?Lt:"";if(K&&w.hidden!==!0){let Ne=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Ne!==void 0){let rt=Ke(q,Ne,String(K));G.reasoning.chunks=[rt]}else G.reasoning.chunks.push(String(K))}if(G.reasoning.status=w.done?"complete":"streaming",w.done){G.reasoning.completedAt=Me((Mt=w.completedAt)!=null?Mt:w.timestamp);let Ne=(xt=G.reasoning.startedAt)!=null?xt:Date.now();G.reasoning.durationMs=Math.max(0,((Rt=G.reasoning.completedAt)!=null?Rt:Date.now())-Ne)}G.streaming=G.reasoning.status!=="complete",g(G)}else if(ot==="reasoning_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&R.has(z)&&P.has(z)){let rt=P.get(z);if(rt.reasoning){let ct=typeof w.text=="string"?w.text:"";ct&&rt.reasoning.chunks.length===0&&rt.reasoning.chunks.push(ct),rt.reasoning.status="complete",rt.streaming=!1,g(rt)}R.delete(z),P.delete(z);continue}let q=(Ot=(Xt=Pe(w,!1))!=null?Xt:Pe(w,!0))!=null?Ot:`reason-${p()}`,G=typeof w.text=="string"?w.text:"";!H.get(q)&&(G||w.scope==="loop")&&ne(q);let K=H.get(q);if(K!=null&&K.reasoning){(w.scope==="loop"||w.scope==="turn")&&(K.reasoning.scope=w.scope),G&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(G),K.reasoning.status="complete",K.reasoning.completedAt=Me((Zt=w.completedAt)!=null?Zt:w.timestamp);let rt=(br=K.reasoning.startedAt)!=null?br:Date.now();K.reasoning.durationMs=Math.max(0,((Nr=K.reasoning.completedAt)!=null?Nr:Date.now())-rt),K.streaming=!1,g(K)}let Ne=F(w);Ne&&j.byStep.delete(Ne)}else if(ot==="tool_start"){y&&(y.streaming=!1,g(y),y=null),typeof w.iteration=="number"&&(we=w.iteration);let z=(sr=(or=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?or:V(w,!0))!=null?sr:`tool-${p()}`,q=(Zr=w.toolName)!=null?Zr:w.name;if($e(q)){re.add(z);continue}Ae(Z(w),z);let G=Q(z),K=(zt=G.toolCall)!=null?zt:{id:z,status:"pending"};K.name=q!=null?q:K.name,K.status="running",w.parameters!==void 0?K.args=w.parameters:w.args!==void 0&&(K.args=w.args),K.startedAt=(Or=K.startedAt)!=null?Or:Me((ar=w.startedAt)!=null?ar:w.timestamp),K.completedAt=void 0,K.durationMs=void 0,G.toolCall=K,G.streaming=!0,w.executionId&&(G.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(G)}else if(ot==="tool_output_delta"){let z=(Pn=(Hn=V(w,!1))!=null?Hn:V(w,!0))!=null?Pn:`tool-${p()}`;if(re.has(z))continue;let q=Q(z),G=(Bn=q.toolCall)!=null?Bn:{id:z,status:"running"};G.startedAt=(xr=G.startedAt)!=null?xr:Me((ir=w.startedAt)!=null?ir:w.timestamp);let K=(to=(zn=(eo=w.text)!=null?eo:w.delta)!=null?zn:w.message)!=null?to:"";K&&(G.chunks=(At=G.chunks)!=null?At:[],G.chunks.push(String(K))),G.status="running",q.toolCall=G,q.streaming=!0;let Ne=w.agentContext;(Ne||w.executionId)&&(q.agentMetadata=(Fr=q.agentMetadata)!=null?Fr:{executionId:(vr=Ne==null?void 0:Ne.executionId)!=null?vr:w.executionId,iteration:(wr=Ne==null?void 0:Ne.iteration)!=null?wr:w.iteration}),g(q)}else if(ot==="tool_complete"){let z=(yt=(lr=V(w,!1))!=null?lr:V(w,!0))!=null?yt:`tool-${p()}`;if(re.has(z)){re.delete(z);continue}let q=Q(z),G=(Io=q.toolCall)!=null?Io:{id:z,status:"running"};G.status="complete",w.result!==void 0&&(G.result=w.result),typeof w.duration=="number"&&(G.duration=w.duration),G.completedAt=Me((Cr=w.completedAt)!=null?Cr:w.timestamp);let K=(Ro=w.duration)!=null?Ro:w.executionTime;if(typeof K=="number")G.durationMs=K;else{let ct=(In=G.startedAt)!=null?In:Date.now();G.durationMs=Math.max(0,((is=G.completedAt)!=null?is:Date.now())-ct)}q.toolCall=G,q.streaming=!1;let Ne=w.agentContext;(Ne||w.executionId)&&(q.agentMetadata=(ro=q.agentMetadata)!=null?ro:{executionId:(no=Ne==null?void 0:Ne.executionId)!=null?no:w.executionId,iteration:(_r=Ne==null?void 0:Ne.iteration)!=null?_r:w.iteration}),g(q);let rt=Z(w);rt&&k.byCall.delete(rt)}else if(ot==="await"&&w.toolName){let z=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,q=(oo=z!=null?z:w.toolId)!=null?oo:`local-${p()}`,G=Q(q),K=w.toolName,Ne=w.origin==="webmcp"&&!Jo(K)?`webmcp:${K}`:K,rt=Jo(Ne),ct=(Wo=G.toolCall)!=null?Wo:{id:q,status:"pending"};ct.name=Ne,ct.args=w.parameters,ct.status=rt?"running":"complete",ct.chunks=(Ho=ct.chunks)!=null?Ho:[],ct.startedAt=(Dn=ct.startedAt)!=null?Dn:Me((vt=(so=w.startedAt)!=null?so:w.timestamp)!=null?vt:w.awaitedAt),rt?(ct.completedAt=void 0,ct.duration=void 0,ct.durationMs=void 0):ct.completedAt=(Nn=ct.completedAt)!=null?Nn:ct.startedAt,G.toolCall=ct,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(St=w.executionId)!=null?St:(An=G.agentMetadata)==null?void 0:An.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},g(G)}else if(ot==="text_start"){let z=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&q){R.set(z,q);continue}let G=y;G&&(Ze==="flow"?(ge(G),Wt=G):(G.streaming=!1,g(G)),y=null),L=typeof w.id=="string"?w.id:L,W=""}else if(ot==="text_delta"){let z=typeof w.id=="string"?w.id:null,q=z?R.get(z):void 0;if(z&&q){let K=typeof w.delta=="string"?w.delta:"",Ne=((Vn=S.get(z))!=null?Vn:"")+K;if(S.set(z,Ne),Ne.trim()==="")continue;let rt=X(z,q);rt.agentMetadata={...rt.agentMetadata,executionId:w.executionId,parentToolId:q},tt(rt,Ne,K,void 0);continue}if(L=typeof w.id=="string"?w.id:L,Ze==="flow"){let K=typeof w.delta=="string"?w.delta:"";if(W+=K,W.trim()==="")continue;let Ne=ee();Ne.agentMetadata={executionId:w.executionId,iteration:w.iteration},tt(Ne,W,K,void 0),v=Ne;continue}let G=ee();G.content+=(Kn=w.delta)!=null?Kn:"",G.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:be!=null?be:void 0,agentName:pe==null?void 0:pe.agentName},v=G,g(G)}else if(ot==="text_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&R.has(z)){let G=P.get(z);G&&ge(G),R.delete(z),S.delete(z),P.delete(z);continue}let q=y;q&&(Ze==="flow"?(ge(q),Wt=q):(((On=q.content)!=null?On:"")===""&&typeof w.text=="string"&&(q.content=w.text),q.streaming=!1,g(q)),y=null),L=null,W=""}else if(ot==="step_complete"){let z=w.stepType,q=w.executionType;if(z==="tool"||q==="context")continue;if(w.success===!1){let G=w.error,K=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&Reflect.has(G,"message")?String((ao=G.message)!=null?ao:"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let Ne=y;Ne&&Ne.streaming&&(Ne.streaming=!1,g(Ne)),n({type:"status",status:"idle"});continue}{let G=Wt;Wt=null;let K=w.stopReason,Ne=(Ce=w.result)==null?void 0:Ce.response;if(G)K&&(G.stopReason=K),Ne!=null?gt(G,Ne):G.streaming!==!1&&(le.delete(G.id),Ie.delete(G.id),G.streaming=!1,g(G));else{let rt=Ne!=null&&Ne!=="";if(rt||K){let ct=ee();K&&(ct.stopReason=K),rt?ge(ct,Ne):(ct.streaming=!1,g(ct))}}continue}}else if(ot==="execution_start")Ze=w.kind==="flow"?"flow":"agent",qt=!0,Ze==="agent"&&(pe={executionId:w.executionId,agentId:($r=w.agentId)!=null?$r:"virtual",agentName:(Gn=w.agentName)!=null?Gn:"",status:"running",currentIteration:0,maxTurns:(Ft=w.maxTurns)!=null?Ft:1,startedAt:Me(w.startedAt)});else if(ot==="turn_start"){let z=typeof w.iteration=="number"?w.iteration:we;if(z!==we){if(pe&&(pe.currentIteration=z),Ct==="separate"&&z>1){let q=y;q&&(q.streaming=!1,g(q),Cn.set(z-1,q),y=null)}we=z}be=typeof w.id=="string"?w.id:null,v=null}else if(ot==="tool_input_delta"){let z=(Jn=w.toolCallId)!=null?Jn:k.lastId;if(z){let q=U.get(z);q!=null&&q.toolCall&&(q.toolCall.chunks=(jr=q.toolCall.chunks)!=null?jr:[],q.toolCall.chunks.push((Fs=w.delta)!=null?Fs:""),g(q))}}else{if(ot==="tool_input_complete")continue;if(ot==="turn_complete"){let z=w.stopReason,q=y!=null?y:v;if(z&&q!==null){let G=w.id;(!G||((ls=q.agentMetadata)==null?void 0:ls.turnId)===G)&&(q.stopReason=z,g(q))}be===w.id&&(be=null)}else if(ot==="media_start"){let z=String(w.id);Se.set(z,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(ot==="media_delta"){let z=Se.get(String(w.id));z&&typeof w.delta=="string"&&z.parts.push(w.delta)}else if(ot==="media_complete"){let z=String(w.id),q=Se.get(z);Se.delete(z);let G=(Bo=(_s=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?_s:q==null?void 0:q.mediaType)!=null?Bo:"application/octet-stream",K=typeof w.data=="string"?w.data:void 0,Ne=typeof w.url=="string"?w.url:q&&q.parts.length>0?q.parts.join(""):void 0,rt=null;if(K)rt={type:"media",data:K,mediaType:G};else if(Ne){let En=G.toLowerCase();rt={type:En==="image"||En.startsWith("image/")?"image-url":"file-url",url:Ne,mediaType:G}}let ct=(Ar=w.toolCallId)!=null?Ar:q==null?void 0:q.toolCallId,$i=rt?[rt]:[],po=[];for(let En of $i){if(!En||typeof En!="object")continue;let pn=En,zr=typeof pn.type=="string"?pn.type:void 0,Lr=typeof pn.mediaType=="string"?pn.mediaType.toLowerCase():"",on=null,Mn="";if(zr==="media"){let gn=typeof pn.data=="string"?pn.data:void 0;if(!gn)continue;Mn=Lr.length>0?Lr:"application/octet-stream",on=`data:${Mn};base64,${gn}`}else if(zr==="image-url"){let gn=typeof pn.url=="string"?pn.url:void 0;if(!gn)continue;Mn=Lr,on=gn}else if(zr==="file-url"){let gn=typeof pn.url=="string"?pn.url:void 0;if(!gn)continue;Mn=Lr,on=gn}else continue;if(on)if(zr==="image-url"||Mn.startsWith("image/"))po.push({type:"image",image:on,...Mn.includes("/")?{mimeType:Mn}:{}});else if(Mn.startsWith("audio/"))po.push({type:"audio",audio:on,mimeType:Mn});else if(Mn.startsWith("video/"))po.push({type:"video",video:on,mimeType:Mn});else{let gn=Mn||"application/octet-stream";po.push({type:"file",data:on,mimeType:gn,filename:Sy(gn)})}}if(po.length>0){let En=p(),pn=ct,Lr={id:`agent-media-${typeof pn=="string"&&pn.length>0?`${pn}-${En}`:String(En)}`,role:"assistant",content:"",contentParts:po,createdAt:new Date().toISOString(),streaming:!1,sequence:En,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:we}};g(Lr);let on=y;on&&(on.streaming=!1,g(on)),y=null,A.current=null}}else if(ot==="execution_complete"){let z=(io=w.kind)!=null?io:Ze;z==="agent"&&pe&&(pe.status=w.success?"complete":"error",pe.completedAt=Me(w.completedAt),pe.stopReason=w.stopReason);let q=y;q&&(z==="flow"&&q.streaming!==!1?ge(q):(q.streaming=!1,g(q)),y=null),L=null,W="",Wt=null,n({type:"status",status:"idle",terminal:!0})}else if(ot==="execution_error"){let z=typeof w.error=="string"?w.error:(nn=(lt=w.error)==null?void 0:lt.message)!=null?nn:"Execution error";n({type:"error",error:new Error(z)})}else if(ot!=="ping"){if(ot==="approval_start"){let z=(rn=w.approvalId)!=null?rn:`approval-${p()}`,q={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:"pending",agentId:(Sr=pe==null?void 0:pe.agentId)!=null?Sr:"virtual",executionId:(Ur=($s=w.executionId)!=null?$s:pe==null?void 0:pe.executionId)!=null?Ur:"",toolName:(Do=w.toolName)!=null?Do:"",toolType:w.toolType,description:(_=w.description)!=null?_:`Execute ${(Tr=w.toolName)!=null?Tr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(ot==="step_await"&&w.awaitReason==="approval_required"){let z=(cs=w.approvalId)!=null?cs:`approval-${p()}`,q={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:"pending",agentId:(Xn=pe==null?void 0:pe.agentId)!=null?Xn:"virtual",executionId:(qr=(Er=w.executionId)!=null?Er:pe==null?void 0:pe.executionId)!=null?qr:"",toolName:(Mr=w.toolName)!=null?Mr:"",toolType:w.toolType,description:(ds=w.description)!=null?ds:`Execute ${(cr=w.toolName)!=null?cr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(ot==="approval_complete"){let z=w.approvalId;if(z){let G={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:(Ia=w.decision)!=null?Ia:"approved",agentId:(bn=pe==null?void 0:pe.agentId)!=null?bn:"virtual",executionId:(dr=(Sn=w.executionId)!=null?Sn:pe==null?void 0:pe.executionId)!=null?dr:"",toolName:(Tn=w.toolName)!=null?Tn:"",description:(No=w.description)!=null?No:"",resolvedAt:Date.now()}};g(G)}}else if(ot==="artifact_start"||ot==="artifact_delta"||ot==="artifact_update"||ot==="artifact_complete"){if(ot==="artifact_start"){let z=w.artifactType,q=String(w.id),G=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:q,artifactType:z,title:G,component:typeof w.component=="string"?w.component:void 0}),fe.set(q,{markdown:"",title:G}),!ae.has(q)){ae.add(q);let K={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:G,artifactType:z,status:"streaming"}})};se.set(q,K),g(K)}}else if(ot==="artifact_delta"){let z=String(w.id),q=typeof w.delta=="string"?w.delta:String((pr=w.delta)!=null?pr:"");n({type:"artifact_delta",id:z,artDelta:q});let G=fe.get(z);G&&(G.markdown+=q)}else if(ot==="artifact_update"){let z=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:z,component:typeof w.component=="string"?w.component:void 0})}else if(ot==="artifact_complete"){let z=String(w.id);n({type:"artifact_complete",id:z});let q=se.get(z);if(q){q.streaming=!1;try{let G=JSON.parse((xn=q.rawContent)!=null?xn:"{}");if(G.props){G.props.status="complete";let K=fe.get(z);K!=null&&K.markdown&&(G.props.markdown=K.markdown)}q.rawContent=JSON.stringify(G)}catch{}fe.delete(z),g(q),se.delete(z)}}}else if(ot==="transcript_insert"){let z=w.message;if(!z||typeof z!="object")continue;let q=String((kr=z.id)!=null?kr:`msg-${p()}`),G=z.role,Ne={id:q,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:p()};if(g(Ne),Ne.rawContent)try{let rt=JSON.parse(Ne.rawContent),ct=(ps=rt==null?void 0:rt.props)==null?void 0:ps.artifactId;typeof ct=="string"&&ae.add(ct)}catch{}y=null,A.current=null,le.delete(q),Ie.delete(q)}else if(ot==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let z=typeof w.error=="string"?w.error:((Oo=w.error)==null?void 0:Oo.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(z)});let q=y;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}else if(ot==="step_error"||ot==="dispatch_error"||ot==="flow_error"){let z=null;if(w.error instanceof Error)z=w.error;else if(ot==="dispatch_error"){let q=(us=w.message)!=null?us:w.error;q!=null&&q!==""&&(z=new Error(String(q)))}else{let q=w.error;typeof q=="string"&&q!==""?z=new Error(q):q!=null&&typeof q=="object"&&Reflect.has(q,"message")&&(z=new Error(String((lo=q.message)!=null?lo:q)))}if(z){n({type:"error",error:z});let q=y;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}}}}it.length=0};;){let{done:E,value:ue}=await s.read();if(E)break;i+=a.decode(ue,{stream:!0});let Te=i.split(`
|
|
12
12
|
|
|
13
|
-
`);i=(
|
|
14
|
-
`),nt="message",Qe="",ht=null;for(let ce of He)ce.startsWith("event:")?nt=ce.replace("event:","").trim():ce.startsWith("data:")?Qe+=ce.replace("data:","").trim():ce.startsWith("id:")&&(ht=ce.slice(3).trim());let me=()=>{ht!==null&&ht!==""&&n({type:"cursor",id:ht})};if(!Qe){me();continue}let B;try{B=JSON.parse(Qe)}catch(ce){n({type:"error",error:ce instanceof Error?ce:new Error("Failed to parse chat stream payload")});continue}let xe=nt!=="message"?nt:(br=B.type)!=null?br:"message";if((Ue=this.onSSEEvent)==null||Ue.call(this,xe,B),this.parseSSEEvent){S.current=b;let ce=await this.handleCustomSSEEvent(B,n,S,g,p,T);if(S.current&&S.current!==b&&(b=S.current),ce){me();continue}}it.push({payloadType:xe,payload:B}),Ve(),me()}}Ve()}};function uy(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function aa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Xo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Va="[Image]";function my(e){return typeof e=="string"?[{type:"text",text:e}]:e}function gy(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function fy(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function hy(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ka(e){return{type:"text",text:e}}function yy(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function by(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function xy(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 Hm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],vy=["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"],Gr=[...Hm,...vy];function wy(e){return Hm.includes(e)||e.startsWith("image/")}function Ga(e){return wy(e.type)}async function Bm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ga(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Dm(e,t=Gr,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 Cy(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Nm(e,t){let n=Cy(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"}dl();var Om=16e3,Ay=24e3,Sy=4096,Ty=1380533830;function Ey(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Ty?new Uint8Array(e,44):new Uint8Array(e)}function My(e){var r;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var ia=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(){var s,a,i,d;if(this.callLive)return;let t=(s=this.config)==null?void 0:s.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Om,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(v=>v.stop());return}this.mediaStream=c;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:Om});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let f=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new Ss(Ay);if(o!==this.callGeneration){f.destroy(),c.getTracks().forEach(v=>v.stop()),u.close().catch(()=>{});return}this.playback=f,f.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let g=`${My(r)}/ws/agents/${encodeURIComponent(t)}/voice`,b=new WebSocket(g,["runtype.bearer",n]);b.binaryType="arraybuffer",this.ws=b,b.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,c,b,o))},b.onmessage=v=>this.handleMessage(v,o),b.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},b.onclose=v=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(v.code!==1e3){let S=v.code?` (code ${v.code})`:"";this.emitError(new Error(`Voice connection closed${S}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,r,o){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Sy,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let p=0;p<d.length;p++){let u=Math.max(-1,Math.min(1,d[p]));c[p]=u<0?u*32768:u*32767}r.send(c.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){var o,s;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let r;try{r=JSON.parse(t.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let r=Ey(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(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,r){this.transcriptCallbacks.forEach(o=>o(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Qo=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!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(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 Yo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ia(e.runtype);case"browser":if(!Qo.isSupported())throw new Error("Browser speech recognition not supported");return new Qo(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 pl(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Yo({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Yo({type:"runtype",runtype:e.runtype});if(Qo.isSupported())return Yo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ja(e){try{return pl(e),!0}catch{return!1}}function la(e){var n;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 r of t){let o=e.find(s=>s.name===r);if(o)return o}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var Zo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t.text),s=r.getVoices();if(t.voice){let i=s.find(d=>d.name===t.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):la(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var c,p;let d=i.error;d==="canceled"||d==="interrupted"?(c=n.onEnd)==null||c.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Ts=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!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){var r,o;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(t,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function ul(e){if(!e)return"";let t=ky(e);return Fm(t!==null?t:e)}function ky(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 r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Fm(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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
|
|
13
|
+
`);i=(hr=Te.pop())!=null?hr:"";for(let ke of Te){let He=ke.split(`
|
|
14
|
+
`),nt="message",Qe="",ht=null;for(let ce of He)ce.startsWith("event:")?nt=ce.replace("event:","").trim():ce.startsWith("data:")?Qe+=ce.replace("data:","").trim():ce.startsWith("id:")&&(ht=ce.slice(3).trim());let me=()=>{ht!==null&&ht!==""&&n({type:"cursor",id:ht})};if(!Qe){me();continue}let B;try{B=JSON.parse(Qe)}catch(ce){n({type:"error",error:ce instanceof Error?ce:new Error("Failed to parse chat stream payload")});continue}let xe=nt!=="message"?nt:(yr=B.type)!=null?yr:"message";if((Ue=this.onSSEEvent)==null||Ue.call(this,xe,B),this.parseSSEEvent){A.current=y;let ce=await this.handleCustomSSEEvent(B,n,A,g,p,T);if(A.current&&A.current!==y&&(y=A.current),ce){me();continue}}it.push({payloadType:xe,payload:B}),Ve(),me()}}Ve()}};function My(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function da(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Yo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Xa="[Image]";function ky(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ly(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Py(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Iy(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Qa(e){return{type:"text",text:e}}function Ry(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function Wy(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Hy(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 Vm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],By=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Qr=[...Vm,...By];function Dy(e){return Vm.includes(e)||e.startsWith("image/")}function Ya(e){return Dy(e.type)}async function Km(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ya(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Gm(e,t=Qr,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 Ny(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Jm(e,t){let n=Ny(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"}xl();var Xm=16e3,Oy=24e3,Fy=4096,_y=1380533830;function $y(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===_y?new Uint8Array(e,44):new Uint8Array(e)}function jy(e){var r;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var pa=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(){var s,a,i,d;if(this.callLive)return;let t=(s=this.config)==null?void 0:s.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Xm,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(v=>v.stop());return}this.mediaStream=c;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:Xm});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let f=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new Ms(Oy);if(o!==this.callGeneration){f.destroy(),c.getTracks().forEach(v=>v.stop()),u.close().catch(()=>{});return}this.playback=f,f.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let g=`${jy(r)}/ws/agents/${encodeURIComponent(t)}/voice`,y=new WebSocket(g,["runtype.bearer",n]);y.binaryType="arraybuffer",this.ws=y,y.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,c,y,o))},y.onmessage=v=>this.handleMessage(v,o),y.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},y.onclose=v=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(v.code!==1e3){let A=v.code?` (code ${v.code})`:"";this.emitError(new Error(`Voice connection closed${A}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,r,o){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Fy,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let p=0;p<d.length;p++){let u=Math.max(-1,Math.min(1,d[p]));c[p]=u<0?u*32768:u*32767}r.send(c.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){var o,s;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let r;try{r=JSON.parse(t.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let r=$y(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(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,r){this.transcriptCallbacks.forEach(o=>o(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Zo=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!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(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 es(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new pa(e.runtype);case"browser":if(!Zo.isSupported())throw new Error("Browser speech recognition not supported");return new Zo(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 vl(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return es({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return es({type:"runtype",runtype:e.runtype});if(Zo.isSupported())return es({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Za(e){try{return vl(e),!0}catch{return!1}}function ua(e){var n;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 r of t){let o=e.find(s=>s.name===r);if(o)return o}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var ts=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t.text),s=r.getVoices();if(t.voice){let i=s.find(d=>d.name===t.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):ua(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var c,p;let d=i.error;d==="canceled"||d==="interrupted"?(c=n.onEnd)==null||c.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var ks=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!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){var r,o;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(t,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function wl(e){if(!e)return"";let t=Uy(e);return Qm(t!==null?t:e)}function Uy(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 r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Qm(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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /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
|
|
16
|
+
`),t.trim()}var ng=null;var Cl=()=>ng?ng():Promise.resolve().then(()=>(tg(),eg));var Gy=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Jy(e,t){return Gy.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 r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
|
|
17
17
|
|
|
18
|
-
_Details: ${n.message}_`:r}var ca=e=>({isError:!0,content:[{type:"text",text:e}]}),Km=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Gm=e=>Ko(e)||e===Hr,da=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 Ts(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,o,s,a,i,d,c,p,u;if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let f=t.message.toolCall,g=!!(f!=null&&f.name)&&(Ko(f.name)||f.name===Hr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&g&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.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:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i: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 f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(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),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,o;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new As(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,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(){var o,s,a,i,d,c;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(o=t.host)!=null?o:this.config.apiUrl,r=(c=(d=t.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId)!=null?c:this.config.agentId;!n||!r||!this.config.clientToken||ml().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ja((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=Zo.isSupported()?new Zo({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let c=(r=t.host)!=null?r:this.config.apiUrl,p=(d=(i=t.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId)!=null?d:this.config.agentId,u=this.config.clientToken,f=t.browserFallback!==!1;if(c&&p&&u)return ml().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:b})=>{let v=new g({host:c,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return f&&n?new b(v,n,{onFallback:S=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${S.message}`)}):v});if(f&&n)return u&&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){var n,r;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Yo(o);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){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:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,o,s,a,i,d,c,p,u,f,g;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=t.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=t.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=t.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(u=t.runtype)==null?void 0:u.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((f=t.browser)==null?void 0:f.language)||"en-US",continuous:(g=t.browser)==null?void 0:g.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),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(){var t;return(t=this.clientSession)!=null?t: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(!Hy(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new As(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:u}=t,g={id:a!=null?a:n==="user"?aa():n==="assistant"?Xo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...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 r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:u=!1,voiceProcessing:f,rawContent:g}=r,v={id:d!=null?d:o==="user"?aa():o==="assistant"?Xo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,c={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var c,p,u,f,g;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let o=aa(),s=Xo();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||Va,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(b){if(this.status==="resuming"||this.reconnecting)return;let v=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));if(!v){let S=gl(b,this.config.errorMessage);if(S){let T={id:s,role:"assistant",createdAt:new Date().toISOString(),content:S,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(b instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,b):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(b))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort(),this.teardownReconnect();let t=Xo();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let p=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!p){let u=gl(c,this.config.errorMessage);if(u){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(t,n){var s,a,i;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort(),n!=null&&n.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let r=n!=null&&n.preserveAssistantId?n.assistantMessageId:void 0,o=!1;for(let d of this.messages)d.streaming&&d.id!==r&&(d.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId,n==null?void 0:n.seedContent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(i=(a=this.callbacks).onError)==null||i.call(a,d instanceof Error?d:new Error(String(d)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,f,g,b;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(c?v=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let S=null;if(v instanceof Response){if(!v.ok){let T=await v.json().catch(()=>null);throw new Error((f=T==null?void 0:T.error)!=null?f:`Approval request failed: ${v.status}`)}S=v.body}else v instanceof ReadableStream&&(S=v);S?await this.connectStream(S,{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(v){let S=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,S||(b=(g=this.callbacks).onError)==null||b.call(g,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,f,g,b,v,S,T,L,P,E,k;let r=this.messages.find(C=>C.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!o||!s){(b=(g=this.callbacks).onError)==null||b.call(g,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=(v=t.toolCall)==null?void 0:v.args,I=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(I.length===1){let j=typeof((S=I[0])==null?void 0:S.question)=="string"?I[0].question:"";j&&(a={[j]:n})}}this.markAskUserQuestionResolved(t,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(L=t.toolCall)==null?void 0:L.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let C=typeof n=="string"?n:Object.entries(n).map(([I,j])=>`${I}: ${Array.isArray(j)?j.join(", "):j}`).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!=null?a:{};c.forEach((I,j)=>{let $=typeof(I==null?void 0:I.question)=="string"?I.question:"";if(!$)return;let R=C[$],N=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${j}`,role:"assistant",content:$,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${j}`,role:"user",content:N||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:n});if(!C.ok){let I=await C.json().catch(()=>null);throw new Error((P=I==null?void 0:I.error)!=null?P:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let I=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,I||(k=(E=this.callbacks).onError)==null||k.call(E,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.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:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var o,s;let n=this.messages.find(a=>a.id===t.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,o;if(((r=t.toolCall)==null?void 0:r.name)!==Hr)return!1;let n=this.messages.find(s=>s.id===t.id);return((o=(n!=null?n:t).agentMetadata)==null?void 0:o.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,r,o=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:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,c,p,u;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async f=>{var k,C,I,j,$,R,N;let g=(k=f.toolCall)==null?void 0:k.name,b=(C=f.toolCall)==null?void 0:C.id;if(!g||!b)return null;let v=`${t}:${b}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(f))return null;this.webMcpInflightKeys.add(v),r.push(v);let S=this.markWebMcpToolRunning(f),T=(j=(I=f.agentMetadata)==null?void 0:I.webMcpToolCallId)!=null?j:g;if(g===Hr)return{dedupeKey:v,resumeKey:T,output:nl(),toolMessage:f,startedAt:S,completedAt:Date.now()};let L=new AbortController;this.webMcpResolveControllers.add(L),o.push(L);let P=this.client.executeWebMcpToolCall(g,($=f.toolCall)==null?void 0:$.args,L.signal),E;if(!P)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await P}catch(O){let Z=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return Z||(N=(R=this.callbacks).onError)==null||N.call(R,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(f,ca(Z?"Aborted by cancel()":Km(O)),S),this.webMcpInflightKeys.delete(v),null}return L.signal.aborted?(this.markWebMcpToolComplete(f,ca("Aborted by cancel()"),S),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:T,output:E,toolMessage:f,startedAt:S,completedAt:Date.now()}})),i=[];try{if(i=a.filter(b=>b!==null),i.length===0)return;let f={};for(let b of i)f[b.resumeKey]=b.output;let g=await this.client.resumeFlow(t,f,{signal:s.signal});if(!g.ok){let b=await g.json().catch(()=>null);throw new Error((d=b==null?void 0:b.error)!=null?d:`Resume failed: ${g.status}`)}for(let b of i)this.webMcpResolvedKeys.add(b.dedupeKey),this.markWebMcpToolComplete(b.toolMessage,b.output,b.startedAt,b.completedAt,((c=b.toolMessage.toolCall)==null?void 0:c.name)===Hr?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,f instanceof Error?f:new Error(String(f)));else for(let b of i)this.markWebMcpToolComplete(b.toolMessage,ca("Aborted by cancel()"),b.startedAt)}finally{for(let f of r)this.webMcpInflightKeys.delete(f);for(let f of o)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var b,v,S,T,L,P,E,k,C,I,j,$;let n=(b=t.agentMetadata)==null?void 0:b.executionId,r=(v=t.toolCall)==null?void 0:v.name,o=(S=t.toolCall)==null?void 0:S.id;if(!n){(L=(T=this.callbacks).onError)==null||L.call(T,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let R=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(R)||this.webMcpResolvedKeys.has(R))return;this.webMcpInflightKeys.add(R);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(R)}catch(N){(E=(P=this.callbacks).onError)==null||E.call(P,N instanceof Error?N:new Error(String(N)))}finally{this.webMcpInflightKeys.delete(R)}return}let s=`${n}:${o}`;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:d}=i;this.setStreaming(!0);let c=r===Hr,p=(k=t.toolCall)==null?void 0:k.args,u=c?null:this.client.executeWebMcpToolCall(r,p,d),f="execute",g=a;try{let R;if(c?R=nl():u?R=await u:R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ca("Aborted by cancel()"),a);return}let N=(I=(C=t.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?I:r;f="resume",await this.resumeWithToolOutput(n,N,R,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,R,a,g,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(R){let N=R instanceof Error&&(R.name==="AbortError"||R.message.includes("aborted")||R.message.includes("abort"));(f==="execute"||N||d.aborted)&&this.markWebMcpToolComplete(t,ca(N||d.aborted?"Aborted by cancel()":Km(R)),a),N||($=(j=this.callbacks).onError)==null||$.call(j,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,o){var a,i;let s=await this.client.resumeFlow(t,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let 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(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.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){var o;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;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:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){var o,s;let n=(o=this.agentExecution)==null?void 0:o.executionId;if(!n||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var t;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((t=this.abortController)==null?void 0:t.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>{var n,r,o;return((n=t.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&((r=t.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||t.variant==="approval"&&((o=t.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var t,n;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(n=(t=this.callbacks).onReconnect)==null||n.call(t,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(r=>{this.reconnecting&&this.resumable&&r.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(Vm(),zm)).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,r,o)=>t.connectStream(n,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>{var r,o;return(o=(r=t.callbacks).onReconnect)==null?void 0:o.call(r,n)},buildErrorContent:n=>gl(new Error(n),t.config.errorMessage),onError:n=>{var r,o;return(o=(r=t.callbacks).onError)==null?void 0:o.call(r,n)}}}reconnectNow(){var t;if(this.reconnecting){(t=this.reconnectController)==null||t.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Xo(),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(){var t;this.reconnecting=!1,(t=this.reconnectController)==null||t.teardown(),this.clearResumable()}clearResumable(){var n,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&((r=(n=this.config).onExecutionState)==null||r.call(n,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(()=>{var r,o;this.executionStateTimer=null,(o=(r=this.config).onExecutionState)==null||o.call(r,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!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=ul(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return la(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let r=ul(n.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"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),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var p,u,f,g,b,v,S,T,L,P,E,k,C,I,j;if(s!==r)return o;let a={...o,...n};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=o.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(f=a.agentMetadata)!=null?f:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let $=o.approval,R=n.approval;a.approval={...$,...R,executionId:R.executionId||$.executionId,toolName:R.toolName||$.toolName,description:R.description||$.description,toolType:(g=R.toolType)!=null?g:$.toolType,reason:(b=R.reason)!=null?b:$.reason,parameters:(v=R.parameters)!=null?v:$.parameters}}let i=(S=n.toolCall)==null?void 0:S.name,d=(T=n.agentMetadata)==null?void 0:T.executionId,c=(L=n.toolCall)==null?void 0:L.id;if(i&&Gm(i)&&d&&c&&((P=n.agentMetadata)==null?void 0:P.awaitingLocalTool)===!0){let $=`${d}:${c}`,R=this.webMcpInflightKeys.has($),N=this.webMcpResolvedKeys.has($),O=(E=o.toolCall)==null?void 0:E.name,Z=((k=o.agentMetadata)==null?void 0:k.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&O!==void 0&&Gm(O)&&((I=o.toolCall)==null?void 0:I.status)==="complete";(R||N||Z)&&(a.agentMetadata={...(j=a.agentMetadata)!=null?j:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.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,r)=>{var d,c;let o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};import{Activity as By,ArrowDown as Dy,ArrowUp as Ny,ArrowUpRight as Oy,Bot as Fy,ChevronDown as _y,ChevronUp as $y,ChevronRight as jy,ChevronLeft as Uy,Check as qy,Clipboard as zy,ClipboardCopy as Vy,Copy as Ky,File as Gy,FileCode as Jy,FileSpreadsheet as Xy,FileText as Qy,ImagePlus as Yy,Loader as Zy,LoaderCircle as eb,Mic as tb,Paperclip as nb,RefreshCw as rb,Search as ob,Send as sb,ShieldAlert as ab,ShieldCheck as ib,ShieldX as lb,Square as cb,ThumbsDown as db,ThumbsUp as pb,Upload as ub,Volume2 as mb,X as gb,User as fb,Mail as hb,Phone as yb,Calendar as bb,Clock as xb,Building as vb,MapPin as wb,Lock as Cb,Key as Ab,CreditCard as Sb,AtSign as Tb,Hash as Eb,Globe as Mb,Link as kb,CircleCheck as Lb,CircleX as Pb,TriangleAlert as Ib,Info as Rb,Ban as Wb,Shield as Hb,ArrowLeft as Bb,ArrowRight as Db,ExternalLink as Nb,Ellipsis as Ob,EllipsisVertical as Fb,Menu as _b,House as $b,Plus as jb,Minus as Ub,Pencil as qb,Trash as zb,Trash2 as Vb,Save as Kb,Download as Gb,Share as Jb,Funnel as Xb,Settings as Qb,RotateCw as Yb,Maximize as Zb,Minimize as ex,ShoppingCart as tx,ShoppingBag as nx,Package as rx,Truck as ox,Tag as sx,Gift as ax,Receipt as ix,Wallet as lx,Store as cx,DollarSign as dx,Percent as px,Play as ux,Pause as mx,VolumeX as gx,Camera as fx,Image as hx,Film as yx,Headphones as bx,MessageCircle as xx,MessageSquare as vx,Bell as wx,Heart as Cx,Star as Ax,Eye as Sx,EyeOff as Tx,Bookmark as Ex,CalendarDays as Mx,History as kx,Timer as Lx,Folder as Px,FolderOpen as Ix,Files as Rx,Sparkles as Wx,Zap as Hx,Sun as Bx,Moon as Dx,Flag as Nx,Monitor as Ox,Smartphone as Fx}from"lucide";var _x={activity:By,"arrow-down":Dy,"arrow-up":Ny,"arrow-up-right":Oy,bot:Fy,"chevron-down":_y,"chevron-up":$y,"chevron-right":jy,"chevron-left":Uy,check:qy,clipboard:zy,"clipboard-copy":Vy,copy:Ky,file:Gy,"file-code":Jy,"file-spreadsheet":Xy,"file-text":Qy,"image-plus":Yy,loader:Zy,"loader-circle":eb,mic:tb,paperclip:nb,"refresh-cw":rb,search:ob,send:sb,"shield-alert":ab,"shield-check":ib,"shield-x":lb,square:cb,"thumbs-down":db,"thumbs-up":pb,upload:ub,"volume-2":mb,x:gb,user:fb,mail:hb,phone:yb,calendar:bb,clock:xb,building:vb,"map-pin":wb,lock:Cb,key:Ab,"credit-card":Sb,"at-sign":Tb,hash:Eb,globe:Mb,link:kb,"circle-check":Lb,"circle-x":Pb,"triangle-alert":Ib,info:Rb,ban:Wb,shield:Hb,"arrow-left":Bb,"arrow-right":Db,"external-link":Nb,ellipsis:Ob,"ellipsis-vertical":Fb,menu:_b,house:$b,plus:jb,minus:Ub,pencil:qb,trash:zb,"trash-2":Vb,save:Kb,download:Gb,share:Jb,funnel:Xb,settings:Qb,"rotate-cw":Yb,maximize:Zb,minimize:ex,"shopping-cart":tx,"shopping-bag":nx,package:rx,truck:ox,tag:sx,gift:ax,receipt:ix,wallet:lx,store:cx,"dollar-sign":dx,percent:px,play:ux,pause:mx,"volume-x":gx,camera:fx,image:hx,film:yx,headphones:bx,"message-circle":xx,"message-square":vx,bell:wx,heart:Cx,star:Ax,eye:Sx,"eye-off":Tx,bookmark:Ex,"calendar-days":Mx,history:kx,timer:Lx,folder:Px,"folder-open":Ix,files:Rx,sparkles:Wx,zap:Hx,sun:Bx,moon:Dx,flag:Nx,monitor:Ox,smartphone:Fx},ye=(e,t=24,n="currentColor",r=2)=>{let o=_x[e];return o?$x(o,t,n,r):(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 $x(e,t,n,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.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 d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),o.appendChild(d)}),o}var Ya={allowedTypes:Gr,maxFileSize:10*1024*1024,maxFiles:4};function jx(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ux(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 Es=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ya.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Ya.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Ya.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:Ya.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){var n,r,o,s,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let p=Dm(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,u);continue}try{let u=await Bm(c),f=Ga(c)?URL.createObjectURL(c):null,g={id:jx(),file:c,previewUrl:f,contentPart:u};this.attachments.push(g),this.renderPreview(g)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ga(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=y("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",r.appendChild(a)}else{let a=y("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=Ux(t.file.type),d=ye(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=Nm(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ye("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var Jm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function pa(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];Jm(s)&&Jm(o)?n[r]=pa(s,o):n[r]=o}return n}var tr="min(440px, calc(100vw - 24px))",fl="440px",qx={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:tr,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)"},Dt={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:qx,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,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 Xm(e,t){if(!(!e&&!t))return e?t?pa(e,t):e:t}function hl(e){var t,n,r,o,s,a,i,d,c,p,u,f,g,b,v,S,T,L,P,E,k;return e?{...Dt,...e,theme:Xm(Dt.theme,e.theme),darkTheme:Xm(Dt.darkTheme,e.darkTheme),launcher:{...Dt.launcher,...e.launcher,dock:{...(t=Dt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Dt.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Dt.copy,...e.copy},sendButton:{...Dt.sendButton,...e.sendButton},statusIndicator:{...Dt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Dt.voiceRecognition,...e.voiceRecognition},features:(()=>{var re,se,ae,fe,$e,V,Q,Me,J,le;let C=(re=Dt.features)==null?void 0:re.artifacts,I=(se=e.features)==null?void 0:se.artifacts,j=(ae=Dt.features)==null?void 0:ae.scrollToBottom,$=(fe=e.features)==null?void 0:fe.scrollToBottom,R=($e=Dt.features)==null?void 0:$e.scrollBehavior,N=(V=e.features)==null?void 0:V.scrollBehavior,O=(Q=Dt.features)==null?void 0:Q.streamAnimation,Z=(Me=e.features)==null?void 0:Me.streamAnimation,Ee=(J=Dt.features)==null?void 0:J.askUserQuestion,de=(le=e.features)==null?void 0:le.askUserQuestion,ee=C===void 0&&I===void 0?void 0:{...C,...I,layout:{...C==null?void 0:C.layout,...I==null?void 0:I.layout}},Le=j===void 0&&$===void 0?void 0:{...j,...$},Pe=R===void 0&&N===void 0?void 0:{...R,...N},ne=O===void 0&&Z===void 0?void 0:{...O,...Z},Ae=Ee===void 0&&de===void 0?void 0:{...Ee,...de,styles:{...Ee==null?void 0:Ee.styles,...de==null?void 0:de.styles}};return{...Dt.features,...e.features,...Le!==void 0?{scrollToBottom:Le}:{},...Pe!==void 0?{scrollBehavior:Pe}:{},...ee!==void 0?{artifacts:ee}:{},...ne!==void 0?{streamAnimation:ne}:{},...Ae!==void 0?{askUserQuestion:Ae}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Dt.suggestionChips,suggestionChipsConfig:{...Dt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Dt.layout,...e.layout,header:{...(a=Dt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Dt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(u=(p=Dt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(v=(b=Dt.layout)==null?void 0:b.messages)==null?void 0:v.timestamp,...(T=(S=e.layout)==null?void 0:S.messages)==null?void 0:T.timestamp}},slots:{...(L=Dt.layout)==null?void 0:L.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{...Dt.markdown,...e.markdown,options:{...(E=Dt.markdown)==null?void 0:E.options,...(k=e.markdown)==null?void 0:k.options}},messageActions:{...Dt.messageActions,...e.messageActions}}:Dt}var Qm={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"}},Ym={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"}},Zm={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:tr,maxWidth:fl,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"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 Ms(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Ms(e,r):r}function yl(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Ms(e,a);d!==void 0&&(t[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function eg(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 tg(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=tg(s,o):n[r]=o}return n}function zx(e,t){return t?tg(e,t):e}function ua(e,t={}){var o,s,a,i,d,c,p,u,f,g,b,v,S;let n={palette:Qm,semantic:Ym,components:Zm},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(b=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:b.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(S=e==null?void 0:e.semantic)==null?void 0:S.typography}},components:zx(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=eg(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(L=>L.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)r=T.transform(r);return r}function bl(e){var v,S,T,L,P,E,k,C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe,ne,Ae,re,se,ae,fe,$e,V,Q,Me,J,le,Ie,he,Ke,gt,Wt,tt,ge,X,it,Ve,Se,we,Ze,qt,be,pe,vn,Ct,fn,yr,br,Ue,M,ue,Te,ke,He,nt,Qe,ht,me,B,xe,ce,ft,Je,Lt,Mt,xt,Rt,Xt,Ot,en,xr,Nr,or,sr,Xr,zt,ar,Or,Hn,kn,Bn,ir,vr,Qr,zn,Yr,At,wr,Cr,Fr,lr,yt,Lo,Ar,Po,Ln,ss,Zr,_r,eo,to,Io,Ro,no,vt,Dn,Nn,wn,St,Vn,Kn,On,ro;let t=yl(e),n={};for(let[Ce,$r]of Object.entries(t)){let Gn=Ce.replace(/\./g,"-");n[`--persona-${Gn}`]=$r.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(S=n["--persona-semantic-colors-secondary"])!=null?S:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(T=n["--persona-semantic-colors-accent"])!=null?T:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(L=n["--persona-semantic-colors-surface"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(P=n["--persona-semantic-colors-background"])!=null?P:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(E=n["--persona-semantic-colors-container"])!=null?E:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(k=n["--persona-semantic-colors-text"])!=null?k:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(C=n["--persona-semantic-colors-text-muted"])!=null?C:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(I=n["--persona-semantic-colors-text-inverse"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(j=n["--persona-semantic-colors-border"])!=null?j:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=($=n["--persona-semantic-colors-divider"])!=null?$:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(R=n["--persona-components-voice-recording-indicator"])!=null?R:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(N=n["--persona-components-voice-recording-background"])!=null?N:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(O=n["--persona-components-voice-processing-icon"])!=null?O:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(Z=n["--persona-components-voice-speaking-icon"])!=null?Z:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Ee=n["--persona-components-approval-requested-background"])!=null?Ee:n["--persona-surface"],n["--persona-approval-border"]=(de=n["--persona-components-approval-requested-border"])!=null?de:n["--persona-border"],n["--persona-approval-text"]=(ee=n["--persona-components-approval-requested-text"])!=null?ee:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Le=n["--persona-components-approval-requested-shadow"])!=null?Le:"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"]=(Pe=n["--persona-components-approval-approve-background"])!=null?Pe:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(ne=n["--persona-components-approval-deny-background"])!=null?ne:n["--persona-container"],n["--persona-attachment-image-bg"]=(Ae=n["--persona-components-attachment-image-background"])!=null?Ae:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(re=n["--persona-components-attachment-image-border"])!=null?re:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(se=n["--persona-semantic-typography-fontFamily"])!=null?se:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(ae=n["--persona-semantic-typography-fontSize"])!=null?ae:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(fe=n["--persona-semantic-typography-fontWeight"])!=null?fe:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=($e=n["--persona-semantic-typography-lineHeight"])!=null?$e: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"]=(V=n["--persona-palette-radius-sm"])!=null?V:"0.125rem",n["--persona-radius-md"]=(Q=n["--persona-palette-radius-md"])!=null?Q:"0.375rem",n["--persona-radius-lg"]=(Me=n["--persona-palette-radius-lg"])!=null?Me:"0.5rem",n["--persona-radius-xl"]=(J=n["--persona-palette-radius-xl"])!=null?J:"0.75rem",n["--persona-radius-full"]=(le=n["--persona-palette-radius-full"])!=null?le:"9999px",n["--persona-launcher-radius"]=(he=(Ie=n["--persona-components-launcher-borderRadius"])!=null?Ie:n["--persona-palette-radius-full"])!=null?he:"9999px",n["--persona-launcher-bg"]=(Ke=n["--persona-components-launcher-background"])!=null?Ke:n["--persona-primary"],n["--persona-launcher-fg"]=(gt=n["--persona-components-launcher-foreground"])!=null?gt:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Wt=n["--persona-components-launcher-border"])!=null?Wt:n["--persona-border"],n["--persona-button-primary-bg"]=(tt=n["--persona-components-button-primary-background"])!=null?tt:n["--persona-primary"],n["--persona-button-primary-fg"]=(ge=n["--persona-components-button-primary-foreground"])!=null?ge:n["--persona-text-inverse"],n["--persona-button-radius"]=(it=(X=n["--persona-components-button-primary-borderRadius"])!=null?X:n["--persona-palette-radius-full"])!=null?it:"9999px",n["--persona-panel-radius"]=(Se=(Ve=n["--persona-components-panel-borderRadius"])!=null?Ve:n["--persona-radius-xl"])!=null?Se:"0.75rem",n["--persona-panel-border"]=(we=n["--persona-components-panel-border"])!=null?we:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(qt=(Ze=n["--persona-components-panel-shadow"])!=null?Ze:n["--persona-palette-shadows-xl"])!=null?qt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(be=n["--persona-components-launcher-shadow"])!=null?be:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(vn=(pe=n["--persona-components-input-borderRadius"])!=null?pe:n["--persona-radius-lg"])!=null?vn:"0.5rem",n["--persona-message-user-radius"]=(fn=(Ct=n["--persona-components-message-user-borderRadius"])!=null?Ct:n["--persona-radius-lg"])!=null?fn:"0.5rem",n["--persona-message-assistant-radius"]=(br=(yr=n["--persona-components-message-assistant-borderRadius"])!=null?yr:n["--persona-radius-lg"])!=null?br:"0.5rem",n["--persona-header-bg"]=(Ue=n["--persona-components-header-background"])!=null?Ue:n["--persona-surface"],n["--persona-header-border"]=(M=n["--persona-components-header-border"])!=null?M:n["--persona-divider"],n["--persona-header-icon-bg"]=(ue=n["--persona-components-header-iconBackground"])!=null?ue:n["--persona-primary"],n["--persona-header-icon-fg"]=(Te=n["--persona-components-header-iconForeground"])!=null?Te:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(ke=n["--persona-components-header-titleForeground"])!=null?ke:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(He=n["--persona-components-header-subtitleForeground"])!=null?He:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(nt=n["--persona-components-header-actionIconForeground"])!=null?nt:n["--persona-muted"];let r=(Qe=e.components)==null?void 0:Qe.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(ht=e.components)==null?void 0:ht.introCard;n["--persona-intro-card-bg"]=(me=n["--persona-components-introCard-background"])!=null?me:n["--persona-surface"],n["--persona-intro-card-radius"]=(B=n["--persona-components-introCard-borderRadius"])!=null?B:"1rem",n["--persona-intro-card-padding"]=(xe=n["--persona-components-introCard-padding"])!=null?xe:"1.5rem",n["--persona-intro-card-shadow"]=(ft=(ce=o==null?void 0:o.shadow)!=null?ce:n["--persona-components-introCard-shadow"])!=null?ft:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Je=n["--persona-components-input-background"])!=null?Je:n["--persona-surface"],n["--persona-input-placeholder"]=(Lt=n["--persona-components-input-placeholder"])!=null?Lt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Mt=n["--persona-components-message-user-background"])!=null?Mt:n["--persona-accent"],n["--persona-message-user-text"]=(xt=n["--persona-components-message-user-text"])!=null?xt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Rt=n["--persona-components-message-user-shadow"])!=null?Rt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Xt=n["--persona-components-message-assistant-background"])!=null?Xt:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ot=n["--persona-components-message-assistant-text"])!=null?Ot:n["--persona-text"],n["--persona-message-assistant-border"]=(en=n["--persona-components-message-assistant-border"])!=null?en:n["--persona-border"],n["--persona-message-assistant-shadow"]=(xr=n["--persona-components-message-assistant-shadow"])!=null?xr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(or=(Nr=n["--persona-components-scrollToBottom-background"])!=null?Nr:n["--persona-button-primary-bg"])!=null?or:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(Xr=(sr=n["--persona-components-scrollToBottom-foreground"])!=null?sr:n["--persona-button-primary-fg"])!=null?Xr:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(zt=n["--persona-components-scrollToBottom-border"])!=null?zt:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ar=n["--persona-components-scrollToBottom-size"])!=null?ar:"40px",n["--persona-scroll-to-bottom-radius"]=(kn=(Hn=(Or=n["--persona-components-scrollToBottom-borderRadius"])!=null?Or:n["--persona-button-radius"])!=null?Hn:n["--persona-radius-full"])!=null?kn:"9999px",n["--persona-scroll-to-bottom-shadow"]=(ir=(Bn=n["--persona-components-scrollToBottom-shadow"])!=null?Bn:n["--persona-palette-shadows-sm"])!=null?ir:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(vr=n["--persona-components-scrollToBottom-padding"])!=null?vr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Qr=n["--persona-components-scrollToBottom-gap"])!=null?Qr:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Yr=(zn=n["--persona-components-scrollToBottom-fontSize"])!=null?zn:n["--persona-palette-typography-fontSize-sm"])!=null?Yr:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(At=n["--persona-components-scrollToBottom-iconSize"])!=null?At:"14px",n["--persona-tool-bubble-shadow"]=(wr=n["--persona-components-toolBubble-shadow"])!=null?wr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Cr=n["--persona-components-reasoningBubble-shadow"])!=null?Cr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Fr=n["--persona-components-composer-shadow"])!=null?Fr:"none",n["--persona-md-inline-code-bg"]=(lr=n["--persona-components-markdown-inlineCode-background"])!=null?lr:n["--persona-container"],n["--persona-md-inline-code-color"]=(yt=n["--persona-components-markdown-inlineCode-foreground"])!=null?yt:n["--persona-text"],n["--persona-md-link-color"]=(Ar=(Lo=n["--persona-components-markdown-link-foreground"])!=null?Lo:n["--persona-accent"])!=null?Ar:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let c=n["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(n["--persona-md-prose-font-family"]=c),n["--persona-md-code-block-bg"]=(Po=n["--persona-components-markdown-codeBlock-background"])!=null?Po:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Ln=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Ln:n["--persona-border"],n["--persona-md-code-block-text-color"]=(ss=n["--persona-components-markdown-codeBlock-textColor"])!=null?ss:"inherit",n["--persona-md-table-header-bg"]=(Zr=n["--persona-components-markdown-table-headerBackground"])!=null?Zr:n["--persona-container"],n["--persona-md-table-border-color"]=(_r=n["--persona-components-markdown-table-borderColor"])!=null?_r:n["--persona-border"],n["--persona-md-hr-color"]=(eo=n["--persona-components-markdown-hr-color"])!=null?eo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(to=n["--persona-components-markdown-blockquote-borderColor"])!=null?to:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Io=n["--persona-components-markdown-blockquote-background"])!=null?Io:"transparent",n["--persona-md-blockquote-text-color"]=(Ro=n["--persona-components-markdown-blockquote-textColor"])!=null?Ro:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(no=n["--persona-components-collapsibleWidget-container"])!=null?no:n["--persona-surface"],n["--cw-surface"]=(vt=n["--persona-components-collapsibleWidget-surface"])!=null?vt:n["--persona-surface"],n["--cw-border"]=(Dn=n["--persona-components-collapsibleWidget-border"])!=null?Dn:n["--persona-border"],n["--persona-message-border"]=(Nn=n["--persona-components-message-border"])!=null?Nn:n["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let g=p==null?void 0:p.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let b=p==null?void 0:p.artifact;if(b!=null&&b.toolbar){let Ce=b.toolbar;Ce.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=Ce.iconHoverColor),Ce.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=Ce.iconHoverBackground),Ce.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=Ce.iconPadding),Ce.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=Ce.iconBorderRadius),Ce.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=Ce.iconBorder),Ce.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Ce.toggleGroupGap),Ce.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=Ce.toggleBorderRadius),Ce.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=Ce.copyBackground),Ce.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=Ce.copyBorder),Ce.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=Ce.copyColor),Ce.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Ce.copyBorderRadius),Ce.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=Ce.copyPadding),Ce.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=Ce.copyMenuBackground,n["--persona-dropdown-bg"]=(wn=n["--persona-dropdown-bg"])!=null?wn:Ce.copyMenuBackground),Ce.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=Ce.copyMenuBorder,n["--persona-dropdown-border"]=(St=n["--persona-dropdown-border"])!=null?St:Ce.copyMenuBorder),Ce.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=Ce.copyMenuShadow,n["--persona-dropdown-shadow"]=(Vn=n["--persona-dropdown-shadow"])!=null?Vn:Ce.copyMenuShadow),Ce.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=Ce.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Kn=n["--persona-dropdown-radius"])!=null?Kn:Ce.copyMenuBorderRadius),Ce.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Ce.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(On=n["--persona-dropdown-item-hover-bg"])!=null?On:Ce.copyMenuItemHoverBackground),Ce.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=Ce.iconBackground),Ce.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=Ce.toolbarBorder)}if(b!=null&&b.tab){let Ce=b.tab;Ce.background&&(n["--persona-artifact-tab-bg"]=Ce.background),Ce.activeBackground&&(n["--persona-artifact-tab-active-bg"]=Ce.activeBackground),Ce.activeBorder&&(n["--persona-artifact-tab-active-border"]=Ce.activeBorder),Ce.borderRadius&&(n["--persona-artifact-tab-radius"]=Ce.borderRadius),Ce.textColor&&(n["--persona-artifact-tab-color"]=Ce.textColor),Ce.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=Ce.hoverBackground),Ce.listBackground&&(n["--persona-artifact-tab-list-bg"]=Ce.listBackground),Ce.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=Ce.listBorderColor),Ce.listPadding&&(n["--persona-artifact-tab-list-padding"]=Ce.listPadding)}if(b!=null&&b.pane){let Ce=b.pane;if(Ce.toolbarBackground){let $r=(ro=Ms(e,Ce.toolbarBackground))!=null?ro:Ce.toolbarBackground;n["--persona-artifact-toolbar-bg"]=$r}}return n}var Vx={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"};var Kx={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"}}},ng=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Za=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Gx=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Za()},rg=e=>Gx(e),Jx=e=>ua(e),Xx=e=>{var n;let t=ua(void 0,{validate:!1});return ua({...e,palette:{...t.palette,colors:{...Kx.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ma=e=>{let t=rg(e),n=ng(e==null?void 0:e.theme),r=ng(e==null?void 0:e.darkTheme);return t==="dark"?Xx(pa(n!=null?n:{},r!=null?r:{})):Jx(n)},Qx=e=>bl(e),es=(e,t)=>{let n=ma(t),r=Qx(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},xl=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Za())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Za());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};import{Idiomorph as Yx}from"idiomorph";var ei=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Yx.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var og=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var ti={index:-1,draft:""};function sg(e){let{direction:t,history:n,currentValue:r,atStart:o,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}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:{...ti}}}function ag(e,t){var n,r,o,s,a,i,d,c,p,u,f,g,b,v,S,T,L,P,E,k,C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe,ne,Ae,re,se,ae;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(b=(g=e.toolCall)==null?void 0:g.status)!=null?b:"",(S=(v=e.toolCall)==null?void 0:v.name)!=null?S:"",(P=(L=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:L.length)!=null?P:0,(I=(C=(k=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:k[e.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?I:"",typeof((j=e.toolCall)==null?void 0:j.args)=="string"?e.toolCall.args.length:($=e.toolCall)!=null&&$.args?JSON.stringify(e.toolCall.args).length:0,(O=(N=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:N.length)!=null?O:0,(ee=(de=(Ee=(Z=e.reasoning)==null?void 0:Z.chunks)==null?void 0:Ee[e.reasoning.chunks.length-1])==null?void 0:de.length)!=null?ee:0,(Ae=(ne=(Pe=(Le=e.reasoning)==null?void 0:Le.chunks)==null?void 0:Pe[e.reasoning.chunks.length-1])==null?void 0:ne.slice(-32))!=null?Ae:"",(se=(re=e.contentParts)==null?void 0:re.length)!=null?se:0,(ae=e.stopReason)!=null?ae:"",t].join("\0")}function ig(){return new Map}function lg(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function cg(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function dg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ni(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Br(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Co(e,t){return Br(e)-e.scrollTop<=t}function ri(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function oi(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return t&&n<0?"pause":!t&&o&&n>0&&r?"resume":"none"}function pg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function ug(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 mg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var nn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},xn=1e5,Ao=xn+1;var ga={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Zx=["pre","code","a","script","style"],si=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:ga.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ga.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:ga.speed,duration:(o=e==null?void 0:e.duration)!=null?o:ga.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ga.buffer}},fg=[{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"}],fa=new Map;for(let e of fg)fa.set(e.name,e);var ev=e=>{fa.set(e.name,e)},tv=e=>{fg.some(t=>t.name===e)||fa.delete(e)},nv=()=>Array.from(fa.keys()),ks=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=fa.get(e))!=null?r:null},ai=(e,t,n,r,o)=>{if(!o)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);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(`
|
|
19
|
-
`);return s<0?"":e.slice(0,s)}return e},rv=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},ov=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},vl=/\s/,sv=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},av=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(vl.test(s[i])){let c=i;for(;c<s.length&&vl.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let p=i;for(;p<s.length&&!vl.test(s[p]);)c.appendChild(rv(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(c),i=p}o.replaceChild(a,e)},iv=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(ov(r,c,t,n.value)),n.value+=1));o.replaceChild(a,e)},ha=(e,t,n,r)=>{var u,f;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((u=r==null?void 0:r.skipTags)!=null?u:Zx).map(g=>g.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)sv(d,s)||i.push(d),d=a.nextNode();let c={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?av:iv;for(let g of i)p(g,n,c);return o.innerHTML},ii=(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},ya=(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},gg=new WeakMap,lv=(e,t)=>{var s;if(!e.styles)return;let n=gg.get(t);if(n||(n=new Set,gg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},wl=new WeakMap,cv=(e,t)=>{if(!e.onAttach)return;let n=wl.get(t);if(n||(n=new Map,wl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},hg=e=>{let t=wl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},li=(e,t)=>{lv(e,t),cv(e,t)};function Cl(e,t=xn){let n=e.style.position,r=e.style.zIndex,o=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=r,e.style.isolation=o}}var ba=0,So=null;function Al(e=document){var n;if(ba++,ba===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;So={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,ba=Math.max(0,ba-1),ba===0&&So)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=So.originalOverflow,o.style.position=So.originalPosition,o.style.top=So.originalTop,o.style.width=So.originalWidth,s.scrollTo(0,So.scrollY),So=null}}}var xa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},dn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},To=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},nr=e=>{var n,r,o,s,a,i;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:xa.side,width:(o=t==null?void 0:t.width)!=null?o:xa.width,animate:(s=t==null?void 0:t.animate)!=null?s:xa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:xa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:xa.maxHeight}};var hr={"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 dv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ci=(e,t={})=>{var S,T,L,P,E,k;let{showClose:n=!0,wrapperClassName:r=dv,buttonSize:o,iconSize:s="28px"}=t,a=(S=e==null?void 0:e.launcher)!=null?S:{},i=(T=o!=null?o:a.closeButtonSize)!=null?T:"32px",d=y("div",r),c=(L=a.closeButtonTooltipText)!=null?L:"Close chat",p=(P=a.closeButtonShowTooltip)!=null?P:!0,u=(E=a.closeButtonIconName)!=null?E:"x",f=(k=a.closeButtonIconText)!=null?k:"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),b=Et("button",{className:Zs("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":c},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Mn.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}}),v=ye(u,s,"currentColor",1);if(v?(v.style.display="block",b.appendChild(v)):b.textContent=f,d.appendChild(b),p&&c){let C=null,I=()=>{if(C)return;let $=b.ownerDocument,R=$.body;if(!R)return;C=Wr($,"div","persona-clear-chat-tooltip"),C.textContent=c;let N=Wr($,"div");N.className="persona-clear-chat-tooltip-arrow",C.appendChild(N);let O=b.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(Ao),C.style.left=`${O.left+O.width/2}px`,C.style.top=`${O.top-8}px`,C.style.transform="translate(-50%, -100%)",R.appendChild(C)},j=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",I),d.addEventListener("mouseleave",j),b.addEventListener("focus",I),b.addEventListener("blur",j),d._cleanupTooltip=()=>{j(),d.removeEventListener("mouseenter",I),d.removeEventListener("mouseleave",j),b.removeEventListener("focus",I),b.removeEventListener("blur",j)}}return{button:b,wrapper:d}},pv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",di=(e,t={})=>{var C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe;let{wrapperClassName:n=pv,buttonSize:r,iconSize:o="20px"}=t,a=(I=((C=e==null?void 0:e.launcher)!=null?C:{}).clearChat)!=null?I:{},i=(j=r!=null?r:a.size)!=null?j:"32px",d=($=a.iconName)!=null?$:"refresh-cw",c=(R=a.iconColor)!=null?R:"",p=(N=a.backgroundColor)!=null?N:"",u=(O=a.borderWidth)!=null?O:"",f=(Z=a.borderColor)!=null?Z:"",g=(Ee=a.borderRadius)!=null?Ee:"",b=(de=a.paddingX)!=null?de:"",v=(ee=a.paddingY)!=null?ee:"",S=(Le=a.tooltipText)!=null?Le:"Clear chat",T=(Pe=a.showTooltip)!=null?Pe:!0,L=y("div",n),P=!!(u||f),E=Et("button",{className:Zs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!P&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":S},style:{height:i,width:i,color:c||Mn.actionIconColor,backgroundColor:p||void 0,border:P?`${u||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:b||void 0,paddingRight:b||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),k=ye(d,o,"currentColor",1);if(k&&(k.style.display="block",E.appendChild(k)),L.appendChild(E),T&&S){let ne=null,Ae=()=>{if(ne)return;let se=E.ownerDocument,ae=se.body;if(!ae)return;ne=Wr(se,"div","persona-clear-chat-tooltip"),ne.textContent=S;let fe=Wr(se,"div");fe.className="persona-clear-chat-tooltip-arrow",ne.appendChild(fe);let $e=E.getBoundingClientRect();ne.style.position="fixed",ne.style.zIndex=String(Ao),ne.style.left=`${$e.left+$e.width/2}px`,ne.style.top=`${$e.top-8}px`,ne.style.transform="translate(-50%, -100%)",ae.appendChild(ne)},re=()=>{ne&&ne.parentNode&&(ne.parentNode.removeChild(ne),ne=null)};L.addEventListener("mouseenter",Ae),L.addEventListener("mouseleave",re),E.addEventListener("focus",Ae),E.addEventListener("blur",re),L._cleanupTooltip=()=>{re(),L.removeEventListener("mouseenter",Ae),L.removeEventListener("mouseleave",re),E.removeEventListener("focus",Ae),E.removeEventListener("blur",re)}}return{button:E,wrapper:L}};var Mn={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))"},Eo=e=>{var k,C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe,ne,Ae;let{config:t,showClose:n=!0}=e,r=Et("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),o=(k=t==null?void 0:t.launcher)!=null?k:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(I=o.closeButtonPlacement)!=null?I:"inline",i=(j=o.headerIconHidden)!=null?j:!1,d=o.headerIconName,c=Et("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let re=parseFloat(s)||24,se=ye(d,re*.6,"currentColor",1);se?c.replaceChildren(se):c.textContent=(R=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?R:"\u{1F4AC}"}else if((N=t==null?void 0:t.launcher)!=null&&N.iconUrl){let re=y("img");re.src=t.launcher.iconUrl,re.alt="",re.className="persona-rounded-xl persona-object-cover",re.style.height=s,re.style.width=s,c.replaceChildren(re)}else c.textContent=(Z=(O=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?Z:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Et("span",{className:"persona-text-base persona-font-semibold",text:(de=(Ee=t==null?void 0:t.launcher)==null?void 0:Ee.title)!=null?de:"Chat Assistant",style:{color:Mn.titleColor}}),f=Et("span",{className:"persona-text-xs",text:(Le=(ee=t==null?void 0:t.launcher)==null?void 0:ee.subtitle)!=null?Le:"Here to help you get answers fast",style:{color:Mn.subtitleColor}});p.append(u,f),i?r.append(p):r.append(c,p);let g=(Pe=o.clearChat)!=null?Pe:{},b=(ne=g.enabled)!=null?ne:!0,v=(Ae=g.placement)!=null?Ae:"inline",S=null,T=null;if(b){let se=di(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=se.button,T=se.wrapper,v==="top-right"&&(T.style.right="48px"),v==="inline"&&r.appendChild(T)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&v==="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:P,wrapper:E}=ci(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&r.appendChild(E),{header:r,iconHolder:c,headerTitle:u,headerSubtitle:f,closeButton:P,closeButtonWrapper:E,clearChatButton:S,clearChatButtonWrapper:T}},Ls=(e,t,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function ts(e){let{items:t,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=e,a=y("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(Ao)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let S=document.createElement("hr");a.appendChild(S)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",g.id),g.destructive&&b.setAttribute("data-destructive",""),g.icon){let S=ye(g.icon,16,"currentColor",1.5);S&&b.appendChild(S)}let v=document.createElement("span");v.textContent=g.label,b.appendChild(v),b.addEventListener("click",S=>{S.stopPropagation(),p(),n(g.id)}),a.appendChild(b)}let i=null;function d(){if(!s)return;let g=r.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,o==="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 c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=b=>{!a.contains(b.target)&&!r.contains(b.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:p,toggle:u,destroy:f}}function Gt(e){let{icon:t,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=ye(t,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function pi(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let p=y("button",c);if(p.type="button",p.setAttribute("aria-label",n),t){let f=ye(t,s!=null?s:14,"currentColor",2);f&&p.appendChild(f)}let u=y("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))p.setAttribute(f,g);return p}function ui(e){let{items:t,selectedId:n,onSelect:r,className:o}=e,s=y("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let u;p.icon?u=Gt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(u=y("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),s.appendChild(u)}function c(p){a=p,d()}return{element:s,setSelected:c}}function Sl(e){var g,b;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,c=y("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",t);let p=y("span","persona-combo-btn-label");p.textContent=t,c.appendChild(p);let u=ye(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),d&&(c.style.borderRadius=(g=d.borderRadius)!=null?g:"10px",c.style.padding=(b=d.padding)!=null?b:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var v,S;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(S=d.border)!=null?S:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=ts({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),o(v)},anchor:c,position:s,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",v=>{v.stopPropagation();let S=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",S?"false":"true"),f.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{p.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var yg=e=>{var r;let t=Eo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.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",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function uv(e,t,n){var r,o,s;if(t!=null&&t.length)for(let a of t){let i=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=ye(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=y("div","persona-relative");d.appendChild(i);let c=ts({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var bg=e=>{var L,P,E,k,C,I,j,$,R;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(L=t==null?void 0:t.launcher)!=null?L:{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,p;if(d)c=Sl({label:(P=a.title)!=null?P:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Mn.titleColor,p=(E=c.querySelector(".persona-combo-btn-label"))!=null?E:c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=y("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Mn.titleColor,p.textContent=(k=a.title)!=null?k:"Chat Assistant",c.appendChild(p),uv(c,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let O=o.onTitleClick;c.addEventListener("click",Z=>{Z.target.closest("button")||O()}),c.addEventListener("keydown",Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),O())})}let N=o==null?void 0:o.titleRowHover;N&&(c.style.borderRadius=(I=N.borderRadius)!=null?I:"10px",c.style.padding=(j=N.padding)!=null?j:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var O,Z;c.style.backgroundColor=(O=N.background)!=null?O:"",c.style.borderColor=(Z=N.border)!=null?Z:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let u=($=a.closeButtonSize)!=null?$:"32px",f=y("div",""),g=y("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||Mn.actionIconColor;let b=(R=a.closeButtonIconName)!=null?R:"x",v=ye(b,"28px","currentColor",1);v?g.appendChild(v):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let S=y("div");S.style.display="none";let T=y("span");return T.style.display="none",{header:i,iconHolder:S,headerTitle:p,headerSubtitle:T,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Tl={default:yg,minimal:bg},xg=e=>{var t;return(t=Tl[e])!=null?t:Tl.default},va=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let c=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=y("div");p.style.display="none";let u=y("span"),f=y("span"),g=y("button");g.style.display="none";let b=y("div");return b.style.display="none",{header:c,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:g,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=xg(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0: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 mi=e=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"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,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());t.style.height=`${d}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}},gi=e=>{var k,C,I,j,$,R,N,O,Z,Ee,de,ee;let t=(k=e==null?void 0:e.sendButton)!=null?k:{},n=(C=t.useIcon)!=null?C:!1,r=(I=t.iconText)!=null?I:"\u2191",o=t.iconName,s=(j=t.stopIconName)!=null?j:"square",a=($=t.tooltipText)!=null?$:"Send message",i=(R=t.stopTooltipText)!=null?R:"Stop generating",d=(O=(N=e==null?void 0:e.copy)==null?void 0:N.sendButtonLabel)!=null?O:"Send",c=(Ee=(Z=e==null?void 0:e.copy)==null?void 0:Z.stopButtonLabel)!=null?Ee:"Stop",p=(de=t.showTooltip)!=null?de:!1,u=(ee=t.size)!=null?ee:"40px",f=t.backgroundColor,g=t.textColor,b=y("div","persona-send-button-wrapper"),v=Et("button",{className:Zs("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&&!f&&"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&&f||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}}),S=null,T=null;if(n){let Le=parseFloat(u)||24,Pe=(g==null?void 0:g.trim())||"currentColor";o?(S=ye(o,Le,Pe,2),S?v.appendChild(S):v.textContent=r):v.textContent=r,T=ye(s,Le,Pe,2)}else v.textContent=d;let L=null;p&&a&&(L=y("div","persona-send-button-tooltip"),L.textContent=a,b.appendChild(L)),v.setAttribute("aria-label",a),b.appendChild(v);let P="send";return{button:v,wrapper:b,setMode:Le=>{if(Le===P)return;P=Le;let Pe=Le==="stop"?i:a;if(v.setAttribute("aria-label",Pe),L&&(L.textContent=Pe),n){if(S&&T){let ne=Le==="stop"?T:S;v.replaceChildren(ne)}}else v.textContent=Le==="stop"?c:d}}},fi=e=>{var L,P,E,k,C,I,j,$,R,N,O,Z;let t=(L=e==null?void 0:e.voiceRecognition)!=null?L:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((P=t.provider)==null?void 0:P.type)==="runtype";if(!(r||o))return null;let a=(k=(E=e==null?void 0:e.sendButton)==null?void 0:E.size)!=null?k:"40px",i=(C=t.iconName)!=null?C:"mic",d=(I=t.iconSize)!=null?I:a,c=parseFloat(d)||24,p=($=t.backgroundColor)!=null?$:(j=e==null?void 0:e.sendButton)==null?void 0:j.backgroundColor,u=(N=t.iconColor)!=null?N:(R=e==null?void 0:e.sendButton)==null?void 0:R.textColor,f=y("div","persona-send-button-wrapper"),g=Et("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:p||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}}),v=ye(i,c,u||"currentColor",1.5);v?g.appendChild(v):g.textContent="\u{1F3A4}",f.appendChild(g);let S=(O=t.tooltipText)!=null?O:"Start voice recognition";if(((Z=t.showTooltip)!=null?Z:!1)&&S){let Ee=y("div","persona-send-button-tooltip");Ee.textContent=S,f.appendChild(Ee)}return{button:g,wrapper:f}},hi=e=>{var b,v,S,T,L,P,E,k;let t=(b=e==null?void 0:e.attachments)!=null?b:{};if(t.enabled!==!0)return null;let n=(S=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?S:"40px",r=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=y("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((T=t.allowedTypes)!=null?T:Gr).join(","),o.multiple=((L=t.maxFiles)!=null?L:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(P=t.buttonIconName)!=null?P:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=y("div","persona-send-button-wrapper"),p=Et("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(E=t.buttonTooltipText)!=null?E:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let u=ye(s,d,"currentColor",1.5);u?p.appendChild(u):p.textContent="\u{1F4CE}",p.addEventListener("click",C=>{C.preventDefault(),o.click()}),c.appendChild(p);let f=(k=t.buttonTooltipText)!=null?k:"Attach file",g=y("div","persona-send-button-tooltip");return g.textContent=f,c.appendChild(g),{button:p,wrapper:c,input:o,previewsContainer:r}},yi=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let c=y("a");c.href=t.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},bi=()=>Et("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var wa=e=>{var b,v,S,T,L,P;let{config:t}=e,n=Et("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=bi(),o=Et("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}=mi(t);a();let i=gi(t),d=fi(t),c=hi(t),p=yi(t);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let u=Et("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),f=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&f.append(c.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),u.append(f,g),o.append(u),o.addEventListener("click",E=>{E.target!==i.button&&E.target!==i.wrapper&&E.target!==(d==null?void 0:d.button)&&E.target!==(d==null?void 0:d.wrapper)&&E.target!==(c==null?void 0:c.button)&&E.target!==(c==null?void 0:c.wrapper)&&s.focus()}),n.append(r,o,p),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(b=d==null?void 0:d.button)!=null?b:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:p,attachmentButton:(S=c==null?void 0:c.button)!=null?S:null,attachmentButtonWrapper:(T=c==null?void 0:c.wrapper)!=null?T:null,attachmentInput:(L=c==null?void 0:c.input)!=null?L:null,attachmentPreviewsContainer:(P=c==null?void 0:c.previewsContainer)!=null?P:null,actionsRow:u,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var vg=()=>{let e=Et("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),n=ye("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=ye("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},wg=e=>{var b,v,S,T,L,P;let{config:t}=e,n=Et("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=bi();r.style.display="none";let o=yi(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=mi(t);s.style.maxHeight="100px",a();let i=gi(t),d=fi(t),c=hi(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let p=Et("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&u.append(c.wrapper);let f=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),p.addEventListener("click",E=>{E.target!==i.button&&E.target!==i.wrapper&&E.target!==(d==null?void 0:d.button)&&E.target!==(d==null?void 0:d.wrapper)&&E.target!==(c==null?void 0:c.button)&&E.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&p.append(c.input),p.append(u,s,f),c&&n.append(c.previewsContainer),n.append(p,r,o);let g=p;return{footer:n,suggestions:r,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(b=d==null?void 0:d.button)!=null?b:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:o,attachmentButton:(S=c==null?void 0:c.button)!=null?S:null,attachmentButtonWrapper:(T=c==null?void 0:c.wrapper)!=null?T:null,attachmentInput:(L=c==null?void 0:c.input)!=null?L:null,attachmentPreviewsContainer:(P=c==null?void 0:c.previewsContainer)!=null?P:null,actionsRow:g,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var Cg=e=>{var p,u,f,g,b,v,S,T,L,P,E,k,C,I,j,$,R;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=dn(e);if(To(e)){let N=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},O=y("div","persona-widget-wrapper persona-fixed persona-transition");O.setAttribute("data-persona-composer-bar",""),O.dataset.state="collapsed",O.dataset.expandedSize=(b=N.expandedSize)!=null?b:"anchored",O.style.zIndex=String((S=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?S:xn);let Z=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Z.style.width="100%",O.appendChild(Z);let Ee=y("div","persona-widget-pill-root");return Ee.setAttribute("data-persona-composer-bar",""),Ee.dataset.state="collapsed",Ee.dataset.expandedSize=(T=N.expandedSize)!=null?T:"anchored",Ee.style.zIndex=String((P=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?P:xn),{wrapper:O,panel:Z,pillRoot:Ee}}if(n){let N=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),O=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return N.appendChild(O),{wrapper:N,panel:O}}if(!t){let N=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),O=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(k=(E=e==null?void 0:e.launcher)==null?void 0:E.width)!=null?k:"100%";return N.style.width=Z,O.style.width="100%",N.appendChild(O),{wrapper:N,panel:O}}let o=(C=e==null?void 0:e.launcher)!=null?C:{},s=o.position&&hr[o.position]?hr[o.position]:hr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((j=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?j:xn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=($=e==null?void 0:e.launcher)==null?void 0:$.width)!=null?R:e==null?void 0:e.launcherWidth,c=d!=null?d:tr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},mv=(e,t)=>{var E,k,C,I,j,$,R,N,O;let n=y("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:r,wrapper:o}=ci(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(C=(k=(E=e==null?void 0:e.launcher)==null?void 0:E.clearChat)==null?void 0:k.enabled)!=null?C:!0,a=null,i=null;if(s){let Z=di(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Z.button,i=Z.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Et("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Et("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let p=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(j=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?j:"Hello \u{1F44B}"}),u=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=($=e==null?void 0:e.copy)==null?void 0:$.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),f=Et("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,u),g=y("div","persona-flex persona-flex-col persona-gap-3"),b=(N=e==null?void 0:e.layout)==null?void 0:N.contentMaxWidth;b&&(g.style.maxWidth=b,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(f.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(f,g);let S=Et("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"}}),T=wg({config:e}),{root:L,textNode:P}=vg();return n.append(d,o,c,S),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:g,composerOverlay:S,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:p,introSubtitle:u,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:L,peekTextNode:P}},Ag=(e,t=!0)=>{var S,T,L,P,E,k,C,I,j;if(To(e))return mv(e,t);let n=Et("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(S=e==null?void 0:e.layout)==null?void 0:S.header,o=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,s=r?va(e,r,{showClose:t}):Eo({config:e,showClose:t}),a=Et("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=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(P=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?P:"Hello \u{1F44B}"}),d=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(E=e==null?void 0:e.copy)==null?void 0:E.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),c=Et("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:dn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),p=y("div","persona-flex persona-flex-col persona-gap-3"),u=(C=e==null?void 0:e.layout)==null?void 0:C.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((I=e==null?void 0:e.copy)==null?void 0:I.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,p);let g=wa({config:e}),b=((j=e==null?void 0:e.layout)==null?void 0:j.showFooter)!==!1;o?Ls(n,s,e):(s.header.style.display="none",Ls(n,s,e)),n.append(a);let v=Et("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 b||(g.footer.style.display="none"),n.append(g.footer),n.append(v),{container:n,body:a,messagesWrapper:p,composerOverlay:v,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:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer: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 El=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
|
|
18
|
+
_Details: ${n.message}_`:r}var ma=e=>({isError:!0,content:[{type:"text",text:e}]}),sg=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,ag=e=>Jo(e)||e===Hr,ga=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 ks(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,o,s,a,i,d,c,p,u;if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let f=t.message.toolCall,g=!!(f!=null&&f.name)&&(Jo(f.name)||f.name===Hr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&g&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.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:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i: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 f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(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),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,o;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Es(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,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(){var o,s,a,i,d,c;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(o=t.host)!=null?o:this.config.apiUrl,r=(c=(d=t.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId)!=null?c:this.config.agentId;!n||!r||!this.config.clientToken||Cl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Za((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=ts.isSupported()?new ts({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let c=(r=t.host)!=null?r:this.config.apiUrl,p=(d=(i=t.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId)!=null?d:this.config.agentId,u=this.config.clientToken,f=t.browserFallback!==!1;if(c&&p&&u)return Cl().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:y})=>{let v=new g({host:c,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return f&&n?new y(v,n,{onFallback:A=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${A.message}`)}):v});if(f&&n)return u&&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){var n,r;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=es(o);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){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:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,o,s,a,i,d,c,p,u,f,g;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=t.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=t.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=t.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(u=t.runtype)==null?void 0:u.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((f=t.browser)==null?void 0:f.language)||"en-US",continuous:(g=t.browser)==null?void 0:g.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),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(){var t;return(t=this.clientSession)!=null?t: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(!Jy(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new Es(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:u}=t,g={id:a!=null?a:n==="user"?da():n==="assistant"?Yo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...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 r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:u=!1,voiceProcessing:f,rawContent:g}=r,v={id:d!=null?d:o==="user"?da():o==="assistant"?Yo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,c={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var c,p,u,f,g;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let o=da(),s=Yo();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||Xa,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(y){if(this.status==="resuming"||this.reconnecting)return;let v=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));if(!v){let A=Al(y,this.config.errorMessage);if(A){let T={id:s,role:"assistant",createdAt:new Date().toISOString(),content:A,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(y instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,y):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(y))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort(),this.teardownReconnect();let t=Yo();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let p=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!p){let u=Al(c,this.config.errorMessage);if(u){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(t,n){var s,a,i;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort(),n!=null&&n.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let r=n!=null&&n.preserveAssistantId?n.assistantMessageId:void 0,o=!1;for(let d of this.messages)d.streaming&&d.id!==r&&(d.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId,n==null?void 0:n.seedContent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(i=(a=this.callbacks).onError)==null||i.call(a,d instanceof Error?d:new Error(String(d)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,f,g,y;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(c?v=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let A=null;if(v instanceof Response){if(!v.ok){let T=await v.json().catch(()=>null);throw new Error((f=T==null?void 0:T.error)!=null?f:`Approval request failed: ${v.status}`)}A=v.body}else v instanceof ReadableStream&&(A=v);A?await this.connectStream(A,{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(v){let A=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,A||(y=(g=this.callbacks).onError)==null||y.call(g,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,f,g,y,v,A,T,L,W,R,P;let r=this.messages.find(S=>S.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!o||!s){(y=(g=this.callbacks).onError)==null||y.call(g,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 S=(v=t.toolCall)==null?void 0:v.args,H=Array.isArray(S==null?void 0:S.questions)?S.questions:[];if(H.length===1){let U=typeof((A=H[0])==null?void 0:A.question)=="string"?H[0].question:"";U&&(a={[U]:n})}}this.markAskUserQuestionResolved(t,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(L=t.toolCall)==null?void 0:L.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let S=typeof n=="string"?n:Object.entries(n).map(([H,U])=>`${H}: ${Array.isArray(U)?U.join(", "):U}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let S=a!=null?a:{};c.forEach((H,U)=>{let j=typeof(H==null?void 0:H.question)=="string"?H.question:"";if(!j)return;let k=S[j],O=Array.isArray(k)?k.join(", "):typeof k=="string"?k:"";this.appendMessage({id:`ask-user-q-${i}-${U}`,role:"assistant",content:j,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${U}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let S=await this.client.resumeFlow(o,{[s]:n});if(!S.ok){let H=await S.json().catch(()=>null);throw new Error((W=H==null?void 0:H.error)!=null?W:`Resume failed: ${S.status}`)}S.body?await this.connectStream(S.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(S){let H=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));this.setStreaming(!1),this.abortController=null,H||(P=(R=this.callbacks).onError)==null||P.call(R,S instanceof Error?S:new Error(String(S)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.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:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var o,s;let n=this.messages.find(a=>a.id===t.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,o;if(((r=t.toolCall)==null?void 0:r.name)!==Hr)return!1;let n=this.messages.find(s=>s.id===t.id);return((o=(n!=null?n:t).agentMetadata)==null?void 0:o.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,r,o=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:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,c,p,u;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async f=>{var P,S,H,U,j,k,O;let g=(P=f.toolCall)==null?void 0:P.name,y=(S=f.toolCall)==null?void 0:S.id;if(!g||!y)return null;let v=`${t}:${y}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(f))return null;this.webMcpInflightKeys.add(v),r.push(v);let A=this.markWebMcpToolRunning(f),T=(U=(H=f.agentMetadata)==null?void 0:H.webMcpToolCallId)!=null?U:g;if(g===Hr)return{dedupeKey:v,resumeKey:T,output:pl(),toolMessage:f,startedAt:A,completedAt:Date.now()};let L=new AbortController;this.webMcpResolveControllers.add(L),o.push(L);let W=this.client.executeWebMcpToolCall(g,(j=f.toolCall)==null?void 0:j.args,L.signal),R;if(!W)R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{R=await W}catch(F){let Z=F instanceof Error&&(F.name==="AbortError"||F.message.includes("aborted")||F.message.includes("abort"));return Z||(O=(k=this.callbacks).onError)==null||O.call(k,F instanceof Error?F:new Error(String(F))),this.markWebMcpToolComplete(f,ma(Z?"Aborted by cancel()":sg(F)),A),this.webMcpInflightKeys.delete(v),null}return L.signal.aborted?(this.markWebMcpToolComplete(f,ma("Aborted by cancel()"),A),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:T,output:R,toolMessage:f,startedAt:A,completedAt:Date.now()}})),i=[];try{if(i=a.filter(y=>y!==null),i.length===0)return;let f={};for(let y of i)f[y.resumeKey]=y.output;let g=await this.client.resumeFlow(t,f,{signal:s.signal});if(!g.ok){let y=await g.json().catch(()=>null);throw new Error((d=y==null?void 0:y.error)!=null?d:`Resume failed: ${g.status}`)}for(let y of i)this.webMcpResolvedKeys.add(y.dedupeKey),this.markWebMcpToolComplete(y.toolMessage,y.output,y.startedAt,y.completedAt,((c=y.toolMessage.toolCall)==null?void 0:c.name)===Hr?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,f instanceof Error?f:new Error(String(f)));else for(let y of i)this.markWebMcpToolComplete(y.toolMessage,ma("Aborted by cancel()"),y.startedAt)}finally{for(let f of r)this.webMcpInflightKeys.delete(f);for(let f of o)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var y,v,A,T,L,W,R,P,S,H,U,j;let n=(y=t.agentMetadata)==null?void 0:y.executionId,r=(v=t.toolCall)==null?void 0:v.name,o=(A=t.toolCall)==null?void 0:A.id;if(!n){(L=(T=this.callbacks).onError)==null||L.call(T,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let k=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(k)||this.webMcpResolvedKeys.has(k))return;this.webMcpInflightKeys.add(k);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(k)}catch(O){(R=(W=this.callbacks).onError)==null||R.call(W,O instanceof Error?O:new Error(String(O)))}finally{this.webMcpInflightKeys.delete(k)}return}let s=`${n}:${o}`;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:d}=i;this.setStreaming(!0);let c=r===Hr,p=(P=t.toolCall)==null?void 0:P.args,u=c?null:this.client.executeWebMcpToolCall(r,p,d),f="execute",g=a;try{let k;if(c?k=pl():u?k=await u:k={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ma("Aborted by cancel()"),a);return}let O=(H=(S=t.agentMetadata)==null?void 0:S.webMcpToolCallId)!=null?H:r;f="resume",await this.resumeWithToolOutput(n,O,k,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,k,a,g,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(k){let O=k instanceof Error&&(k.name==="AbortError"||k.message.includes("aborted")||k.message.includes("abort"));(f==="execute"||O||d.aborted)&&this.markWebMcpToolComplete(t,ma(O||d.aborted?"Aborted by cancel()":sg(k)),a),O||(j=(U=this.callbacks).onError)==null||j.call(U,k instanceof Error?k:new Error(String(k)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,o){var a,i;let s=await this.client.resumeFlow(t,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let 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(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.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){var o;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;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:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){var o,s;let n=(o=this.agentExecution)==null?void 0:o.executionId;if(!n||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var t;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((t=this.abortController)==null?void 0:t.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>{var n,r,o;return((n=t.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&((r=t.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||t.variant==="approval"&&((o=t.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var t,n;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(n=(t=this.callbacks).onReconnect)==null||n.call(t,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(r=>{this.reconnecting&&this.resumable&&r.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(og(),rg)).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,r,o)=>t.connectStream(n,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>{var r,o;return(o=(r=t.callbacks).onReconnect)==null?void 0:o.call(r,n)},buildErrorContent:n=>Al(new Error(n),t.config.errorMessage),onError:n=>{var r,o;return(o=(r=t.callbacks).onError)==null?void 0:o.call(r,n)}}}reconnectNow(){var t;if(this.reconnecting){(t=this.reconnectController)==null||t.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Yo(),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(){var t;this.reconnecting=!1,(t=this.reconnectController)==null||t.teardown(),this.clearResumable()}clearResumable(){var n,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&((r=(n=this.config).onExecutionState)==null||r.call(n,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(()=>{var r,o;this.executionStateTimer=null,(o=(r=this.config).onExecutionState)==null||o.call(r,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!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=wl(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return ua(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let r=wl(n.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"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),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var p,u,f,g,y,v,A,T,L,W,R,P,S,H,U;if(s!==r)return o;let a={...o,...n};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=o.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(f=a.agentMetadata)!=null?f:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let j=o.approval,k=n.approval;a.approval={...j,...k,executionId:k.executionId||j.executionId,toolName:k.toolName||j.toolName,description:k.description||j.description,toolType:(g=k.toolType)!=null?g:j.toolType,reason:(y=k.reason)!=null?y:j.reason,parameters:(v=k.parameters)!=null?v:j.parameters}}let i=(A=n.toolCall)==null?void 0:A.name,d=(T=n.agentMetadata)==null?void 0:T.executionId,c=(L=n.toolCall)==null?void 0:L.id;if(i&&ag(i)&&d&&c&&((W=n.agentMetadata)==null?void 0:W.awaitingLocalTool)===!0){let j=`${d}:${c}`,k=this.webMcpInflightKeys.has(j),O=this.webMcpResolvedKeys.has(j),F=(R=o.toolCall)==null?void 0:R.name,Z=((P=o.agentMetadata)==null?void 0:P.executionId)===d&&((S=o.toolCall)==null?void 0:S.id)===c&&F!==void 0&&ag(F)&&((H=o.toolCall)==null?void 0:H.status)==="complete";(k||O||Z)&&(a.agentMetadata={...(U=a.agentMetadata)!=null?U:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.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,r)=>{var d,c;let o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};import{Activity as Xy,ArrowDown as Qy,ArrowUp as Yy,ArrowUpRight as Zy,Bot as eb,ChevronDown as tb,ChevronUp as nb,ChevronRight as rb,ChevronLeft as ob,Check as sb,Clipboard as ab,ClipboardCopy as ib,Copy as lb,File as cb,FileCode as db,FileSpreadsheet as pb,FileText as ub,ImagePlus as mb,Loader as gb,LoaderCircle as fb,Mic as hb,Paperclip as yb,RefreshCw as bb,Search as xb,Send as vb,ShieldAlert as wb,ShieldCheck as Cb,ShieldX as Ab,Square as Sb,ThumbsDown as Tb,ThumbsUp as Eb,Upload as Mb,Volume2 as kb,X as Lb,User as Pb,Mail as Ib,Phone as Rb,Calendar as Wb,Clock as Hb,Building as Bb,MapPin as Db,Lock as Nb,Key as Ob,CreditCard as Fb,AtSign as _b,Hash as $b,Globe as jb,Link as Ub,CircleCheck as qb,CircleX as zb,TriangleAlert as Vb,Info as Kb,Ban as Gb,Shield as Jb,ArrowLeft as Xb,ArrowRight as Qb,ExternalLink as Yb,Ellipsis as Zb,EllipsisVertical as ex,Menu as tx,House as nx,Plus as rx,Minus as ox,Pencil as sx,Trash as ax,Trash2 as ix,Save as lx,Download as cx,Share as dx,Funnel as px,Settings as ux,RotateCw as mx,Maximize as gx,Minimize as fx,ShoppingCart as hx,ShoppingBag as yx,Package as bx,Truck as xx,Tag as vx,Gift as wx,Receipt as Cx,Wallet as Ax,Store as Sx,DollarSign as Tx,Percent as Ex,Play as Mx,Pause as kx,VolumeX as Lx,Camera as Px,Image as Ix,Film as Rx,Headphones as Wx,MessageCircle as Hx,MessageSquare as Bx,Bell as Dx,Heart as Nx,Star as Ox,Eye as Fx,EyeOff as _x,Bookmark as $x,CalendarDays as jx,History as Ux,Timer as qx,Folder as zx,FolderOpen as Vx,Files as Kx,Sparkles as Gx,Zap as Jx,Sun as Xx,Moon as Qx,Flag as Yx,Monitor as Zx,Smartphone as ev}from"lucide";var tv={activity:Xy,"arrow-down":Qy,"arrow-up":Yy,"arrow-up-right":Zy,bot:eb,"chevron-down":tb,"chevron-up":nb,"chevron-right":rb,"chevron-left":ob,check:sb,clipboard:ab,"clipboard-copy":ib,copy:lb,file:cb,"file-code":db,"file-spreadsheet":pb,"file-text":ub,"image-plus":mb,loader:gb,"loader-circle":fb,mic:hb,paperclip:yb,"refresh-cw":bb,search:xb,send:vb,"shield-alert":wb,"shield-check":Cb,"shield-x":Ab,square:Sb,"thumbs-down":Tb,"thumbs-up":Eb,upload:Mb,"volume-2":kb,x:Lb,user:Pb,mail:Ib,phone:Rb,calendar:Wb,clock:Hb,building:Bb,"map-pin":Db,lock:Nb,key:Ob,"credit-card":Fb,"at-sign":_b,hash:$b,globe:jb,link:Ub,"circle-check":qb,"circle-x":zb,"triangle-alert":Vb,info:Kb,ban:Gb,shield:Jb,"arrow-left":Xb,"arrow-right":Qb,"external-link":Yb,ellipsis:Zb,"ellipsis-vertical":ex,menu:tx,house:nx,plus:rx,minus:ox,pencil:sx,trash:ax,"trash-2":ix,save:lx,download:cx,share:dx,funnel:px,settings:ux,"rotate-cw":mx,maximize:gx,minimize:fx,"shopping-cart":hx,"shopping-bag":yx,package:bx,truck:xx,tag:vx,gift:wx,receipt:Cx,wallet:Ax,store:Sx,"dollar-sign":Tx,percent:Ex,play:Mx,pause:kx,"volume-x":Lx,camera:Px,image:Ix,film:Rx,headphones:Wx,"message-circle":Hx,"message-square":Bx,bell:Dx,heart:Nx,star:Ox,eye:Fx,"eye-off":_x,bookmark:$x,"calendar-days":jx,history:Ux,timer:qx,folder:zx,"folder-open":Vx,files:Kx,sparkles:Gx,zap:Jx,sun:Xx,moon:Qx,flag:Yx,monitor:Zx,smartphone:ev},ye=(e,t=24,n="currentColor",r=2)=>{let o=tv[e];return o?nv(o,t,n,r):(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 nv(e,t,n,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.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 d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),o.appendChild(d)}),o}var ni={allowedTypes:Qr,maxFileSize:10*1024*1024,maxFiles:4};function rv(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ov(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 Ls=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:ni.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:ni.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:ni.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:ni.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){var n,r,o,s,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let p=Gm(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,u);continue}try{let u=await Km(c),f=Ya(c)?URL.createObjectURL(c):null,g={id:rv(),file:c,previewUrl:f,contentPart:u};this.attachments.push(g),this.renderPreview(g)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ya(t.file),r=b("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=b("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",r.appendChild(a)}else{let a=b("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=ov(t.file.type),d=ye(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=b("span");c.textContent=Jm(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=b("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ye("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var ig=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function fa(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];ig(s)&&ig(o)?n[r]=fa(s,o):n[r]=o}return n}var tr="min(440px, calc(100vw - 24px))",Sl="440px",sv={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:tr,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)"},Dt={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:sv,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,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 lg(e,t){if(!(!e&&!t))return e?t?fa(e,t):e:t}function Tl(e){var t,n,r,o,s,a,i,d,c,p,u,f,g,y,v,A,T,L,W,R,P;return e?{...Dt,...e,theme:lg(Dt.theme,e.theme),darkTheme:lg(Dt.darkTheme,e.darkTheme),launcher:{...Dt.launcher,...e.launcher,dock:{...(t=Dt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Dt.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Dt.copy,...e.copy},sendButton:{...Dt.sendButton,...e.sendButton},statusIndicator:{...Dt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Dt.voiceRecognition,...e.voiceRecognition},features:(()=>{var re,se,ae,fe,$e,V,Q,Me,J,le;let S=(re=Dt.features)==null?void 0:re.artifacts,H=(se=e.features)==null?void 0:se.artifacts,U=(ae=Dt.features)==null?void 0:ae.scrollToBottom,j=(fe=e.features)==null?void 0:fe.scrollToBottom,k=($e=Dt.features)==null?void 0:$e.scrollBehavior,O=(V=e.features)==null?void 0:V.scrollBehavior,F=(Q=Dt.features)==null?void 0:Q.streamAnimation,Z=(Me=e.features)==null?void 0:Me.streamAnimation,Ee=(J=Dt.features)==null?void 0:J.askUserQuestion,de=(le=e.features)==null?void 0:le.askUserQuestion,ee=S===void 0&&H===void 0?void 0:{...S,...H,layout:{...S==null?void 0:S.layout,...H==null?void 0:H.layout}},Le=U===void 0&&j===void 0?void 0:{...U,...j},Pe=k===void 0&&O===void 0?void 0:{...k,...O},ne=F===void 0&&Z===void 0?void 0:{...F,...Z},Ae=Ee===void 0&&de===void 0?void 0:{...Ee,...de,styles:{...Ee==null?void 0:Ee.styles,...de==null?void 0:de.styles}};return{...Dt.features,...e.features,...Le!==void 0?{scrollToBottom:Le}:{},...Pe!==void 0?{scrollBehavior:Pe}:{},...ee!==void 0?{artifacts:ee}:{},...ne!==void 0?{streamAnimation:ne}:{},...Ae!==void 0?{askUserQuestion:Ae}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Dt.suggestionChips,suggestionChipsConfig:{...Dt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Dt.layout,...e.layout,header:{...(a=Dt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Dt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(u=(p=Dt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(v=(y=Dt.layout)==null?void 0:y.messages)==null?void 0:v.timestamp,...(T=(A=e.layout)==null?void 0:A.messages)==null?void 0:T.timestamp}},slots:{...(L=Dt.layout)==null?void 0:L.slots,...(W=e.layout)==null?void 0:W.slots}},markdown:{...Dt.markdown,...e.markdown,options:{...(R=Dt.markdown)==null?void 0:R.options,...(P=e.markdown)==null?void 0:P.options}},messageActions:{...Dt.messageActions,...e.messageActions}}:Dt}var cg={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"}},dg={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"}},pg={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:tr,maxWidth:Sl,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"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 Ps(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Ps(e,r):r}function El(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Ps(e,a);d!==void 0&&(t[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function ug(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 mg(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=mg(s,o):n[r]=o}return n}function av(e,t){return t?mg(e,t):e}function ha(e,t={}){var o,s,a,i,d,c,p,u,f,g,y,v,A;let n={palette:cg,semantic:dg,components:pg},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(y=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:y.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(A=e==null?void 0:e.semantic)==null?void 0:A.typography}},components:av(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=ug(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(L=>L.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)r=T.transform(r);return r}function Ml(e){var v,A,T,L,W,R,P,S,H,U,j,k,O,F,Z,Ee,de,ee,Le,Pe,ne,Ae,re,se,ae,fe,$e,V,Q,Me,J,le,Ie,he,Ke,gt,Wt,tt,ge,X,it,Ve,Se,we,Ze,qt,be,pe,Cn,Ct,yn,hr,yr,Ue,E,ue,Te,ke,He,nt,Qe,ht,me,B,xe,ce,ft,Je,Lt,Mt,xt,Rt,Xt,Ot,Zt,br,Nr,or,sr,Zr,zt,ar,Or,Hn,Pn,Bn,ir,xr,eo,zn,to,At,vr,wr,Fr,lr,yt,Io,Cr,Ro,In,is,no,_r,ro,oo,Wo,Ho,so,vt,Dn,Nn,An,St,Vn,Kn,On,ao;let t=El(e),n={};for(let[Ce,$r]of Object.entries(t)){let Gn=Ce.replace(/\./g,"-");n[`--persona-${Gn}`]=$r.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(A=n["--persona-semantic-colors-secondary"])!=null?A:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(T=n["--persona-semantic-colors-accent"])!=null?T:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(L=n["--persona-semantic-colors-surface"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(W=n["--persona-semantic-colors-background"])!=null?W:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(R=n["--persona-semantic-colors-container"])!=null?R:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(P=n["--persona-semantic-colors-text"])!=null?P:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(S=n["--persona-semantic-colors-text-muted"])!=null?S:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(H=n["--persona-semantic-colors-text-inverse"])!=null?H:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(U=n["--persona-semantic-colors-border"])!=null?U:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(j=n["--persona-semantic-colors-divider"])!=null?j:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(k=n["--persona-components-voice-recording-indicator"])!=null?k:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(O=n["--persona-components-voice-recording-background"])!=null?O:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(F=n["--persona-components-voice-processing-icon"])!=null?F:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(Z=n["--persona-components-voice-speaking-icon"])!=null?Z:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Ee=n["--persona-components-approval-requested-background"])!=null?Ee:n["--persona-surface"],n["--persona-approval-border"]=(de=n["--persona-components-approval-requested-border"])!=null?de:n["--persona-border"],n["--persona-approval-text"]=(ee=n["--persona-components-approval-requested-text"])!=null?ee:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Le=n["--persona-components-approval-requested-shadow"])!=null?Le:"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"]=(Pe=n["--persona-components-approval-approve-background"])!=null?Pe:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(ne=n["--persona-components-approval-deny-background"])!=null?ne:n["--persona-container"],n["--persona-attachment-image-bg"]=(Ae=n["--persona-components-attachment-image-background"])!=null?Ae:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(re=n["--persona-components-attachment-image-border"])!=null?re:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(se=n["--persona-semantic-typography-fontFamily"])!=null?se:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(ae=n["--persona-semantic-typography-fontSize"])!=null?ae:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(fe=n["--persona-semantic-typography-fontWeight"])!=null?fe:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=($e=n["--persona-semantic-typography-lineHeight"])!=null?$e: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"]=(V=n["--persona-palette-radius-sm"])!=null?V:"0.125rem",n["--persona-radius-md"]=(Q=n["--persona-palette-radius-md"])!=null?Q:"0.375rem",n["--persona-radius-lg"]=(Me=n["--persona-palette-radius-lg"])!=null?Me:"0.5rem",n["--persona-radius-xl"]=(J=n["--persona-palette-radius-xl"])!=null?J:"0.75rem",n["--persona-radius-full"]=(le=n["--persona-palette-radius-full"])!=null?le:"9999px",n["--persona-launcher-radius"]=(he=(Ie=n["--persona-components-launcher-borderRadius"])!=null?Ie:n["--persona-palette-radius-full"])!=null?he:"9999px",n["--persona-launcher-bg"]=(Ke=n["--persona-components-launcher-background"])!=null?Ke:n["--persona-primary"],n["--persona-launcher-fg"]=(gt=n["--persona-components-launcher-foreground"])!=null?gt:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Wt=n["--persona-components-launcher-border"])!=null?Wt:n["--persona-border"],n["--persona-button-primary-bg"]=(tt=n["--persona-components-button-primary-background"])!=null?tt:n["--persona-primary"],n["--persona-button-primary-fg"]=(ge=n["--persona-components-button-primary-foreground"])!=null?ge:n["--persona-text-inverse"],n["--persona-button-radius"]=(it=(X=n["--persona-components-button-primary-borderRadius"])!=null?X:n["--persona-palette-radius-full"])!=null?it:"9999px",n["--persona-panel-radius"]=(Se=(Ve=n["--persona-components-panel-borderRadius"])!=null?Ve:n["--persona-radius-xl"])!=null?Se:"0.75rem",n["--persona-panel-border"]=(we=n["--persona-components-panel-border"])!=null?we:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(qt=(Ze=n["--persona-components-panel-shadow"])!=null?Ze:n["--persona-palette-shadows-xl"])!=null?qt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(be=n["--persona-components-launcher-shadow"])!=null?be:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(Cn=(pe=n["--persona-components-input-borderRadius"])!=null?pe:n["--persona-radius-lg"])!=null?Cn:"0.5rem",n["--persona-message-user-radius"]=(yn=(Ct=n["--persona-components-message-user-borderRadius"])!=null?Ct:n["--persona-radius-lg"])!=null?yn:"0.5rem",n["--persona-message-assistant-radius"]=(yr=(hr=n["--persona-components-message-assistant-borderRadius"])!=null?hr:n["--persona-radius-lg"])!=null?yr:"0.5rem",n["--persona-header-bg"]=(Ue=n["--persona-components-header-background"])!=null?Ue:n["--persona-surface"],n["--persona-header-border"]=(E=n["--persona-components-header-border"])!=null?E:n["--persona-divider"],n["--persona-header-icon-bg"]=(ue=n["--persona-components-header-iconBackground"])!=null?ue:n["--persona-primary"],n["--persona-header-icon-fg"]=(Te=n["--persona-components-header-iconForeground"])!=null?Te:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(ke=n["--persona-components-header-titleForeground"])!=null?ke:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(He=n["--persona-components-header-subtitleForeground"])!=null?He:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(nt=n["--persona-components-header-actionIconForeground"])!=null?nt:n["--persona-muted"];let r=(Qe=e.components)==null?void 0:Qe.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(ht=e.components)==null?void 0:ht.introCard;n["--persona-intro-card-bg"]=(me=n["--persona-components-introCard-background"])!=null?me:n["--persona-surface"],n["--persona-intro-card-radius"]=(B=n["--persona-components-introCard-borderRadius"])!=null?B:"1rem",n["--persona-intro-card-padding"]=(xe=n["--persona-components-introCard-padding"])!=null?xe:"1.5rem",n["--persona-intro-card-shadow"]=(ft=(ce=o==null?void 0:o.shadow)!=null?ce:n["--persona-components-introCard-shadow"])!=null?ft:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Je=n["--persona-components-input-background"])!=null?Je:n["--persona-surface"],n["--persona-input-placeholder"]=(Lt=n["--persona-components-input-placeholder"])!=null?Lt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Mt=n["--persona-components-message-user-background"])!=null?Mt:n["--persona-accent"],n["--persona-message-user-text"]=(xt=n["--persona-components-message-user-text"])!=null?xt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Rt=n["--persona-components-message-user-shadow"])!=null?Rt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Xt=n["--persona-components-message-assistant-background"])!=null?Xt:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ot=n["--persona-components-message-assistant-text"])!=null?Ot:n["--persona-text"],n["--persona-message-assistant-border"]=(Zt=n["--persona-components-message-assistant-border"])!=null?Zt:n["--persona-border"],n["--persona-message-assistant-shadow"]=(br=n["--persona-components-message-assistant-shadow"])!=null?br:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(or=(Nr=n["--persona-components-scrollToBottom-background"])!=null?Nr:n["--persona-button-primary-bg"])!=null?or:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(Zr=(sr=n["--persona-components-scrollToBottom-foreground"])!=null?sr:n["--persona-button-primary-fg"])!=null?Zr:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(zt=n["--persona-components-scrollToBottom-border"])!=null?zt:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ar=n["--persona-components-scrollToBottom-size"])!=null?ar:"40px",n["--persona-scroll-to-bottom-radius"]=(Pn=(Hn=(Or=n["--persona-components-scrollToBottom-borderRadius"])!=null?Or:n["--persona-button-radius"])!=null?Hn:n["--persona-radius-full"])!=null?Pn:"9999px",n["--persona-scroll-to-bottom-shadow"]=(ir=(Bn=n["--persona-components-scrollToBottom-shadow"])!=null?Bn:n["--persona-palette-shadows-sm"])!=null?ir:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(xr=n["--persona-components-scrollToBottom-padding"])!=null?xr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(eo=n["--persona-components-scrollToBottom-gap"])!=null?eo:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(to=(zn=n["--persona-components-scrollToBottom-fontSize"])!=null?zn:n["--persona-palette-typography-fontSize-sm"])!=null?to:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(At=n["--persona-components-scrollToBottom-iconSize"])!=null?At:"14px",n["--persona-tool-bubble-shadow"]=(vr=n["--persona-components-toolBubble-shadow"])!=null?vr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(wr=n["--persona-components-reasoningBubble-shadow"])!=null?wr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Fr=n["--persona-components-composer-shadow"])!=null?Fr:"none",n["--persona-md-inline-code-bg"]=(lr=n["--persona-components-markdown-inlineCode-background"])!=null?lr:n["--persona-container"],n["--persona-md-inline-code-color"]=(yt=n["--persona-components-markdown-inlineCode-foreground"])!=null?yt:n["--persona-text"],n["--persona-md-link-color"]=(Cr=(Io=n["--persona-components-markdown-link-foreground"])!=null?Io:n["--persona-accent"])!=null?Cr:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let c=n["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(n["--persona-md-prose-font-family"]=c),n["--persona-md-code-block-bg"]=(Ro=n["--persona-components-markdown-codeBlock-background"])!=null?Ro:n["--persona-container"],n["--persona-md-code-block-border-color"]=(In=n["--persona-components-markdown-codeBlock-borderColor"])!=null?In:n["--persona-border"],n["--persona-md-code-block-text-color"]=(is=n["--persona-components-markdown-codeBlock-textColor"])!=null?is:"inherit",n["--persona-md-table-header-bg"]=(no=n["--persona-components-markdown-table-headerBackground"])!=null?no:n["--persona-container"],n["--persona-md-table-border-color"]=(_r=n["--persona-components-markdown-table-borderColor"])!=null?_r:n["--persona-border"],n["--persona-md-hr-color"]=(ro=n["--persona-components-markdown-hr-color"])!=null?ro:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(oo=n["--persona-components-markdown-blockquote-borderColor"])!=null?oo:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Wo=n["--persona-components-markdown-blockquote-background"])!=null?Wo:"transparent",n["--persona-md-blockquote-text-color"]=(Ho=n["--persona-components-markdown-blockquote-textColor"])!=null?Ho:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(so=n["--persona-components-collapsibleWidget-container"])!=null?so:n["--persona-surface"],n["--cw-surface"]=(vt=n["--persona-components-collapsibleWidget-surface"])!=null?vt:n["--persona-surface"],n["--cw-border"]=(Dn=n["--persona-components-collapsibleWidget-border"])!=null?Dn:n["--persona-border"],n["--persona-message-border"]=(Nn=n["--persona-components-message-border"])!=null?Nn:n["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let g=p==null?void 0:p.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let y=p==null?void 0:p.artifact;if(y!=null&&y.toolbar){let Ce=y.toolbar;Ce.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=Ce.iconHoverColor),Ce.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=Ce.iconHoverBackground),Ce.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=Ce.iconPadding),Ce.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=Ce.iconBorderRadius),Ce.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=Ce.iconBorder),Ce.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Ce.toggleGroupGap),Ce.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=Ce.toggleBorderRadius),Ce.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=Ce.copyBackground),Ce.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=Ce.copyBorder),Ce.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=Ce.copyColor),Ce.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Ce.copyBorderRadius),Ce.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=Ce.copyPadding),Ce.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=Ce.copyMenuBackground,n["--persona-dropdown-bg"]=(An=n["--persona-dropdown-bg"])!=null?An:Ce.copyMenuBackground),Ce.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=Ce.copyMenuBorder,n["--persona-dropdown-border"]=(St=n["--persona-dropdown-border"])!=null?St:Ce.copyMenuBorder),Ce.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=Ce.copyMenuShadow,n["--persona-dropdown-shadow"]=(Vn=n["--persona-dropdown-shadow"])!=null?Vn:Ce.copyMenuShadow),Ce.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=Ce.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Kn=n["--persona-dropdown-radius"])!=null?Kn:Ce.copyMenuBorderRadius),Ce.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Ce.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(On=n["--persona-dropdown-item-hover-bg"])!=null?On:Ce.copyMenuItemHoverBackground),Ce.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=Ce.iconBackground),Ce.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=Ce.toolbarBorder)}if(y!=null&&y.tab){let Ce=y.tab;Ce.background&&(n["--persona-artifact-tab-bg"]=Ce.background),Ce.activeBackground&&(n["--persona-artifact-tab-active-bg"]=Ce.activeBackground),Ce.activeBorder&&(n["--persona-artifact-tab-active-border"]=Ce.activeBorder),Ce.borderRadius&&(n["--persona-artifact-tab-radius"]=Ce.borderRadius),Ce.textColor&&(n["--persona-artifact-tab-color"]=Ce.textColor),Ce.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=Ce.hoverBackground),Ce.listBackground&&(n["--persona-artifact-tab-list-bg"]=Ce.listBackground),Ce.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=Ce.listBorderColor),Ce.listPadding&&(n["--persona-artifact-tab-list-padding"]=Ce.listPadding)}if(y!=null&&y.pane){let Ce=y.pane;if(Ce.toolbarBackground){let $r=(ao=Ps(e,Ce.toolbarBackground))!=null?ao:Ce.toolbarBackground;n["--persona-artifact-toolbar-bg"]=$r}}return n}var iv={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"};var lv={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"}}},gg=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ri=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},cv=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":ri()},fg=e=>cv(e),dv=e=>ha(e),pv=e=>{var n;let t=ha(void 0,{validate:!1});return ha({...e,palette:{...t.palette,colors:{...lv.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ya=e=>{let t=fg(e),n=gg(e==null?void 0:e.theme),r=gg(e==null?void 0:e.darkTheme);return t==="dark"?pv(fa(n!=null?n:{},r!=null?r:{})):dv(n)},uv=e=>Ml(e),ns=(e,t)=>{let n=ya(t),r=uv(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},kl=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(ri())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(ri());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};import{Idiomorph as mv}from"idiomorph";var oi=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;mv.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===o.getAttribute("data-tool-elapsed")?!1:void 0;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var hg=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var si={index:-1,draft:""};function yg(e){let{direction:t,history:n,currentValue:r,atStart:o,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}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:{...si}}}function bg(e,t){var n,r,o,s,a,i,d,c,p,u,f,g,y,v,A,T,L,W,R,P,S,H,U,j,k,O,F,Z,Ee,de,ee,Le,Pe,ne,Ae,re,se,ae;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(y=(g=e.toolCall)==null?void 0:g.status)!=null?y:"",(A=(v=e.toolCall)==null?void 0:v.name)!=null?A:"",(W=(L=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:L.length)!=null?W:0,(H=(S=(P=(R=e.toolCall)==null?void 0:R.chunks)==null?void 0:P[e.toolCall.chunks.length-1])==null?void 0:S.slice(-32))!=null?H:"",typeof((U=e.toolCall)==null?void 0:U.args)=="string"?e.toolCall.args.length:(j=e.toolCall)!=null&&j.args?JSON.stringify(e.toolCall.args).length:0,(F=(O=(k=e.reasoning)==null?void 0:k.chunks)==null?void 0:O.length)!=null?F:0,(ee=(de=(Ee=(Z=e.reasoning)==null?void 0:Z.chunks)==null?void 0:Ee[e.reasoning.chunks.length-1])==null?void 0:de.length)!=null?ee:0,(Ae=(ne=(Pe=(Le=e.reasoning)==null?void 0:Le.chunks)==null?void 0:Pe[e.reasoning.chunks.length-1])==null?void 0:ne.slice(-32))!=null?Ae:"",(se=(re=e.contentParts)==null?void 0:re.length)!=null?se:0,(ae=e.stopReason)!=null?ae:"",t].join("\0")}function xg(){return new Map}function vg(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function wg(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Cg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ai(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Br(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function So(e,t){return Br(e)-e.scrollTop<=t}function ii(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function li(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return t&&n<0?"pause":!t&&o&&n>0&&r?"resume":"none"}function Ag(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Sg(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 Tg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var tn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},wn=1e5,To=wn+1;var ba={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},gv=["pre","code","a","script","style"],ci=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:ba.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ba.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:ba.speed,duration:(o=e==null?void 0:e.duration)!=null?o:ba.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ba.buffer}},Mg=[{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"}],xa=new Map;for(let e of Mg)xa.set(e.name,e);var fv=e=>{xa.set(e.name,e)},hv=e=>{Mg.some(t=>t.name===e)||xa.delete(e)},yv=()=>Array.from(xa.keys()),Is=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=xa.get(e))!=null?r:null},di=(e,t,n,r,o)=>{if(!o)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);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(`
|
|
19
|
+
`);return s<0?"":e.slice(0,s)}return e},bv=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},xv=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},Ll=/\s/,vv=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},wv=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(Ll.test(s[i])){let c=i;for(;c<s.length&&Ll.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let p=i;for(;p<s.length&&!Ll.test(s[p]);)c.appendChild(bv(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(c),i=p}o.replaceChild(a,e)},Cv=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(xv(r,c,t,n.value)),n.value+=1));o.replaceChild(a,e)},va=(e,t,n,r)=>{var u,f;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((u=r==null?void 0:r.skipTags)!=null?u:gv).map(g=>g.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)vv(d,s)||i.push(d),d=a.nextNode();let c={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?wv:Cv;for(let g of i)p(g,n,c);return o.innerHTML},pi=(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},wa=(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},Eg=new WeakMap,Av=(e,t)=>{var s;if(!e.styles)return;let n=Eg.get(t);if(n||(n=new Set,Eg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},Pl=new WeakMap,Sv=(e,t)=>{if(!e.onAttach)return;let n=Pl.get(t);if(n||(n=new Map,Pl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},kg=e=>{let t=Pl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},ui=(e,t)=>{Av(e,t),Sv(e,t)};function Il(e,t=wn){let n=e.style.position,r=e.style.zIndex,o=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=r,e.style.isolation=o}}var Ca=0,Eo=null;function Rl(e=document){var n;if(Ca++,Ca===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;Eo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,Ca=Math.max(0,Ca-1),Ca===0&&Eo)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=Eo.originalOverflow,o.style.position=Eo.originalPosition,o.style.top=Eo.originalTop,o.style.width=Eo.originalWidth,s.scrollTo(0,Eo.scrollY),Eo=null}}}var Aa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},dn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},Mo=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},nr=e=>{var n,r,o,s,a,i;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:Aa.side,width:(o=t==null?void 0:t.width)!=null?o:Aa.width,animate:(s=t==null?void 0:t.animate)!=null?s:Aa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Aa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Aa.maxHeight}};var fr={"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 Tv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",mi=(e,t={})=>{var A,T,L,W,R,P;let{showClose:n=!0,wrapperClassName:r=Tv,buttonSize:o,iconSize:s="28px"}=t,a=(A=e==null?void 0:e.launcher)!=null?A:{},i=(T=o!=null?o:a.closeButtonSize)!=null?T:"32px",d=b("div",r),c=(L=a.closeButtonTooltipText)!=null?L:"Close chat",p=(W=a.closeButtonShowTooltip)!=null?W:!0,u=(R=a.closeButtonIconName)!=null?R:"x",f=(P=a.closeButtonIconText)!=null?P:"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),y=Et("button",{className:na("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":c},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Ln.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}}),v=ye(u,s,"currentColor",1);if(v?(v.style.display="block",y.appendChild(v)):y.textContent=f,d.appendChild(y),p&&c){let S=null,H=()=>{if(S)return;let j=y.ownerDocument,k=j.body;if(!k)return;S=Wr(j,"div","persona-clear-chat-tooltip"),S.textContent=c;let O=Wr(j,"div");O.className="persona-clear-chat-tooltip-arrow",S.appendChild(O);let F=y.getBoundingClientRect();S.style.position="fixed",S.style.zIndex=String(To),S.style.left=`${F.left+F.width/2}px`,S.style.top=`${F.top-8}px`,S.style.transform="translate(-50%, -100%)",k.appendChild(S)},U=()=>{S&&S.parentNode&&(S.parentNode.removeChild(S),S=null)};d.addEventListener("mouseenter",H),d.addEventListener("mouseleave",U),y.addEventListener("focus",H),y.addEventListener("blur",U),d._cleanupTooltip=()=>{U(),d.removeEventListener("mouseenter",H),d.removeEventListener("mouseleave",U),y.removeEventListener("focus",H),y.removeEventListener("blur",U)}}return{button:y,wrapper:d}},Ev="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",gi=(e,t={})=>{var S,H,U,j,k,O,F,Z,Ee,de,ee,Le,Pe;let{wrapperClassName:n=Ev,buttonSize:r,iconSize:o="20px"}=t,a=(H=((S=e==null?void 0:e.launcher)!=null?S:{}).clearChat)!=null?H:{},i=(U=r!=null?r:a.size)!=null?U:"32px",d=(j=a.iconName)!=null?j:"refresh-cw",c=(k=a.iconColor)!=null?k:"",p=(O=a.backgroundColor)!=null?O:"",u=(F=a.borderWidth)!=null?F:"",f=(Z=a.borderColor)!=null?Z:"",g=(Ee=a.borderRadius)!=null?Ee:"",y=(de=a.paddingX)!=null?de:"",v=(ee=a.paddingY)!=null?ee:"",A=(Le=a.tooltipText)!=null?Le:"Clear chat",T=(Pe=a.showTooltip)!=null?Pe:!0,L=b("div",n),W=!!(u||f),R=Et("button",{className:na("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!W&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":A},style:{height:i,width:i,color:c||Ln.actionIconColor,backgroundColor:p||void 0,border:W?`${u||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:y||void 0,paddingRight:y||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),P=ye(d,o,"currentColor",1);if(P&&(P.style.display="block",R.appendChild(P)),L.appendChild(R),T&&A){let ne=null,Ae=()=>{if(ne)return;let se=R.ownerDocument,ae=se.body;if(!ae)return;ne=Wr(se,"div","persona-clear-chat-tooltip"),ne.textContent=A;let fe=Wr(se,"div");fe.className="persona-clear-chat-tooltip-arrow",ne.appendChild(fe);let $e=R.getBoundingClientRect();ne.style.position="fixed",ne.style.zIndex=String(To),ne.style.left=`${$e.left+$e.width/2}px`,ne.style.top=`${$e.top-8}px`,ne.style.transform="translate(-50%, -100%)",ae.appendChild(ne)},re=()=>{ne&&ne.parentNode&&(ne.parentNode.removeChild(ne),ne=null)};L.addEventListener("mouseenter",Ae),L.addEventListener("mouseleave",re),R.addEventListener("focus",Ae),R.addEventListener("blur",re),L._cleanupTooltip=()=>{re(),L.removeEventListener("mouseenter",Ae),L.removeEventListener("mouseleave",re),R.removeEventListener("focus",Ae),R.removeEventListener("blur",re)}}return{button:R,wrapper:L}};var Ln={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))"},ko=e=>{var P,S,H,U,j,k,O,F,Z,Ee,de,ee,Le,Pe,ne,Ae;let{config:t,showClose:n=!0}=e,r=Et("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),o=(P=t==null?void 0:t.launcher)!=null?P:{},s=(S=o.headerIconSize)!=null?S:"48px",a=(H=o.closeButtonPlacement)!=null?H:"inline",i=(U=o.headerIconHidden)!=null?U:!1,d=o.headerIconName,c=Et("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let re=parseFloat(s)||24,se=ye(d,re*.6,"currentColor",1);se?c.replaceChildren(se):c.textContent=(k=(j=t==null?void 0:t.launcher)==null?void 0:j.agentIconText)!=null?k:"\u{1F4AC}"}else if((O=t==null?void 0:t.launcher)!=null&&O.iconUrl){let re=b("img");re.src=t.launcher.iconUrl,re.alt="",re.className="persona-rounded-xl persona-object-cover",re.style.height=s,re.style.width=s,c.replaceChildren(re)}else c.textContent=(Z=(F=t==null?void 0:t.launcher)==null?void 0:F.agentIconText)!=null?Z:"\u{1F4AC}";let p=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Et("span",{className:"persona-text-base persona-font-semibold",text:(de=(Ee=t==null?void 0:t.launcher)==null?void 0:Ee.title)!=null?de:"Chat Assistant",style:{color:Ln.titleColor}}),f=Et("span",{className:"persona-text-xs",text:(Le=(ee=t==null?void 0:t.launcher)==null?void 0:ee.subtitle)!=null?Le:"Here to help you get answers fast",style:{color:Ln.subtitleColor}});p.append(u,f),i?r.append(p):r.append(c,p);let g=(Pe=o.clearChat)!=null?Pe:{},y=(ne=g.enabled)!=null?ne:!0,v=(Ae=g.placement)!=null?Ae:"inline",A=null,T=null;if(y){let se=gi(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});A=se.button,T=se.wrapper,v==="top-right"&&(T.style.right="48px"),v==="inline"&&r.appendChild(T)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&v==="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:W,wrapper:R}=mi(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&r.appendChild(R),{header:r,iconHolder:c,headerTitle:u,headerSubtitle:f,closeButton:W,closeButtonWrapper:R,clearChatButton:A,clearChatButtonWrapper:T}},Rs=(e,t,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function rs(e){let{items:t,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=e,a=b("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(To)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let A=document.createElement("hr");a.appendChild(A)}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 A=ye(g.icon,16,"currentColor",1.5);A&&y.appendChild(A)}let v=document.createElement("span");v.textContent=g.label,y.appendChild(v),y.addEventListener("click",A=>{A.stopPropagation(),p(),n(g.id)}),a.appendChild(y)}let i=null;function d(){if(!s)return;let g=r.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,o==="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 c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=y=>{!a.contains(y.target)&&!r.contains(y.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:p,toggle:u,destroy:f}}function Gt(e){let{icon:t,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=ye(t,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function fi(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let p=b("button",c);if(p.type="button",p.setAttribute("aria-label",n),t){let f=ye(t,s!=null?s:14,"currentColor",2);f&&p.appendChild(f)}let u=b("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))p.setAttribute(f,g);return p}function hi(e){let{items:t,selectedId:n,onSelect:r,className:o}=e,s=b("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let u;p.icon?u=Gt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(u=b("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),s.appendChild(u)}function c(p){a=p,d()}return{element:s,setSelected:c}}function Wl(e){var g,y;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,c=b("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",t);let p=b("span","persona-combo-btn-label");p.textContent=t,c.appendChild(p);let u=ye(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),d&&(c.style.borderRadius=(g=d.borderRadius)!=null?g:"10px",c.style.padding=(y=d.padding)!=null?y:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var v,A;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(A=d.border)!=null?A:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=rs({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),o(v)},anchor:c,position:s,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",v=>{v.stopPropagation();let A=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",A?"false":"true"),f.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{p.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Lg=e=>{var r;let t=ko({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.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",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function Mv(e,t,n){var r,o,s;if(t!=null&&t.length)for(let a of t){let i=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=ye(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=b("div","persona-relative");d.appendChild(i);let c=rs({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Pg=e=>{var L,W,R,P,S,H,U,j,k;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(L=t==null?void 0:t.launcher)!=null?L:{},i=b("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,p;if(d)c=Wl({label:(W=a.title)!=null?W:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Ln.titleColor,p=(R=c.querySelector(".persona-combo-btn-label"))!=null?R:c;else{if(c=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=b("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Ln.titleColor,p.textContent=(P=a.title)!=null?P:"Chat Assistant",c.appendChild(p),Mv(c,o==null?void 0:o.trailingActions,(S=o==null?void 0:o.onAction)!=null?S:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let F=o.onTitleClick;c.addEventListener("click",Z=>{Z.target.closest("button")||F()}),c.addEventListener("keydown",Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),F())})}let O=o==null?void 0:o.titleRowHover;O&&(c.style.borderRadius=(H=O.borderRadius)!=null?H:"10px",c.style.padding=(U=O.padding)!=null?U:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var F,Z;c.style.backgroundColor=(F=O.background)!=null?F:"",c.style.borderColor=(Z=O.border)!=null?Z:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let u=(j=a.closeButtonSize)!=null?j:"32px",f=b("div",""),g=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");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||Ln.actionIconColor;let y=(k=a.closeButtonIconName)!=null?k:"x",v=ye(y,"28px","currentColor",1);v?g.appendChild(v):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let A=b("div");A.style.display="none";let T=b("span");return T.style.display="none",{header:i,iconHolder:A,headerTitle:p,headerSubtitle:T,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Hl={default:Lg,minimal:Pg},Ig=e=>{var t;return(t=Hl[e])!=null?t:Hl.default},Sa=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let c=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=b("div");p.style.display="none";let u=b("span"),f=b("span"),g=b("button");g.style.display="none";let y=b("div");return y.style.display="none",{header:c,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:g,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=Ig(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0: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 yi=e=>{var a,i;let t=b("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"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,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());t.style.height=`${d}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}},bi=e=>{var P,S,H,U,j,k,O,F,Z,Ee,de,ee;let t=(P=e==null?void 0:e.sendButton)!=null?P:{},n=(S=t.useIcon)!=null?S:!1,r=(H=t.iconText)!=null?H:"\u2191",o=t.iconName,s=(U=t.stopIconName)!=null?U:"square",a=(j=t.tooltipText)!=null?j:"Send message",i=(k=t.stopTooltipText)!=null?k:"Stop generating",d=(F=(O=e==null?void 0:e.copy)==null?void 0:O.sendButtonLabel)!=null?F:"Send",c=(Ee=(Z=e==null?void 0:e.copy)==null?void 0:Z.stopButtonLabel)!=null?Ee:"Stop",p=(de=t.showTooltip)!=null?de:!1,u=(ee=t.size)!=null?ee:"40px",f=t.backgroundColor,g=t.textColor,y=b("div","persona-send-button-wrapper"),v=Et("button",{className:na("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&&!f&&"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&&f||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}}),A=null,T=null;if(n){let Le=parseFloat(u)||24,Pe=(g==null?void 0:g.trim())||"currentColor";o?(A=ye(o,Le,Pe,2),A?v.appendChild(A):v.textContent=r):v.textContent=r,T=ye(s,Le,Pe,2)}else v.textContent=d;let L=null;p&&a&&(L=b("div","persona-send-button-tooltip"),L.textContent=a,y.appendChild(L)),v.setAttribute("aria-label",a),y.appendChild(v);let W="send";return{button:v,wrapper:y,setMode:Le=>{if(Le===W)return;W=Le;let Pe=Le==="stop"?i:a;if(v.setAttribute("aria-label",Pe),L&&(L.textContent=Pe),n){if(A&&T){let ne=Le==="stop"?T:A;v.replaceChildren(ne)}}else v.textContent=Le==="stop"?c:d}}},xi=e=>{var L,W,R,P,S,H,U,j,k,O,F,Z;let t=(L=e==null?void 0:e.voiceRecognition)!=null?L:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((W=t.provider)==null?void 0:W.type)==="runtype";if(!(r||o))return null;let a=(P=(R=e==null?void 0:e.sendButton)==null?void 0:R.size)!=null?P:"40px",i=(S=t.iconName)!=null?S:"mic",d=(H=t.iconSize)!=null?H:a,c=parseFloat(d)||24,p=(j=t.backgroundColor)!=null?j:(U=e==null?void 0:e.sendButton)==null?void 0:U.backgroundColor,u=(O=t.iconColor)!=null?O:(k=e==null?void 0:e.sendButton)==null?void 0:k.textColor,f=b("div","persona-send-button-wrapper"),g=Et("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:p||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}}),v=ye(i,c,u||"currentColor",1.5);v?g.appendChild(v):g.textContent="\u{1F3A4}",f.appendChild(g);let A=(F=t.tooltipText)!=null?F:"Start voice recognition";if(((Z=t.showTooltip)!=null?Z:!1)&&A){let Ee=b("div","persona-send-button-tooltip");Ee.textContent=A,f.appendChild(Ee)}return{button:g,wrapper:f}},vi=e=>{var y,v,A,T,L,W,R,P;let t=(y=e==null?void 0:e.attachments)!=null?y:{};if(t.enabled!==!0)return null;let n=(A=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?A:"40px",r=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=b("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((T=t.allowedTypes)!=null?T:Qr).join(","),o.multiple=((L=t.maxFiles)!=null?L:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(W=t.buttonIconName)!=null?W:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=b("div","persona-send-button-wrapper"),p=Et("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":(R=t.buttonTooltipText)!=null?R:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let u=ye(s,d,"currentColor",1.5);u?p.appendChild(u):p.textContent="\u{1F4CE}",p.addEventListener("click",S=>{S.preventDefault(),o.click()}),c.appendChild(p);let f=(P=t.buttonTooltipText)!=null?P:"Attach file",g=b("div","persona-send-button-tooltip");return g.textContent=f,c.appendChild(g),{button:p,wrapper:c,input:o,previewsContainer:r}},wi=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=b("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let c=b("a");c.href=t.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},Ci=()=>Et("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Ta=e=>{var y,v,A,T,L,W;let{config:t}=e,n=Et("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=Ci(),o=Et("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}=yi(t);a();let i=bi(t),d=xi(t),c=vi(t),p=wi(t);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let u=Et("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),f=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&f.append(c.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),u.append(f,g),o.append(u),o.addEventListener("click",R=>{R.target!==i.button&&R.target!==i.wrapper&&R.target!==(d==null?void 0:d.button)&&R.target!==(d==null?void 0:d.wrapper)&&R.target!==(c==null?void 0:c.button)&&R.target!==(c==null?void 0:c.wrapper)&&s.focus()}),n.append(r,o,p),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:p,attachmentButton:(A=c==null?void 0:c.button)!=null?A:null,attachmentButtonWrapper:(T=c==null?void 0:c.wrapper)!=null?T:null,attachmentInput:(L=c==null?void 0:c.input)!=null?L:null,attachmentPreviewsContainer:(W=c==null?void 0:c.previewsContainer)!=null?W:null,actionsRow:u,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var Rg=()=>{let e=Et("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=b("span","persona-pill-peek__icon"),n=ye("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=b("span","persona-pill-peek__text"),o=b("span","persona-pill-peek__caret"),s=ye("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},Wg=e=>{var y,v,A,T,L,W;let{config:t}=e,n=Et("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Ci();r.style.display="none";let o=wi(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=yi(t);s.style.maxHeight="100px",a();let i=bi(t),d=xi(t),c=vi(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let p=Et("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=b("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&u.append(c.wrapper);let f=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),p.addEventListener("click",R=>{R.target!==i.button&&R.target!==i.wrapper&&R.target!==(d==null?void 0:d.button)&&R.target!==(d==null?void 0:d.wrapper)&&R.target!==(c==null?void 0:c.button)&&R.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&p.append(c.input),p.append(u,s,f),c&&n.append(c.previewsContainer),n.append(p,r,o);let g=p;return{footer:n,suggestions:r,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:o,attachmentButton:(A=c==null?void 0:c.button)!=null?A:null,attachmentButtonWrapper:(T=c==null?void 0:c.wrapper)!=null?T:null,attachmentInput:(L=c==null?void 0:c.input)!=null?L:null,attachmentPreviewsContainer:(W=c==null?void 0:c.previewsContainer)!=null?W:null,actionsRow:g,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var Hg=e=>{var p,u,f,g,y,v,A,T,L,W,R,P,S,H,U,j,k;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=dn(e);if(Mo(e)){let O=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},F=b("div","persona-widget-wrapper persona-fixed persona-transition");F.setAttribute("data-persona-composer-bar",""),F.dataset.state="collapsed",F.dataset.expandedSize=(y=O.expandedSize)!=null?y:"anchored",F.style.zIndex=String((A=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?A:wn);let Z=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Z.style.width="100%",F.appendChild(Z);let Ee=b("div","persona-widget-pill-root");return Ee.setAttribute("data-persona-composer-bar",""),Ee.dataset.state="collapsed",Ee.dataset.expandedSize=(T=O.expandedSize)!=null?T:"anchored",Ee.style.zIndex=String((W=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?W:wn),{wrapper:F,panel:Z,pillRoot:Ee}}if(n){let O=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),F=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild(F),{wrapper:O,panel:F}}if(!t){let O=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),F=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(P=(R=e==null?void 0:e.launcher)==null?void 0:R.width)!=null?P:"100%";return O.style.width=Z,F.style.width="100%",O.appendChild(F),{wrapper:O,panel:F}}let o=(S=e==null?void 0:e.launcher)!=null?S:{},s=o.position&&fr[o.position]?fr[o.position]:fr["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((U=(H=e==null?void 0:e.launcher)==null?void 0:H.zIndex)!=null?U:wn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(k=(j=e==null?void 0:e.launcher)==null?void 0:j.width)!=null?k:e==null?void 0:e.launcherWidth,c=d!=null?d:tr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},kv=(e,t)=>{var R,P,S,H,U,j,k,O,F;let n=b("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:r,wrapper:o}=mi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(S=(P=(R=e==null?void 0:e.launcher)==null?void 0:R.clearChat)==null?void 0:P.enabled)!=null?S:!0,a=null,i=null;if(s){let Z=gi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Z.button,i=Z.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Et("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Et("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let p=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(U=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeTitle)!=null?U:"Hello \u{1F44B}"}),u=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(j=e==null?void 0:e.copy)==null?void 0:j.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),f=Et("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,u),g=b("div","persona-flex persona-flex-col persona-gap-3"),y=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;y&&(g.style.maxWidth=y,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((F=e==null?void 0:e.copy)==null?void 0:F.showWelcomeCard)!==!1||(f.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(f,g);let A=Et("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"}}),T=Wg({config:e}),{root:L,textNode:W}=Rg();return n.append(d,o,c,A),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:g,composerOverlay:A,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:p,introSubtitle:u,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:L,peekTextNode:W}},Bg=(e,t=!0)=>{var A,T,L,W,R,P,S,H,U;if(Mo(e))return kv(e,t);let n=Et("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(A=e==null?void 0:e.layout)==null?void 0:A.header,o=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,s=r?Sa(e,r,{showClose:t}):ko({config:e,showClose:t}),a=Et("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=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(W=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?W:"Hello \u{1F44B}"}),d=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(P=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeSubtitle)!=null?P:"Ask anything about your account or products."}),c=Et("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:dn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),p=b("div","persona-flex persona-flex-col persona-gap-3"),u=(S=e==null?void 0:e.layout)==null?void 0:S.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((H=e==null?void 0:e.copy)==null?void 0:H.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,p);let g=Ta({config:e}),y=((U=e==null?void 0:e.layout)==null?void 0:U.showFooter)!==!1;o?Rs(n,s,e):(s.header.style.display="none",Rs(n,s,e)),n.append(a);let v=Et("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(v),{container:n,body:a,messagesWrapper:p,composerOverlay:v,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:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer: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 Bl=(e,t)=>{let n=b("button");n.type="button",n.innerHTML=`
|
|
20
20
|
<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>
|
|
21
21
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
22
22
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -24,14 +24,14 @@ _Details: ${n.message}_`:r}var ca=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
24
24
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
25
25
|
</span>
|
|
26
26
|
<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>
|
|
27
|
-
`,n.addEventListener("click",t);let r=s=>{var P,E,k,C,I,j,$,R,N,O,Z,Ee,de;let a=(P=s.launcher)!=null?P:{},i=dn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ee=(E=a.title)!=null?E:"Chat Assistant";d.textContent=ee,d.setAttribute("title",ee)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let ee=(k=a.subtitle)!=null?k:"Here to help you get answers fast";c.textContent=ee,c.setAttribute("title",ee)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let ee=(C=a.agentIconSize)!=null?C:"40px";if(u.style.height=ee,u.style.width=ee,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 Le=parseFloat(ee)||24,Pe=ye(a.agentIconName,Le*.6,"var(--persona-text-inverse, #ffffff)",2);Pe?(u.appendChild(Pe),u.style.display=""):(u.textContent=(I=a.agentIconText)!=null?I:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(j=a.agentIconText)!=null?j:"\u{1F4AC}",u.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let ee=($=a.agentIconSize)!=null?$:"40px";f.style.height=ee,f.style.width=ee,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let ee=(R=a.callToActionIconSize)!=null?R:"32px";g.style.height=ee,g.style.width=ee,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 Le=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,Le=(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 Pe=parseFloat(ee)||24,ne=Math.max(Pe-Le,8),Ae=ye(a.callToActionIconName,ne,"currentColor",2);Ae?g.appendChild(Ae):g.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}else g.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}let b=a.position&&hr[a.position]?hr[a.position]:hr["bottom-right"],v="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",S="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?S:`${v} ${b}`,i||(n.style.zIndex=String((Z=a.zIndex)!=null?Z:xn));let T="1px solid var(--persona-border, #e5e7eb)",L="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(Ee=a.border)!=null?Ee:T,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:L,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=(de=a.collapsedMaxWidth)!=null?de:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:o}};var Sg=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:o}=Cg(e),s=Ag(e,t),a={wrapper:n,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:c,replaceHeader:f=>(d.element.replaceWith(f.header),d.element=f.header,d.iconHolder=f.iconHolder,d.headerTitle=f.headerTitle,d.headerSubtitle=f.headerSubtitle,d.closeButton=f.closeButton,d.closeButtonWrapper=f.closeButtonWrapper,d.clearChatButton=f.clearChatButton,d.clearChatButtonWrapper=f.clearChatButtonWrapper,f),replaceComposer:f=>{c.footer.replaceWith(f),c.footer=f}}},Ml=({config:e,plugins:t,onToggle:n})=>{let r=t.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:e,defaultRenderer:()=>El(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=El(e,n);return{instance:o,element:o.element}};var gv=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}},fv=(e,t)=>{if(!e)return null;let n=gv(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},hv=(e,t)=>{let n=y("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},yv=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(":"))},Ll=320,Eg=320,bv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),xv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),vv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),wv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Cv=(e,t,n)=>{if(e.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var u;let c=y("img");c.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Ll}px`,c.style.maxHeight=`${Eg}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,c.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{p=!0}),yv(i.image)?(c.src=i.image,r.appendChild(c)):(p=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},Av=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!kl(r.audio))return;let o=y("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ll}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Sv=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!kl(r.video))return;let o=y("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ll}px`,o.style.maxHeight=`${Eg}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Tv=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!kl(r.data))return;let o=y("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ps=()=>{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 r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(o),e},Mg=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Ps};if(t){let o=t(r);if(o!==null)return o}return Ps()},Ev=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=y("img");o.src=r,o.alt=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}else n.textContent=r,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},Tg=(e,t,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?r.textContent=t.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Mv=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];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},kg=(e,t,n)=>{var b,v,S,T,L,P,E;let r=(b=t.showCopy)!=null?b:!0,o=(v=t.showUpvote)!=null?v:!0,s=(S=t.showDownvote)!=null?S:!0,a=(T=t.showReadAloud)!=null?T:!1;if(!r&&!o&&!s&&!a){let k=y("div");return k.style.display="none",k.id=`actions-${e.id}`,k.setAttribute("data-actions-for",e.id),k}let i=(L=t.visibility)!=null?L:"hover",d=(P=t.align)!=null?P:"right",c=(E=t.layout)!=null?E:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],f=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);f.id=`actions-${e.id}`,f.setAttribute("data-actions-for",e.id);let g=(k,C,I)=>{let j=Gt({icon:k,label:C,size:14,className:"persona-message-action-btn"});return j.setAttribute("data-action",I),j};return r&&f.appendChild(g("copy","Copy message","copy")),a&&f.appendChild(g("volume-2","Read aloud","read-aloud")),o&&f.appendChild(g("thumbs-up","Upvote","upvote")),s&&f.appendChild(g("thumbs-down","Downvote","downvote")),f},Ca=(e,t,n,r,o,s)=>{var re,se,ae,fe,$e,V,Q,Me,J,le,Ie,he,Ke,gt,Wt,tt,ge;let a=n!=null?n:{},i=(re=a.layout)!=null?re:"bubble",d=a.avatar,c=a.timestamp,p=(se=d==null?void 0:d.show)!=null?se:!1,u=(ae=c==null?void 0:c.show)!=null?ae:!1,f=(fe=d==null?void 0:d.position)!=null?fe:"left",g=($e=c==null?void 0:c.position)!=null?$e:"below",b=Mv(e.role,i),v=y("div",b.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let S=bv(e),T=(Q=(V=e.content)==null?void 0:V.trim())!=null?Q:"",P=S.length>0&&T===Va,E=si((J=(Me=s==null?void 0:s.widgetConfig)==null?void 0:Me.features)==null?void 0:J.streamAnimation),k=(he=(Ie=(le=s==null?void 0:s.widgetConfig)==null?void 0:le.features)==null?void 0:Ie.streamAnimation)==null?void 0:he.plugins,C=e.role==="assistant"&&E.type!=="none"?ks(E.type,k):null,I=e.role==="assistant"&&((Ke=C==null?void 0:C.isAnimating)==null?void 0:Ke.call(C,e))===!0,j=e.role==="assistant"&&C!==null&&(!!e.streaming||I);j&&(C!=null&&C.bubbleClass)&&v.classList.add(C.bubbleClass);let $=document.createElement("div");$.classList.add("persona-message-content"),e.streaming&&$.classList.add("persona-content-streaming"),j&&C&&(C.containerClass&&$.classList.add(C.containerClass),$.style.setProperty("--persona-stream-step",`${E.speed}ms`),$.style.setProperty("--persona-stream-duration",`${E.duration}ms`));let R=j?ai((gt=e.content)!=null?gt:"",E.buffer,C,e,!!e.streaming):(Wt=e.content)!=null?Wt:"",N=t({text:R,message:e,streaming:!!e.streaming,raw:e.rawContent}),O=N;j&&(C==null?void 0:C.wrap)==="char"?O=ha(N,"char",e.id,{skipTags:C.skipTags}):j&&(C==null?void 0:C.wrap)==="word"&&(O=ha(N,"word",e.id,{skipTags:C.skipTags}));let Z=null;if(P?(Z=document.createElement("div"),Z.innerHTML=O,Z.style.display="none",$.appendChild(Z)):$.innerHTML=O,j&&(C!=null&&C.useCaret)&&!P&&T){let X=ii(),it=$.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ve=it[it.length-1];if(Ve!=null&&Ve.parentNode)Ve.parentNode.insertBefore(X,Ve.nextSibling);else{let Se=$.lastElementChild;Se?Se.appendChild(X):$.appendChild(X)}}if(u&&g==="inline"&&e.createdAt){let X=Tg(e,c,"span");X.classList.add("persona-timestamp-inline");let it=$.lastElementChild;it?it.appendChild(X):$.appendChild(X)}if(S.length>0){let X=Cv(S,!P&&!!T,()=>{P&&Z&&(Z.style.display="")});X?v.appendChild(X):P&&Z&&(Z.style.display="")}let Ee=xv(e);if(Ee.length>0){let X=Av(Ee);X&&v.appendChild(X)}let de=vv(e);if(de.length>0){let X=Sv(de);X&&v.appendChild(X)}let ee=wv(e);if(ee.length>0){let X=Tv(ee);X&&v.appendChild(X)}if(v.appendChild($),u&&g==="below"&&e.createdAt){let X=Tg(e,c);X.classList.add("persona-mt-1"),v.appendChild(X)}let Le=e.role==="assistant"?fv(e.stopReason,(ge=(tt=s==null?void 0:s.widgetConfig)==null?void 0:tt.copy)==null?void 0:ge.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(R&&R.trim()),it=E.placeholder==="skeleton",Ve=it&&E.buffer==="line"&&X;if(X)Ve&&v.appendChild(ya());else if(it)v.appendChild(ya());else{let Se=Mg("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Se&&v.appendChild(Se)}}if(Le&&e.stopReason&&!e.streaming&&(T||($.style.display="none"),v.appendChild(hv(e.stopReason,Le))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let X=kg(e,r,o);v.appendChild(X)}if(!p||e.role==="system")return v;let ne=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ae=Ev(d,e.role);return f==="right"||f==="left"&&e.role==="user"?ne.append(v,Ae):ne.append(Ae,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ne},kv=(e,t,n,r,o,s)=>{let a=n!=null?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}):Ca(e,t,n,r,o,s)};var Is=new Set,Lv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Pv=(e,t)=>{var r,o;let n=(o=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
28
|
-
`):""}
|
|
29
|
-
`);let o=
|
|
30
|
-
`):""},Il=(e,t)=>{var n,r,o;e.style.backgroundColor=(n=t.codeBlockBackgroundColor)!=null?n:"var(--persona-container, #f3f4f6)",e.style.borderColor=(r=t.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",e.style.color=(o=t.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},Wv=(e,t)=>{var p,u,f,g,b;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,o=(u=r==null?void 0:r.collapsedMode)!=null?u:"tool-call",s=Rv(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?Im(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(g=t==null?void 0:t.toolCall)!=null?g:{},c=a;return o==="tool-name"?c=((b=n.name)==null?void 0:b.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=ol(n,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=ol(n,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},Pg=(e,t,n)=>{var p;let r=Rs.has(e),o=(p=n==null?void 0:n.toolCall)!=null?p:{},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",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let u=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",f=ye(r?"chevron-up":"chevron-down",16,u,2);f?c.appendChild(f):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Rl=(e,t)=>{var O,Z,Ee,de,ee,Le,Pe,ne,Ae;let n=e.toolCall,r=(O=t==null?void 0:t.toolCall)!=null?O:{},o=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let s=(Ee=(Z=t==null?void 0:t.features)==null?void 0:Z.toolCallDisplay)!=null?Ee:{},a=s.expandable!==!1,i=a&&Rs.has(e.id),{summary:d,previewText:c,isActive:p}=Wv(e,t),u=y("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"),r.headerBackgroundColor&&(u.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(u.style.paddingLeft=r.headerPaddingX,u.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(u.style.paddingTop=r.headerPaddingY,u.style.paddingBottom=r.headerPaddingY);let f=y("div","persona-flex persona-flex-col persona-text-left"),g=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(g.style.color=r.headerTextColor);let b=String((de=n.startedAt)!=null?de:Date.now()),v=()=>{let re=y("span","");return re.setAttribute("data-tool-elapsed",b),re.textContent=oa(n),re},S=(Le=r.renderCollapsedSummary)==null?void 0:Le.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:(ee=s.collapsedMode)!=null?ee:"tool-call",isActive:p,config:t!=null?t:{},elapsed:oa(n),createElapsedElement:v});typeof S=="string"&&S.trim()?(g.textContent=S,f.appendChild(g)):S instanceof HTMLElement?f.appendChild(S):(g.textContent=d,f.appendChild(g));let T=(Pe=s.loadingAnimation)!=null?Pe:"none",L=r.activeTextTemplate,P=r.completeTextTemplate,E=p?L:P,k=S instanceof HTMLElement,C=(re,se,ae)=>{let fe=ae;for(let $e of se){let V=y("span","persona-tool-char");V.style.setProperty("--char-index",String(fe)),V.textContent=$e===" "?"\xA0":$e,re.appendChild(V),fe++}return fe},I=(re,se)=>{var V;g.textContent="";let ae=((V=n.name)==null?void 0:V.trim())||"tool",fe=qa(re,ae),$e=0;for(let Q of fe){let Me=Q.styles.length>0?(()=>{let J=y("span",Q.styles.map(le=>`persona-tool-text-${le}`).join(" "));return g.appendChild(J),J})():g;if(Q.isDuration&&p)Me.appendChild(v());else{let J=Q.isDuration?oa(n):Q.text;se?$e=C(Me,J,$e):Me.appendChild(document.createTextNode(J))}}};if(!k)if(p&&T!=="none"){let re=(ne=r.loadingAnimationDuration)!=null?ne:2e3;if(g.setAttribute("data-preserve-animation","true"),T==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${re}ms`),E&&I(E,!1);else if(g.classList.add(`persona-tool-loading-${T}`),g.style.setProperty("--persona-tool-anim-duration",`${re}ms`),T==="shimmer-color"&&(r.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),E)I(E,!0);else{let se=g.textContent||d;g.textContent="",C(g,se,0)}}else E&&I(E,!1);let j=null;if(a){j=y("div","persona-flex persona-items-center");let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=ye(i?"chevron-up":"chevron-down",16,re,2);se?j.appendChild(se):j.textContent=i?"Hide":"Show";let ae=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ae.append(j),u.append(f,ae)}else u.append(f);let $=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if($.setAttribute("data-persona-collapsed-preview","tool"),$.style.display="none",$.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&c){let re=(Ae=r.renderCollapsedPreview)==null?void 0:Ae.call(r,{message:e,toolCall:n,defaultPreview:c,isActive:p,config:t!=null?t:{}});Iv($,re)||($.textContent=c),$.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,$),o;let R=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(R.style.display=i?"":"none",r.contentBackgroundColor&&(R.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(R.style.color=r.contentTextColor),r.contentPaddingX&&(R.style.paddingLeft=r.contentPaddingX,R.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(R.style.paddingTop=r.contentPaddingY,R.style.paddingBottom=r.contentPaddingY),n.name){let re=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?re.style.color=r.contentTextColor:r.headerTextColor&&(re.style.color=r.headerTextColor),re.textContent=n.name,R.appendChild(re)}if(n.args!==void 0){let re=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Arguments";let ae=y("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");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Il(ae,r),ae.textContent=wo(n.args),re.append(se,ae),R.appendChild(re)}if(n.chunks&&n.chunks.length){let re=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Activity";let ae=y("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");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Il(ae,r),ae.textContent=n.chunks.join(""),re.append(se,ae),R.appendChild(re)}if(n.status==="complete"&&n.result!==void 0){let re=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Result";let ae=y("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");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Il(ae,r),ae.textContent=wo(n.result),re.append(se,ae),R.appendChild(re)}if(n.status==="complete"&&typeof n.duration=="number"){let re=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(re.style.color=r.contentTextColor),re.textContent=`Duration: ${n.duration}ms`,R.appendChild(re)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),j){j.innerHTML="";let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=ye(i?"chevron-up":"chevron-down",16,re,2);se?j.appendChild(se):j.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",$.style.display=i?"none":$.textContent||$.childNodes.length?"":"none"})(),o.append(u,$,R),o};var ns=new Map,xi=e=>{let n=(e.startsWith(Rr)?e.slice(Rr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Ig=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Rg=(e,t)=>{var r,o,s;let n=(o=(r=Ig(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=ns.get(e))!=null?s:n==="expanded"},Wg=(e,t,n)=>{var a,i;let r=Ig(n);e.setAttribute("aria-expanded",t?"true":"false");let o=e.querySelector("[data-approval-details-label]");o&&(o.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=ye(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},Hg=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=Rg(e,n);Wg(r,s,n),o.style.display=s?"":"none"};var vi=(e,t)=>{var I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe,ne,Ae,re;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(n==null?void 0:n.status)==="pending",s=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(I=r==null?void 0:r.backgroundColor)!=null?I:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(j=r==null?void 0:r.borderColor)!=null?j:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":($=r==null?void 0:r.titleColor)!=null?$:"currentColor",p=ye(d,20,c,2);p&&i.appendChild(p);let u=y("div","persona-flex-1 persona-min-w-0"),f=y("div","persona-flex persona-items-center persona-gap-2"),g=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(g.style.color=r.titleColor),g.textContent=(R=r==null?void 0:r.title)!=null?R:"Approval Required",f.appendChild(g),!o){let se=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");se.setAttribute("data-approval-status",n.status),n.status==="approved"?(se.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",se.style.color="var(--persona-palette-colors-success-700, #15803d)",se.textContent="Approved"):n.status==="denied"?(se.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",se.style.color="var(--persona-palette-colors-error-700, #b91c1c)",se.textContent="Denied"):n.status==="timeout"&&(se.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",se.style.color="var(--persona-palette-colors-warning-700, #b45309)",se.textContent="Timeout"),f.appendChild(se)}u.appendChild(f);let v=n.toolType==="webmcp"||n.toolName.startsWith(Rr)?Ys(n.toolName):void 0,S=(N=r==null?void 0:r.formatDescription)==null?void 0:N.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),T=!n.toolName,L=S||(T?n.description:`The assistant wants to use \u201C${v!=null?v:xi(n.toolName)}\u201D.`),P=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(P.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(P.style.color=r.descriptionColor),P.textContent=L,u.appendChild(P),n.reason){let se=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");se.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?se.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(se.style.color=r.descriptionColor);let ae=y("span","persona-font-medium");ae.textContent=`${(O=r==null?void 0:r.reasonLabel)!=null?O:"Agent's stated reason:"} `,se.appendChild(ae),se.appendChild(document.createTextNode(n.reason)),u.appendChild(se)}let E=(Z=r==null?void 0:r.detailsDisplay)!=null?Z:"collapsed",k=!!n.description&&!T,C=k||!!n.parameters;if(E!=="hidden"&&C){let se=Rg(e.id,t),ae=y("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");ae.type="button",ae.setAttribute("data-expand-header","true"),ae.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor);let fe=y("span");fe.setAttribute("data-approval-details-label","true");let $e=y("span","persona-inline-flex persona-items-center");$e.setAttribute("data-approval-details-chevron","true"),ae.append(fe,$e),Wg(ae,se,t),u.appendChild(ae);let V=y("div");if(V.setAttribute("data-approval-details","true"),V.style.display=se?"":"none",k){let Q=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(Q.style.color=r.descriptionColor),Q.textContent=n.description,V.appendChild(Q)}if(n.parameters){let Q=y("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(Q.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(Q.style.color=r.parameterTextColor),Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Q.textContent=wo(n.parameters),V.appendChild(Q)}u.appendChild(V)}if(o){let se=y("div","persona-flex persona-gap-2 persona-mt-2");se.setAttribute("data-approval-buttons","true");let ae=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");ae.type="button",ae.style.backgroundColor=(Ee=r==null?void 0:r.approveButtonColor)!=null?Ee:"var(--persona-approval-approve-bg, #22c55e)",ae.style.color=(de=r==null?void 0:r.approveButtonTextColor)!=null?de:"#ffffff",ae.setAttribute("data-approval-action","approve");let fe=ye("shield-check",14,(ee=r==null?void 0:r.approveButtonTextColor)!=null?ee:"#ffffff",2);fe&&(fe.style.marginRight="4px",ae.appendChild(fe));let $e=document.createTextNode((Le=r==null?void 0:r.approveLabel)!=null?Le:"Approve");ae.appendChild($e);let V=y("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");V.type="button",V.style.backgroundColor=(Pe=r==null?void 0:r.denyButtonColor)!=null?Pe:"transparent",V.style.color=(ne=r==null?void 0:r.denyButtonTextColor)!=null?ne:"var(--persona-feedback-error, #dc2626)",V.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,V.setAttribute("data-approval-action","deny");let Q=ye("shield-x",14,(Ae=r==null?void 0:r.denyButtonTextColor)!=null?Ae:"var(--persona-feedback-error, #dc2626)",2);Q&&(Q.style.marginRight="4px",V.appendChild(Q));let Me=document.createTextNode((re=r==null?void 0:r.denyLabel)!=null?re:"Deny");V.appendChild(Me),se.append(ae,V),u.appendChild(se)}return a.append(i,u),s.appendChild(a),s};function Hv(e){var n,r;let t=(n=e.getRootNode)==null?void 0:n.call(e);return t instanceof ShadowRoot?t:((r=e.ownerDocument)!=null?r:document).body}function Bg(e){var v;let{anchor:t,content:n,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=e,c=(v=e.container)!=null?v:Hv(t),p=!1,u=null,f=()=>{if(!p)return;let S=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${S.width}px`);let T=r==="top-start"||r==="top-end"?S.top-o-n.getBoundingClientRect().height:S.bottom+o,L=r==="bottom-end"||r==="top-end"?S.right-n.getBoundingClientRect().width:S.left;n.style.top=`${T}px`,n.style.left=`${L}px`},g=()=>{p&&(p=!1,u&&(u(),u=null),n.remove())},b=()=>{var k,C,I;if(p)return;p=!0,a!=null&&(n.style.zIndex=String(a)),c.appendChild(n),f();let S=(C=((k=t.ownerDocument)!=null?k:document).defaultView)!=null?C:window,T=(I=t.ownerDocument)!=null?I:document,L=()=>{if(!t.isConnected){g(),d==null||d("anchor-removed");return}f()},P=j=>{let $=typeof j.composedPath=="function"?j.composedPath():[];$.includes(n)||$.includes(t)||(g(),d==null||d("outside"))},E=S.setTimeout(()=>{T.addEventListener("pointerdown",P,!0)},0);S.addEventListener("scroll",L,!0),S.addEventListener("resize",L),u=()=>{S.clearTimeout(E),T.removeEventListener("pointerdown",P,!0),S.removeEventListener("scroll",L,!0),S.removeEventListener("resize",L)},i==null||i()};return{get isOpen(){return p},open:b,close:g,toggle:()=>p?g():b(),reposition:f,destroy:g}}function Dg(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Bv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Ng=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},rs=(e,t)=>{Ng(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)},Dv=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Nv=(e,t)=>{var r,o;let n=(r=t==null?void 0:t.detailsDisplay)!=null?r:"collapsed";return(o=ns.get(e))!=null?o:n==="expanded"},Wl=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},Ov=(e,t)=>{var c,p;let n=y("span","persona-approval-title");t!=null&&t.titleColor&&(n.style.color=t.titleColor);let o=e.toolType==="webmcp"||e.toolName.startsWith(Rr)?Ys(e.toolName):void 0,s=(p=t==null?void 0:t.formatDescription)==null?void 0:p.call(t,{toolName:e.toolName,toolType:e.toolType,description:(c=e.description)!=null?c:"",parameters:e.parameters,...o?{displayTitle:o}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=o!=null?o:xi(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),i){n.append(" from ");let u=document.createElement("strong");u.textContent=i,n.appendChild(u)}return n},Fv=e=>{let t=y("div","persona-approval-resolved"),n=ye("ban",15,"currentColor",2);n&&t.appendChild(n);let r=y("span","persona-approval-resolved-name");return r.textContent=e.toolName?xi(e.toolName):"Tool",t.append(r,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},_v=(e,t,n,r,o,s,a)=>{var j,$,R,N,O,Z,Ee;let i=y("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"),r!=null&&r.backgroundColor&&(i.style.background=r.backgroundColor),r!=null&&r.borderColor&&(i.style.borderColor=r.borderColor),(r==null?void 0:r.shadow)!==void 0&&(i.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let d=(j=r==null?void 0:r.detailsDisplay)!=null?j:"collapsed",c=!!n.description&&d!=="hidden",p=n.parameters!=null&&d!=="hidden",u=c||p,f=u&&Nv(t.id,r),g=($=r==null?void 0:r.showDetailsLabel)!=null?$:"Show details",b=(R=r==null?void 0:r.hideDetailsLabel)!=null?R:"Hide details",v=y("button","persona-approval-head");v.type="button",u?(v.setAttribute("data-action","toggle-params"),v.setAttribute("aria-expanded",f?"true":"false"),v.setAttribute("aria-label",f?b:g)):v.setAttribute("data-static","true");let S=y("span","persona-approval-logo"),T=ye("shield-check",16,"currentColor",2);T&&S.appendChild(T),v.appendChild(S);let L=Ov(n,r);if(u){let de=y("span","persona-approval-toggle");de.setAttribute("aria-hidden","true");let ee=ye("chevron-down",14,"currentColor",2);ee&&de.appendChild(ee),L.append(" "),L.appendChild(de)}v.appendChild(L),i.appendChild(v);let P=y("div","persona-approval-body");if(u){let de=y("div","persona-approval-details");if(de.setAttribute("data-role","params"),de.hidden=!f,c){let ee=y("p","persona-approval-desc");r!=null&&r.descriptionColor&&(ee.style.color=r.descriptionColor),ee.textContent=n.description,de.appendChild(ee)}if(p){let ee=y("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(ee.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ee.style.color=r.parameterTextColor),ee.textContent=wo(n.parameters),de.appendChild(ee)}P.appendChild(de)}if(n.reason){let de=y("p","persona-approval-reason");r!=null&&r.reasonColor?de.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(de.style.color=r.descriptionColor);let ee=y("span","persona-approval-reason-label");ee.textContent=`${(N=r==null?void 0:r.reasonLabel)!=null?N:"Agent's stated reason:"} `,de.append(ee,document.createTextNode(n.reason)),P.appendChild(de)}let E=y("div","persona-approval-actions"),k=null,C=de=>{r!=null&&r.approveButtonColor&&(de.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(de.style.color=r.approveButtonTextColor)},I=y("button","persona-approval-deny");if(I.type="button",I.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(I.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(I.style.color=r.denyButtonTextColor),I.append((O=r==null?void 0:r.denyLabel)!=null?O:"Deny"),a){let de=y("div","persona-approval-split"),ee=y("button","persona-approval-primary");ee.type="button",ee.setAttribute("data-action","always"),C(ee),ee.append((Z=r==null?void 0:r.approveLabel)!=null?Z:"Always allow",Wl("\u23CE"));let Le=y("button","persona-approval-caret");Le.type="button",Le.setAttribute("data-action","toggle-menu"),Le.setAttribute("aria-label","More options"),C(Le);let Pe=ye("chevron-down",15,"currentColor",2);Pe&&Le.appendChild(Pe),de.append(ee,Le),E.append(de,I),I.append(Wl("Esc"));let ne=y("div","persona-approval-menu"),Ae=y("button","persona-approval-menu-item");Ae.type="button",Ae.append("Allow once",Wl("\u2318\u23CE")),ne.appendChild(Ae),k=Bg({anchor:de,content:ne,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,k),Ae.addEventListener("click",()=>{rs(e,t.id),o()})}else{let de=y("button","persona-approval-primary persona-approval-primary--solo");de.type="button",de.setAttribute("data-action","allow"),C(de),de.append((Ee=r==null?void 0:r.approveLabel)!=null?Ee:"Allow"),E.append(de,I)}return P.appendChild(E),i.appendChild(P),i.addEventListener("click",de=>{let ee=de.target instanceof Element?de.target.closest("[data-action]"):null;if(!ee)return;let Le=ee.getAttribute("data-action");if(Le==="toggle-params"){let Pe=i.querySelector('[data-role="params"]');if(Pe){let ne=Pe.hidden;Pe.hidden=!ne,v.setAttribute("aria-expanded",ne?"true":"false"),v.setAttribute("aria-label",ne?b:g),ns.set(t.id,ne)}return}if(Le==="toggle-menu"){k==null||k.toggle();return}if(Le==="always"){rs(e,t.id),o({remember:!0});return}if(Le==="allow"){rs(e,t.id),o();return}if(Le==="deny"){rs(e,t.id),s();return}}),i},Og=()=>{let e=Bv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:o,deny:s,config:a})=>{let i=r==null?void 0:r.approval;if(!i)return null;let d=Dv(a);if(i.status!=="pending"){if(rs(e,r.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Fv(i)}Ng(e,r.id);let c=(d==null?void 0:d.enableAlwaysAllow)===!0,p=_v(e,r,i,d,o,s,c);if(c){e.pendingOrder.includes(r.id)||e.pendingOrder.push(r.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=f=>{Dg(f)||r.id===e.latestPendingApprovalId&&(f.key!=="Escape"&&f.key!=="Enter"||(f.preventDefault(),f.stopImmediatePropagation(),rs(e,r.id),f.key==="Escape"?s():f.metaKey||f.ctrlKey?o():o({remember:!0})))};e.keyHandlers.set(r.id,u),document.addEventListener("keydown",u)}return p}},teardown:()=>{for(let r of[...e.keyHandlers.keys(),...e.popovers.keys()])rs(e,r);e.latestPendingApprovalId=null}}};var Fg=e=>{let t=[],n=null;return{buttons:t,render:(o,s,a,i,d,c)=>{e.innerHTML="",t.length=0;let p=(c==null?void 0:c.agentPushed)===!0;if(p||(n=null),!o||!o.length||!p&&(i!=null?i:s?s.getMessages():[]).some(S=>S.role==="user"))return;let u=document.createDocumentFragment(),f=s?s.isStreaming():!1,g=b=>{switch(b){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(o.forEach(b=>{let v=y("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");v.type="button",v.textContent=b,v.disabled=f,d!=null&&d.fontFamily&&(v.style.fontFamily=g(d.fontFamily)),d!=null&&d.fontWeight&&(v.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(v.style.paddingLeft=d.paddingX,v.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(v.style.paddingTop=d.paddingY,v.style.paddingBottom=d.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:b},bubbles:!0,composed:!0})),s.sendMessage(b))}),u.appendChild(v),t.push(v)}),e.appendChild(u),p){let b=JSON.stringify(o);b!==n&&(n=b,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var Aa=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){var n;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),(n=this.store)==null||n.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 r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=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(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Sa=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 r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}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 r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}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(r){n(r)}})}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(r){n(r)}})}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(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}};var $v=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),jv=new Set(["step_start","execution_start"]),Uv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),qv=new Set(["step_complete","agent_turn_complete"]),zv=new Set(["flow_complete","agent_complete"]),_g=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),jg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,os=(e,t)=>{let n=e[t];return jg(n)?n:void 0};function Hl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function wi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Vv(e,t){return typeof t.type=="string"?t.type:e}function Kv(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 Gv(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 $g(e){var r,o,s,a,i;let t=os(e,"result"),n=[os(e,"tokens"),os(e,"totalTokens"),t?os(t,"tokens"):void 0,os(e,"usage"),t?os(t,"usage"):void 0];for(let d of n){if(!d)continue;let c=(o=(r=qn(d.output))!=null?r:qn(d.outputTokens))!=null?o:qn(d.completionTokens);if(c!==void 0)return c}return(i=(s=qn(e.outputTokens))!=null?s:qn(e.completionTokens))!=null?i:t?(a=qn(t.outputTokens))!=null?a:qn(t.completionTokens):void 0}function Jv(e){var n,r,o,s,a;let t=os(e,"result");return(a=(o=(r=(n=qn(e.executionTime))!=null?n:qn(e.executionTimeMs))!=null?r:qn(e.execution_time))!=null?o:qn(e.duration))!=null?a:t?(s=qn(t.executionTime))!=null?s:qn(t.executionTimeMs):void 0}function Xv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Ta=class{constructor(t=Xv){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:wi(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){var s;if(!jg(n)){_g.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Vv(t,n),o=this.now();if($v.has(r)){this.startRun(o);return}if(jv.has(r)){this.run||this.startRun(o);return}if(Uv.has(r)){if(!Gv(r,n))return;let a=Kv(n);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Hl(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:wi(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(qv.has(r)){if(!this.run)return;let a=this.run,i=$g(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+Hl(a.visibleCharCount),p=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:wi(c,p),outputTokens:c,durationMs:p,source:d?"usage":"estimate"};return}if(zv.has(r)){if(!this.run)return;let a=this.run,i=$g(n),d=i!=null?i:a.exactOutputTokens+Hl(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:wi(d,p),outputTokens:d,durationMs:p,source:c},this.run=null;return}if(_g.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let o=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=Jv(n);return s!=null?s:r-t.startedAt}};function Ws(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Qv={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)"}},Yv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Zv=["flowName","stepName","reasoningText","text","name","tool","toolName"],ew=100;function tw(e,t){let n={...Qv,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return Yv}function nw(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function rw(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${o}.${s}`}function ow(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let o=r.split("."),s=n;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function sw(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function aw(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 iw(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function lw(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 cw(e,t,n){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Bl(e,t,n,r,o,s,a,i){var f;let d=o.has(e.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Ws(c,(f=r.classNames)==null?void 0:f.eventRow);let p=a.find(g=>g.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let g=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(u()),c;function u(){var O,Z;let g=y("div",""),b=y("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");b.setAttribute("data-event-id",e.id);let v=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),S=ye(d?"chevron-down":"chevron-right","14px","currentColor",2);S&&v.appendChild(S);let T=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=(O=r.timestampFormat)!=null?O:"relative";T.textContent=L==="relative"?nw(e.timestamp,n):rw(e.timestamp);let P=null;r.showSequenceNumbers!==!1&&(P=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),P.textContent=String(t+1));let E=tw(e.type,r.badgeColors),k=y("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");k.style.backgroundColor=E.bg,k.style.color=E.text,k.style.borderColor=E.text+"50",k.textContent=e.type;let C=(Z=r.descriptionFields)!=null?Z:Zv,I=ow(e.payload,C),j=null;I&&(j=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),j.textContent=I);let $=y("div","persona-flex-1 persona-min-w-0"),R=y("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"),N=ye("clipboard","12px","currentColor",1.5);return N&&R.appendChild(N),R.addEventListener("click",async Ee=>{Ee.stopPropagation(),await sw(aw(e)),R.innerHTML="";let de=ye("check","12px","currentColor",1.5);de&&R.appendChild(de),setTimeout(()=>{R.innerHTML="";let ee=ye("clipboard","12px","currentColor",1.5);ee&&R.appendChild(ee)},1500)}),b.appendChild(v),b.appendChild(T),P&&b.appendChild(P),b.appendChild(k),j&&b.appendChild(j),b.appendChild($),b.appendChild(R),g.appendChild(b),d&&g.appendChild(cw(e,a,i)),g}}function Ug(e){var b,v,S,T,L;let{buffer:t,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=e,i=(b=o==null?void 0:o.features)==null?void 0:b.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",p=(S=i==null?void 0:i.label)!=null?S:"",u=(L=(T=o==null?void 0:o.features)==null?void 0:T.eventStream)!=null?L:{},f=s.find(P=>P.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&o){let P=f.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>g().element,onClose:r});if(P)return{element:P,update:()=>{},destroy:()=>{}}}return g();function g(){let P=u.classNames,E=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ws(E,P==null?void 0:P.panel);let k=[],C="",I="",j=null,$=[],R={},N=0,O=ni(),Z=0,Ee=0,de=!1,ee=null,Le=!1,Pe=0,ne=new Set,Ae=new Map,re="",se="",ae=null,fe,$e,V,Q,Me=null,J=null,le=null;function Ie(){let me=y("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),B=y("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(Ws(B,P==null?void 0:P.headerBar),a){J=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),J.style.cursor="help",Me=y("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"),Me.textContent="-- tok/s",le=y("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"),le.style.display="none",le.style.pointerEvents="none";let Ot=J,en=le,xr=()=>{if(!en.textContent)return;let or=Ot.getBoundingClientRect(),sr=me.getBoundingClientRect();en.style.left=`${or.left-sr.left}px`,en.style.top=`${or.bottom-sr.top+4}px`,en.style.display="block"},Nr=()=>{en.style.display="none"};J.addEventListener("mouseenter",xr),J.addEventListener("mouseleave",Nr),J.appendChild(Me)}let xe=y("div","persona-flex-1");fe=y("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 ce=y("option","");ce.value="",ce.textContent="All events (0)",fe.appendChild(ce),$e=y("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"),$e.type="button",$e.title="Copy All";let Je=ye("clipboard-copy","12px","currentColor",1.5);Je&&$e.appendChild(Je);let Lt=y("span","persona-event-copy-all persona-text-xs");Lt.textContent="Copy All",$e.appendChild(Lt),J&&B.appendChild(J),B.appendChild(xe),B.appendChild(fe),B.appendChild($e);let Mt=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ws(Mt,P==null?void 0:P.searchBar);let xt=ye("search","14px","var(--persona-muted, #9ca3af)",1.5),Rt=y("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");xt&&Rt.appendChild(xt),V=y("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"),Ws(V,P==null?void 0:P.searchInput),V.type="text",V.placeholder="Search event payloads...",Q=y("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"),Q.type="button",Q.style.display="none";let Xt=ye("x","12px","currentColor",2);return Xt&&Q.appendChild(Xt),Mt.appendChild(Rt),Mt.appendChild(V),Mt.appendChild(Q),me.appendChild(B),me.appendChild(Mt),le&&me.appendChild(le),me}let he,Ke=s.find(me=>me.renderEventStreamToolbar);if(Ke!=null&&Ke.renderEventStreamToolbar&&o){let me=Ke.renderEventStreamToolbar({config:o,defaultRenderer:()=>Ie(),eventCount:t.getSize(),filteredCount:0,onFilterChange:B=>{C=B,be(),Ct()},onSearchChange:B=>{I=B,be(),Ct()}});he=me!=null?me:Ie()}else he=Ie();let gt=y("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");gt.style.display="none";function Wt(){if(!a||!Me||!J)return;let me=a(),B=iw(me);Me.textContent=B;let xe=lw(me);le&&(le.textContent=xe,xe||(le.style.display="none")),J.setAttribute("aria-label",xe?`Throughput: ${B}, ${xe}`:`Throughput: ${B}`)}let tt=y("div","persona-flex-1 persona-min-h-0 persona-relative"),ge=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ge.style.height="100%";let X=y("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");Ws(X,P==null?void 0:P.scrollIndicator),X.style.display="none",X.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let it=ye(c,"14px","currentColor",2);it&&X.appendChild(it);let Ve=y("span","");Ve.textContent=p,X.appendChild(Ve);let Se=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Se.style.display="none",tt.appendChild(ge),tt.appendChild(Se),tt.appendChild(X),E.setAttribute("tabindex","0"),E.appendChild(he),E.appendChild(gt),E.appendChild(tt);function we(){let me=t.getAll(),B={};for(let Mt of me)B[Mt.type]=(B[Mt.type]||0)+1;let xe=Object.keys(B).sort(),ce=xe.length!==$.length||!xe.every((Mt,xt)=>Mt===$[xt]),ft=!ce&&xe.some(Mt=>B[Mt]!==R[Mt]),Je=me.length!==Object.values(R).reduce((Mt,xt)=>Mt+xt,0);if(!ce&&!ft&&!Je||($=xe,R=B,!fe))return;let Lt=fe.value;if(fe.options[0].textContent=`All events (${me.length})`,ce){for(;fe.options.length>1;)fe.remove(1);for(let Mt of xe){let xt=y("option","");xt.value=Mt,xt.textContent=`${Mt} (${B[Mt]||0})`,fe.appendChild(xt)}Lt&&xe.includes(Lt)?fe.value=Lt:Lt&&(fe.value="",C="")}else for(let Mt=1;Mt<fe.options.length;Mt++){let xt=fe.options[Mt];xt.textContent=`${xt.value} (${B[xt.value]||0})`}}function Ze(){let me=t.getAll();if(C&&(me=me.filter(B=>B.type===C)),I){let B=I.toLowerCase();me=me.filter(xe=>xe.type.toLowerCase().includes(B)||xe.payload.toLowerCase().includes(B))}return me}function qt(){return C!==""||I!==""}function be(){N=0,Z=0,O.resume(),X.style.display="none"}function pe(me){ne.has(me)?ne.delete(me):ne.add(me),ae=me;let B=ge.scrollTop,xe=O.isFollowing();Le=!0,O.pause(),Ct(),ge.scrollTop=B,xe&&O.resume(),Le=!1}function vn(){return Co(ge,50)}function Ct(){Ee=Date.now(),de=!1,Wt(),we();let me=t.getEvictedCount();me>0?(gt.textContent=`${me.toLocaleString()} older events truncated`,gt.style.display=""):gt.style.display="none",k=Ze();let B=k.length,xe=t.getSize()>0;B===0&&xe&&qt()?(Se.textContent=I?`No events matching '${I}'`:"No events matching filter",Se.style.display="",ge.style.display="none"):(Se.style.display="none",ge.style.display=""),$e&&($e.title=qt()?`Copy Filtered (${B})`:"Copy All"),d&&!O.isFollowing()&&B>N&&(Z+=B-N,Ve.textContent=p?`${p}${Z>0?` (${Z})`:""}`:"",X.style.display=""),N=B;let ce=t.getAll(),ft=ce.length>0?ce[0].timestamp:0,Je=new Set(k.map(xt=>xt.id));for(let xt of ne)Je.has(xt)||ne.delete(xt);let Lt=C!==re||I!==se,Mt=Ae.size===0&&k.length>0;if(Lt||Mt||k.length===0){ge.innerHTML="",Ae.clear();let xt=document.createDocumentFragment();for(let Rt=0;Rt<k.length;Rt++){let Xt=Bl(k[Rt],Rt,ft,u,ne,pe,s,o);Ae.set(k[Rt].id,Xt),xt.appendChild(Xt)}ge.appendChild(xt),re=C,se=I,ae=null}else{if(ae!==null){let Rt=Ae.get(ae);if(Rt&&Rt.parentNode===ge){let Xt=k.findIndex(Ot=>Ot.id===ae);if(Xt>=0){let Ot=Bl(k[Xt],Xt,ft,u,ne,pe,s,o);ge.insertBefore(Ot,Rt),Rt.remove(),Ae.set(ae,Ot)}}ae=null}let xt=new Set(k.map(Rt=>Rt.id));for(let[Rt,Xt]of Ae)xt.has(Rt)||(Xt.remove(),Ae.delete(Rt));for(let Rt=0;Rt<k.length;Rt++){let Xt=k[Rt];if(!Ae.has(Xt.id)){let Ot=Bl(Xt,Rt,ft,u,ne,pe,s,o);Ae.set(Xt.id,Ot),ge.appendChild(Ot)}}}O.isFollowing()&&(ge.scrollTop=ge.scrollHeight)}function fn(){if(Date.now()-Ee>=ew){ee!==null&&(cancelAnimationFrame(ee),ee=null),Ct();return}de||(de=!0,ee=requestAnimationFrame(()=>{ee=null,Ct()}))}let yr=(me,B)=>{if(!$e)return;$e.innerHTML="";let xe=ye(me,"12px","currentColor",1.5);xe&&$e.appendChild(xe);let ce=y("span","persona-text-xs");ce.textContent="Copy All",$e.appendChild(ce),setTimeout(()=>{$e.innerHTML="";let ft=ye("clipboard-copy","12px","currentColor",1.5);ft&&$e.appendChild(ft);let Je=y("span","persona-text-xs");Je.textContent="Copy All",$e.appendChild(Je),$e.disabled=!1},B)},br=async()=>{if($e){$e.disabled=!0;try{let me;qt()?me=k:n?(me=await n(),me.length===0&&(me=t.getAll())):me=t.getAll();let B=me.map(xe=>{try{return JSON.parse(xe.payload)}catch{return xe.payload}});await navigator.clipboard.writeText(JSON.stringify(B,null,2)),yr("check",1500)}catch{yr("x",1500)}}},Ue=()=>{fe&&(C=fe.value,be(),Ct())},M=()=>{!V||!Q||(Q.style.display=V.value?"":"none",j&&clearTimeout(j),j=setTimeout(()=>{I=V.value,be(),Ct()},150))},ue=()=>{!V||!Q||(V.value="",I="",Q.style.display="none",j&&clearTimeout(j),be(),Ct())},Te=()=>{if(Le)return;let me=ge.scrollTop,{action:B,nextLastScrollTop:xe}=ri({following:O.isFollowing(),currentScrollTop:me,lastScrollTop:Pe,nearBottom:vn(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Pe=xe,B==="resume"?(O.resume(),Z=0,X.style.display="none"):B==="pause"&&(O.pause(),d&&(Ve.textContent=p,X.style.display=""))},ke=me=>{let B=oi({following:O.isFollowing(),deltaY:me.deltaY,nearBottom:vn(),resumeWhenNearBottom:!0});B==="pause"?(O.pause(),d&&(Ve.textContent=p,X.style.display="")):B==="resume"&&(O.resume(),Z=0,X.style.display="none")},He=()=>{d&&(ge.scrollTop=ge.scrollHeight,O.resume(),Z=0,X.style.display="none")},nt=me=>{let B=me.target;if(!B||B.closest("button"))return;let xe=B.closest("[data-event-id]");if(!xe)return;let ce=xe.getAttribute("data-event-id");ce&&pe(ce)},Qe=me=>{if((me.metaKey||me.ctrlKey)&&me.key==="f"){me.preventDefault(),V==null||V.focus(),V==null||V.select();return}me.key==="Escape"&&(V&&document.activeElement===V?(ue(),V.blur(),E.focus()):r&&r())};$e&&$e.addEventListener("click",br),fe&&fe.addEventListener("change",Ue),V&&V.addEventListener("input",M),Q&&Q.addEventListener("click",ue),ge.addEventListener("scroll",Te),ge.addEventListener("wheel",ke,{passive:!0}),ge.addEventListener("click",nt),X.addEventListener("click",He),E.addEventListener("keydown",Qe);function ht(){j&&clearTimeout(j),ee!==null&&(cancelAnimationFrame(ee),ee=null),de=!1,Ae.clear(),$e&&$e.removeEventListener("click",br),fe&&fe.removeEventListener("change",Ue),V&&V.removeEventListener("input",M),Q&&Q.removeEventListener("click",ue),ge.removeEventListener("scroll",Te),ge.removeEventListener("wheel",ke),ge.removeEventListener("click",nt),X.removeEventListener("click",He),E.removeEventListener("keydown",Qe)}return{element:E,update:fn,destroy:ht}}}function qg(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",o=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(g)}else u.textContent=a;if(c.append(p,u),i.append(d,c),o==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var zg=(e,t)=>{var r,o,s;let n=(s=(o=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:t.config,defaultRenderer:()=>qg(e,t)});if(p)return p}return qg(e,t)};var Dl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},Mo=new Dl;Mo.register("PersonaArtifactCard",zg);function dw(e){var o;let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=e.props)!=null?o:{},null,2),t.appendChild(n),t.appendChild(r),t}function Vg(e,t){var $e,V,Q,Me;let n=(V=($e=e.features)==null?void 0:$e.artifacts)==null?void 0:V.layout,o=((Q=n==null?void 0:n.toolbarPreset)!=null?Q:"default")==="document",s=(Me=n==null?void 0:n.panePadding)==null?void 0:Me.trim(),a=e.markdown?vs(e.markdown):null,i=Xs(e.sanitize),d=J=>{let le=a?a(J):Kr(J);return i?i(le):le},c=typeof document!="undefined"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{c==null||c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),N==null||N.hide()};c&&c.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let u=y("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");u.setAttribute("data-persona-theme-zone","artifact-pane"),o&&u.classList.add("persona-artifact-pane-document");let f=y("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");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&f.classList.add("persona-artifact-toolbar-document");let g=y("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let b=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");b.type="button",b.textContent="Close",b.setAttribute("aria-label","Close artifacts panel"),b.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let v="rendered",S=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?Gt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Gt({icon:"eye",label:"Rendered view"}),L=o?Gt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Gt({icon:"code-2",label:"Source"}),P=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),E=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,k=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,C=n==null?void 0:n.documentToolbarCopyMenuItems,I=!!(k&&C&&C.length>0),j=null,$,R=null,N=null;if(o&&(E||k)&&!I){if($=E?pi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k){let J=ye("chevron-down",14,"currentColor",2);J&&$.appendChild(J)}}else o&&I?(j=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=E?pi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=Gt({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"}}),j.append($,R)):o?$=Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):$=Gt({icon:"copy",label:"Copy"});let O=o?Gt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"refresh-cw",label:"Refresh"}),Z=o?Gt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"x",label:"Close"}),Ee=()=>{var Ke,gt,Wt;let J=(Ke=Ae.find(tt=>tt.id===re))!=null?Ke:Ae[Ae.length-1],le=(gt=J==null?void 0:J.id)!=null?gt:null,Ie=(J==null?void 0:J.artifactType)==="markdown"&&(Wt=J.markdown)!=null?Wt:"",he=J?JSON.stringify({component:J.component,props:J.props},null,2):"";return{markdown:Ie,jsonPayload:he,id:le}},de=async()=>{var Ke;let{markdown:J,jsonPayload:le}=Ee(),Ie=(Ke=Ae.find(gt=>gt.id===re))!=null?Ke:Ae[Ae.length-1],he=(Ie==null?void 0:Ie.artifactType)==="markdown"?J:Ie?le:"";try{await navigator.clipboard.writeText(he)}catch{}};if($.addEventListener("click",async()=>{let J=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(J&&I){let{markdown:le,jsonPayload:Ie,id:he}=Ee();try{await J({actionId:"primary",artifactId:he,markdown:le,jsonPayload:Ie})}catch{}return}await de()}),R&&(C!=null&&C.length)){let J=()=>{var Ie;return(Ie=u.closest("[data-persona-root]"))!=null?Ie:document.body},le=()=>{N=ts({items:C.map(Ie=>({id:Ie.id,label:Ie.label})),onSelect:async Ie=>{let{markdown:he,jsonPayload:Ke,id:gt}=Ee(),Wt=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Wt?await Wt({actionId:Ie,artifactId:gt,markdown:he,jsonPayload:Ke}):Ie==="markdown"||Ie==="md"?await navigator.clipboard.writeText(he):Ie==="json"||Ie==="source"?await navigator.clipboard.writeText(Ke):await navigator.clipboard.writeText(he||Ke)}catch{}},anchor:j!=null?j:R,position:"bottom-right",portal:J()})};u.isConnected?le():requestAnimationFrame(le),R.addEventListener("click",Ie=>{Ie.stopPropagation(),N==null||N.toggle()})}O.addEventListener("click",async()=>{var J;try{await((J=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:J.call(n))}catch{}ae()}),Z.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let ee=()=>{o&&(T.setAttribute("aria-pressed",v==="rendered"?"true":"false"),L.setAttribute("aria-pressed",v==="source"?"true":"false"))};T.addEventListener("click",()=>{v="rendered",ee(),ae()}),L.addEventListener("click",()=>{v="source",ee(),ae()});let Le=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(f.replaceChildren(),S.append(T,L),j?P.append(j,O,Z):P.append($,O,Z),f.append(S,Le,P),ee()):(f.appendChild(g),f.appendChild(b)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let Pe=y("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"),ne=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Pe.style.paddingLeft=s,Pe.style.paddingRight=s,ne.style.padding=s),u.appendChild(f),u.appendChild(Pe),u.appendChild(ne);let Ae=[],re=null,se=!1,ae=()=>{var he,Ke,gt,Wt;let J=o&&Ae.length<=1;Pe.classList.toggle("persona-hidden",J),Pe.replaceChildren();for(let tt of Ae){let ge=y("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");ge.type="button",ge.textContent=tt.title||tt.id.slice(0,8),tt.id===re&&ge.classList.add("persona-bg-persona-container","persona-border-persona-border"),ge.addEventListener("click",()=>t.onSelect(tt.id)),Pe.appendChild(ge)}ne.replaceChildren();let le=re&&Ae.find(tt=>tt.id===re)||Ae[Ae.length-1];if(!le)return;if(o){let tt=le.artifactType==="markdown"?"MD":(he=le.component)!=null?he:"Component",X=(le.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Le.textContent=`${X} \xB7 ${tt}`}else g.textContent="Artifacts";if(le.artifactType==="markdown"){if(o&&v==="source"){let ge=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ge.textContent=(Ke=le.markdown)!=null?Ke:"",ne.appendChild(ge);return}let tt=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");tt.innerHTML=d((gt=le.markdown)!=null?gt:""),ne.appendChild(tt);return}let Ie=le.component?Mo.get(le.component):void 0;if(Ie){let ge={message:{id:le.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=Ie((Wt=le.props)!=null?Wt:{},ge);if(X){ne.appendChild(X);return}}catch{}}ne.appendChild(dw(le))},fe=()=>{var le;let J=Ae.length>0;if(u.classList.toggle("persona-hidden",!J),c){let Ie=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ke=((le=Ie==null?void 0:Ie.classList.contains("persona-artifact-narrow-host"))!=null?le:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;J&&Ke&&se?(c.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:c,update(J){var le,Ie,he;Ae=J.artifacts,re=(he=(Ie=J.selectedId)!=null?Ie:(le=J.artifacts[J.artifacts.length-1])==null?void 0:le.id)!=null?he:null,Ae.length>0&&(se=!0),ae(),fe()},setMobileOpen(J){se=J,!J&&c?(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):fe()}}}function rr(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Kg(e,t){var s,a,i,d;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"),!rr(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function pw(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")}function Ci(e,t){var d,c,p,u,f,g,b,v,S,T;if(!rr(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"),pw(e),Kg(e,t);return}let n=(c=(d=t.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(g=n==null?void 0:n.paneBackground)==null?void 0:g.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let o=(b=n==null?void 0:n.panePadding)==null?void 0:b.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(S=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:S.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Kg(e,t)}var Gg=["panel","seamless"];function Ai(e,t){var i,d,c,p,u,f;for(let g of Gg)e.classList.remove(`persona-artifact-appearance-${g}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!rr(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=n==null?void 0:n.paneAppearance)!=null?c:"panel",o=Gg.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let g=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function Jg(e,t){var n,r,o;return!t||!rr(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function uw(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function mw(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function gw(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function fw(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function Xg(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function Qg(e,t,n,r,o,s){let a=uw(o,200),i=fw(t,n,r,200);i=Math.max(a,i);let d=mw(s);return d!==null&&(i=Math.min(i,d)),gw(e,a,i)}var Yg={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"}},Nl=(e,t,n,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var b,v,S;if(s.dataset.enhanced==="true")return;let a=(b=s.dataset.tvForm)!=null?b:"init";s.dataset.enhanced="true";let i=(v=Yg[a])!=null?v:Yg.init;s.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),c=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let T=y("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var C,I;let L=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${t.id}-${a}-${T.name}`;let P=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=T.label,L.appendChild(P);let E=(C=T.type)!=null?C:"text",k;E==="textarea"?(k=document.createElement("textarea"),k.rows=3):(k=document.createElement("input"),k.type=E),k.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",k.id=`${t.id}-${a}-${T.name}`,k.name=T.name,k.placeholder=(I=T.placeholder)!=null?I:"",T.required&&(k.required=!0),L.appendChild(k),p.appendChild(L)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=y("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=(S=i.submitLabel)!=null?S:"Submit",u.appendChild(f),u.appendChild(g),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async T=>{var k,C;T.preventDefault();let L=(k=n.formEndpoint)!=null?k:"/form",P=new FormData(p),E={};P.forEach((I,j)=>{E[j]=I}),E.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let I=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let j=await I.json();f.textContent=(C=j.message)!=null?C:"Thanks! We'll be in touch soon.",j.success&&j.nextPrompt&&await r.sendMessage(String(j.nextPrompt))}catch(I){f.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Ol=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,o;return((r=n.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(s=>s.id));return[...n.filter(s=>!r.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Si=new Ol;var Zg=()=>{let e=new Map,t=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:t,off:n,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var hw=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},yw=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(n,o+1)}return null},Ti=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=hw(e),n=yw(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},Fl=e=>typeof e=="string"?e:e==null?"":String(e),Hs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Fl(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=Fl(n.element);if(r&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Fl(n.text)}}},ef=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ei=e=>{let t=new Set(ef(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(ef(e.getSessionMetadata().processedActionMessageIds))},r=()=>{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!="undefined"&&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((c,p)=>c||(p==null?void 0:p({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),r();let d={action:i,message:s.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",d)},u=c(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var bw=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},xw=e=>e.map(t=>({...t,streaming:!1})),vw=e=>e.map(t=>({...t,status:"complete"})),_l=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?bw(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?xw(n.messages):void 0,artifacts:n.artifacts?vw(n.artifacts):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as ww,STR as Cw,OBJ as Aw}from"partial-json";function Sw(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Tw(e,t){if(!Sw(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 $l(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let o=ww(n,Cw|Aw),s=Tw(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Ew(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function jl(e,t){let{config:n,message:r,onPropsUpdate:o}=t,s=Mo.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:r,config:n,updateProps:i=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Mw(){let e=$l();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function tf(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 Ul(e){let t=tf(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 ql(e){let t=tf(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 r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var kw=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function zl(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=kw}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=r,g.appendChild(b);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=o,g.appendChild(v),f.appendChild(g);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let C=1;C<=5;C++){let I=document.createElement("button");I.type="button",I.className="persona-feedback-rating-btn persona-feedback-star-btn",I.setAttribute("role","radio"),I.setAttribute("aria-checked","false"),I.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${c[C-1]}`),I.title=c[C-1],I.dataset.rating=String(C),I.innerHTML=`
|
|
27
|
+
`,n.addEventListener("click",t);let r=s=>{var W,R,P,S,H,U,j,k,O,F,Z,Ee,de;let a=(W=s.launcher)!=null?W:{},i=dn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ee=(R=a.title)!=null?R:"Chat Assistant";d.textContent=ee,d.setAttribute("title",ee)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let ee=(P=a.subtitle)!=null?P:"Here to help you get answers fast";c.textContent=ee,c.setAttribute("title",ee)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let ee=(S=a.agentIconSize)!=null?S:"40px";if(u.style.height=ee,u.style.width=ee,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 Le=parseFloat(ee)||24,Pe=ye(a.agentIconName,Le*.6,"var(--persona-text-inverse, #ffffff)",2);Pe?(u.appendChild(Pe),u.style.display=""):(u.textContent=(H=a.agentIconText)!=null?H:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(U=a.agentIconText)!=null?U:"\u{1F4AC}",u.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let ee=(j=a.agentIconSize)!=null?j:"40px";f.style.height=ee,f.style.width=ee,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let ee=(k=a.callToActionIconSize)!=null?k:"32px";g.style.height=ee,g.style.width=ee,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 Le=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,Le=(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 Pe=parseFloat(ee)||24,ne=Math.max(Pe-Le,8),Ae=ye(a.callToActionIconName,ne,"currentColor",2);Ae?g.appendChild(Ae):g.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else g.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}let y=a.position&&fr[a.position]?fr[a.position]:fr["bottom-right"],v="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",A="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?A:`${v} ${y}`,i||(n.style.zIndex=String((Z=a.zIndex)!=null?Z:wn));let T="1px solid var(--persona-border, #e5e7eb)",L="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(Ee=a.border)!=null?Ee:T,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:L,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=(de=a.collapsedMaxWidth)!=null?de:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:o}};var Dg=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:o}=Hg(e),s=Bg(e,t),a={wrapper:n,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:c,replaceHeader:f=>(d.element.replaceWith(f.header),d.element=f.header,d.iconHolder=f.iconHolder,d.headerTitle=f.headerTitle,d.headerSubtitle=f.headerSubtitle,d.closeButton=f.closeButton,d.closeButtonWrapper=f.closeButtonWrapper,d.clearChatButton=f.clearChatButton,d.clearChatButtonWrapper=f.clearChatButtonWrapper,f),replaceComposer:f=>{c.footer.replaceWith(f),c.footer=f}}},Dl=({config:e,plugins:t,onToggle:n})=>{let r=t.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:e,defaultRenderer:()=>Bl(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=Bl(e,n);return{instance:o,element:o.element}};var Lv=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}},Pv=(e,t)=>{if(!e)return null;let n=Lv(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},Iv=(e,t)=>{let n=b("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},Rv=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},Nl=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(":"))},Ol=320,Og=320,Wv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Hv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Bv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Dv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Nv=(e,t,n)=>{if(e.length===0)return null;try{let r=b("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var u;let c=b("img");c.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Ol}px`,c.style.maxHeight=`${Og}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,c.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{p=!0}),Rv(i.image)?(c.src=i.image,r.appendChild(c)):(p=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},Ov=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!Nl(r.audio))return;let o=b("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ol}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Fv=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!Nl(r.video))return;let o=b("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ol}px`,o.style.maxHeight=`${Og}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},_v=e=>{if(e.length===0)return null;try{let t=b("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!Nl(r.data))return;let o=b("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ws=()=>{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 r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(o),e},Fg=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Ws};if(t){let o=t(r);if(o!==null)return o}return Ws()},$v=(e,t)=>{let n=b("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=b("img");o.src=r,o.alt=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}else n.textContent=r,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},Ng=(e,t,n="div")=>{let r=b(n,"persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?r.textContent=t.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},jv=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];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},_g=(e,t,n)=>{var y,v,A,T,L,W,R;let r=(y=t.showCopy)!=null?y:!0,o=(v=t.showUpvote)!=null?v:!0,s=(A=t.showDownvote)!=null?A:!0,a=(T=t.showReadAloud)!=null?T:!1;if(!r&&!o&&!s&&!a){let P=b("div");return P.style.display="none",P.id=`actions-${e.id}`,P.setAttribute("data-actions-for",e.id),P}let i=(L=t.visibility)!=null?L:"hover",d=(W=t.align)!=null?W:"right",c=(R=t.layout)!=null?R:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],f=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);f.id=`actions-${e.id}`,f.setAttribute("data-actions-for",e.id);let g=(P,S,H)=>{let U=Gt({icon:P,label:S,size:14,className:"persona-message-action-btn"});return U.setAttribute("data-action",H),U};return r&&f.appendChild(g("copy","Copy message","copy")),a&&f.appendChild(g("volume-2","Read aloud","read-aloud")),o&&f.appendChild(g("thumbs-up","Upvote","upvote")),s&&f.appendChild(g("thumbs-down","Downvote","downvote")),f},Ea=(e,t,n,r,o,s)=>{var re,se,ae,fe,$e,V,Q,Me,J,le,Ie,he,Ke,gt,Wt,tt,ge;let a=n!=null?n:{},i=(re=a.layout)!=null?re:"bubble",d=a.avatar,c=a.timestamp,p=(se=d==null?void 0:d.show)!=null?se:!1,u=(ae=c==null?void 0:c.show)!=null?ae:!1,f=(fe=d==null?void 0:d.position)!=null?fe:"left",g=($e=c==null?void 0:c.position)!=null?$e:"below",y=jv(e.role,i),v=b("div",y.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let A=Wv(e),T=(Q=(V=e.content)==null?void 0:V.trim())!=null?Q:"",W=A.length>0&&T===Xa,R=ci((J=(Me=s==null?void 0:s.widgetConfig)==null?void 0:Me.features)==null?void 0:J.streamAnimation),P=(he=(Ie=(le=s==null?void 0:s.widgetConfig)==null?void 0:le.features)==null?void 0:Ie.streamAnimation)==null?void 0:he.plugins,S=e.role==="assistant"&&R.type!=="none"?Is(R.type,P):null,H=e.role==="assistant"&&((Ke=S==null?void 0:S.isAnimating)==null?void 0:Ke.call(S,e))===!0,U=e.role==="assistant"&&S!==null&&(!!e.streaming||H);U&&(S!=null&&S.bubbleClass)&&v.classList.add(S.bubbleClass);let j=document.createElement("div");j.classList.add("persona-message-content"),e.streaming&&j.classList.add("persona-content-streaming"),U&&S&&(S.containerClass&&j.classList.add(S.containerClass),j.style.setProperty("--persona-stream-step",`${R.speed}ms`),j.style.setProperty("--persona-stream-duration",`${R.duration}ms`));let k=U?di((gt=e.content)!=null?gt:"",R.buffer,S,e,!!e.streaming):(Wt=e.content)!=null?Wt:"",O=t({text:k,message:e,streaming:!!e.streaming,raw:e.rawContent}),F=O;U&&(S==null?void 0:S.wrap)==="char"?F=va(O,"char",e.id,{skipTags:S.skipTags}):U&&(S==null?void 0:S.wrap)==="word"&&(F=va(O,"word",e.id,{skipTags:S.skipTags}));let Z=null;if(W?(Z=document.createElement("div"),Z.innerHTML=F,Z.style.display="none",j.appendChild(Z)):j.innerHTML=F,U&&(S!=null&&S.useCaret)&&!W&&T){let X=pi(),it=j.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ve=it[it.length-1];if(Ve!=null&&Ve.parentNode)Ve.parentNode.insertBefore(X,Ve.nextSibling);else{let Se=j.lastElementChild;Se?Se.appendChild(X):j.appendChild(X)}}if(u&&g==="inline"&&e.createdAt){let X=Ng(e,c,"span");X.classList.add("persona-timestamp-inline");let it=j.lastElementChild;it?it.appendChild(X):j.appendChild(X)}if(A.length>0){let X=Nv(A,!W&&!!T,()=>{W&&Z&&(Z.style.display="")});X?v.appendChild(X):W&&Z&&(Z.style.display="")}let Ee=Hv(e);if(Ee.length>0){let X=Ov(Ee);X&&v.appendChild(X)}let de=Bv(e);if(de.length>0){let X=Fv(de);X&&v.appendChild(X)}let ee=Dv(e);if(ee.length>0){let X=_v(ee);X&&v.appendChild(X)}if(v.appendChild(j),u&&g==="below"&&e.createdAt){let X=Ng(e,c);X.classList.add("persona-mt-1"),v.appendChild(X)}let Le=e.role==="assistant"?Pv(e.stopReason,(ge=(tt=s==null?void 0:s.widgetConfig)==null?void 0:tt.copy)==null?void 0:ge.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(k&&k.trim()),it=R.placeholder==="skeleton",Ve=it&&R.buffer==="line"&&X;if(X)Ve&&v.appendChild(wa());else if(it)v.appendChild(wa());else{let Se=Fg("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Se&&v.appendChild(Se)}}if(Le&&e.stopReason&&!e.streaming&&(T||(j.style.display="none"),v.appendChild(Iv(e.stopReason,Le))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let X=_g(e,r,o);v.appendChild(X)}if(!p||e.role==="system")return v;let ne=b("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ae=$v(d,e.role);return f==="right"||f==="left"&&e.role==="user"?ne.append(v,Ae):ne.append(Ae,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ne},Uv=(e,t,n,r,o,s)=>{let a=n!=null?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}):Ea(e,t,n,r,o,s)};var Hs=new Set,qv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),zv=(e,t)=>{var r,o;let n=(o=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
|
|
28
|
+
`):""},$g=(e,t)=>{let n=Hs.has(e),r=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=ye(n?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=n?"Hide":"Show"}o.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Fl=(e,t)=>{var de,ee,Le,Pe,ne,Ae,re,se,ae,fe,$e;let n=e.reasoning,r=b("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let o=(ee=(de=t==null?void 0:t.features)==null?void 0:de.reasoningDisplay)!=null?ee:{},s=o.expandable!==!1,a=s&&Hs.has(e.id),i=n.status!=="complete",d=zv(e,(Le=o.previewMaxLines)!=null?Le:3),c=b("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",s&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let p=b("div","persona-flex persona-flex-col persona-text-left"),u=b("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(Pe=t==null?void 0:t.reasoning)!=null?Pe:{},y=String((ne=n.startedAt)!=null?ne:Date.now()),v=()=>{let V=b("span","");return V.setAttribute("data-tool-elapsed",y),V.textContent=Ka(n),V},A=(Ae=g.renderCollapsedSummary)==null?void 0:Ae.call(g,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ka(n),createElapsedElement:v});typeof A=="string"&&A.trim()?(u.textContent=A,p.appendChild(u)):A instanceof HTMLElement?p.appendChild(A):(u.textContent=f,p.appendChild(u));let T=b("span","persona-text-xs persona-text-persona-primary");T.textContent=jm(n),p.appendChild(T);let L=(re=o.loadingAnimation)!=null?re:"none",W=g.activeTextTemplate,R=g.completeTextTemplate,P=i?W:R,S=A instanceof HTMLElement,H=(V,Q,Me)=>{let J=Me;for(let le of Q){let Ie=b("span","persona-tool-char");Ie.style.setProperty("--char-index",String(J)),Ie.textContent=le===" "?"\xA0":le,V.appendChild(Ie),J++}return J},U=(V,Q)=>{u.textContent="";let Me=Ga(V,""),J=0;for(let le of Me){let Ie=le.styles.length>0?(()=>{let he=b("span",le.styles.map(Ke=>`persona-tool-text-${Ke}`).join(" "));return u.appendChild(he),he})():u;if(le.isDuration&&i)Ie.appendChild(v());else{let he=le.isDuration?Ka(n):le.text;Q?J=H(Ie,he,J):Ie.appendChild(document.createTextNode(he))}}};if(!S&&P)if(T.style.display="none",u.style.display="",i&&L!=="none"){let V=(se=g.loadingAnimationDuration)!=null?se:2e3;u.setAttribute("data-preserve-animation","true"),L==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),U(P,!1)):(u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),L==="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)),U(P,!0))}else U(P,!1);else if(!S&&i&&L!=="none"){u.style.display="";let V=(ae=g.loadingAnimationDuration)!=null?ae:2e3;if(u.setAttribute("data-preserve-animation","true"),L==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`);else{u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),L==="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 Q=u.textContent||f;u.textContent="",H(u,Q,0)}n.status==="complete"&&(u.style.display="none")}else S||(n.status==="complete"?u.style.display="none":u.style.display="");let j=null;if(s){j=b("div","persona-flex persona-items-center");let Q=ye(a?"chevron-up":"chevron-down",16,"currentColor",2);Q?j.appendChild(Q):j.textContent=a?"Hide":"Show";let Me=b("div","persona-flex persona-items-center persona-ml-auto");Me.append(j),c.append(p,Me)}else c.append(p);let k=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(k.setAttribute("data-persona-collapsed-preview","reasoning"),k.style.display="none",k.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let V=($e=(fe=t==null?void 0:t.reasoning)==null?void 0:fe.renderCollapsedPreview)==null?void 0:$e.call(fe,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});qv(k,V)||(k.textContent=d),k.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,k),r;let O=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");O.style.display=a?"":"none";let F=n.chunks.join(""),Z=b("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Z.textContent=F||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(Z),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),j){j.innerHTML="";let Q=ye(a?"chevron-up":"chevron-down",16,"currentColor",2);Q?j.appendChild(Q):j.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",k.style.display=a?"none":k.textContent||k.childNodes.length?"":"none"})(),r.append(c,k,O),r};var Bs=new Set,Vv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Kv=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let r=((s=n.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
|
|
29
|
+
`);let o=Ao(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
|
|
30
|
+
`):""},_l=(e,t)=>{var n,r,o;e.style.backgroundColor=(n=t.codeBlockBackgroundColor)!=null?n:"var(--persona-container, #f3f4f6)",e.style.borderColor=(r=t.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",e.style.color=(o=t.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},Gv=(e,t)=>{var p,u,f,g,y;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,o=(u=r==null?void 0:r.collapsedMode)!=null?u:"tool-call",s=Kv(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?Um(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(g=t==null?void 0:t.toolCall)!=null?g:{},c=a;return o==="tool-name"?c=((y=n.name)==null?void 0:y.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=ml(n,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=ml(n,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},jg=(e,t,n)=>{var p;let r=Bs.has(e),o=(p=n==null?void 0:n.toolCall)!=null?p:{},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",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let u=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",f=ye(r?"chevron-up":"chevron-down",16,u,2);f?c.appendChild(f):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},$l=(e,t)=>{var F,Z,Ee,de,ee,Le,Pe,ne,Ae;let n=e.toolCall,r=(F=t==null?void 0:t.toolCall)!=null?F:{},o=b("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let s=(Ee=(Z=t==null?void 0:t.features)==null?void 0:Z.toolCallDisplay)!=null?Ee:{},a=s.expandable!==!1,i=a&&Bs.has(e.id),{summary:d,previewText:c,isActive:p}=Gv(e,t),u=b("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(u.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(u.style.paddingLeft=r.headerPaddingX,u.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(u.style.paddingTop=r.headerPaddingY,u.style.paddingBottom=r.headerPaddingY);let f=b("div","persona-flex persona-flex-col persona-text-left"),g=b("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(g.style.color=r.headerTextColor);let y=String((de=n.startedAt)!=null?de:Date.now()),v=()=>{let re=b("span","");return re.setAttribute("data-tool-elapsed",y),re.textContent=la(n),re},A=(Le=r.renderCollapsedSummary)==null?void 0:Le.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:(ee=s.collapsedMode)!=null?ee:"tool-call",isActive:p,config:t!=null?t:{},elapsed:la(n),createElapsedElement:v});typeof A=="string"&&A.trim()?(g.textContent=A,f.appendChild(g)):A instanceof HTMLElement?f.appendChild(A):(g.textContent=d,f.appendChild(g));let T=(Pe=s.loadingAnimation)!=null?Pe:"none",L=r.activeTextTemplate,W=r.completeTextTemplate,R=p?L:W,P=A instanceof HTMLElement,S=(re,se,ae)=>{let fe=ae;for(let $e of se){let V=b("span","persona-tool-char");V.style.setProperty("--char-index",String(fe)),V.textContent=$e===" "?"\xA0":$e,re.appendChild(V),fe++}return fe},H=(re,se)=>{var V;g.textContent="";let ae=((V=n.name)==null?void 0:V.trim())||"tool",fe=Ga(re,ae),$e=0;for(let Q of fe){let Me=Q.styles.length>0?(()=>{let J=b("span",Q.styles.map(le=>`persona-tool-text-${le}`).join(" "));return g.appendChild(J),J})():g;if(Q.isDuration&&p)Me.appendChild(v());else{let J=Q.isDuration?la(n):Q.text;se?$e=S(Me,J,$e):Me.appendChild(document.createTextNode(J))}}};if(!P)if(p&&T!=="none"){let re=(ne=r.loadingAnimationDuration)!=null?ne:2e3;if(g.setAttribute("data-preserve-animation","true"),T==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${re}ms`),R&&H(R,!1);else if(g.classList.add(`persona-tool-loading-${T}`),g.style.setProperty("--persona-tool-anim-duration",`${re}ms`),T==="shimmer-color"&&(r.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),R)H(R,!0);else{let se=g.textContent||d;g.textContent="",S(g,se,0)}}else R&&H(R,!1);let U=null;if(a){U=b("div","persona-flex persona-items-center");let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=ye(i?"chevron-up":"chevron-down",16,re,2);se?U.appendChild(se):U.textContent=i?"Hide":"Show";let ae=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ae.append(U),u.append(f,ae)}else u.append(f);let j=b("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(j.setAttribute("data-persona-collapsed-preview","tool"),j.style.display="none",j.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&c){let re=(Ae=r.renderCollapsedPreview)==null?void 0:Ae.call(r,{message:e,toolCall:n,defaultPreview:c,isActive:p,config:t!=null?t:{}});Vv(j,re)||(j.textContent=c),j.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,j),o;let k=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(k.style.display=i?"":"none",r.contentBackgroundColor&&(k.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(k.style.color=r.contentTextColor),r.contentPaddingX&&(k.style.paddingLeft=r.contentPaddingX,k.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(k.style.paddingTop=r.contentPaddingY,k.style.paddingBottom=r.contentPaddingY),n.name){let re=b("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?re.style.color=r.contentTextColor:r.headerTextColor&&(re.style.color=r.headerTextColor),re.textContent=n.name,k.appendChild(re)}if(n.args!==void 0){let re=b("div","persona-space-y-1"),se=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Arguments";let ae=b("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");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",_l(ae,r),ae.textContent=Ao(n.args),re.append(se,ae),k.appendChild(re)}if(n.chunks&&n.chunks.length){let re=b("div","persona-space-y-1"),se=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Activity";let ae=b("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");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",_l(ae,r),ae.textContent=n.chunks.join(""),re.append(se,ae),k.appendChild(re)}if(n.status==="complete"&&n.result!==void 0){let re=b("div","persona-space-y-1"),se=b("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Result";let ae=b("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");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",_l(ae,r),ae.textContent=Ao(n.result),re.append(se,ae),k.appendChild(re)}if(n.status==="complete"&&typeof n.duration=="number"){let re=b("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(re.style.color=r.contentTextColor),re.textContent=`Duration: ${n.duration}ms`,k.appendChild(re)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),U){U.innerHTML="";let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=ye(i?"chevron-up":"chevron-down",16,re,2);se?U.appendChild(se):U.textContent=i?"Hide":"Show"}k.style.display=i?"":"none",j.style.display=i?"none":j.textContent||j.childNodes.length?"":"none"})(),o.append(u,j,k),o};var os=new Map,Ai=e=>{let n=(e.startsWith(Rr)?e.slice(Rr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Ug=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,qg=(e,t)=>{var r,o,s;let n=(o=(r=Ug(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=os.get(e))!=null?s:n==="expanded"},zg=(e,t,n)=>{var a,i;let r=Ug(n);e.setAttribute("aria-expanded",t?"true":"false");let o=e.querySelector("[data-approval-details-label]");o&&(o.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=ye(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},Vg=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=qg(e,n);zg(r,s,n),o.style.display=s?"":"none"};var Si=(e,t)=>{var H,U,j,k,O,F,Z,Ee,de,ee,Le,Pe,ne,Ae,re;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(n==null?void 0:n.status)==="pending",s=b("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(H=r==null?void 0:r.backgroundColor)!=null?H:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(U=r==null?void 0:r.borderColor)!=null?U:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=b("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=b("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(j=r==null?void 0:r.titleColor)!=null?j:"currentColor",p=ye(d,20,c,2);p&&i.appendChild(p);let u=b("div","persona-flex-1 persona-min-w-0"),f=b("div","persona-flex persona-items-center persona-gap-2"),g=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(g.style.color=r.titleColor),g.textContent=(k=r==null?void 0:r.title)!=null?k:"Approval Required",f.appendChild(g),!o){let se=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");se.setAttribute("data-approval-status",n.status),n.status==="approved"?(se.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",se.style.color="var(--persona-palette-colors-success-700, #15803d)",se.textContent="Approved"):n.status==="denied"?(se.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",se.style.color="var(--persona-palette-colors-error-700, #b91c1c)",se.textContent="Denied"):n.status==="timeout"&&(se.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",se.style.color="var(--persona-palette-colors-warning-700, #b45309)",se.textContent="Timeout"),f.appendChild(se)}u.appendChild(f);let v=n.toolType==="webmcp"||n.toolName.startsWith(Rr)?ta(n.toolName):void 0,A=(O=r==null?void 0:r.formatDescription)==null?void 0:O.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),T=!n.toolName,L=A||(T?n.description:`The assistant wants to use \u201C${v!=null?v:Ai(n.toolName)}\u201D.`),W=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(W.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(W.style.color=r.descriptionColor),W.textContent=L,u.appendChild(W),n.reason){let se=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");se.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?se.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(se.style.color=r.descriptionColor);let ae=b("span","persona-font-medium");ae.textContent=`${(F=r==null?void 0:r.reasonLabel)!=null?F:"Agent's stated reason:"} `,se.appendChild(ae),se.appendChild(document.createTextNode(n.reason)),u.appendChild(se)}let R=(Z=r==null?void 0:r.detailsDisplay)!=null?Z:"collapsed",P=!!n.description&&!T,S=P||!!n.parameters;if(R!=="hidden"&&S){let se=qg(e.id,t),ae=b("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");ae.type="button",ae.setAttribute("data-expand-header","true"),ae.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor);let fe=b("span");fe.setAttribute("data-approval-details-label","true");let $e=b("span","persona-inline-flex persona-items-center");$e.setAttribute("data-approval-details-chevron","true"),ae.append(fe,$e),zg(ae,se,t),u.appendChild(ae);let V=b("div");if(V.setAttribute("data-approval-details","true"),V.style.display=se?"":"none",P){let Q=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(Q.style.color=r.descriptionColor),Q.textContent=n.description,V.appendChild(Q)}if(n.parameters){let Q=b("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(Q.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(Q.style.color=r.parameterTextColor),Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Q.textContent=Ao(n.parameters),V.appendChild(Q)}u.appendChild(V)}if(o){let se=b("div","persona-flex persona-gap-2 persona-mt-2");se.setAttribute("data-approval-buttons","true");let ae=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");ae.type="button",ae.style.backgroundColor=(Ee=r==null?void 0:r.approveButtonColor)!=null?Ee:"var(--persona-approval-approve-bg, #22c55e)",ae.style.color=(de=r==null?void 0:r.approveButtonTextColor)!=null?de:"#ffffff",ae.setAttribute("data-approval-action","approve");let fe=ye("shield-check",14,(ee=r==null?void 0:r.approveButtonTextColor)!=null?ee:"#ffffff",2);fe&&(fe.style.marginRight="4px",ae.appendChild(fe));let $e=document.createTextNode((Le=r==null?void 0:r.approveLabel)!=null?Le:"Approve");ae.appendChild($e);let V=b("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");V.type="button",V.style.backgroundColor=(Pe=r==null?void 0:r.denyButtonColor)!=null?Pe:"transparent",V.style.color=(ne=r==null?void 0:r.denyButtonTextColor)!=null?ne:"var(--persona-feedback-error, #dc2626)",V.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,V.setAttribute("data-approval-action","deny");let Q=ye("shield-x",14,(Ae=r==null?void 0:r.denyButtonTextColor)!=null?Ae:"var(--persona-feedback-error, #dc2626)",2);Q&&(Q.style.marginRight="4px",V.appendChild(Q));let Me=document.createTextNode((re=r==null?void 0:r.denyLabel)!=null?re:"Deny");V.appendChild(Me),se.append(ae,V),u.appendChild(se)}return a.append(i,u),s.appendChild(a),s};function Jv(e){var n,r;let t=(n=e.getRootNode)==null?void 0:n.call(e);return t instanceof ShadowRoot?t:((r=e.ownerDocument)!=null?r:document).body}function Kg(e){var v;let{anchor:t,content:n,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=e,c=(v=e.container)!=null?v:Jv(t),p=!1,u=null,f=()=>{if(!p)return;let A=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${A.width}px`);let T=r==="top-start"||r==="top-end"?A.top-o-n.getBoundingClientRect().height:A.bottom+o,L=r==="bottom-end"||r==="top-end"?A.right-n.getBoundingClientRect().width:A.left;n.style.top=`${T}px`,n.style.left=`${L}px`},g=()=>{p&&(p=!1,u&&(u(),u=null),n.remove())},y=()=>{var P,S,H;if(p)return;p=!0,a!=null&&(n.style.zIndex=String(a)),c.appendChild(n),f();let A=(S=((P=t.ownerDocument)!=null?P:document).defaultView)!=null?S:window,T=(H=t.ownerDocument)!=null?H:document,L=()=>{if(!t.isConnected){g(),d==null||d("anchor-removed");return}f()},W=U=>{let j=typeof U.composedPath=="function"?U.composedPath():[];j.includes(n)||j.includes(t)||(g(),d==null||d("outside"))},R=A.setTimeout(()=>{T.addEventListener("pointerdown",W,!0)},0);A.addEventListener("scroll",L,!0),A.addEventListener("resize",L),u=()=>{A.clearTimeout(R),T.removeEventListener("pointerdown",W,!0),A.removeEventListener("scroll",L,!0),A.removeEventListener("resize",L)},i==null||i()};return{get isOpen(){return p},open:y,close:g,toggle:()=>p?g():y(),reposition:f,destroy:g}}function Gg(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Xv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Jg=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},ss=(e,t)=>{Jg(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)},Qv=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Yv=(e,t)=>{var r,o;let n=(r=t==null?void 0:t.detailsDisplay)!=null?r:"collapsed";return(o=os.get(e))!=null?o:n==="expanded"},jl=e=>{let t=b("span","persona-approval-kbd");return t.textContent=e,t},Zv=(e,t)=>{var c,p;let n=b("span","persona-approval-title");t!=null&&t.titleColor&&(n.style.color=t.titleColor);let o=e.toolType==="webmcp"||e.toolName.startsWith(Rr)?ta(e.toolName):void 0,s=(p=t==null?void 0:t.formatDescription)==null?void 0:p.call(t,{toolName:e.toolName,toolType:e.toolType,description:(c=e.description)!=null?c:"",parameters:e.parameters,...o?{displayTitle:o}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=o!=null?o:Ai(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),i){n.append(" from ");let u=document.createElement("strong");u.textContent=i,n.appendChild(u)}return n},ew=e=>{let t=b("div","persona-approval-resolved"),n=ye("ban",15,"currentColor",2);n&&t.appendChild(n);let r=b("span","persona-approval-resolved-name");return r.textContent=e.toolName?Ai(e.toolName):"Tool",t.append(r,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},tw=(e,t,n,r,o,s,a)=>{var U,j,k,O,F,Z,Ee;let i=b("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"),r!=null&&r.backgroundColor&&(i.style.background=r.backgroundColor),r!=null&&r.borderColor&&(i.style.borderColor=r.borderColor),(r==null?void 0:r.shadow)!==void 0&&(i.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let d=(U=r==null?void 0:r.detailsDisplay)!=null?U:"collapsed",c=!!n.description&&d!=="hidden",p=n.parameters!=null&&d!=="hidden",u=c||p,f=u&&Yv(t.id,r),g=(j=r==null?void 0:r.showDetailsLabel)!=null?j:"Show details",y=(k=r==null?void 0:r.hideDetailsLabel)!=null?k:"Hide details",v=b("button","persona-approval-head");v.type="button",u?(v.setAttribute("data-action","toggle-params"),v.setAttribute("aria-expanded",f?"true":"false"),v.setAttribute("aria-label",f?y:g)):v.setAttribute("data-static","true");let A=b("span","persona-approval-logo"),T=ye("shield-check",16,"currentColor",2);T&&A.appendChild(T),v.appendChild(A);let L=Zv(n,r);if(u){let de=b("span","persona-approval-toggle");de.setAttribute("aria-hidden","true");let ee=ye("chevron-down",14,"currentColor",2);ee&&de.appendChild(ee),L.append(" "),L.appendChild(de)}v.appendChild(L),i.appendChild(v);let W=b("div","persona-approval-body");if(u){let de=b("div","persona-approval-details");if(de.setAttribute("data-role","params"),de.hidden=!f,c){let ee=b("p","persona-approval-desc");r!=null&&r.descriptionColor&&(ee.style.color=r.descriptionColor),ee.textContent=n.description,de.appendChild(ee)}if(p){let ee=b("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(ee.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ee.style.color=r.parameterTextColor),ee.textContent=Ao(n.parameters),de.appendChild(ee)}W.appendChild(de)}if(n.reason){let de=b("p","persona-approval-reason");r!=null&&r.reasonColor?de.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(de.style.color=r.descriptionColor);let ee=b("span","persona-approval-reason-label");ee.textContent=`${(O=r==null?void 0:r.reasonLabel)!=null?O:"Agent's stated reason:"} `,de.append(ee,document.createTextNode(n.reason)),W.appendChild(de)}let R=b("div","persona-approval-actions"),P=null,S=de=>{r!=null&&r.approveButtonColor&&(de.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(de.style.color=r.approveButtonTextColor)},H=b("button","persona-approval-deny");if(H.type="button",H.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(H.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(H.style.color=r.denyButtonTextColor),H.append((F=r==null?void 0:r.denyLabel)!=null?F:"Deny"),a){let de=b("div","persona-approval-split"),ee=b("button","persona-approval-primary");ee.type="button",ee.setAttribute("data-action","always"),S(ee),ee.append((Z=r==null?void 0:r.approveLabel)!=null?Z:"Always allow",jl("\u23CE"));let Le=b("button","persona-approval-caret");Le.type="button",Le.setAttribute("data-action","toggle-menu"),Le.setAttribute("aria-label","More options"),S(Le);let Pe=ye("chevron-down",15,"currentColor",2);Pe&&Le.appendChild(Pe),de.append(ee,Le),R.append(de,H),H.append(jl("Esc"));let ne=b("div","persona-approval-menu"),Ae=b("button","persona-approval-menu-item");Ae.type="button",Ae.append("Allow once",jl("\u2318\u23CE")),ne.appendChild(Ae),P=Kg({anchor:de,content:ne,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,P),Ae.addEventListener("click",()=>{ss(e,t.id),o()})}else{let de=b("button","persona-approval-primary persona-approval-primary--solo");de.type="button",de.setAttribute("data-action","allow"),S(de),de.append((Ee=r==null?void 0:r.approveLabel)!=null?Ee:"Allow"),R.append(de,H)}return W.appendChild(R),i.appendChild(W),i.addEventListener("click",de=>{let ee=de.target instanceof Element?de.target.closest("[data-action]"):null;if(!ee)return;let Le=ee.getAttribute("data-action");if(Le==="toggle-params"){let Pe=i.querySelector('[data-role="params"]');if(Pe){let ne=Pe.hidden;Pe.hidden=!ne,v.setAttribute("aria-expanded",ne?"true":"false"),v.setAttribute("aria-label",ne?y:g),os.set(t.id,ne)}return}if(Le==="toggle-menu"){P==null||P.toggle();return}if(Le==="always"){ss(e,t.id),o({remember:!0});return}if(Le==="allow"){ss(e,t.id),o();return}if(Le==="deny"){ss(e,t.id),s();return}}),i},Xg=()=>{let e=Xv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:o,deny:s,config:a})=>{let i=r==null?void 0:r.approval;if(!i)return null;let d=Qv(a);if(i.status!=="pending"){if(ss(e,r.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return ew(i)}Jg(e,r.id);let c=(d==null?void 0:d.enableAlwaysAllow)===!0,p=tw(e,r,i,d,o,s,c);if(c){e.pendingOrder.includes(r.id)||e.pendingOrder.push(r.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=f=>{Gg(f)||r.id===e.latestPendingApprovalId&&(f.key!=="Escape"&&f.key!=="Enter"||(f.preventDefault(),f.stopImmediatePropagation(),ss(e,r.id),f.key==="Escape"?s():f.metaKey||f.ctrlKey?o():o({remember:!0})))};e.keyHandlers.set(r.id,u),document.addEventListener("keydown",u)}return p}},teardown:()=>{for(let r of[...e.keyHandlers.keys(),...e.popovers.keys()])ss(e,r);e.latestPendingApprovalId=null}}};var Qg=e=>{let t=[],n=null;return{buttons:t,render:(o,s,a,i,d,c)=>{e.innerHTML="",t.length=0;let p=(c==null?void 0:c.agentPushed)===!0;if(p||(n=null),!o||!o.length||!p&&(i!=null?i:s?s.getMessages():[]).some(A=>A.role==="user"))return;let u=document.createDocumentFragment(),f=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(o.forEach(y=>{let v=b("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=y,v.disabled=f,d!=null&&d.fontFamily&&(v.style.fontFamily=g(d.fontFamily)),d!=null&&d.fontWeight&&(v.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(v.style.paddingLeft=d.paddingX,v.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(v.style.paddingTop=d.paddingY,v.style.paddingBottom=d.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:y},bubbles:!0,composed:!0})),s.sendMessage(y))}),u.appendChild(v),t.push(v)}),e.appendChild(u),p){let y=JSON.stringify(o);y!==n&&(n=y,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var Ma=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){var n;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),(n=this.store)==null||n.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 r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=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(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ka=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 r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}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 r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}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(r){n(r)}})}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(r){n(r)}})}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(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}};var nw=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),rw=new Set(["step_start","execution_start"]),ow=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),sw=new Set(["step_complete","agent_turn_complete"]),aw=new Set(["flow_complete","agent_complete"]),Yg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),ef=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,as=(e,t)=>{let n=e[t];return ef(n)?n:void 0};function Ul(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Ti(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function iw(e,t){return typeof t.type=="string"?t.type:e}function lw(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 cw(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 Zg(e){var r,o,s,a,i;let t=as(e,"result"),n=[as(e,"tokens"),as(e,"totalTokens"),t?as(t,"tokens"):void 0,as(e,"usage"),t?as(t,"usage"):void 0];for(let d of n){if(!d)continue;let c=(o=(r=qn(d.output))!=null?r:qn(d.outputTokens))!=null?o:qn(d.completionTokens);if(c!==void 0)return c}return(i=(s=qn(e.outputTokens))!=null?s:qn(e.completionTokens))!=null?i:t?(a=qn(t.outputTokens))!=null?a:qn(t.completionTokens):void 0}function dw(e){var n,r,o,s,a;let t=as(e,"result");return(a=(o=(r=(n=qn(e.executionTime))!=null?n:qn(e.executionTimeMs))!=null?r:qn(e.execution_time))!=null?o:qn(e.duration))!=null?a:t?(s=qn(t.executionTime))!=null?s:qn(t.executionTimeMs):void 0}function pw(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var La=class{constructor(t=pw){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:Ti(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){var s;if(!ef(n)){Yg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=iw(t,n),o=this.now();if(nw.has(r)){this.startRun(o);return}if(rw.has(r)){this.run||this.startRun(o);return}if(ow.has(r)){if(!cw(r,n))return;let a=lw(n);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Ul(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Ti(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(sw.has(r)){if(!this.run)return;let a=this.run,i=Zg(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+Ul(a.visibleCharCount),p=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:Ti(c,p),outputTokens:c,durationMs:p,source:d?"usage":"estimate"};return}if(aw.has(r)){if(!this.run)return;let a=this.run,i=Zg(n),d=i!=null?i:a.exactOutputTokens+Ul(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:Ti(d,p),outputTokens:d,durationMs:p,source:c},this.run=null;return}if(Yg.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let o=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=dw(n);return s!=null?s:r-t.startedAt}};function Ds(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var uw={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)"}},mw={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},gw=["flowName","stepName","reasoningText","text","name","tool","toolName"],fw=100;function hw(e,t){let n={...uw,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return mw}function yw(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function bw(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${o}.${s}`}function xw(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let o=r.split("."),s=n;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function vw(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function ww(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 Cw(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Aw(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 Sw(e,t,n){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=b("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=b("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function ql(e,t,n,r,o,s,a,i){var f;let d=o.has(e.id),c=b("div","persona-border-b persona-border-persona-divider persona-text-xs");Ds(c,(f=r.classNames)==null?void 0:f.eventRow);let p=a.find(g=>g.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let g=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(u()),c;function u(){var F,Z;let g=b("div",""),y=b("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");y.setAttribute("data-event-id",e.id);let v=b("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),A=ye(d?"chevron-down":"chevron-right","14px","currentColor",2);A&&v.appendChild(A);let T=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=(F=r.timestampFormat)!=null?F:"relative";T.textContent=L==="relative"?yw(e.timestamp,n):bw(e.timestamp);let W=null;r.showSequenceNumbers!==!1&&(W=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),W.textContent=String(t+1));let R=hw(e.type,r.badgeColors),P=b("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");P.style.backgroundColor=R.bg,P.style.color=R.text,P.style.borderColor=R.text+"50",P.textContent=e.type;let S=(Z=r.descriptionFields)!=null?Z:gw,H=xw(e.payload,S),U=null;H&&(U=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),U.textContent=H);let j=b("div","persona-flex-1 persona-min-w-0"),k=b("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),O=ye("clipboard","12px","currentColor",1.5);return O&&k.appendChild(O),k.addEventListener("click",async Ee=>{Ee.stopPropagation(),await vw(ww(e)),k.innerHTML="";let de=ye("check","12px","currentColor",1.5);de&&k.appendChild(de),setTimeout(()=>{k.innerHTML="";let ee=ye("clipboard","12px","currentColor",1.5);ee&&k.appendChild(ee)},1500)}),y.appendChild(v),y.appendChild(T),W&&y.appendChild(W),y.appendChild(P),U&&y.appendChild(U),y.appendChild(j),y.appendChild(k),g.appendChild(y),d&&g.appendChild(Sw(e,a,i)),g}}function tf(e){var y,v,A,T,L;let{buffer:t,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=e,i=(y=o==null?void 0:o.features)==null?void 0:y.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",p=(A=i==null?void 0:i.label)!=null?A:"",u=(L=(T=o==null?void 0:o.features)==null?void 0:T.eventStream)!=null?L:{},f=s.find(W=>W.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&o){let W=f.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>g().element,onClose:r});if(W)return{element:W,update:()=>{},destroy:()=>{}}}return g();function g(){let W=u.classNames,R=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ds(R,W==null?void 0:W.panel);let P=[],S="",H="",U=null,j=[],k={},O=0,F=ai(),Z=0,Ee=0,de=!1,ee=null,Le=!1,Pe=0,ne=new Set,Ae=new Map,re="",se="",ae=null,fe,$e,V,Q,Me=null,J=null,le=null;function Ie(){let me=b("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),B=b("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Ds(B,W==null?void 0:W.headerBar),a){J=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),J.style.cursor="help",Me=b("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Me.textContent="-- tok/s",le=b("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),le.style.display="none",le.style.pointerEvents="none";let Ot=J,Zt=le,br=()=>{if(!Zt.textContent)return;let or=Ot.getBoundingClientRect(),sr=me.getBoundingClientRect();Zt.style.left=`${or.left-sr.left}px`,Zt.style.top=`${or.bottom-sr.top+4}px`,Zt.style.display="block"},Nr=()=>{Zt.style.display="none"};J.addEventListener("mouseenter",br),J.addEventListener("mouseleave",Nr),J.appendChild(Me)}let xe=b("div","persona-flex-1");fe=b("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let ce=b("option","");ce.value="",ce.textContent="All events (0)",fe.appendChild(ce),$e=b("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),$e.type="button",$e.title="Copy All";let Je=ye("clipboard-copy","12px","currentColor",1.5);Je&&$e.appendChild(Je);let Lt=b("span","persona-event-copy-all persona-text-xs");Lt.textContent="Copy All",$e.appendChild(Lt),J&&B.appendChild(J),B.appendChild(xe),B.appendChild(fe),B.appendChild($e);let Mt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ds(Mt,W==null?void 0:W.searchBar);let xt=ye("search","14px","var(--persona-muted, #9ca3af)",1.5),Rt=b("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");xt&&Rt.appendChild(xt),V=b("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Ds(V,W==null?void 0:W.searchInput),V.type="text",V.placeholder="Search event payloads...",Q=b("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Q.type="button",Q.style.display="none";let Xt=ye("x","12px","currentColor",2);return Xt&&Q.appendChild(Xt),Mt.appendChild(Rt),Mt.appendChild(V),Mt.appendChild(Q),me.appendChild(B),me.appendChild(Mt),le&&me.appendChild(le),me}let he,Ke=s.find(me=>me.renderEventStreamToolbar);if(Ke!=null&&Ke.renderEventStreamToolbar&&o){let me=Ke.renderEventStreamToolbar({config:o,defaultRenderer:()=>Ie(),eventCount:t.getSize(),filteredCount:0,onFilterChange:B=>{S=B,be(),Ct()},onSearchChange:B=>{H=B,be(),Ct()}});he=me!=null?me:Ie()}else he=Ie();let gt=b("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");gt.style.display="none";function Wt(){if(!a||!Me||!J)return;let me=a(),B=Cw(me);Me.textContent=B;let xe=Aw(me);le&&(le.textContent=xe,xe||(le.style.display="none")),J.setAttribute("aria-label",xe?`Throughput: ${B}, ${xe}`:`Throughput: ${B}`)}let tt=b("div","persona-flex-1 persona-min-h-0 persona-relative"),ge=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ge.style.height="100%";let X=b("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Ds(X,W==null?void 0:W.scrollIndicator),X.style.display="none",X.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let it=ye(c,"14px","currentColor",2);it&&X.appendChild(it);let Ve=b("span","");Ve.textContent=p,X.appendChild(Ve);let Se=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Se.style.display="none",tt.appendChild(ge),tt.appendChild(Se),tt.appendChild(X),R.setAttribute("tabindex","0"),R.appendChild(he),R.appendChild(gt),R.appendChild(tt);function we(){let me=t.getAll(),B={};for(let Mt of me)B[Mt.type]=(B[Mt.type]||0)+1;let xe=Object.keys(B).sort(),ce=xe.length!==j.length||!xe.every((Mt,xt)=>Mt===j[xt]),ft=!ce&&xe.some(Mt=>B[Mt]!==k[Mt]),Je=me.length!==Object.values(k).reduce((Mt,xt)=>Mt+xt,0);if(!ce&&!ft&&!Je||(j=xe,k=B,!fe))return;let Lt=fe.value;if(fe.options[0].textContent=`All events (${me.length})`,ce){for(;fe.options.length>1;)fe.remove(1);for(let Mt of xe){let xt=b("option","");xt.value=Mt,xt.textContent=`${Mt} (${B[Mt]||0})`,fe.appendChild(xt)}Lt&&xe.includes(Lt)?fe.value=Lt:Lt&&(fe.value="",S="")}else for(let Mt=1;Mt<fe.options.length;Mt++){let xt=fe.options[Mt];xt.textContent=`${xt.value} (${B[xt.value]||0})`}}function Ze(){let me=t.getAll();if(S&&(me=me.filter(B=>B.type===S)),H){let B=H.toLowerCase();me=me.filter(xe=>xe.type.toLowerCase().includes(B)||xe.payload.toLowerCase().includes(B))}return me}function qt(){return S!==""||H!==""}function be(){O=0,Z=0,F.resume(),X.style.display="none"}function pe(me){ne.has(me)?ne.delete(me):ne.add(me),ae=me;let B=ge.scrollTop,xe=F.isFollowing();Le=!0,F.pause(),Ct(),ge.scrollTop=B,xe&&F.resume(),Le=!1}function Cn(){return So(ge,50)}function Ct(){Ee=Date.now(),de=!1,Wt(),we();let me=t.getEvictedCount();me>0?(gt.textContent=`${me.toLocaleString()} older events truncated`,gt.style.display=""):gt.style.display="none",P=Ze();let B=P.length,xe=t.getSize()>0;B===0&&xe&&qt()?(Se.textContent=H?`No events matching '${H}'`:"No events matching filter",Se.style.display="",ge.style.display="none"):(Se.style.display="none",ge.style.display=""),$e&&($e.title=qt()?`Copy Filtered (${B})`:"Copy All"),d&&!F.isFollowing()&&B>O&&(Z+=B-O,Ve.textContent=p?`${p}${Z>0?` (${Z})`:""}`:"",X.style.display=""),O=B;let ce=t.getAll(),ft=ce.length>0?ce[0].timestamp:0,Je=new Set(P.map(xt=>xt.id));for(let xt of ne)Je.has(xt)||ne.delete(xt);let Lt=S!==re||H!==se,Mt=Ae.size===0&&P.length>0;if(Lt||Mt||P.length===0){ge.innerHTML="",Ae.clear();let xt=document.createDocumentFragment();for(let Rt=0;Rt<P.length;Rt++){let Xt=ql(P[Rt],Rt,ft,u,ne,pe,s,o);Ae.set(P[Rt].id,Xt),xt.appendChild(Xt)}ge.appendChild(xt),re=S,se=H,ae=null}else{if(ae!==null){let Rt=Ae.get(ae);if(Rt&&Rt.parentNode===ge){let Xt=P.findIndex(Ot=>Ot.id===ae);if(Xt>=0){let Ot=ql(P[Xt],Xt,ft,u,ne,pe,s,o);ge.insertBefore(Ot,Rt),Rt.remove(),Ae.set(ae,Ot)}}ae=null}let xt=new Set(P.map(Rt=>Rt.id));for(let[Rt,Xt]of Ae)xt.has(Rt)||(Xt.remove(),Ae.delete(Rt));for(let Rt=0;Rt<P.length;Rt++){let Xt=P[Rt];if(!Ae.has(Xt.id)){let Ot=ql(Xt,Rt,ft,u,ne,pe,s,o);Ae.set(Xt.id,Ot),ge.appendChild(Ot)}}}F.isFollowing()&&(ge.scrollTop=ge.scrollHeight)}function yn(){if(Date.now()-Ee>=fw){ee!==null&&(cancelAnimationFrame(ee),ee=null),Ct();return}de||(de=!0,ee=requestAnimationFrame(()=>{ee=null,Ct()}))}let hr=(me,B)=>{if(!$e)return;$e.innerHTML="";let xe=ye(me,"12px","currentColor",1.5);xe&&$e.appendChild(xe);let ce=b("span","persona-text-xs");ce.textContent="Copy All",$e.appendChild(ce),setTimeout(()=>{$e.innerHTML="";let ft=ye("clipboard-copy","12px","currentColor",1.5);ft&&$e.appendChild(ft);let Je=b("span","persona-text-xs");Je.textContent="Copy All",$e.appendChild(Je),$e.disabled=!1},B)},yr=async()=>{if($e){$e.disabled=!0;try{let me;qt()?me=P:n?(me=await n(),me.length===0&&(me=t.getAll())):me=t.getAll();let B=me.map(xe=>{try{return JSON.parse(xe.payload)}catch{return xe.payload}});await navigator.clipboard.writeText(JSON.stringify(B,null,2)),hr("check",1500)}catch{hr("x",1500)}}},Ue=()=>{fe&&(S=fe.value,be(),Ct())},E=()=>{!V||!Q||(Q.style.display=V.value?"":"none",U&&clearTimeout(U),U=setTimeout(()=>{H=V.value,be(),Ct()},150))},ue=()=>{!V||!Q||(V.value="",H="",Q.style.display="none",U&&clearTimeout(U),be(),Ct())},Te=()=>{if(Le)return;let me=ge.scrollTop,{action:B,nextLastScrollTop:xe}=ii({following:F.isFollowing(),currentScrollTop:me,lastScrollTop:Pe,nearBottom:Cn(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Pe=xe,B==="resume"?(F.resume(),Z=0,X.style.display="none"):B==="pause"&&(F.pause(),d&&(Ve.textContent=p,X.style.display=""))},ke=me=>{let B=li({following:F.isFollowing(),deltaY:me.deltaY,nearBottom:Cn(),resumeWhenNearBottom:!0});B==="pause"?(F.pause(),d&&(Ve.textContent=p,X.style.display="")):B==="resume"&&(F.resume(),Z=0,X.style.display="none")},He=()=>{d&&(ge.scrollTop=ge.scrollHeight,F.resume(),Z=0,X.style.display="none")},nt=me=>{let B=me.target;if(!B||B.closest("button"))return;let xe=B.closest("[data-event-id]");if(!xe)return;let ce=xe.getAttribute("data-event-id");ce&&pe(ce)},Qe=me=>{if((me.metaKey||me.ctrlKey)&&me.key==="f"){me.preventDefault(),V==null||V.focus(),V==null||V.select();return}me.key==="Escape"&&(V&&document.activeElement===V?(ue(),V.blur(),R.focus()):r&&r())};$e&&$e.addEventListener("click",yr),fe&&fe.addEventListener("change",Ue),V&&V.addEventListener("input",E),Q&&Q.addEventListener("click",ue),ge.addEventListener("scroll",Te),ge.addEventListener("wheel",ke,{passive:!0}),ge.addEventListener("click",nt),X.addEventListener("click",He),R.addEventListener("keydown",Qe);function ht(){U&&clearTimeout(U),ee!==null&&(cancelAnimationFrame(ee),ee=null),de=!1,Ae.clear(),$e&&$e.removeEventListener("click",yr),fe&&fe.removeEventListener("change",Ue),V&&V.removeEventListener("input",E),Q&&Q.removeEventListener("click",ue),ge.removeEventListener("scroll",Te),ge.removeEventListener("wheel",ke),ge.removeEventListener("click",nt),X.removeEventListener("click",He),R.removeEventListener("keydown",Qe)}return{element:R,update:yn,destroy:ht}}}function nf(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",o=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(g)}else u.textContent=a;if(c.append(p,u),i.append(d,c),o==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var rf=(e,t)=>{var r,o,s;let n=(s=(o=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:t.config,defaultRenderer:()=>nf(e,t)});if(p)return p}return nf(e,t)};var zl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},Lo=new zl;Lo.register("PersonaArtifactCard",rf);function Tw(e){var o;let t=b("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=b("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=e.props)!=null?o:{},null,2),t.appendChild(n),t.appendChild(r),t}function of(e,t){var $e,V,Q,Me;let n=(V=($e=e.features)==null?void 0:$e.artifacts)==null?void 0:V.layout,o=((Q=n==null?void 0:n.toolbarPreset)!=null?Q:"default")==="document",s=(Me=n==null?void 0:n.panePadding)==null?void 0:Me.trim(),a=e.markdown?As(e.markdown):null,i=Zs(e.sanitize),d=J=>{let le=a?a(J):Xr(J);return i?i(le):le},c=typeof document!="undefined"?b("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{c==null||c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};c&&c.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let u=b("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");u.setAttribute("data-persona-theme-zone","artifact-pane"),o&&u.classList.add("persona-artifact-pane-document");let f=b("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&f.classList.add("persona-artifact-toolbar-document");let g=b("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let y=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");y.type="button",y.textContent="Close",y.setAttribute("aria-label","Close artifacts panel"),y.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let v="rendered",A=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?Gt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Gt({icon:"eye",label:"Rendered view"}),L=o?Gt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Gt({icon:"code-2",label:"Source"}),W=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),R=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,P=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,S=n==null?void 0:n.documentToolbarCopyMenuItems,H=!!(P&&S&&S.length>0),U=null,j,k=null,O=null;if(o&&(R||P)&&!H){if(j=R?fi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let J=ye("chevron-down",14,"currentColor",2);J&&j.appendChild(J)}}else o&&H?(U=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),j=R?fi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k=Gt({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"}}),U.append(j,k)):o?j=Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):j=Gt({icon:"copy",label:"Copy"});let F=o?Gt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"refresh-cw",label:"Refresh"}),Z=o?Gt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"x",label:"Close"}),Ee=()=>{var Ke,gt,Wt;let J=(Ke=Ae.find(tt=>tt.id===re))!=null?Ke:Ae[Ae.length-1],le=(gt=J==null?void 0:J.id)!=null?gt:null,Ie=(J==null?void 0:J.artifactType)==="markdown"&&(Wt=J.markdown)!=null?Wt:"",he=J?JSON.stringify({component:J.component,props:J.props},null,2):"";return{markdown:Ie,jsonPayload:he,id:le}},de=async()=>{var Ke;let{markdown:J,jsonPayload:le}=Ee(),Ie=(Ke=Ae.find(gt=>gt.id===re))!=null?Ke:Ae[Ae.length-1],he=(Ie==null?void 0:Ie.artifactType)==="markdown"?J:Ie?le:"";try{await navigator.clipboard.writeText(he)}catch{}};if(j.addEventListener("click",async()=>{let J=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(J&&H){let{markdown:le,jsonPayload:Ie,id:he}=Ee();try{await J({actionId:"primary",artifactId:he,markdown:le,jsonPayload:Ie})}catch{}return}await de()}),k&&(S!=null&&S.length)){let J=()=>{var Ie;return(Ie=u.closest("[data-persona-root]"))!=null?Ie:document.body},le=()=>{O=rs({items:S.map(Ie=>({id:Ie.id,label:Ie.label})),onSelect:async Ie=>{let{markdown:he,jsonPayload:Ke,id:gt}=Ee(),Wt=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Wt?await Wt({actionId:Ie,artifactId:gt,markdown:he,jsonPayload:Ke}):Ie==="markdown"||Ie==="md"?await navigator.clipboard.writeText(he):Ie==="json"||Ie==="source"?await navigator.clipboard.writeText(Ke):await navigator.clipboard.writeText(he||Ke)}catch{}},anchor:U!=null?U:k,position:"bottom-right",portal:J()})};u.isConnected?le():requestAnimationFrame(le),k.addEventListener("click",Ie=>{Ie.stopPropagation(),O==null||O.toggle()})}F.addEventListener("click",async()=>{var J;try{await((J=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:J.call(n))}catch{}ae()}),Z.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let ee=()=>{o&&(T.setAttribute("aria-pressed",v==="rendered"?"true":"false"),L.setAttribute("aria-pressed",v==="source"?"true":"false"))};T.addEventListener("click",()=>{v="rendered",ee(),ae()}),L.addEventListener("click",()=>{v="source",ee(),ae()});let Le=b("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(f.replaceChildren(),A.append(T,L),U?W.append(U,F,Z):W.append(j,F,Z),f.append(A,Le,W),ee()):(f.appendChild(g),f.appendChild(y)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let Pe=b("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),ne=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Pe.style.paddingLeft=s,Pe.style.paddingRight=s,ne.style.padding=s),u.appendChild(f),u.appendChild(Pe),u.appendChild(ne);let Ae=[],re=null,se=!1,ae=()=>{var he,Ke,gt,Wt;let J=o&&Ae.length<=1;Pe.classList.toggle("persona-hidden",J),Pe.replaceChildren();for(let tt of Ae){let ge=b("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ge.type="button",ge.textContent=tt.title||tt.id.slice(0,8),tt.id===re&&ge.classList.add("persona-bg-persona-container","persona-border-persona-border"),ge.addEventListener("click",()=>t.onSelect(tt.id)),Pe.appendChild(ge)}ne.replaceChildren();let le=re&&Ae.find(tt=>tt.id===re)||Ae[Ae.length-1];if(!le)return;if(o){let tt=le.artifactType==="markdown"?"MD":(he=le.component)!=null?he:"Component",X=(le.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Le.textContent=`${X} \xB7 ${tt}`}else g.textContent="Artifacts";if(le.artifactType==="markdown"){if(o&&v==="source"){let ge=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ge.textContent=(Ke=le.markdown)!=null?Ke:"",ne.appendChild(ge);return}let tt=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");tt.innerHTML=d((gt=le.markdown)!=null?gt:""),ne.appendChild(tt);return}let Ie=le.component?Lo.get(le.component):void 0;if(Ie){let ge={message:{id:le.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=Ie((Wt=le.props)!=null?Wt:{},ge);if(X){ne.appendChild(X);return}}catch{}}ne.appendChild(Tw(le))},fe=()=>{var le;let J=Ae.length>0;if(u.classList.toggle("persona-hidden",!J),c){let Ie=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ke=((le=Ie==null?void 0:Ie.classList.contains("persona-artifact-narrow-host"))!=null?le:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;J&&Ke&&se?(c.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:c,update(J){var le,Ie,he;Ae=J.artifacts,re=(he=(Ie=J.selectedId)!=null?Ie:(le=J.artifacts[J.artifacts.length-1])==null?void 0:le.id)!=null?he:null,Ae.length>0&&(se=!0),ae(),fe()},setMobileOpen(J){se=J,!J&&c?(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):fe()}}}function rr(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function sf(e,t){var s,a,i,d;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"),!rr(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function Ew(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")}function Ei(e,t){var d,c,p,u,f,g,y,v,A,T;if(!rr(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"),Ew(e),sf(e,t);return}let n=(c=(d=t.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(g=n==null?void 0:n.paneBackground)==null?void 0:g.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let o=(y=n==null?void 0:n.panePadding)==null?void 0:y.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(A=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:A.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),sf(e,t)}var af=["panel","seamless"];function Mi(e,t){var i,d,c,p,u,f;for(let g of af)e.classList.remove(`persona-artifact-appearance-${g}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!rr(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=n==null?void 0:n.paneAppearance)!=null?c:"panel",o=af.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let g=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function lf(e,t){var n,r,o;return!t||!rr(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Mw(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function kw(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Lw(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Pw(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function cf(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function df(e,t,n,r,o,s){let a=Mw(o,200),i=Pw(t,n,r,200);i=Math.max(a,i);let d=kw(s);return d!==null&&(i=Math.min(i,d)),Lw(e,a,i)}var pf={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"}},Vl=(e,t,n,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var y,v,A;if(s.dataset.enhanced==="true")return;let a=(y=s.dataset.tvForm)!=null?y:"init";s.dataset.enhanced="true";let i=(v=pf[a])!=null?v:pf.init;s.classList.add("persona-form-card","persona-space-y-4");let d=b("div","persona-space-y-1"),c=b("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let T=b("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var S,H;let L=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${t.id}-${a}-${T.name}`;let W=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");W.textContent=T.label,L.appendChild(W);let R=(S=T.type)!=null?S:"text",P;R==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=R),P.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",P.id=`${t.id}-${a}-${T.name}`,P.name=T.name,P.placeholder=(H=T.placeholder)!=null?H:"",T.required&&(P.required=!0),L.appendChild(P),p.appendChild(L)});let u=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=b("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=(A=i.submitLabel)!=null?A:"Submit",u.appendChild(f),u.appendChild(g),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async T=>{var P,S;T.preventDefault();let L=(P=n.formEndpoint)!=null?P:"/form",W=new FormData(p),R={};W.forEach((H,U)=>{R[U]=H}),R.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let H=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(R)});if(!H.ok)throw new Error(`Form submission failed (${H.status})`);let U=await H.json();f.textContent=(S=U.message)!=null?S:"Thanks! We'll be in touch soon.",U.success&&U.nextPrompt&&await r.sendMessage(String(U.nextPrompt))}catch(H){f.textContent=H instanceof Error?H.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Kl=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,o;return((r=n.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(s=>s.id));return[...n.filter(s=>!r.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},ki=new Kl;var uf=()=>{let e=new Map,t=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:t,off:n,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Iw=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Rw=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(n,o+1)}return null},Li=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Iw(e),n=Rw(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},Gl=e=>typeof e=="string"?e:e==null?"":String(e),Ns={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Gl(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=Gl(n.element);if(r&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Gl(n.text)}}},mf=e=>Array.isArray(e)?e.map(t=>String(t)):[],Pi=e=>{let t=new Set(mf(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(mf(e.getSessionMetadata().processedActionMessageIds))},r=()=>{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!="undefined"&&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((c,p)=>c||(p==null?void 0:p({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),r();let d={action:i,message:s.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",d)},u=c(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var Ww=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Hw=e=>e.map(t=>({...t,streaming:!1})),Bw=e=>e.map(t=>({...t,status:"complete"})),Jl=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?Ww(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?Hw(n.messages):void 0,artifacts:n.artifacts?Bw(n.artifacts):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as Dw,STR as Nw,OBJ as Ow}from"partial-json";function Fw(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function _w(e,t){if(!Fw(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 Xl(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let o=Dw(n,Nw|Ow),s=_w(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function $w(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ql(e,t){let{config:n,message:r,onPropsUpdate:o}=t,s=Lo.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:r,config:n,updateProps:i=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function jw(){let e=Xl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function gf(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 Ii(e){let t=gf(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 Yl(e){let t=gf(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 r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var Uw=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Zl(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=Uw}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,f=document.createElement("div");f.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=r,g.appendChild(y);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=o,g.appendChild(v),f.appendChild(g);let A=document.createElement("div");A.className="persona-feedback-rating persona-feedback-rating-csat",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let S=1;S<=5;S++){let H=document.createElement("button");H.type="button",H.className="persona-feedback-rating-btn persona-feedback-star-btn",H.setAttribute("role","radio"),H.setAttribute("aria-checked","false"),H.setAttribute("aria-label",`${S} star${S>1?"s":""}: ${c[S-1]}`),H.title=c[S-1],H.dataset.rating=String(S),H.innerHTML=`
|
|
31
31
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
32
32
|
<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>
|
|
33
33
|
</svg>
|
|
34
|
-
`,I.addEventListener("click",()=>{u=C,T.forEach((j,$)=>{let R=$<C;j.classList.toggle("selected",R),j.setAttribute("aria-checked",$===C-1?"true":"false")})}),T.push(I),S.appendChild(I)}f.appendChild(S);let L=null;if(d){let C=document.createElement("div");C.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),C.appendChild(L),f.appendChild(C)}let P=document.createElement("div");P.className="persona-feedback-actions";let E=document.createElement("button");E.type="button",E.className="persona-feedback-btn persona-feedback-btn-skip",E.textContent=i,E.addEventListener("click",()=>{n==null||n(),p.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=a,k.addEventListener("click",async()=>{if(u===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let C=(L==null?void 0:L.value.trim())||void 0;await t(u,C),p.remove()}catch(C){k.disabled=!1,k.textContent=a,console.error("[CSAT Feedback] Failed to submit:",C)}}),P.appendChild(E),P.appendChild(k),f.appendChild(P),p.appendChild(f),p}function Vl(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:p="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 f=null,g=document.createElement("div");g.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,b.appendChild(v);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=o,b.appendChild(S),g.appendChild(b);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=c;let E=document.createElement("span");E.className="persona-feedback-label-high",E.textContent=p,L.appendChild(P),L.appendChild(E);let k=document.createElement("div");k.className="persona-feedback-numbers";let C=[];for(let N=0;N<=10;N++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-number-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`Rating ${N} out of 10`),O.textContent=String(N),O.dataset.rating=String(N),N<=6?O.classList.add("persona-feedback-detractor"):N<=8?O.classList.add("persona-feedback-passive"):O.classList.add("persona-feedback-promoter"),O.addEventListener("click",()=>{f=N,C.forEach((Z,Ee)=>{Z.classList.toggle("selected",Ee===N),Z.setAttribute("aria-checked",Ee===N?"true":"false")})}),C.push(O),k.appendChild(O)}T.appendChild(L),T.appendChild(k),g.appendChild(T);let I=null;if(d){let N=document.createElement("div");N.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"),N.appendChild(I),g.appendChild(N)}let j=document.createElement("div");j.className="persona-feedback-actions";let $=document.createElement("button");$.type="button",$.className="persona-feedback-btn persona-feedback-btn-skip",$.textContent=i,$.addEventListener("click",()=>{n==null||n(),u.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(f===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let N=(I==null?void 0:I.value.trim())||void 0;await t(f,N),u.remove()}catch(N){R.disabled=!1,R.textContent=a,console.error("[NPS Feedback] Failed to submit:",N)}}),j.appendChild($),j.appendChild(R),g.appendChild(j),u.appendChild(g),u}var Bs="persona-chat-history",Lw=30*1e3,Pw={"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 Iw(e){var r,o,s;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(o=Pw[i.type])!=null?o:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Mi(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 Rw(e){var t,n,r,o,s,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function Ww(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Kl=e=>!e||typeof e!="object"?{}:{...e},nf=e=>e.map(t=>({...t,streaming:!1})),rf=(e,t,n)=>{let r=e!=null&&e.markdown?vs(e.markdown):null,o=Xs(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(e==null?void 0: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=>{var p,u,f;let a=(p=s.text)!=null?p:"",i=(u=s.message.rawContent)!=null?u:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});g!==null&&(a=g.text,g.persist||(s.message.__skipPersist=!0),g.resubmit&&!s.streaming&&n&&n())}let d=Vo()!==null,c;if(e!=null&&e.postprocessMessage){let g=e.postprocessMessage({...s,text:a,raw:(f=i!=null?i:s.text)!=null?f:""});c=o?o(g):g}else if(r){let g=s.streaming?rm(a):a,b=r(g);c=o&&d?o(b):b}else c=Kr(a);return c}};function of(e){var i,d,c,p;let t=y("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",o=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=ye(n,r,o,s);if(a&&t.appendChild(a),e!=null&&e.label){let u=y("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var Gl=(e,t,n)=>{var $c,jc,Uc,qc,zc,Vc,Kc,Gc,Jc,Xc,Qc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Rd,Wd,Hd,Bd,Dd;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 r=hl(t),o=Si.getForInstance(r.plugins),{plugin:s,teardown:a}=Og();r.components&&Mo.registerAll(r.components);let i=Zg(),c=r.persistState===!1?null:($c=r.storageAdapter)!=null?$c:_l(),p={},u=null,f=!1,g=l=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:h,open:x}=m;return x&&(f=!0),h}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return l};if(c!=null&&c.load)try{let l=c.load();if(l&&typeof l.then=="function")u=l.then(m=>{let h=m!=null?m:{messages:[],metadata:{}};return g(h)});else{let m=l!=null?l:{messages:[],metadata:{}},h=g(m);h.metadata&&(p=Kl(h.metadata)),(jc=h.messages)!=null&&jc.length&&(r={...r,initialMessages:h.messages}),(Uc=h.artifacts)!=null&&Uc.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(qc=h.selectedArtifactId)!=null?qc:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=g({messages:[],metadata:{}});(zc=l.messages)!=null&&zc.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let b=()=>p,v=l=>{var h;p=(h=l({...p}))!=null?h:{},Pn()},S=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ti],T=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Hs.message,Hs.messageAndClick],L=Ei({parsers:S,handlers:T,getSessionMetadata:b,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null});L.syncFromMetadata();let P=(Kc=(Vc=r.launcher)==null?void 0:Vc.enabled)!=null?Kc:!0,E=(Jc=(Gc=r.launcher)==null?void 0:Gc.autoExpand)!=null?Jc:!1,k=(Xc=r.autoFocusInput)!=null?Xc:!1,C=E,I=P,j=(Yc=(Qc=r.layout)==null?void 0:Qc.header)==null?void 0:Yc.layout,$=!1,R=()=>To(r),N=()=>P||R(),O=R()?!1:P?E:!0,Z=!1,Ee=null,de=()=>{Z=!0,Ee&&clearTimeout(Ee),Ee=setTimeout(()=>{Z&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Z=!1)},1e4)},ee=rf(r,L,de),Le=(ed=(Zc=r.features)==null?void 0:Zc.showReasoning)!=null?ed:!0,Pe=(nd=(td=r.features)==null?void 0:td.showToolCalls)!=null?nd:!0,ne=(od=(rd=r.features)==null?void 0:rd.showEventStreamToggle)!=null?od:!1,Ae=(ad=(sd=r.features)==null?void 0:sd.scrollToBottom)!=null?ad:{},re=(ld=(id=r.features)==null?void 0:id.scrollBehavior)!=null?ld:{},ae=`${(dd=typeof r.persistState=="object"?(cd=r.persistState)==null?void 0:cd.keyPrefix:void 0)!=null?dd:"persona-"}event-stream`,fe=ne?new Sa(ae):null,$e=(md=(ud=(pd=r.features)==null?void 0:pd.eventStream)==null?void 0:ud.maxEvents)!=null?md:2e3,V=ne?new Aa($e,fe):null,Q=ne?new Ta:null,Me=null,J=!1,le=null,Ie=0;fe==null||fe.open().then(()=>V==null?void 0:V.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let he={onCopy:l=>{var m,h;i.emit("message:copy",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.id,"copy").catch(x=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",x)}),(h=(m=r.messageActions)==null?void 0:m.onCopy)==null||h.call(m,l)},onFeedback:l=>{var m,h;i.emit("message:feedback",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.messageId,l.type).catch(x=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",x)}),(h=(m=r.messageActions)==null?void 0:m.onFeedback)==null||h.call(m,l)}},Ke=(gd=r.statusIndicator)!=null?gd:{},gt=l=>{var m,h,x,A,W,U;return l==="idle"?(m=Ke.idleText)!=null?m:nn.idle:l==="connecting"?(h=Ke.connectingText)!=null?h:nn.connecting:l==="connected"?(x=Ke.connectedText)!=null?x:nn.connected:l==="error"?(A=Ke.errorText)!=null?A:nn.error:l==="paused"?(W=Ke.pausedText)!=null?W:nn.paused:l==="resuming"?(U=Ke.resumingText)!=null?U:nn.resuming:nn[l]};function Wt(l,m,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=m,A.style.color="inherit",A.style.textDecoration="none",l.appendChild(A)}else l.textContent=m}let tt=Sg({config:r,showClose:N()}),{wrapper:ge,panel:X,pillRoot:it}=tt.shell,Ve=tt.panelElements,{container:Se,body:we,messagesWrapper:Ze,suggestions:qt,textarea:be,sendButton:pe,sendButtonWrapper:vn,composerForm:Ct,statusText:fn,introTitle:yr,introSubtitle:br,closeButton:Ue,iconHolder:M,headerTitle:ue,headerSubtitle:Te,header:ke,footer:He,actionsRow:nt,leftActions:Qe,rightActions:ht}=Ve,me=Ve.setSendButtonMode,B=Ve.micButton,xe=Ve.micButtonWrapper,ce=Ve.attachmentButton,ft=Ve.attachmentButtonWrapper,Je=Ve.attachmentInput,Lt=Ve.attachmentPreviewsContainer;Se.classList.add("persona-relative"),we.classList.add("persona-relative");let Mt=12,xt=()=>{var l;return(l=Ae.label)!=null?l:""},Rt=()=>{var l;return(l=Ae.iconName)!=null?l:"arrow-down"},Xt=()=>Ae.enabled!==!1,Ot=()=>{var l;return(l=re.mode)!=null?l:"anchor-top"},en=()=>Ot()==="follow"||Ot()==="anchor-top"&&so,xr=()=>{var l;return(l=re.anchorTopOffset)!=null?l:16},Nr=()=>{var l;return(l=re.restorePosition)!=null?l:"bottom"},or=()=>re.pauseOnInteraction===!0,sr=()=>re.showActivityWhilePinned!==!1,Xr=()=>re.announce===!0,zt=y("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");zt.type="button",zt.style.display="none",zt.setAttribute("data-persona-scroll-to-bottom","true");let ar=y("span","persona-flex persona-items-center"),Or=y("span",""),Hn=y("span","");Hn.setAttribute("data-persona-scroll-to-bottom-count",""),Hn.style.display="none",zt.append(ar,Or,Hn),Se.appendChild(zt);let kn=y("div","persona-stream-anchor-spacer");kn.setAttribute("aria-hidden","true"),kn.setAttribute("data-persona-anchor-spacer",""),kn.style.flexShrink="0",kn.style.pointerEvents="none",kn.style.height="0px",we.appendChild(kn);let Bn=y("div","persona-sr-only");Bn.setAttribute("aria-live","polite"),Bn.setAttribute("aria-atomic","true"),Bn.setAttribute("role","status"),Bn.setAttribute("data-persona-live-region",""),Object.assign(Bn.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"}),Se.appendChild(Bn);let ir=null,vr=null,Qr=l=>{!Xr()||!l||(vr=l,ir===null&&(ir=setTimeout(()=>{ir=null,vr&&Xr()&&(Bn.textContent=vr),vr=null},400)))},zn=()=>{let m=He.style.display==="none"?0:He.offsetHeight;zt.style.bottom=`${m+Mt}px`};zn();let Yr=()=>{let l=!!xt();zt.setAttribute("aria-label",xt()||"Jump to latest"),zt.title=xt(),zt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),ar.innerHTML="";let m=ye(Rt(),"14px","currentColor",2);m?(ar.appendChild(m),ar.style.display=""):ar.style.display="none",Or.textContent=xt(),Or.style.display=l?"":"none"};Yr();let At=null,wr=null,Cr=o.find(l=>l.renderHeader);if(Cr!=null&&Cr.renderHeader){let l=Cr.renderHeader({config:r,defaultRenderer:()=>{let m=Eo({config:r,showClose:N()});return Ls(Se,m,r),m.header},onClose:()=>_t(!1,"user")});if(l){let m=Se.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),ke=l,tt.header.element=l)}}let Fr=()=>{var m,h,x,A;if(!V)return;if(J=!0,!Me&&V&&(Me=Ug({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>lr(),config:r,plugins:o,getThroughput:()=>{var W;return(W=Q==null?void 0:Q.getMetric())!=null?W:{status:"idle"}}})),Me&&(we.style.display="none",(m=He.parentNode)==null||m.insertBefore(Me.element,He),Me.update()),yt){yt.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let W=(A=(x=(h=r.features)==null?void 0:h.eventStream)==null?void 0:x.classNames)==null?void 0:A.toggleButtonActive;W&&W.split(/\s+/).forEach(U=>U&&yt.classList.add(U))}let l=()=>{if(!J)return;let W=Date.now();W-Ie>=200&&(Me==null||Me.update(),Ie=W),le=requestAnimationFrame(l)};Ie=0,le=requestAnimationFrame(l),Fn(),i.emit("eventStream:opened",{timestamp:Date.now()})},lr=()=>{var l,m,h;if(J){if(J=!1,Me&&Me.element.remove(),we.style.display="",yt){yt.style.boxShadow="";let x=(h=(m=(l=r.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:h.toggleButtonActive;x&&x.split(/\s+/).forEach(A=>A&&yt.classList.remove(A))}le!==null&&(cancelAnimationFrame(le),le=null),Fn(),i.emit("eventStream:closed",{timestamp:Date.now()})}},yt=null;if(ne){let l=(hd=(fd=r.features)==null?void 0:fd.eventStream)==null?void 0:hd.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");yt=y("button",m),yt.style.width="28px",yt.style.height="28px",yt.style.color=Mn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let h=ye("activity","18px","currentColor",1.5);h&&yt.appendChild(h);let x=Ve.clearChatButtonWrapper,A=Ve.closeButtonWrapper,W=x||A;W&&W.parentNode===ke?ke.insertBefore(yt,W):ke.appendChild(yt),yt.addEventListener("click",()=>{J?lr():Fr()})}let Lo=l=>{var A,W,U,_,D;let m=r.attachments;if(!(m!=null&&m.enabled))return;let h=(A=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?A:l.querySelector(".persona-attachment-previews");if(!h){h=y("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 ie=l.querySelector("[data-persona-composer-form]");ie!=null&&ie.parentNode?ie.parentNode.insertBefore(h,ie):l.insertBefore(h,l.firstChild)}if(!((W=l.querySelector("[data-persona-composer-attachment-input]"))!=null?W:l.querySelector('input[type="file"]'))){let ie=y("input");ie.type="file",ie.setAttribute("data-persona-composer-attachment-input",""),ie.accept=((U=m.allowedTypes)!=null?U:Gr).join(","),ie.multiple=((_=m.maxFiles)!=null?_:4)>1,ie.style.display="none",ie.setAttribute("aria-label",(D=m.buttonTooltipText)!=null?D:"Attach files"),l.appendChild(ie)}},Ar=o.find(l=>l.renderComposer);if(Ar!=null&&Ar.renderComposer){let l=r.composer,m=Ar.renderComposer({config:r,defaultRenderer:()=>wa({config:r}).footer,onSubmit:h=>{var U;if(!F||F.isStreaming())return;let x=h.trim(),A=(U=At==null?void 0:At.hasAttachments())!=null?U:!1;if(!x&&!A)return;hc();let W;A&&(W=[],W.push(...At.getContentParts()),x&&W.push(Ka(x))),F.sendMessage(x,{contentParts:W}),A&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Je==null||Je.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((yd=r.voiceRecognition)==null?void 0:yd.enabled)===!0?()=>{wr==null||wr()}:void 0});m&&(tt.replaceComposer(m),He=tt.composer.footer)}let Po=l=>{let m=(...oe)=>{for(let Y of oe){let ve=l.querySelector(Y);if(ve)return ve}return null},h=l.querySelector("[data-persona-composer-form]"),x=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),W=l.querySelector("[data-persona-composer-mic]"),U=l.querySelector("[data-persona-composer-status]");h&&(Ct=h),x&&(be=x),A&&(pe=A),W&&(B=W,xe=W.parentElement),U&&(fn=U);let _=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(qt=_);let D=m("[data-persona-composer-attachment-button]",".persona-attachment-button");D&&(ce=D,ft=D.parentElement),Je=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Lt=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ie=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ie&&(nt=ie)};Lo(He),Po(He);let Ln=(Cd=(bd=r.layout)==null?void 0:bd.contentMaxWidth)!=null?Cd:R()?(wd=(vd=(xd=r.launcher)==null?void 0:xd.composerBar)==null?void 0:vd.contentMaxWidth)!=null?wd:"720px":void 0;if(Ln&&(Ze.style.maxWidth=Ln,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%"),Ln&&Ct&&!R()&&(Ct.style.maxWidth=Ln,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),Ln&&qt&&!R()&&(qt.style.maxWidth=Ln,qt.style.marginLeft="auto",qt.style.marginRight="auto"),Ln&&Lt&&!R()&&(Lt.style.maxWidth=Ln,Lt.style.marginLeft="auto",Lt.style.marginRight="auto"),(Ad=r.attachments)!=null&&Ad.enabled&&Je&&Lt){At=Es.fromConfig(r.attachments),At.setPreviewsContainer(Lt),Je.addEventListener("change",h=>{let x=h.target;At==null||At.handleFileSelect(x.files),x.value=""});let l=r.attachments.dropOverlay,m=of(l);Se.appendChild(m)}(()=>{var x,A;let l=(A=(x=r.layout)==null?void 0:x.slots)!=null?A:{},m=W=>{switch(W){case"body-top":return Se.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ze;case"footer-top":return qt;case"composer":return Ct;case"footer-bottom":return fn;default:return null}},h=(W,U)=>{var _;switch(W){case"header-left":case"header-center":case"header-right":if(W==="header-left")ke.insertBefore(U,ke.firstChild);else if(W==="header-right")ke.appendChild(U);else{let D=ke.querySelector(".persona-flex-col");D?(_=D.parentNode)==null||_.insertBefore(U,D.nextSibling):ke.appendChild(U)}break;case"body-top":{let D=we.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith(U):we.insertBefore(U,we.firstChild);break}case"body-bottom":we.appendChild(U);break;case"footer-top":qt.replaceWith(U);break;case"footer-bottom":fn.replaceWith(U);break;default:break}};for(let[W,U]of Object.entries(l))if(U)try{let _=U({config:r,defaultContent:()=>m(W)});_&&h(W,_)}catch(_){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${W}":`,_)}})();let Zr=l=>{var U,_;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 W=h.getAttribute("data-bubble-type");if(W==="reasoning")Is.has(A)?Is.delete(A):Is.add(A),Lg(A,x);else if(W==="tool")Rs.has(A)?Rs.delete(A):Rs.add(A),Pg(A,x,r);else if(W==="approval"){let D=r.approval!==!1?r.approval:void 0,ie=((U=D==null?void 0:D.detailsDisplay)!=null?U:"collapsed")==="expanded",oe=(_=ns.get(A))!=null?_:ie;ns.set(A,!oe),Hg(A,x,r)}Mr.delete(A)};Ze.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Zr(l))}),Ze.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Zr(l))}),Ze.addEventListener("copy",l=>{let{clipboardData:m}=l;if(!m)return;let h=Ze.getRootNode(),x=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let A=x.toString(),W=og(A);!W||W===A||(m.setData("text/plain",W),l.preventDefault())});let _r=new Map,eo=null,to="idle",Io={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Ro=(l,m)=>{let{icon:h,label:x}=Io[m];l.setAttribute("aria-label",x),l.title=x,l.setAttribute("aria-pressed",m==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",m!=="idle"),l.classList.toggle("persona-message-action-loading",m==="loading");let A=ye(h,14,"currentColor",2);A&&(l.innerHTML="",l.appendChild(A))},no=()=>{Ze.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{var W;let h=m.closest("[data-actions-for]"),x=(W=h==null?void 0:h.getAttribute("data-actions-for"))!=null?W:null;Ro(m,x&&x===eo?to:"idle")})};Ze.addEventListener("click",l=>{var U;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 W=h.getAttribute("data-action");if(W==="copy"){let D=F.getMessages().find(ie=>ie.id===A);if(D&&he.onCopy){let ie=D.content||"";navigator.clipboard.writeText(ie).then(()=>{h.classList.add("persona-message-action-success");let oe=ye("check",14,"currentColor",2);oe&&(h.innerHTML="",h.appendChild(oe)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Y=ye("copy",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))},2e3)}).catch(oe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",oe)}),he.onCopy(D)}}else if(W==="read-aloud")F.toggleReadAloud(A);else if(W==="upvote"||W==="downvote"){let D=((U=_r.get(A))!=null?U:null)===W,ie=W==="upvote"?"thumbs-up":"thumbs-down";if(D){_r.delete(A),h.classList.remove("persona-message-action-active");let oe=ye(ie,14,"currentColor",2);oe&&(h.innerHTML="",h.appendChild(oe))}else{let oe=W==="upvote"?"downvote":"upvote",Y=x.querySelector(`[data-action="${oe}"]`);if(Y){Y.classList.remove("persona-message-action-active");let qe=ye(oe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);qe&&(Y.innerHTML="",Y.appendChild(qe))}_r.set(A,W),h.classList.add("persona-message-action-active");let ve=ye(ie,14,"currentColor",2);ve&&(ve.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ve)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Fe=F.getMessages().find(je=>je.id===A);Fe&&he.onFeedback&&he.onFeedback({type:W,messageId:Fe.id,message:Fe})}}}),Ze.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 W=h.getAttribute("data-approval-action");if(!W)return;let U=W==="approve"?"approved":"denied",D=F.getMessages().find(oe=>oe.id===A);if(!(D!=null&&D.approval))return;let ie=x.querySelector("[data-approval-buttons]");ie&&ie.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?F.resolveWebMcpApproval(A,U):F.resolveApproval(D.approval,U)});let vt=null,Dn=null,Nn={artifacts:[],selectedId:null},wn=!1,St={current:null};Ze.addEventListener("click",l=>{var Y,ve,Oe,Fe,je;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-download-artifact");if(!x||((Oe=(ve=(Y=r.features)==null?void 0:Y.artifacts)==null?void 0:ve.onArtifactAction)==null?void 0:Oe.call(ve,{type:"download",artifactId:x}))===!0)return;let W=F.getArtifactById(x),U=W==null?void 0:W.markdown,_=(W==null?void 0:W.title)||"artifact";if(!U){let qe=h.closest("[data-open-artifact]"),ut=qe==null?void 0:qe.closest("[data-message-id]"),st=ut==null?void 0:ut.getAttribute("data-message-id");if(st){let Re=F.getMessages().find(ze=>ze.id===st);if(Re!=null&&Re.rawContent)try{let ze=JSON.parse(Re.rawContent);U=(Fe=ze==null?void 0:ze.props)==null?void 0:Fe.markdown,_=((je=ze==null?void 0:ze.props)==null?void 0:je.title)||_}catch{}}}if(!U)return;let D=new Blob([U],{type:"text/markdown"}),ie=URL.createObjectURL(D),oe=document.createElement("a");oe.href=ie,oe.download=`${_}.md`,oe.click(),URL.revokeObjectURL(ie)}),Ze.addEventListener("click",l=>{var W,U,_;let h=l.target.closest("[data-open-artifact]");if(!h)return;let x=h.getAttribute("data-open-artifact");!x||((_=(U=(W=r.features)==null?void 0:W.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:_.call(U,{type:"open",artifactId:x}))===!0||(l.preventDefault(),l.stopPropagation(),wn=!1,F.selectArtifact(x),Sr())}),Ze.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let Vn=Ve.composerOverlay,Kn=(l,m,h)=>{var _,D,ie,oe;let x=m.trim();if(!x||!St.current)return;let A=(_=l.getAttribute("data-tool-call-id"))!=null?_:"",W=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:x,answers:h.structured,values:(D=h.values)!=null?D:h.source==="multi"?x.split(", "):[x],isFreeText:W,source:h.source},bubbles:!0,composed:!0})),Jo(Vn,A);let U=St.current.getMessages().find(Y=>{var ve;return((ve=Y.toolCall)==null?void 0:ve.id)===A});(ie=U==null?void 0:U.agentMetadata)!=null&&ie.awaitingLocalTool?St.current.resolveAskUserQuestion(U,(oe=h.structured)!=null?oe:x):St.current.sendMessage(x)},On=l=>{var A;let m=St.current;if(!m)return;let h=(A=l.getAttribute("data-tool-call-id"))!=null?A:"",x=m.getMessages().find(W=>{var U;return((U=W.toolCall)==null?void 0:U.id)===h});x&&m.persistAskUserQuestionProgress(x,{answers:Na(l,x),currentIndex:er(l)})},ro=l=>Object.entries(l).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Ce=l=>{var A,W,U;if(((W=(A=r.features)==null?void 0:A.askUserQuestion)==null?void 0:W.groupedAutoAdvance)===!1)return;let m=er(l),h=Cs(l);if(m>=h-1)return;let x=(U=St.current)==null?void 0:U.getMessages().find(_=>{var D;return((D=_.toolCall)==null?void 0:D.id)===l.getAttribute("data-tool-call-id")});x&&(Oa(l,x,r,m+1),On(l))};Vn.addEventListener("click",l=>{var W,U,_,D,ie,oe,Y,ve,Oe,Fe,je,qe,ut,st;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 Be=(W=x.getAttribute("data-tool-call-id"))!=null?W:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),Jo(Vn,Be);let Re=(U=St.current)==null?void 0:U.getMessages().find(ze=>{var Xe;return((Xe=ze.toolCall)==null?void 0:Xe.id)===Be});(_=Re==null?void 0:Re.agentMetadata)!=null&&_.awaitingLocalTool&&((D=St.current)==null||D.markAskUserQuestionResolved(Re),(ie=St.current)==null||ie.resolveAskUserQuestion(Re,"(dismissed)"));return}if(A==="pick"){let Be=h.getAttribute("data-option-label");if(!Be)return;let Re=x.getAttribute("data-multi-select")==="true",ze=xo(x);if(ze&&Re){let Xe=Go(x)[er(x)],bt=new Set(Array.isArray(Xe)?Xe:[]);bt.has(Be)?bt.delete(Be):bt.add(Be),vo(x,Array.from(bt)),On(x);return}if(ze){vo(x,Be),On(x),Ce(x);return}if(Re){let Xe=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Xe?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Xe);let bt=x.querySelector('[data-ask-user-action="submit-multi"]');bt&&(bt.disabled=el(x).length===0);return}Kn(x,Be,{source:"pick",values:[Be]});return}if(A==="submit-multi"){let Be=el(x);if(Be.length===0)return;Kn(x,Be.join(", "),{source:"multi",values:Be});return}if(A==="open-free-text"){let Be=x.querySelector('[data-ask-free-text-row="true"]');if(Be){Be.classList.remove("persona-hidden");let Re=Be.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus()}return}if(A==="focus-free-text"){let Be=x.querySelector('[data-ask-free-text-input="true"]');Be==null||Be.focus();return}if(A==="submit-free-text"){let Be=x.querySelector('[data-ask-free-text-input="true"]'),Re=(oe=Be==null?void 0:Be.value)!=null?oe:"";if(!Re.trim())return;if(xo(x)){vo(x,Re.trim()),On(x),Ce(x);return}Kn(x,Re,{source:"free-text"});return}if(A==="next"||A==="back"){if(!St.current)return;let Be=(Y=x.getAttribute("data-tool-call-id"))!=null?Y:"",Re=St.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Be});if(!Re)return;let ze=x.querySelector('[data-ask-free-text-input="true"]'),Xe=(Oe=(ve=ze==null?void 0:ze.value)==null?void 0:ve.trim())!=null?Oe:"";if(Xe){let De=Go(x)[er(x)];(typeof De!="string"||De!==Xe)&&vo(x,Xe)}let bt=A==="next"?1:-1,H=er(x)+bt;Oa(x,Re,r,H),On(x);return}if(A==="submit-all"){if(!St.current)return;let Be=(Fe=x.getAttribute("data-tool-call-id"))!=null?Fe:"",Re=St.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Be});if(!Re)return;let ze=x.querySelector('[data-ask-free-text-input="true"]'),Xe=(qe=(je=ze==null?void 0:ze.value)==null?void 0:je.trim())!=null?qe:"";Xe&&vo(x,Xe);let bt=Na(x,Re);St.current.persistAskUserQuestionProgress(Re,{answers:bt,currentIndex:er(x)});let H=ro(bt);Kn(x,H||"(submitted)",{source:"submit-all",structured:bt});return}if(A==="skip"){if(!St.current)return;let Be=(ut=x.getAttribute("data-tool-call-id"))!=null?ut:"",Re=St.current.getMessages().find(We=>{var Ye;return((Ye=We.toolCall)==null?void 0:Ye.id)===Be});if(!Re)return;let ze=xo(x),Xe=er(x),bt=Cs(x),H=Xe>=bt-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),Jo(Vn,Be),(st=Re.agentMetadata)!=null&&st.awaitingLocalTool&&(St.current.markAskUserQuestionResolved(Re),St.current.resolveAskUserQuestion(Re,"(dismissed)"));return}vo(x,"");let De=x.querySelector('[data-ask-free-text-input="true"]');if(De&&(De.value=""),H){let We=Na(x,Re),Ye=ro(We);Kn(x,Ye||"(skipped)",{source:"submit-all",structured:We});return}Oa(x,Re,r,Xe+1),On(x);return}}),Vn.addEventListener("keydown",l=>{var W;if(l.key!=="Enter")return;let h=l.target;if(!((W=h.matches)!=null&&W.call(h,'[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(xo(x)){vo(x,A.trim()),On(x),Ce(x);return}Kn(x,A,{source:"free-text"})}});let $r=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let m=l.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let h=Vn.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),W=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];W&&(l.preventDefault(),W.click())};document.addEventListener("keydown",$r);let Gn=null,Ft=null,Jn=null,jr=null,Ds=()=>{};function as(){jr==null||jr(),jr=null}let Ns=()=>{var U;if(!Gn||!Ft)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=((U=e.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){Ft.style.removeProperty("position"),Ft.style.removeProperty("left"),Ft.style.removeProperty("top"),Ft.style.removeProperty("bottom"),Ft.style.removeProperty("width"),Ft.style.removeProperty("z-index");return}let x=Gn.firstElementChild;if(!x||x===Ft)return;let A=10;Ft.style.position="absolute",Ft.style.top="0",Ft.style.bottom="0",Ft.style.width=`${A}px`,Ft.style.zIndex="5";let W=x.offsetWidth-A/2;Ft.style.left=`${Math.max(0,W)}px`},Wo=()=>{},Sr=()=>{var h,x,A,W,U;if(!vt||!rr(r))return;Ci(e,r),Ai(e,r),Wo();let l=(W=(A=(x=(h=r.features)==null?void 0:h.artifacts)==null?void 0:x.layout)==null?void 0:A.narrowHostMaxWidth)!=null?W:520,m=X.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),vt.update(Nn),wn?(vt.setMobileOpen(!1),vt.element.classList.add("persona-hidden"),(U=vt.backdrop)==null||U.classList.add("persona-hidden")):Nn.artifacts.length>0&&(vt.element.classList.remove("persona-hidden"),vt.setMobileOpen(!0)),Ds()};if(rr(r)){X.style.position="relative";let l=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(Se),vt=Vg(r,{onSelect:h=>{var x;return(x=St.current)==null?void 0:x.selectArtifact(h)},onDismiss:()=>{wn=!0,Sr()}}),vt.element.classList.add("persona-hidden"),Gn=m,m.appendChild(l),m.appendChild(vt.element),vt.backdrop&&X.appendChild(vt.backdrop),X.appendChild(m),Ds=()=>{var x,A,W,U;if(!Gn||!vt)return;if(!(((W=(A=(x=r.features)==null?void 0:x.artifacts)==null?void 0:A.layout)==null?void 0:W.resizable)===!0)){Jn==null||Jn(),Jn=null,as(),Ft&&(Ft.remove(),Ft=null),vt.element.style.removeProperty("width"),vt.element.style.removeProperty("maxWidth");return}if(!Ft){let _=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");_.setAttribute("role","separator"),_.setAttribute("aria-orientation","vertical"),_.setAttribute("aria-label","Resize artifacts panel"),_.tabIndex=0;let D=e.ownerDocument,ie=(U=D.defaultView)!=null?U:window,oe=Y=>{var ut,st;if(!vt||Y.button!==0||e.classList.contains("persona-artifact-narrow-host")||ie.innerWidth<=640)return;Y.preventDefault(),as();let ve=Y.clientX,Oe=vt.element.getBoundingClientRect().width,Fe=(st=(ut=r.features)==null?void 0:ut.artifacts)==null?void 0:st.layout,je=Be=>{let Re=Gn.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),Xe=ze?0:Xg(Gn,ie),bt=ze?0:_.getBoundingClientRect().width||6,H=Oe-(Be.clientX-ve),De=Qg(H,Re,Xe,bt,Fe==null?void 0:Fe.resizableMinWidth,Fe==null?void 0:Fe.resizableMaxWidth);vt.element.style.width=`${De}px`,vt.element.style.maxWidth="none",Ns()},qe=()=>{D.removeEventListener("pointermove",je),D.removeEventListener("pointerup",qe),D.removeEventListener("pointercancel",qe),jr=null;try{_.releasePointerCapture(Y.pointerId)}catch{}};jr=qe,D.addEventListener("pointermove",je),D.addEventListener("pointerup",qe),D.addEventListener("pointercancel",qe);try{_.setPointerCapture(Y.pointerId)}catch{}};_.addEventListener("pointerdown",oe),Ft=_,Gn.insertBefore(_,vt.element),Jn=()=>{_.removeEventListener("pointerdown",oe)}}if(Ft){let _=Nn.artifacts.length>0&&!wn;Ft.classList.toggle("persona-hidden",!_),Ns()}},Wo=()=>{var ie,oe,Y,ve,Oe,Fe,je,qe,ut,st,Be,Re,ze,Xe;if(!P||!vt||((oe=(ie=r.launcher)==null?void 0:ie.sidebarMode)!=null?oe:!1)||dn(r)&&nr(r).reveal==="emerge")return;let x=(Y=e.ownerDocument.defaultView)!=null?Y:window,A=(Oe=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?Oe:!0,W=(je=(Fe=r.launcher)==null?void 0:Fe.mobileBreakpoint)!=null?je:640;if(A&&x.innerWidth<=W||!Jg(r,P))return;let U=(st=(ut=(qe=r.launcher)==null?void 0:qe.width)!=null?ut:r.launcherWidth)!=null?st:tr,_=(Xe=(ze=(Re=(Be=r.features)==null?void 0:Be.artifacts)==null?void 0:Re.layout)==null?void 0:ze.expandedPanelWidth)!=null?Xe:"min(720px, calc(100vw - 24px))";Nn.artifacts.length>0&&!wn?(X.style.width=_,X.style.maxWidth=_):(X.style.width=U,X.style.maxWidth=U)},typeof ResizeObserver!="undefined"&&(Dn=new ResizeObserver(()=>{Sr()}),Dn.observe(X))}else X.appendChild(Se),R()&&it&&(Ve.peekBanner&&it.appendChild(Ve.peekBanner),it.appendChild(He));e.appendChild(ge),it&&e.appendChild(it);let oo=()=>{var De,We,Ye,Pt,_e,Kt,wt,an,Rn,Ht,mn,_n,Ge,It,$n,Oo,Fo,_o,$o,fs,hs,Jt,jo,go,fo,Vr,Uo,et;if(R()){X.style.width="100%",X.style.maxWidth="100%";let Nt=(We=(De=r.launcher)==null?void 0:De.composerBar)!=null?We:{},Bt=ge.dataset.state==="expanded",Vt=(Ye=Nt.expandedSize)!=null?Ye:"anchored";if(!(Bt&&Vt!=="fullscreen")){Se.style.background="",Se.style.border="",Se.style.borderRadius="",Se.style.overflow="",Se.style.boxShadow="";return}let mt=(_e=(Pt=r.theme)==null?void 0:Pt.components)==null?void 0:_e.panel,jt=ma(r),gn=(un,Zn)=>{var ho;return un==null||un===""?Zn:(ho=Ms(jt,un))!=null?ho:un},jn="1px solid var(--persona-border)",Ir="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",pn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Se.style.background="var(--persona-surface, #ffffff)",Se.style.border=gn(mt==null?void 0:mt.border,jn),Se.style.borderRadius=gn(mt==null?void 0:mt.borderRadius,pn),Se.style.boxShadow=gn(mt==null?void 0:mt.shadow,Ir),Se.style.overflow="hidden";return}let l=dn(r),m=(wt=(Kt=r.launcher)==null?void 0:Kt.sidebarMode)!=null?wt:!1,h=l||m||((Rn=(an=r.launcher)==null?void 0:an.fullHeight)!=null?Rn:!1),x=((Ht=r.launcher)==null?void 0:Ht.enabled)===!1,A=(_n=(mn=r.theme)==null?void 0:mn.components)==null?void 0:_n.panel,W=ma(r),U=(Nt,Bt)=>{var Vt;return Nt==null||Nt===""?Bt:(Vt=Ms(W,Nt))!=null?Vt:Nt},_=(Ge=e.ownerDocument.defaultView)!=null?Ge:window,D=($n=(It=r.launcher)==null?void 0:It.mobileFullscreen)!=null?$n:!0,ie=(Fo=(Oo=r.launcher)==null?void 0:Oo.mobileBreakpoint)!=null?Fo:640,oe=_.innerWidth<=ie,Y=D&&oe&&P,ve=($o=(_o=r.launcher)==null?void 0:_o.position)!=null?$o:"bottom-left",Oe=ve==="bottom-left"||ve==="top-left",Fe=(hs=(fs=r.launcher)==null?void 0:fs.zIndex)!=null?hs:xn,je=m||Y?"none":"1px solid var(--persona-border)",qe=Y?"none":m?Oe?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Y&&(qe="none",je="none");let ut=m||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",st=U(A==null?void 0:A.border,je),Be=U(A==null?void 0:A.shadow,qe),Re=U(A==null?void 0:A.borderRadius,ut),ze=we.scrollTop;e.style.cssText="",ge.style.cssText="",X.style.cssText="",Se.style.cssText="",we.style.cssText="",He.style.cssText="",J&&(we.style.display="none");let Xe=()=>{var Bt;if(ze<=0)return;((Bt=we.ownerDocument.defaultView)!=null?Bt:window).requestAnimationFrame(()=>{if(we.scrollTop===ze)return;let Vt=we.scrollHeight-we.clientHeight;Vt<=0||(we.scrollTop=Math.min(ze,Vt))})};if(Y){ge.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"),ge.style.cssText=`
|
|
34
|
+
`,H.addEventListener("click",()=>{u=S,T.forEach((U,j)=>{let k=j<S;U.classList.toggle("selected",k),U.setAttribute("aria-checked",j===S-1?"true":"false")})}),T.push(H),A.appendChild(H)}f.appendChild(A);let L=null;if(d){let S=document.createElement("div");S.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),S.appendChild(L),f.appendChild(S)}let W=document.createElement("div");W.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==null||n(),p.remove()});let P=document.createElement("button");return P.type="button",P.className="persona-feedback-btn persona-feedback-btn-submit",P.textContent=a,P.addEventListener("click",async()=>{if(u===null){A.classList.add("persona-feedback-shake"),setTimeout(()=>A.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let S=(L==null?void 0:L.value.trim())||void 0;await t(u,S),p.remove()}catch(S){P.disabled=!1,P.textContent=a,console.error("[CSAT Feedback] Failed to submit:",S)}}),W.appendChild(R),W.appendChild(P),f.appendChild(W),p.appendChild(f),p}function ec(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:p="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 f=null,g=document.createElement("div");g.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,y.appendChild(v);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=o,y.appendChild(A),g.appendChild(y);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let W=document.createElement("span");W.className="persona-feedback-label-low",W.textContent=c;let R=document.createElement("span");R.className="persona-feedback-label-high",R.textContent=p,L.appendChild(W),L.appendChild(R);let P=document.createElement("div");P.className="persona-feedback-numbers";let S=[];for(let O=0;O<=10;O++){let F=document.createElement("button");F.type="button",F.className="persona-feedback-rating-btn persona-feedback-number-btn",F.setAttribute("role","radio"),F.setAttribute("aria-checked","false"),F.setAttribute("aria-label",`Rating ${O} out of 10`),F.textContent=String(O),F.dataset.rating=String(O),O<=6?F.classList.add("persona-feedback-detractor"):O<=8?F.classList.add("persona-feedback-passive"):F.classList.add("persona-feedback-promoter"),F.addEventListener("click",()=>{f=O,S.forEach((Z,Ee)=>{Z.classList.toggle("selected",Ee===O),Z.setAttribute("aria-checked",Ee===O?"true":"false")})}),S.push(F),P.appendChild(F)}T.appendChild(L),T.appendChild(P),g.appendChild(T);let H=null;if(d){let O=document.createElement("div");O.className="persona-feedback-comment-container",H=document.createElement("textarea"),H.className="persona-feedback-comment",H.placeholder=s,H.rows=3,H.setAttribute("aria-label","Additional comments"),O.appendChild(H),g.appendChild(O)}let U=document.createElement("div");U.className="persona-feedback-actions";let j=document.createElement("button");j.type="button",j.className="persona-feedback-btn persona-feedback-btn-skip",j.textContent=i,j.addEventListener("click",()=>{n==null||n(),u.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=a,k.addEventListener("click",async()=>{if(f===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let O=(H==null?void 0:H.value.trim())||void 0;await t(f,O),u.remove()}catch(O){k.disabled=!1,k.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),U.appendChild(j),U.appendChild(k),g.appendChild(U),u.appendChild(g),u}var Os="persona-chat-history",qw=30*1e3,zw={"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 Vw(e){var r,o,s;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(o=zw[i.type])!=null?o:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Ri(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 Kw(e){var t,n,r,o,s,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function Gw(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var tc=e=>!e||typeof e!="object"?{}:{...e},ff=e=>e.map(t=>({...t,streaming:!1})),hf=(e,t,n)=>{let r=e!=null&&e.markdown?As(e.markdown):null,o=Zs(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(e==null?void 0: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=>{var p,u,f;let a=(p=s.text)!=null?p:"",i=(u=s.message.rawContent)!=null?u:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});g!==null&&(a=g.text,g.persist||(s.message.__skipPersist=!0),g.resubmit&&!s.streaming&&n&&n())}let d=Go()!==null,c;if(e!=null&&e.postprocessMessage){let g=e.postprocessMessage({...s,text:a,raw:(f=i!=null?i:s.text)!=null?f:""});c=o?o(g):g}else if(r){let g=s.streaming?fm(a):a,y=r(g);c=o&&d?o(y):y}else c=Xr(a);return c}};function yf(e){var i,d,c,p;let t=b("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",o=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=ye(n,r,o,s);if(a&&t.appendChild(a),e!=null&&e.label){let u=b("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var nc=(e,t,n)=>{var Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Rd,Wd,Hd,Bd,Dd,Nd,Od,Fd,_d,$d,jd,Ud,qd,zd,Vd,Kd,Gd;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 r=Tl(t),o=ki.getForInstance(r.plugins),{plugin:s,teardown:a}=Xg();r.components&&Lo.registerAll(r.components);let i=uf(),c=r.persistState===!1?null:(Zc=r.storageAdapter)!=null?Zc:Jl(),p={},u=null,f=!1,g=l=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:h,open:x}=m;return x&&(f=!0),h}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return l};if(c!=null&&c.load)try{let l=c.load();if(l&&typeof l.then=="function")u=l.then(m=>{let h=m!=null?m:{messages:[],metadata:{}};return g(h)});else{let m=l!=null?l:{messages:[],metadata:{}},h=g(m);h.metadata&&(p=tc(h.metadata)),(ed=h.messages)!=null&&ed.length&&(r={...r,initialMessages:h.messages}),(td=h.artifacts)!=null&&td.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(nd=h.selectedArtifactId)!=null?nd:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=g({messages:[],metadata:{}});(rd=l.messages)!=null&&rd.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let y=()=>p,v=l=>{var h;p=(h=l({...p}))!=null?h:{},Lr()},A=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Li],T=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Ns.message,Ns.messageAndClick],L=Pi({parsers:A,handlers:T,getSessionMetadata:y,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null});L.syncFromMetadata();let W=(sd=(od=r.launcher)==null?void 0:od.enabled)!=null?sd:!0,R=(id=(ad=r.launcher)==null?void 0:ad.autoExpand)!=null?id:!1,P=(ld=r.autoFocusInput)!=null?ld:!1,S=R,H=W,U=(dd=(cd=r.layout)==null?void 0:cd.header)==null?void 0:dd.layout,j=!1,k=()=>Mo(r),O=()=>W||k(),F=k()?!1:W?R:!0,Z=!1,Ee=null,de=()=>{Z=!0,Ee&&clearTimeout(Ee),Ee=setTimeout(()=>{Z&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Z=!1)},1e4)},ee=hf(r,L,de),Le=(ud=(pd=r.features)==null?void 0:pd.showReasoning)!=null?ud:!0,Pe=(gd=(md=r.features)==null?void 0:md.showToolCalls)!=null?gd:!0,ne=(hd=(fd=r.features)==null?void 0:fd.showEventStreamToggle)!=null?hd:!1,Ae=(bd=(yd=r.features)==null?void 0:yd.scrollToBottom)!=null?bd:{},re=(vd=(xd=r.features)==null?void 0:xd.scrollBehavior)!=null?vd:{},ae=`${(Cd=typeof r.persistState=="object"?(wd=r.persistState)==null?void 0:wd.keyPrefix:void 0)!=null?Cd:"persona-"}event-stream`,fe=ne?new ka(ae):null,$e=(Td=(Sd=(Ad=r.features)==null?void 0:Ad.eventStream)==null?void 0:Sd.maxEvents)!=null?Td:2e3,V=ne?new Ma($e,fe):null,Q=ne?new La:null,Me=null,J=!1,le=null,Ie=0;fe==null||fe.open().then(()=>V==null?void 0:V.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let he={onCopy:l=>{var m,h;i.emit("message:copy",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.id,"copy").catch(x=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",x)}),(h=(m=r.messageActions)==null?void 0:m.onCopy)==null||h.call(m,l)},onFeedback:l=>{var m,h;i.emit("message:feedback",l),_!=null&&_.isClientTokenMode()&&_.submitMessageFeedback(l.messageId,l.type).catch(x=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",x)}),(h=(m=r.messageActions)==null?void 0:m.onFeedback)==null||h.call(m,l)}},Ke=(Ed=r.statusIndicator)!=null?Ed:{},gt=l=>{var m,h,x,C,M,$;return l==="idle"?(m=Ke.idleText)!=null?m:tn.idle:l==="connecting"?(h=Ke.connectingText)!=null?h:tn.connecting:l==="connected"?(x=Ke.connectedText)!=null?x:tn.connected:l==="error"?(C=Ke.errorText)!=null?C:tn.error:l==="paused"?(M=Ke.pausedText)!=null?M:tn.paused:l==="resuming"?($=Ke.resumingText)!=null?$:tn.resuming:tn[l]};function Wt(l,m,h,x){if(x==="idle"&&h.idleLink){l.textContent="";let C=document.createElement("a");C.href=h.idleLink,C.target="_blank",C.rel="noopener noreferrer",C.textContent=m,C.style.color="inherit",C.style.textDecoration="none",l.appendChild(C)}else l.textContent=m}let tt=Dg({config:r,showClose:O()}),{wrapper:ge,panel:X,pillRoot:it}=tt.shell,Ve=tt.panelElements,{container:Se,body:we,messagesWrapper:Ze,suggestions:qt,textarea:be,sendButton:pe,sendButtonWrapper:Cn,composerForm:Ct,statusText:yn,introTitle:hr,introSubtitle:yr,closeButton:Ue,iconHolder:E,headerTitle:ue,headerSubtitle:Te,header:ke,footer:He,actionsRow:nt,leftActions:Qe,rightActions:ht}=Ve,me=Ve.setSendButtonMode,B=Ve.micButton,xe=Ve.micButtonWrapper,ce=Ve.attachmentButton,ft=Ve.attachmentButtonWrapper,Je=Ve.attachmentInput,Lt=Ve.attachmentPreviewsContainer;Se.classList.add("persona-relative"),we.classList.add("persona-relative");let Mt=12,xt=()=>{var l;return(l=Ae.label)!=null?l:""},Rt=()=>{var l;return(l=Ae.iconName)!=null?l:"arrow-down"},Xt=()=>Ae.enabled!==!1,Ot=()=>{var l;return(l=re.mode)!=null?l:"anchor-top"},Zt=()=>Ot()==="follow"||Ot()==="anchor-top"&&lo,br=()=>{var l;return(l=re.anchorTopOffset)!=null?l:16},Nr=()=>{var l;return(l=re.restorePosition)!=null?l:"bottom"},or=()=>re.pauseOnInteraction===!0,sr=()=>re.showActivityWhilePinned!==!1,Zr=()=>re.announce===!0,zt=b("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");zt.type="button",zt.style.display="none",zt.setAttribute("data-persona-scroll-to-bottom","true");let ar=b("span","persona-flex persona-items-center"),Or=b("span",""),Hn=b("span","");Hn.setAttribute("data-persona-scroll-to-bottom-count",""),Hn.style.display="none",zt.append(ar,Or,Hn),Se.appendChild(zt);let Pn=b("div","persona-stream-anchor-spacer");Pn.setAttribute("aria-hidden","true"),Pn.setAttribute("data-persona-anchor-spacer",""),Pn.style.flexShrink="0",Pn.style.pointerEvents="none",Pn.style.height="0px",we.appendChild(Pn);let Bn=b("div","persona-sr-only");Bn.setAttribute("aria-live","polite"),Bn.setAttribute("aria-atomic","true"),Bn.setAttribute("role","status"),Bn.setAttribute("data-persona-live-region",""),Object.assign(Bn.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"}),Se.appendChild(Bn);let ir=null,xr=null,eo=l=>{!Zr()||!l||(xr=l,ir===null&&(ir=setTimeout(()=>{ir=null,xr&&Zr()&&(Bn.textContent=xr),xr=null},400)))},zn=()=>{let m=He.style.display==="none"?0:He.offsetHeight;zt.style.bottom=`${m+Mt}px`};zn();let to=()=>{let l=!!xt();zt.setAttribute("aria-label",xt()||"Jump to latest"),zt.title=xt(),zt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),ar.innerHTML="";let m=ye(Rt(),"14px","currentColor",2);m?(ar.appendChild(m),ar.style.display=""):ar.style.display="none",Or.textContent=xt(),Or.style.display=l?"":"none"};to();let At=null,vr=null,wr=o.find(l=>l.renderHeader);if(wr!=null&&wr.renderHeader){let l=wr.renderHeader({config:r,defaultRenderer:()=>{let m=ko({config:r,showClose:O()});return Rs(Se,m,r),m.header},onClose:()=>_t(!1,"user")});if(l){let m=Se.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),ke=l,tt.header.element=l)}}let Fr=()=>{var m,h,x,C;if(!V)return;if(J=!0,!Me&&V&&(Me=tf({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>lr(),config:r,plugins:o,getThroughput:()=>{var M;return(M=Q==null?void 0:Q.getMetric())!=null?M:{status:"idle"}}})),Me&&(we.style.display="none",(m=He.parentNode)==null||m.insertBefore(Me.element,He),Me.update()),yt){yt.style.boxShadow=`inset 0 0 0 1.5px ${Ln.actionIconColor}`;let M=(C=(x=(h=r.features)==null?void 0:h.eventStream)==null?void 0:x.classNames)==null?void 0:C.toggleButtonActive;M&&M.split(/\s+/).forEach($=>$&&yt.classList.add($))}let l=()=>{if(!J)return;let M=Date.now();M-Ie>=200&&(Me==null||Me.update(),Ie=M),le=requestAnimationFrame(l)};Ie=0,le=requestAnimationFrame(l),Fn(),i.emit("eventStream:opened",{timestamp:Date.now()})},lr=()=>{var l,m,h;if(J){if(J=!1,Me&&Me.element.remove(),we.style.display="",yt){yt.style.boxShadow="";let x=(h=(m=(l=r.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:h.toggleButtonActive;x&&x.split(/\s+/).forEach(C=>C&&yt.classList.remove(C))}le!==null&&(cancelAnimationFrame(le),le=null),Fn(),i.emit("eventStream:closed",{timestamp:Date.now()})}},yt=null;if(ne){let l=(kd=(Md=r.features)==null?void 0:Md.eventStream)==null?void 0:kd.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");yt=b("button",m),yt.style.width="28px",yt.style.height="28px",yt.style.color=Ln.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let h=ye("activity","18px","currentColor",1.5);h&&yt.appendChild(h);let x=Ve.clearChatButtonWrapper,C=Ve.closeButtonWrapper,M=x||C;M&&M.parentNode===ke?ke.insertBefore(yt,M):ke.appendChild(yt),yt.addEventListener("click",()=>{J?lr():Fr()})}let Io=l=>{var C,M,$,N,D;let m=r.attachments;if(!(m!=null&&m.enabled))return;let h=(C=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?C:l.querySelector(".persona-attachment-previews");if(!h){h=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let ie=l.querySelector("[data-persona-composer-form]");ie!=null&&ie.parentNode?ie.parentNode.insertBefore(h,ie):l.insertBefore(h,l.firstChild)}if(!((M=l.querySelector("[data-persona-composer-attachment-input]"))!=null?M:l.querySelector('input[type="file"]'))){let ie=b("input");ie.type="file",ie.setAttribute("data-persona-composer-attachment-input",""),ie.accept=(($=m.allowedTypes)!=null?$:Qr).join(","),ie.multiple=((N=m.maxFiles)!=null?N:4)>1,ie.style.display="none",ie.setAttribute("aria-label",(D=m.buttonTooltipText)!=null?D:"Attach files"),l.appendChild(ie)}},Cr=o.find(l=>l.renderComposer);if(Cr!=null&&Cr.renderComposer){let l=r.composer,m=Cr.renderComposer({config:r,defaultRenderer:()=>Ta({config:r}).footer,onSubmit:h=>{var $;if(!_||_.isStreaming())return;let x=h.trim(),C=($=At==null?void 0:At.hasAttachments())!=null?$:!1;if(!x&&!C)return;kc();let M;C&&(M=[],M.push(...At.getContentParts()),x&&M.push(Qa(x))),_.sendMessage(x,{contentParts:M}),C&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Je==null||Je.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((Ld=r.voiceRecognition)==null?void 0:Ld.enabled)===!0?()=>{vr==null||vr()}:void 0});m&&(tt.replaceComposer(m),He=tt.composer.footer)}let Ro=l=>{let m=(...oe)=>{for(let Y of oe){let ve=l.querySelector(Y);if(ve)return ve}return null},h=l.querySelector("[data-persona-composer-form]"),x=l.querySelector("[data-persona-composer-input]"),C=l.querySelector("[data-persona-composer-submit]"),M=l.querySelector("[data-persona-composer-mic]"),$=l.querySelector("[data-persona-composer-status]");h&&(Ct=h),x&&(be=x),C&&(pe=C),M&&(B=M,xe=M.parentElement),$&&(yn=$);let N=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");N&&(qt=N);let D=m("[data-persona-composer-attachment-button]",".persona-attachment-button");D&&(ce=D,ft=D.parentElement),Je=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Lt=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ie=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ie&&(nt=ie)};Io(He),Ro(He);let In=(Hd=(Pd=r.layout)==null?void 0:Pd.contentMaxWidth)!=null?Hd:k()?(Wd=(Rd=(Id=r.launcher)==null?void 0:Id.composerBar)==null?void 0:Rd.contentMaxWidth)!=null?Wd:"720px":void 0;if(In&&(Ze.style.maxWidth=In,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%"),In&&Ct&&!k()&&(Ct.style.maxWidth=In,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),In&&qt&&!k()&&(qt.style.maxWidth=In,qt.style.marginLeft="auto",qt.style.marginRight="auto"),In&&Lt&&!k()&&(Lt.style.maxWidth=In,Lt.style.marginLeft="auto",Lt.style.marginRight="auto"),(Bd=r.attachments)!=null&&Bd.enabled&&Je&&Lt){At=Ls.fromConfig(r.attachments),At.setPreviewsContainer(Lt),Je.addEventListener("change",h=>{let x=h.target;At==null||At.handleFileSelect(x.files),x.value=""});let l=r.attachments.dropOverlay,m=yf(l);Se.appendChild(m)}(()=>{var x,C;let l=(C=(x=r.layout)==null?void 0:x.slots)!=null?C:{},m=M=>{switch(M){case"body-top":return Se.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ze;case"footer-top":return qt;case"composer":return Ct;case"footer-bottom":return yn;default:return null}},h=(M,$)=>{var N;switch(M){case"header-left":case"header-center":case"header-right":if(M==="header-left")ke.insertBefore($,ke.firstChild);else if(M==="header-right")ke.appendChild($);else{let D=ke.querySelector(".persona-flex-col");D?(N=D.parentNode)==null||N.insertBefore($,D.nextSibling):ke.appendChild($)}break;case"body-top":{let D=we.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith($):we.insertBefore($,we.firstChild);break}case"body-bottom":we.appendChild($);break;case"footer-top":qt.replaceWith($);break;case"footer-bottom":yn.replaceWith($);break;default:break}};for(let[M,$]of Object.entries(l))if($)try{let N=$({config:r,defaultContent:()=>m(M)});N&&h(M,N)}catch(N){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${M}":`,N)}})();let no=l=>{var $,N;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 C=x.getAttribute("data-message-id");if(!C)return;let M=h.getAttribute("data-bubble-type");if(M==="reasoning")Hs.has(C)?Hs.delete(C):Hs.add(C),$g(C,x);else if(M==="tool")Bs.has(C)?Bs.delete(C):Bs.add(C),jg(C,x,r);else if(M==="approval"){let D=r.approval!==!1?r.approval:void 0,ie=(($=D==null?void 0:D.detailsDisplay)!=null?$:"collapsed")==="expanded",oe=(N=os.get(C))!=null?N:ie;os.set(C,!oe),Vg(C,x,r)}Er.delete(C)};Ze.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),no(l))}),Ze.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),no(l))}),Ze.addEventListener("copy",l=>{let{clipboardData:m}=l;if(!m)return;let h=Ze.getRootNode(),x=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let C=x.toString(),M=hg(C);!M||M===C||(m.setData("text/plain",M),l.preventDefault())});let _r=new Map,ro=null,oo="idle",Wo={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Ho=(l,m)=>{let{icon:h,label:x}=Wo[m];l.setAttribute("aria-label",x),l.title=x,l.setAttribute("aria-pressed",m==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",m!=="idle"),l.classList.toggle("persona-message-action-loading",m==="loading");let C=ye(h,14,"currentColor",2);C&&(l.innerHTML="",l.appendChild(C))},so=()=>{Ze.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{var M;let h=m.closest("[data-actions-for]"),x=(M=h==null?void 0:h.getAttribute("data-actions-for"))!=null?M:null;Ho(m,x&&x===ro?oo:"idle")})};Ze.addEventListener("click",l=>{var $;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 C=x.getAttribute("data-actions-for");if(!C)return;let M=h.getAttribute("data-action");if(M==="copy"){let D=_.getMessages().find(ie=>ie.id===C);if(D&&he.onCopy){let ie=D.content||"";navigator.clipboard.writeText(ie).then(()=>{h.classList.add("persona-message-action-success");let oe=ye("check",14,"currentColor",2);oe&&(h.innerHTML="",h.appendChild(oe)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Y=ye("copy",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))},2e3)}).catch(oe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",oe)}),he.onCopy(D)}}else if(M==="read-aloud")_.toggleReadAloud(C);else if(M==="upvote"||M==="downvote"){let D=(($=_r.get(C))!=null?$:null)===M,ie=M==="upvote"?"thumbs-up":"thumbs-down";if(D){_r.delete(C),h.classList.remove("persona-message-action-active");let oe=ye(ie,14,"currentColor",2);oe&&(h.innerHTML="",h.appendChild(oe))}else{let oe=M==="upvote"?"downvote":"upvote",Y=x.querySelector(`[data-action="${oe}"]`);if(Y){Y.classList.remove("persona-message-action-active");let qe=ye(oe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);qe&&(Y.innerHTML="",Y.appendChild(qe))}_r.set(C,M),h.classList.add("persona-message-action-active");let ve=ye(ie,14,"currentColor",2);ve&&(ve.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ve)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Fe=_.getMessages().find(je=>je.id===C);Fe&&he.onFeedback&&he.onFeedback({type:M,messageId:Fe.id,message:Fe})}}}),Ze.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 C=x.getAttribute("data-message-id");if(!C)return;let M=h.getAttribute("data-approval-action");if(!M)return;let $=M==="approve"?"approved":"denied",D=_.getMessages().find(oe=>oe.id===C);if(!(D!=null&&D.approval))return;let ie=x.querySelector("[data-approval-buttons]");ie&&ie.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?_.resolveWebMcpApproval(C,$):_.resolveApproval(D.approval,$)});let vt=null,Dn=null,Nn={artifacts:[],selectedId:null},An=!1,St={current:null};Ze.addEventListener("click",l=>{var Y,ve,Oe,Fe,je;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-download-artifact");if(!x||((Oe=(ve=(Y=r.features)==null?void 0:Y.artifacts)==null?void 0:ve.onArtifactAction)==null?void 0:Oe.call(ve,{type:"download",artifactId:x}))===!0)return;let M=_.getArtifactById(x),$=M==null?void 0:M.markdown,N=(M==null?void 0:M.title)||"artifact";if(!$){let qe=h.closest("[data-open-artifact]"),ut=qe==null?void 0:qe.closest("[data-message-id]"),st=ut==null?void 0:ut.getAttribute("data-message-id");if(st){let Re=_.getMessages().find(ze=>ze.id===st);if(Re!=null&&Re.rawContent)try{let ze=JSON.parse(Re.rawContent);$=(Fe=ze==null?void 0:ze.props)==null?void 0:Fe.markdown,N=((je=ze==null?void 0:ze.props)==null?void 0:je.title)||N}catch{}}}if(!$)return;let D=new Blob([$],{type:"text/markdown"}),ie=URL.createObjectURL(D),oe=document.createElement("a");oe.href=ie,oe.download=`${N}.md`,oe.click(),URL.revokeObjectURL(ie)}),Ze.addEventListener("click",l=>{var M,$,N;let h=l.target.closest("[data-open-artifact]");if(!h)return;let x=h.getAttribute("data-open-artifact");!x||((N=($=(M=r.features)==null?void 0:M.artifacts)==null?void 0:$.onArtifactAction)==null?void 0:N.call($,{type:"open",artifactId:x}))===!0||(l.preventDefault(),l.stopPropagation(),An=!1,_.selectArtifact(x),Ar())}),Ze.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let Vn=Ve.composerOverlay,Kn=(l,m,h)=>{var N,D,ie,oe;let x=m.trim();if(!x||!St.current)return;let C=(N=l.getAttribute("data-tool-call-id"))!=null?N:"",M=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:C,answer:x,answers:h.structured,values:(D=h.values)!=null?D:h.source==="multi"?x.split(", "):[x],isFreeText:M,source:h.source},bubbles:!0,composed:!0})),Qo(Vn,C);let $=St.current.getMessages().find(Y=>{var ve;return((ve=Y.toolCall)==null?void 0:ve.id)===C});(ie=$==null?void 0:$.agentMetadata)!=null&&ie.awaitingLocalTool?St.current.resolveAskUserQuestion($,(oe=h.structured)!=null?oe:x):St.current.sendMessage(x)},On=l=>{var C;let m=St.current;if(!m)return;let h=(C=l.getAttribute("data-tool-call-id"))!=null?C:"",x=m.getMessages().find(M=>{var $;return(($=M.toolCall)==null?void 0:$.id)===h});x&&m.persistAskUserQuestionProgress(x,{answers:ja(l,x),currentIndex:er(l)})},ao=l=>Object.entries(l).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Ce=l=>{var C,M,$;if(((M=(C=r.features)==null?void 0:C.askUserQuestion)==null?void 0:M.groupedAutoAdvance)===!1)return;let m=er(l),h=Ts(l);if(m>=h-1)return;let x=($=St.current)==null?void 0:$.getMessages().find(N=>{var D;return((D=N.toolCall)==null?void 0:D.id)===l.getAttribute("data-tool-call-id")});x&&(Ua(l,x,r,m+1),On(l))};Vn.addEventListener("click",l=>{var M,$,N,D,ie,oe,Y,ve,Oe,Fe,je,qe,ut,st;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 C=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),C==="dismiss"){let Be=(M=x.getAttribute("data-tool-call-id"))!=null?M:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),Qo(Vn,Be);let Re=($=St.current)==null?void 0:$.getMessages().find(ze=>{var Xe;return((Xe=ze.toolCall)==null?void 0:Xe.id)===Be});(N=Re==null?void 0:Re.agentMetadata)!=null&&N.awaitingLocalTool&&((D=St.current)==null||D.markAskUserQuestionResolved(Re),(ie=St.current)==null||ie.resolveAskUserQuestion(Re,"(dismissed)"));return}if(C==="pick"){let Be=h.getAttribute("data-option-label");if(!Be)return;let Re=x.getAttribute("data-multi-select")==="true",ze=wo(x);if(ze&&Re){let Xe=Xo(x)[er(x)],bt=new Set(Array.isArray(Xe)?Xe:[]);bt.has(Be)?bt.delete(Be):bt.add(Be),Co(x,Array.from(bt)),On(x);return}if(ze){Co(x,Be),On(x),Ce(x);return}if(Re){let Xe=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Xe?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Xe);let bt=x.querySelector('[data-ask-user-action="submit-multi"]');bt&&(bt.disabled=cl(x).length===0);return}Kn(x,Be,{source:"pick",values:[Be]});return}if(C==="submit-multi"){let Be=cl(x);if(Be.length===0)return;Kn(x,Be.join(", "),{source:"multi",values:Be});return}if(C==="open-free-text"){let Be=x.querySelector('[data-ask-free-text-row="true"]');if(Be){Be.classList.remove("persona-hidden");let Re=Be.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus()}return}if(C==="focus-free-text"){let Be=x.querySelector('[data-ask-free-text-input="true"]');Be==null||Be.focus();return}if(C==="submit-free-text"){let Be=x.querySelector('[data-ask-free-text-input="true"]'),Re=(oe=Be==null?void 0:Be.value)!=null?oe:"";if(!Re.trim())return;if(wo(x)){Co(x,Re.trim()),On(x),Ce(x);return}Kn(x,Re,{source:"free-text"});return}if(C==="next"||C==="back"){if(!St.current)return;let Be=(Y=x.getAttribute("data-tool-call-id"))!=null?Y:"",Re=St.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Be});if(!Re)return;let ze=x.querySelector('[data-ask-free-text-input="true"]'),Xe=(Oe=(ve=ze==null?void 0:ze.value)==null?void 0:ve.trim())!=null?Oe:"";if(Xe){let De=Xo(x)[er(x)];(typeof De!="string"||De!==Xe)&&Co(x,Xe)}let bt=C==="next"?1:-1,I=er(x)+bt;Ua(x,Re,r,I),On(x);return}if(C==="submit-all"){if(!St.current)return;let Be=(Fe=x.getAttribute("data-tool-call-id"))!=null?Fe:"",Re=St.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Be});if(!Re)return;let ze=x.querySelector('[data-ask-free-text-input="true"]'),Xe=(qe=(je=ze==null?void 0:ze.value)==null?void 0:je.trim())!=null?qe:"";Xe&&Co(x,Xe);let bt=ja(x,Re);St.current.persistAskUserQuestionProgress(Re,{answers:bt,currentIndex:er(x)});let I=ao(bt);Kn(x,I||"(submitted)",{source:"submit-all",structured:bt});return}if(C==="skip"){if(!St.current)return;let Be=(ut=x.getAttribute("data-tool-call-id"))!=null?ut:"",Re=St.current.getMessages().find(We=>{var Ye;return((Ye=We.toolCall)==null?void 0:Ye.id)===Be});if(!Re)return;let ze=wo(x),Xe=er(x),bt=Ts(x),I=Xe>=bt-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),Qo(Vn,Be),(st=Re.agentMetadata)!=null&&st.awaitingLocalTool&&(St.current.markAskUserQuestionResolved(Re),St.current.resolveAskUserQuestion(Re,"(dismissed)"));return}Co(x,"");let De=x.querySelector('[data-ask-free-text-input="true"]');if(De&&(De.value=""),I){let We=ja(x,Re),Ye=ao(We);Kn(x,Ye||"(skipped)",{source:"submit-all",structured:We});return}Ua(x,Re,r,Xe+1),On(x);return}}),Vn.addEventListener("keydown",l=>{var M;if(l.key!=="Enter")return;let h=l.target;if(!((M=h.matches)!=null&&M.call(h,'[data-ask-free-text-input="true"]')))return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;l.preventDefault();let C=h.value;if(C.trim()){if(wo(x)){Co(x,C.trim()),On(x),Ce(x);return}Kn(x,C,{source:"free-text"})}});let $r=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let m=l.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let h=Vn.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),M=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];M&&(l.preventDefault(),M.click())};document.addEventListener("keydown",$r);let Gn=null,Ft=null,Jn=null,jr=null,Fs=()=>{};function ls(){jr==null||jr(),jr=null}let _s=()=>{var $;if(!Gn||!Ft)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=(($=e.ownerDocument.defaultView)!=null?$:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){Ft.style.removeProperty("position"),Ft.style.removeProperty("left"),Ft.style.removeProperty("top"),Ft.style.removeProperty("bottom"),Ft.style.removeProperty("width"),Ft.style.removeProperty("z-index");return}let x=Gn.firstElementChild;if(!x||x===Ft)return;let C=10;Ft.style.position="absolute",Ft.style.top="0",Ft.style.bottom="0",Ft.style.width=`${C}px`,Ft.style.zIndex="5";let M=x.offsetWidth-C/2;Ft.style.left=`${Math.max(0,M)}px`},Bo=()=>{},Ar=()=>{var h,x,C,M,$;if(!vt||!rr(r))return;Ei(e,r),Mi(e,r),Bo();let l=(M=(C=(x=(h=r.features)==null?void 0:h.artifacts)==null?void 0:x.layout)==null?void 0:C.narrowHostMaxWidth)!=null?M:520,m=X.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),vt.update(Nn),An?(vt.setMobileOpen(!1),vt.element.classList.add("persona-hidden"),($=vt.backdrop)==null||$.classList.add("persona-hidden")):Nn.artifacts.length>0&&(vt.element.classList.remove("persona-hidden"),vt.setMobileOpen(!0)),Fs()};if(rr(r)){X.style.position="relative";let l=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(Se),vt=of(r,{onSelect:h=>{var x;return(x=St.current)==null?void 0:x.selectArtifact(h)},onDismiss:()=>{An=!0,Ar()}}),vt.element.classList.add("persona-hidden"),Gn=m,m.appendChild(l),m.appendChild(vt.element),vt.backdrop&&X.appendChild(vt.backdrop),X.appendChild(m),Fs=()=>{var x,C,M,$;if(!Gn||!vt)return;if(!(((M=(C=(x=r.features)==null?void 0:x.artifacts)==null?void 0:C.layout)==null?void 0:M.resizable)===!0)){Jn==null||Jn(),Jn=null,ls(),Ft&&(Ft.remove(),Ft=null),vt.element.style.removeProperty("width"),vt.element.style.removeProperty("maxWidth");return}if(!Ft){let N=b("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");N.setAttribute("role","separator"),N.setAttribute("aria-orientation","vertical"),N.setAttribute("aria-label","Resize artifacts panel"),N.tabIndex=0;let D=e.ownerDocument,ie=($=D.defaultView)!=null?$:window,oe=Y=>{var ut,st;if(!vt||Y.button!==0||e.classList.contains("persona-artifact-narrow-host")||ie.innerWidth<=640)return;Y.preventDefault(),ls();let ve=Y.clientX,Oe=vt.element.getBoundingClientRect().width,Fe=(st=(ut=r.features)==null?void 0:ut.artifacts)==null?void 0:st.layout,je=Be=>{let Re=Gn.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),Xe=ze?0:cf(Gn,ie),bt=ze?0:N.getBoundingClientRect().width||6,I=Oe-(Be.clientX-ve),De=df(I,Re,Xe,bt,Fe==null?void 0:Fe.resizableMinWidth,Fe==null?void 0:Fe.resizableMaxWidth);vt.element.style.width=`${De}px`,vt.element.style.maxWidth="none",_s()},qe=()=>{D.removeEventListener("pointermove",je),D.removeEventListener("pointerup",qe),D.removeEventListener("pointercancel",qe),jr=null;try{N.releasePointerCapture(Y.pointerId)}catch{}};jr=qe,D.addEventListener("pointermove",je),D.addEventListener("pointerup",qe),D.addEventListener("pointercancel",qe);try{N.setPointerCapture(Y.pointerId)}catch{}};N.addEventListener("pointerdown",oe),Ft=N,Gn.insertBefore(N,vt.element),Jn=()=>{N.removeEventListener("pointerdown",oe)}}if(Ft){let N=Nn.artifacts.length>0&&!An;Ft.classList.toggle("persona-hidden",!N),_s()}},Bo=()=>{var ie,oe,Y,ve,Oe,Fe,je,qe,ut,st,Be,Re,ze,Xe;if(!W||!vt||((oe=(ie=r.launcher)==null?void 0:ie.sidebarMode)!=null?oe:!1)||dn(r)&&nr(r).reveal==="emerge")return;let x=(Y=e.ownerDocument.defaultView)!=null?Y:window,C=(Oe=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?Oe:!0,M=(je=(Fe=r.launcher)==null?void 0:Fe.mobileBreakpoint)!=null?je:640;if(C&&x.innerWidth<=M||!lf(r,W))return;let $=(st=(ut=(qe=r.launcher)==null?void 0:qe.width)!=null?ut:r.launcherWidth)!=null?st:tr,N=(Xe=(ze=(Re=(Be=r.features)==null?void 0:Be.artifacts)==null?void 0:Re.layout)==null?void 0:ze.expandedPanelWidth)!=null?Xe:"min(720px, calc(100vw - 24px))";Nn.artifacts.length>0&&!An?(X.style.width=N,X.style.maxWidth=N):(X.style.width=$,X.style.maxWidth=$)},typeof ResizeObserver!="undefined"&&(Dn=new ResizeObserver(()=>{Ar()}),Dn.observe(X))}else X.appendChild(Se),k()&&it&&(Ve.peekBanner&&it.appendChild(Ve.peekBanner),it.appendChild(He));e.appendChild(ge),it&&e.appendChild(it);let io=()=>{var De,We,Ye,Pt,_e,Kt,wt,an,Rn,Ht,fn,_n,Ge,It,$n,_o,$o,jo,Uo,bs,xs,Jt,qo,ho,yo,Jr,zo,et;if(k()){X.style.width="100%",X.style.maxWidth="100%";let Nt=(We=(De=r.launcher)==null?void 0:De.composerBar)!=null?We:{},Bt=ge.dataset.state==="expanded",Vt=(Ye=Nt.expandedSize)!=null?Ye:"anchored";if(!(Bt&&Vt!=="fullscreen")){Se.style.background="",Se.style.border="",Se.style.borderRadius="",Se.style.overflow="",Se.style.boxShadow="";return}let mt=(_e=(Pt=r.theme)==null?void 0:Pt.components)==null?void 0:_e.panel,jt=ya(r),hn=(mn,Zn)=>{var bo;return mn==null||mn===""?Zn:(bo=Ps(jt,mn))!=null?bo:mn},jn="1px solid var(--persona-border)",Ir="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",un="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Se.style.background="var(--persona-surface, #ffffff)",Se.style.border=hn(mt==null?void 0:mt.border,jn),Se.style.borderRadius=hn(mt==null?void 0:mt.borderRadius,un),Se.style.boxShadow=hn(mt==null?void 0:mt.shadow,Ir),Se.style.overflow="hidden";return}let l=dn(r),m=(wt=(Kt=r.launcher)==null?void 0:Kt.sidebarMode)!=null?wt:!1,h=l||m||((Rn=(an=r.launcher)==null?void 0:an.fullHeight)!=null?Rn:!1),x=((Ht=r.launcher)==null?void 0:Ht.enabled)===!1,C=(_n=(fn=r.theme)==null?void 0:fn.components)==null?void 0:_n.panel,M=ya(r),$=(Nt,Bt)=>{var Vt;return Nt==null||Nt===""?Bt:(Vt=Ps(M,Nt))!=null?Vt:Nt},N=(Ge=e.ownerDocument.defaultView)!=null?Ge:window,D=($n=(It=r.launcher)==null?void 0:It.mobileFullscreen)!=null?$n:!0,ie=($o=(_o=r.launcher)==null?void 0:_o.mobileBreakpoint)!=null?$o:640,oe=N.innerWidth<=ie,Y=D&&oe&&W,ve=(Uo=(jo=r.launcher)==null?void 0:jo.position)!=null?Uo:"bottom-left",Oe=ve==="bottom-left"||ve==="top-left",Fe=(xs=(bs=r.launcher)==null?void 0:bs.zIndex)!=null?xs:wn,je=m||Y?"none":"1px solid var(--persona-border)",qe=Y?"none":m?Oe?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Y&&(qe="none",je="none");let ut=m||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",st=$(C==null?void 0:C.border,je),Be=$(C==null?void 0:C.shadow,qe),Re=$(C==null?void 0:C.borderRadius,ut),ze=we.scrollTop;e.style.cssText="",ge.style.cssText="",X.style.cssText="",Se.style.cssText="",we.style.cssText="",He.style.cssText="",J&&(we.style.display="none");let Xe=()=>{var Bt;if(ze<=0)return;((Bt=we.ownerDocument.defaultView)!=null?Bt:window).requestAnimationFrame(()=>{if(we.scrollTop===ze)return;let Vt=we.scrollHeight-we.clientHeight;Vt<=0||(we.scrollTop=Math.min(ze,Vt))})};if(Y){ge.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"),ge.style.cssText=`
|
|
35
35
|
position: fixed !important;
|
|
36
36
|
inset: 0 !important;
|
|
37
37
|
width: 100% !important;
|
|
@@ -67,7 +67,7 @@ _Details: ${n.message}_`:r}var ca=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
67
67
|
overflow: hidden !important;
|
|
68
68
|
border-radius: 0 !important;
|
|
69
69
|
border: none !important;
|
|
70
|
-
`,we.style.flex="1 1 0%",we.style.minHeight="0",we.style.overflowY="auto",He.style.flexShrink="0"
|
|
70
|
+
`,we.style.flex="1 1 0%",we.style.minHeight="0",we.style.overflowY="auto",He.style.flexShrink="0",j=!0,Xe();return}let bt=(qo=(Jt=r==null?void 0:r.launcher)==null?void 0:Jt.width)!=null?qo:r==null?void 0:r.launcherWidth,I=bt!=null?bt:tr;if(!m&&!l)x&&h?(X.style.width="100%",X.style.maxWidth="100%"):(X.style.width=I,X.style.maxWidth=I);else if(l)if(nr(r).reveal==="emerge"){let Bt=nr(r).width;X.style.width=Bt,X.style.maxWidth=Bt}else X.style.width="100%",X.style.maxWidth="100%";if(Bo(),X.style.boxShadow=Be,X.style.borderRadius=Re,Se.style.border=st,Se.style.borderRadius=Re,l&&!Y&&(C==null?void 0:C.border)===void 0&&(Se.style.border="none",nr(r).side==="right"?Se.style.borderLeft="1px solid var(--persona-border)":Se.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%"),ge.style.display="flex",ge.style.flexDirection="column",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.maxHeight="100%",ge.style.height="100%",x&&(ge.style.overflow="hidden"),X.style.display="flex",X.style.flexDirection="column",X.style.flex="1 1 0%",X.style.minHeight="0",X.style.maxHeight="100%",X.style.height="100%",X.style.overflow="hidden",Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.maxHeight="100%",Se.style.overflow="hidden",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.overflowY="auto",He.style.flexShrink="0"),ge.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"),!m&&!x&&!l&&((ho=fr[ve])!=null?ho:fr["bottom-right"]).split(" ").forEach(Bt=>ge.classList.add(Bt)),m){let Nt=(Jr=(yo=r.launcher)==null?void 0:yo.sidebarWidth)!=null?Jr:"420px";ge.style.cssText=`
|
|
71
71
|
position: fixed !important;
|
|
72
72
|
top: 0 !important;
|
|
73
73
|
bottom: 0 !important;
|
|
@@ -108,23 +108,23 @@ _Details: ${n.message}_`:r}var ca=e=>({isError:!0,content:[{type:"text",text:e}]
|
|
|
108
108
|
flex-shrink: 0 !important;
|
|
109
109
|
border-top: none !important;
|
|
110
110
|
padding: 8px 16px 12px 16px !important;
|
|
111
|
-
`}if(!x&&!l){let Nt="max-height: -moz-available !important; max-height: stretch !important;",Bt=m?"":"padding-top: 1.25em !important;",Vt=m?"":`z-index: ${(et=(Uo=r.launcher)==null?void 0:Uo.zIndex)!=null?et:xn} !important;`;ge.style.cssText+=Nt+Bt+Vt}Xe()};oo(),es(e,r),Ci(e,r),Ai(e,r);let lt=[];lt.push(()=>{document.removeEventListener("keydown",$r)}),lt.push(()=>{ir!==null&&clearTimeout(ir)});let rn=null,on=null;lt.push(()=>{rn==null||rn(),rn=null,on==null||on(),on=null}),Dn&<.push(()=>{Dn==null||Dn.disconnect(),Dn=null}),lt.push(()=>{Jn==null||Jn(),Jn=null,as(),Ft&&(Ft.remove(),Ft=null),vt==null||vt.element.style.removeProperty("width"),vt==null||vt.element.style.removeProperty("maxWidth")}),ne&<.push(()=>{le!==null&&(cancelAnimationFrame(le),le=null),Me==null||Me.destroy(),Me=null,V==null||V.destroy(),V=null,fe=null});let Tr=null,Os=()=>{Tr&&(Tr(),Tr=null),r.colorScheme==="auto"&&(Tr=xl(()=>{es(e,r)}))};Os(),lt.push(()=>{Tr&&(Tr(),Tr=null)}),lt.push(a);let Ur=(Sd=r.features)==null?void 0:Sd.streamAnimation;if(Ur!=null&&Ur.type&&Ur.type!=="none"){let l=ks(Ur.type,Ur.plugins);l&&(li(l,e),lt.push(()=>hg(e)))}let Ho=Fg(qt),Er=null,F,is=l=>{var x,A;if(!F)return;let m=l!=null?l:F.getMessages(),h=((A=(x=r.features)==null?void 0:x.suggestReplies)==null?void 0:A.enabled)!==!1?rl(m):null;h?Ho.render(h,F,be,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(W=>W.role==="user")?Ho.render([],F,be,m):Ho.render(r.suggestionChips,F,be,m,r.suggestionChipsConfig)},cr=!1,Mr=ig(),qr=new Map,kr=new Map,dr=new Map,ls=0,Ma=Vo()!==null,hn=ni(),Cn=0,pr=null,An=!1,Bo=!1,ur=0,yn=null,Lr=null,cs=!1,Do=!1,ds=null,so=!0,ao=!1,ot=null,w=4,z=24,q=80,G=new Map,K={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ne=(Ed=(Td=r.voiceRecognition)==null?void 0:Td.autoResume)!=null?Ed:!1,rt=l=>{i.emit("voice:state",{active:K.active,source:l,timestamp:Date.now()})},ct=()=>{v(l=>({...l,voiceState:{active:K.active,timestamp:Date.now(),manuallyDeactivated:K.manuallyDeactivated}}))},Di=()=>{var x,A;if(((x=r.voiceRecognition)==null?void 0:x.enabled)===!1)return;let l=Kl(p.voiceState),m=!!l.active,h=Number((A=l.timestamp)!=null?A:0);K.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-h<Lw&&setTimeout(()=>{var W,U;K.active||(K.manuallyDeactivated=!1,((U=(W=r.voiceRecognition)==null?void 0:W.provider)==null?void 0:U.type)==="runtype"?F.toggleVoice().then(()=>{K.active=F.isVoiceActive(),rt("restore"),F.isVoiceActive()&&ms()}):La("restore"))},1e3)},io=()=>F?nf(F.getMessages()).filter(l=>!l.__skipPersist):[];function Pn(l){if(!(c!=null&&c.save))return;let h={messages:l?nf(l):F?io():[],metadata:p,artifacts:Nn.artifacts,selectedArtifactId:Nn.selectedId};try{let x=c.save(h);x instanceof Promise&&x.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)})}catch(x){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",x)}}let Qt=null,lo=()=>ge.querySelector("#persona-scroll-container")||we,Xn=()=>{Qt!==null&&(cancelAnimationFrame(Qt),Qt=null),An=!1},Sn=()=>{pr!==null&&(cancelAnimationFrame(pr),pr=null),Bo=!1,Xn()},In=()=>cr&&Ni()&&(Ot()!=="anchor-top"||sr()),Tn=()=>{let l=xt()||"Jump to latest",m=In();zt.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),ur>0?(Hn.textContent=String(ur),Hn.style.display="",zt.setAttribute("aria-label",`${l} (${ur} new)`)):(Hn.textContent="",Hn.style.display="none",zt.setAttribute("aria-label",m?`${l} (response streaming below)`:l))},sc=()=>{ur!==0&&(ur=0,Tn())},Ni=()=>en()?!hn.isFollowing():!Co(we,z),Fn=()=>{if(!Xt()||J){zt.parentNode&&zt.remove(),zt.style.display="none";return}zt.parentNode!==Se&&Se.appendChild(zt),zn();let m=Br(we)>0&&Ni();m?Tn():sc(),zt.style.display=m?"":"none"},Fs=()=>{hn.pause()&&(Sn(),Fn())},co=()=>{hn.resume(),sc(),Fn()},po=(l=!1)=>{en()&&hn.isFollowing()&&(!l&&!cr||(pr!==null&&(cancelAnimationFrame(pr),pr=null),Bo=!0,pr=requestAnimationFrame(()=>{pr=null,Bo=!1,hn.isFollowing()&&Ff(lo(),l?220:140)})))},ac=(l,m,h,x=()=>!0)=>{let A=l.scrollTop,W=m(),U=W-A;if(Xn(),Math.abs(U)<1){An=!0,l.scrollTop=W,Cn=l.scrollTop,An=!1;return}let _=performance.now();An=!0;let D=oe=>1-Math.pow(1-oe,3),ie=oe=>{if(!x()){Xn();return}let Y=m();Y!==W&&(W=Y,U=W-A);let ve=oe-_,Oe=Math.min(ve/h,1),Fe=D(Oe),je=A+U*Fe;l.scrollTop=je,Cn=l.scrollTop,Oe<1?Qt=requestAnimationFrame(ie):(l.scrollTop=W,Cn=l.scrollTop,Qt=null,An=!1)};Qt=requestAnimationFrame(ie)},Ff=(l,m=500)=>{let h=Br(l)-l.scrollTop;if(Math.abs(h)<1){Cn=l.scrollTop;return}if(Math.abs(h)>=q){Xn(),An=!0,l.scrollTop=Br(l),Cn=l.scrollTop,An=!1;return}ac(l,()=>Br(l),m,()=>hn.isFollowing())},ic=()=>{let l=lo();An=!0,l.scrollTop=Br(l),Cn=l.scrollTop,An=!1,Fn()},lc=l=>{let m=0,h=l;for(;h&&h!==we;)m+=h.offsetTop,h=h.offsetParent;return m},cc=()=>{var W;if(Nr()!=="last-user-turn")return!1;let l=(W=F==null?void 0:F.getMessages())!=null?W:[];if(l.length<2)return!1;let m=[...l].reverse().find(U=>U.role==="user");if(!m)return!1;let h=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(m.id):m.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=we.querySelector(`[data-message-id="${h}"]`);if(!x)return!1;let A=Math.min(Math.max(0,lc(x)-xr()),Br(we));return An=!0,we.scrollTop=A,Cn=we.scrollTop,An=!1,Ot()==="follow"&&!Co(we,z)&&hn.pause(),Fn(),!0},dc=l=>{kn.style.height=`${Math.max(0,Math.round(l))}px`,yn&&(yn.spacerHeight=Math.max(0,l))},_s=()=>{Lr!==null&&(cancelAnimationFrame(Lr),Lr=null),Xn(),yn=null,kn.style.height="0px"},_f=l=>{Lr!==null&&cancelAnimationFrame(Lr),Lr=requestAnimationFrame(()=>{var D;Lr=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=we.querySelector(`[data-message-id="${m}"]`);if(!h)return;let x=lc(h),A=(D=yn==null?void 0:yn.spacerHeight)!=null?D:0,W=we.scrollHeight-A,{targetScrollTop:U,spacerHeight:_}=ug({anchorOffsetTop:x,topOffset:xr(),viewportHeight:we.clientHeight,contentHeight:W});yn={initialSpacerHeight:_,contentHeightAtAnchor:W,spacerHeight:_},dc(_),ac(we,()=>U,220)})},$f=()=>{if(en()){if(!hn.isFollowing()||Co(we,1))return;po(!cr);return}if(yn&&yn.initialSpacerHeight>0){let l=we.scrollHeight-yn.spacerHeight,m=mg({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:l});m!==yn.spacerHeight&&dc(m)}Fn()},jf=l=>{let m=Ot();m==="follow"?(co(),po(!0)):m==="anchor-top"&&(so=!1,ao=!0,_f(l))},Uf=()=>{if(Ot()==="anchor-top"){if(ao){so=!1;return}so=!0,_s(),co(),po(!0)}},qf=l=>{let m=new Map;l.forEach(h=>{let x=G.get(h.id);m.set(h.id,{streaming:h.streaming,role:h.role}),!x&&h.role==="assistant"&&(i.emit("assistant:message",h),!Do&&(Ot()!=="anchor-top"||sr())&&Ni()&&(ur+=1,Tn(),Fn(),Qr(ur===1?"1 new message below.":`${ur} new messages below.`))),h.role==="assistant"&&(x!=null&&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}))}),G.clear(),m.forEach((h,x)=>{G.set(x,h)})},zf=(l,m,h)=>{var st,Be,Re,ze,Xe,bt;let x=document.createElement("div"),W=(()=>{var De;let H=o.find(We=>We.renderLoadingIndicator);if(H!=null&&H.renderLoadingIndicator)return H.renderLoadingIndicator;if((De=r.loadingIndicator)!=null&&De.render)return r.loadingIndicator.render})(),U=(H,De)=>De==null?!1:typeof De=="string"?(H.textContent=De,!0):(H.appendChild(De),!0),_=new Set,D=new Set,ie=o.some(H=>H.renderAskUserQuestion),oe=[],Y=[],ve=r.enableComponentStreaming!==!1,Oe=r.approval!==!1,Fe=[];if(m.forEach(H=>{var mn,_n,Ge,It,$n,Oo,Fo,_o,$o,fs,hs,Jt,jo,go,fo,Vr,Uo;_.add(H.id);let De=ie&&yo(H),We=Oe&&H.variant==="approval"&&!!H.approval,Ye=!De&&H.role==="assistant"&&!H.variant&&ve&&Ul(H);if(!We&&dr.has(H.id)){let et=l.querySelector(`#wrapper-${H.id}`);et==null||et.removeAttribute("data-preserve-runtime"),dr.delete(H.id)}if(!Ye&&kr.has(H.id)){let et=l.querySelector(`#wrapper-${H.id}`);et==null||et.removeAttribute("data-preserve-runtime"),kr.delete(H.id)}let Pt=yo(H)?`:${(mn=H.agentMetadata)!=null&&mn.askUserQuestionAnswered?"a":"u"}:${(_n=H.agentMetadata)!=null&&_n.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",_e=ag(H,ls)+Pt,Kt=De||We||Ye?null:lg(Mr,H.id,_e);if(Kt){x.appendChild(Kt.cloneNode(!0)),yo(H)&&((Ge=H.toolCall)!=null&&Ge.id)&&((It=H.agentMetadata)==null?void 0:It.awaitingLocalTool)===!0&&!(($n=H.agentMetadata)!=null&&$n.askUserQuestionAnswered)&&(D.add(H.toolCall.id),na(H,r,Ve.composerOverlay));return}let wt=null,an=o.find(et=>!!(H.variant==="reasoning"&&et.renderReasoning||H.variant==="tool"&&et.renderToolCall||!H.variant&&et.renderMessage)),Rn=(Oo=r.layout)==null?void 0:Oo.messages;if(yo(H)&&((Fo=H.agentMetadata)==null?void 0:Fo.askUserQuestionAnswered)===!0){qr.delete(H.id);let et=l.querySelector(`#wrapper-${H.id}`);et==null||et.removeAttribute("data-preserve-runtime");return}if(Fa(H)&&(($o=(_o=r.features)==null?void 0:_o.suggestReplies)==null?void 0:$o.enabled)!==!1)return;if(yo(H)&&((hs=(fs=r.features)==null?void 0:fs.askUserQuestion)==null?void 0:hs.enabled)!==!1){let et=o.find(Nt=>typeof Nt.renderAskUserQuestion=="function");if(et&&St.current){let Nt=qr.get(H.id),Bt=Nt!==_e,Vt=null;if(Bt){let{payload:jt,complete:gn}=bo(H),jn=H.id,Ir=()=>{var pn;return(pn=St.current)==null?void 0:pn.getMessages().find(un=>un.id===jn)};Vt=et.renderAskUserQuestion({message:H,payload:jt,complete:gn,resolve:pn=>{var Zn;let un=Ir();un&&((Zn=St.current)==null||Zn.resolveAskUserQuestion(un,pn))},dismiss:()=>{var un,Zn,ho;let pn=Ir();(un=pn==null?void 0:pn.agentMetadata)!=null&&un.awaitingLocalTool&&((Zn=St.current)==null||Zn.markAskUserQuestionResolved(pn),(ho=St.current)==null||ho.resolveAskUserQuestion(pn,"(dismissed)"))},config:r})}let $t=Nt!=null;if(Bt&&Vt===null&&!$t){((Jt=H.agentMetadata)==null?void 0:Jt.awaitingLocalTool)===!0&&!((jo=H.agentMetadata)!=null&&jo.askUserQuestionAnswered)&&(D.add(H.toolCall.id),na(H,r,Ve.composerOverlay));return}let mt=document.createElement("div");mt.className="persona-flex",mt.id=`wrapper-${H.id}`,mt.setAttribute("data-wrapper-id",H.id),mt.setAttribute("data-ask-plugin-stub","true"),mt.setAttribute("data-preserve-runtime","true"),x.appendChild(mt),oe.push({messageId:H.id,fingerprint:_e,bubble:Vt});return}else{((go=H.agentMetadata)==null?void 0:go.awaitingLocalTool)===!0&&!((fo=H.agentMetadata)!=null&&fo.askUserQuestionAnswered)&&(D.add(H.toolCall.id),na(H,r,Ve.composerOverlay));return}}else if(We){let et=(Vr=o.find($t=>typeof $t.renderApproval=="function"))!=null?Vr:s,Bt=dr.get(H.id)!==_e,Vt=null;if(Bt&&(et!=null&&et.renderApproval)){let $t=H.id,mt=(jt,gn)=>{var Ir,pn,un;let jn=(Ir=St.current)==null?void 0:Ir.getMessages().find(Zn=>Zn.id===$t);jn!=null&&jn.approval&&(jn.approval.toolType==="webmcp"?(pn=St.current)==null||pn.resolveWebMcpApproval(jn.id,jt):(un=St.current)==null||un.resolveApproval(jn.approval,jt,gn))};Vt=et.renderApproval({message:H,defaultRenderer:()=>vi(H,r),config:r,approve:jt=>mt("approved",jt),deny:jt=>mt("denied",jt)})}if(Bt&&Vt===null){let $t=l.querySelector(`#wrapper-${H.id}`);$t==null||$t.removeAttribute("data-preserve-runtime"),dr.delete(H.id),wt=vi(H,r)}else{let $t=document.createElement("div");$t.className="persona-flex",$t.id=`wrapper-${H.id}`,$t.setAttribute("data-wrapper-id",H.id),$t.setAttribute("data-approval-plugin-stub","true"),$t.setAttribute("data-preserve-runtime","true"),x.appendChild($t),Fe.push({messageId:H.id,fingerprint:_e,bubble:Vt});return}}else if(an)if(H.variant==="reasoning"&&H.reasoning&&an.renderReasoning){if(!Le)return;wt=an.renderReasoning({message:H,defaultRenderer:()=>Pl(H,r),config:r})}else if(H.variant==="tool"&&H.toolCall&&an.renderToolCall){if(!Pe)return;wt=an.renderToolCall({message:H,defaultRenderer:()=>Rl(H,r),config:r})}else an.renderMessage&&(wt=an.renderMessage({message:H,defaultRenderer:()=>{let et=Ca(H,h,Rn,r.messageActions,he,{loadingIndicatorRenderer:W,widgetConfig:r});return H.role!=="user"&&Nl(et,H,r,F),et},config:r}));if(!wt&&Ye){let et=ql(H);if(et){let Nt=kr.get(H.id),Bt=Nt!==_e,Vt=r.wrapComponentDirectiveInBubble!==!1,$t=null;if(Bt){let mt=jl(et,{config:r,message:H,transform:h});if(mt)if(Vt){let jt=document.createElement("div");if(jt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),jt.id=`bubble-${H.id}`,jt.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let gn=document.createElement("div");gn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",gn.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),jt.appendChild(gn)}jt.appendChild(mt),$t=jt}else{let jt=document.createElement("div");if(jt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",jt.id=`bubble-${H.id}`,jt.setAttribute("data-message-id",H.id),jt.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let gn=document.createElement("div");gn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",gn.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),jt.appendChild(gn)}jt.appendChild(mt),$t=jt}}if($t||Nt!=null){let mt=document.createElement("div");mt.className="persona-flex",mt.id=`wrapper-${H.id}`,mt.setAttribute("data-wrapper-id",H.id),mt.setAttribute("data-component-directive-stub","true"),mt.setAttribute("data-preserve-runtime","true"),Vt||mt.classList.add("persona-w-full"),x.appendChild(mt),Y.push({messageId:H.id,fingerprint:_e,bubble:$t});return}}}if(!wt)if(H.variant==="reasoning"&&H.reasoning){if(!Le)return;wt=Pl(H,r)}else if(H.variant==="tool"&&H.toolCall){if(!Pe)return;wt=Rl(H,r)}else if(H.variant==="approval"&&H.approval){if(r.approval===!1)return;wt=vi(H,r)}else{let et=(Uo=r.layout)==null?void 0:Uo.messages;et!=null&&et.renderUserMessage&&H.role==="user"?wt=et.renderUserMessage({message:H,config:r,streaming:!!H.streaming}):et!=null&&et.renderAssistantMessage&&H.role==="assistant"?wt=et.renderAssistantMessage({message:H,config:r,streaming:!!H.streaming}):wt=Ca(H,h,et,r.messageActions,he,{loadingIndicatorRenderer:W,widgetConfig:r}),H.role!=="user"&&wt&&Nl(wt,H,r,F)}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${H.id}`,Ht.setAttribute("data-wrapper-id",H.id),H.role==="user"&&Ht.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&Ht.classList.add("persona-w-full"),Ht.appendChild(wt),cg(Mr,H.id,_e,Ht),x.appendChild(Ht)}),Ve.composerOverlay&&Ve.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let We=De.getAttribute("data-persona-ask-sheet-for");We&&!D.has(We)&&Jo(Ve.composerOverlay,We)}),(Be=(st=r.features)==null?void 0:st.toolCallDisplay)!=null&&Be.grouped){let H=[],De=[];m.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&Pe){De.push(We);return}De.length>1&&H.push(De),De=[]}),De.length>1&&H.push(De),H.forEach((We,Ye)=>{var mn,_n;let Pt=We.map(Ge=>Array.from(x.children).find(It=>It instanceof HTMLElement&&It.getAttribute("data-wrapper-id")===Ge.id)).filter(Ge=>!!Ge);if(Pt.length<2)return;let _e=document.createElement("div");_e.className="persona-flex",_e.id=`wrapper-tool-group-${Ye}-${We[0].id}`,_e.setAttribute("data-wrapper-id",`tool-group-${Ye}-${We[0].id}`);let Kt=document.createElement("div");Kt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Kt.setAttribute("data-persona-tool-group","true");let wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let an=`Called ${We.length} tools`,Rn=(_n=(mn=r.toolCall)==null?void 0:mn.renderGroupedSummary)==null?void 0:_n.call(mn,{messages:We,toolCalls:We.map(Ge=>Ge.toolCall).filter(Ge=>!!Ge),defaultSummary:an,config:r});U(wt,Rn)||(wt.textContent=an);let Ht=document.createElement("div");Ht.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(wt,Ht),_e.appendChild(Kt),Pt[0].before(_e),Pt.forEach((Ge,It)=>{let $n=document.createElement("div");$n.className="persona-tool-group-item persona-relative",$n.setAttribute("data-persona-tool-group-item","true"),It<Pt.length-1&&$n.setAttribute("data-persona-tool-group-connector","true"),$n.appendChild(Ge),Ht.appendChild($n)})})}dg(Mr,_);let je=m.some(H=>H.role==="assistant"&&H.streaming),qe=m[m.length-1],ut=(qe==null?void 0:qe.role)==="assistant"&&!qe.streaming&&qe.variant!=="approval";if(cr&&m.some(H=>H.role==="user")&&!je&&!ut){let H={config:r,streaming:!0,location:"standalone",defaultRenderer:Ps},De=o.find(Ye=>Ye.renderLoadingIndicator),We=null;if(De!=null&&De.renderLoadingIndicator&&(We=De.renderLoadingIndicator(H)),We===null&&((Re=r.loadingIndicator)!=null&&Re.render)&&(We=r.loadingIndicator.render(H)),We===null&&(We=Ps()),We){let Ye=document.createElement("div"),Pt=((ze=r.loadingIndicator)==null?void 0:ze.showBubble)!==!1;Ye.className=Pt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ye.setAttribute("data-typing-indicator","true"),Ye.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ye.appendChild(We);let _e=document.createElement("div");_e.className="persona-flex",_e.id="wrapper-typing-indicator",_e.setAttribute("data-wrapper-id","typing-indicator"),_e.appendChild(Ye),x.appendChild(_e)}}if(!cr&&m.length>0){let H=m[m.length-1],De={config:r,lastMessage:H,messageCount:m.length},We=o.find(Pt=>Pt.renderIdleIndicator),Ye=null;if(We!=null&&We.renderIdleIndicator&&(Ye=We.renderIdleIndicator(De)),Ye===null&&((Xe=r.loadingIndicator)!=null&&Xe.renderIdle)&&(Ye=r.loadingIndicator.renderIdle(De)),Ye){let Pt=document.createElement("div"),_e=((bt=r.loadingIndicator)==null?void 0:bt.showBubble)!==!1;Pt.className=_e?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Pt.setAttribute("data-idle-indicator","true"),Pt.appendChild(Ye);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-idle-indicator",Kt.setAttribute("data-wrapper-id","idle-indicator"),Kt.appendChild(Pt),x.appendChild(Kt)}}if(ei(l,x),oe.length>0)for(let{messageId:H,fingerprint:De,bubble:We}of oe){let Ye=l.querySelector(`#wrapper-${H}`);Ye&&We!==null&&(Ye.replaceChildren(We),Ye.setAttribute("data-bubble-fp",De),qr.set(H,De))}if(qr.size>0)for(let H of qr.keys())_.has(H)||qr.delete(H);if(Y.length>0)for(let{messageId:H,fingerprint:De,bubble:We}of Y){let Ye=l.querySelector(`#wrapper-${H}`);Ye&&We!==null&&(Ye.replaceChildren(We),Ye.setAttribute("data-bubble-fp",De),kr.set(H,De))}if(kr.size>0)for(let H of kr.keys())_.has(H)||kr.delete(H);if(Fe.length>0)for(let{messageId:H,fingerprint:De,bubble:We}of Fe){let Ye=l.querySelector(`#wrapper-${H}`);Ye&&We!==null&&(Ye.replaceChildren(We),Ye.setAttribute("data-bubble-fp",De),dr.set(H,De))}if(dr.size>0)for(let H of dr.keys())_.has(H)||dr.delete(H)},$s=(l,m,h)=>{zf(l,m,h),no()},js=null,Vf=()=>{var h;if(js)return;let l=x=>{let A=x.composedPath();A.includes(ge)||it&&A.includes(it)||_t(!1,"user")};js=l,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},pc=()=>{var m;if(!js)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",js,!0),js=null};lt.push(()=>pc());let Us=null,Kf=()=>{var h;if(Us)return;let l=x=>{x.key==="Escape"&&(x.isComposing||_t(!1,"user"))};Us=l,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},uc=()=>{var m;if(!Us)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",Us,!0),Us=null};lt.push(()=>uc());let qs=!1,mc=new Set,Gf=()=>{var m,h,x,A;let l=(x=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.peek)==null?void 0:x.streamAnimation;return l||((A=r.features)==null?void 0:A.streamAnimation)},ps=()=>{var ut,st,Be,Re;if(!R())return;let l=Ve.peekBanner,m=Ve.peekTextNode;if(!l||!m)return;if(O){l.classList.remove("persona-pill-peek--visible");return}let h=(ut=F==null?void 0:F.getMessages())!=null?ut:[],x;for(let ze=h.length-1;ze>=0;ze--){let Xe=h[ze];if(Xe.role==="assistant"&&Xe.content){x=Xe;break}}if(!x){l.classList.remove("persona-pill-peek--visible");return}let A=x.content,W=!!x.streaming,U=Gf(),_=si(U),D=_.type!=="none"?ks(_.type,U==null?void 0:U.plugins):null,ie=((st=D==null?void 0:D.isAnimating)==null?void 0:st.call(D,x))===!0,oe=D!==null&&(W||ie);oe&&D&&!mc.has(D.name)&&(li(D,e),mc.add(D.name));let Y=oe&&(D!=null&&D.containerClass)?D.containerClass:null,ve=(Be=m.dataset.personaPeekStreamClass)!=null?Be:null;ve&&ve!==Y&&(m.classList.remove(ve),delete m.dataset.personaPeekStreamClass),Y&&ve!==Y&&(m.classList.add(Y),m.dataset.personaPeekStreamClass=Y),oe?(m.style.setProperty("--persona-stream-step",`${_.speed}ms`),m.style.setProperty("--persona-stream-duration",`${_.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let Oe=oe?ai(A,_.buffer,D,x,W):A;if(oe&&_.placeholder==="skeleton"&&W&&(!Oe||!Oe.trim())){let ze=document.createElement("div"),Xe=ya();Xe.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Xe),ei(m,ze)}else{let ze=Math.max(0,Oe.length-100),Xe=Oe.length>100?Oe.slice(-100):Oe,bt=Kr(Xe);if(!oe||!D){let H=Oe.length>100?`\u2026${Xe}`:Xe;m.textContent!==H&&(m.textContent=H)}else{let H=bt;(D.wrap==="char"||D.wrap==="word")&&(H=ha(bt,D.wrap,`peek-${x.id}`,{skipTags:D.skipTags,startIndex:ze}));let De=document.createElement("div");if(De.innerHTML=H,D.useCaret&&Xe.length>0){let We=ii(),Ye=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),Pt=Ye[Ye.length-1];Pt!=null&&Pt.parentNode?Pt.parentNode.insertBefore(We,Pt.nextSibling):De.appendChild(We)}ei(m,De),(Re=D.onAfterRender)==null||Re.call(D,{container:m,bubble:l,messageId:x.id,message:x,speed:_.speed,duration:_.duration})}}let qe=cr||qs;l.classList.toggle("persona-pill-peek--visible",qe)};if(R()){let l=Ve.peekBanner;if(l){let x=A=>{A.preventDefault(),A.stopPropagation(),_t(!0,"user")};l.addEventListener("pointerdown",x),lt.push(()=>{l.removeEventListener("pointerdown",x)})}let m=()=>{qs||(qs=!0,ps())},h=()=>{qs&&(qs=!1,ps())};X.addEventListener("pointerenter",m),X.addEventListener("pointerleave",h),lt.push(()=>{X.removeEventListener("pointerenter",m),X.removeEventListener("pointerleave",h)}),it&&(it.addEventListener("pointerenter",m),it.addEventListener("pointerleave",h),lt.push(()=>{it.removeEventListener("pointerenter",m),it.removeEventListener("pointerleave",h)}))}let Jf=l=>{var ve,Oe,Fe,je,qe,ut,st,Be;let m=(Oe=(ve=r.launcher)==null?void 0:ve.composerBar)!=null?Oe:{},h=(Fe=m.expandedSize)!=null?Fe:"anchored",x=(je=m.bottomOffset)!=null?je:"16px",A=m.collapsedMaxWidth,W=(qe=m.expandedMaxWidth)!=null?qe:"880px",U=(ut=m.expandedTopOffset)!=null?ut:"5vh",_=(st=m.modalMaxWidth)!=null?st:"880px",D=(Be=m.modalMaxHeight)!=null?Be:"min(90vh, 800px)",ie="calc(100vw - 32px)",oe="var(--persona-pill-area-height, 80px)",Y=ge.style;if(Y.left="",Y.right="",Y.top="",Y.bottom="",Y.transform="",Y.width="",Y.maxWidth="",Y.height="",Y.maxHeight="",it){let Re=it.style;Re.bottom=x,Re.width=A!=null?A:""}if(l&&h!=="fullscreen"){if(h==="modal"){Y.top="50%",Y.left="50%",Y.transform="translate(-50%, -50%)",Y.bottom="auto",Y.right="auto",Y.width=_,Y.maxWidth=ie,Y.maxHeight=D,Y.height=D;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${x} + ${oe})`,Y.top=U,Y.width=W,Y.maxWidth=ie}},zs=()=>{var D,ie,oe,Y,ve,Oe,Fe,je;if(!N())return;if(R()){let ut=(oe=((ie=(D=r.launcher)==null?void 0:D.composerBar)!=null?ie:{}).expandedSize)!=null?oe:"anchored",st=O?"expanded":"collapsed";ge.dataset.state=st,ge.dataset.expandedSize=ut,it&&(it.dataset.state=st,it.dataset.expandedSize=ut),ge.style.removeProperty("display"),ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Jf(O),Se.style.display=O?"flex":"none",oo(),O?(Vf(),Kf()):(pc(),uc()),ps();return}let l=dn(r),m=(Y=e.ownerDocument.defaultView)!=null?Y:window,h=(Oe=(ve=r.launcher)==null?void 0:ve.mobileBreakpoint)!=null?Oe:640,x=(je=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?je:!0,A=m.innerWidth<=h,W=x&&A&&P,U=nr(r).reveal;O?(ge.style.removeProperty("display"),ge.style.display=l?"flex":"",ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0"),X.classList.add("persona-scale-100","persona-opacity-100"),Zt?Zt.element.style.display="none":sn&&(sn.style.display="none")):(l?l&&(U==="overlay"||U==="push")&&!W?(ge.style.removeProperty("display"),ge.style.display="flex",ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ge.style.setProperty("display","none","important"),ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ge.style.display="",ge.classList.add("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100"),X.classList.add("persona-scale-95","persona-opacity-0")),Zt?Zt.element.style.display=l?"none":"":sn&&(sn.style.display=l?"none":""))},_t=(l,m="user")=>{var W,U;if(!N()||O===l)return;let h=O;O=l,zs();let x=(()=>{var Fe,je,qe,ut,st,Be,Re,ze,Xe,bt;let _=(je=(Fe=r.launcher)==null?void 0:Fe.sidebarMode)!=null?je:!1,D=(qe=e.ownerDocument.defaultView)!=null?qe:window,ie=(st=(ut=r.launcher)==null?void 0:ut.mobileFullscreen)!=null?st:!0,oe=(Re=(Be=r.launcher)==null?void 0:Be.mobileBreakpoint)!=null?Re:640,Y=D.innerWidth<=oe,ve=dn(r)&&ie&&Y,Oe=R()&&((bt=(Xe=(ze=r.launcher)==null?void 0:ze.composerBar)==null?void 0:Xe.expandedSize)!=null?bt:"fullscreen")==="fullscreen";return _||ie&&Y&&P||ve||Oe})();if(O&&x){if(!rn){let _=e.getRootNode(),D=_ instanceof ShadowRoot?_.host:e.closest(".persona-host");D&&(rn=Cl(D,(U=(W=r.launcher)==null?void 0:W.zIndex)!=null?U:xn))}on||(on=Al(e.ownerDocument))}else O||(rn==null||rn(),rn=null,on==null||on(),on=null);O&&(Vs(),cc()||(Ot()==="follow"?po(!0):ic()));let A={open:O,source:m,timestamp:Date.now()};O&&!h?i.emit("widget:opened",A):!O&&h&&i.emit("widget:closed",A),i.emit("widget:state",{open:O,launcherEnabled:P,voiceActive:K.active,streaming:F.isStreaming()})},Oi=l=>{me(l?"stop":"send"),B&&(B.disabled=l),Ho.buttons.forEach(m=>{m.disabled=l}),He.dataset.personaComposerStreaming=l?"true":"false",He.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},Fi=()=>{K.active||be&&be.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Fi(),200)});let gc=()=>{var h,x,A,W,U,_,D,ie,oe,Y,ve;yr.textContent=(x=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?x:"Hello \u{1F44B}",br.textContent=(W=(A=r.copy)==null?void 0:A.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",be.placeholder=(_=(U=r.copy)==null?void 0:U.inputPlaceholder)!=null?_:"How can I help...";let l=we.querySelector("[data-persona-intro-card]");if(l){let Oe=((D=r.copy)==null?void 0:D.showWelcomeCard)!==!1;l.style.display=Oe?"":"none",Oe?(we.classList.remove("persona-gap-3"),we.classList.add("persona-gap-6")):(we.classList.remove("persona-gap-6"),we.classList.add("persona-gap-3"))}!((oe=(ie=r.sendButton)==null?void 0:ie.useIcon)!=null&&oe)&&!(F!=null&&F.isStreaming())&&(pe.textContent=(ve=(Y=r.copy)==null?void 0:Y.sendButtonLabel)!=null?ve:"Send"),be.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',be.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=p.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{v(m=>({...m,sessionId:l}))}});let No=null,Xf=()=>{No==null&&(No=setInterval(()=>{let l=Ze.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(No),No=null;return}let m=Date.now();l.forEach(h=>{let x=Number(h.getAttribute("data-tool-elapsed"));x&&(h.textContent=ja(m-x))})},100))};F=new da(r,{onMessagesChanged(l){var A,W;$s(Ze,l,ee),Xf(),is(l),po(!cr),qf(l);let m=[...l].reverse().find(U=>U.role==="user"),h=[...l].reverse().find(U=>U.role==="assistant");l.length===0&&(_s(),so=!0,ao=!1),!cs||Do?(cs=!0,ds=(A=m==null?void 0:m.id)!=null?A:null,ot=(W=h==null?void 0:h.id)!=null?W:null):m&&m.id!==ds?(ds=m.id,jf(m.id)):h&&h.id!==ot&&Uf(),h&&(ot=h.id);let x=K.lastUserMessageId;m&&m.id!==x&&(K.lastUserMessageId=m.id,i.emit("user:message",m)),K.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Pn(l),ps()},onStatusChanged(l){var x;let m=(x=r.statusIndicator)!=null?x:{};Wt(fn,(A=>{var W,U,_,D,ie,oe;return A==="idle"?(W=m.idleText)!=null?W:nn.idle:A==="connecting"?(U=m.connectingText)!=null?U:nn.connecting:A==="connected"?(_=m.connectedText)!=null?_:nn.connected:A==="error"?(D=m.errorText)!=null?D:nn.error:A==="paused"?(ie=m.pausedText)!=null?ie:nn.paused:A==="resuming"?(oe=m.resumingText)!=null?oe:nn.resuming:nn[A]})(l),m,l)},onStreamingChanged(l){cr=l,Oi(l),F&&$s(Ze,F.getMessages(),ee),l||po(!0),Fn(),Qr(l?"Responding\u2026":"Response complete."),ps()},onVoiceStatusChanged(l){var m,h;if(i.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":zr(),ms();break;case"processing":zr(),th();break;case"speaking":zr(),nh();break;default:l==="idle"&&F.isBargeInActive()?(zr(),ms(),B==null||B.setAttribute("aria-label","End voice session")):(K.active=!1,zr(),rt("system"),ct());break}},onArtifactsState(l){Nn=l,Sr(),Pn()},onReconnect(l){var x;let{executionId:m,lastEventId:h}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:m,after:h}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:m,after:h,attempt:(x=l.attempt)!=null?x:1}):i.emit("stream:resumed",{executionId:m,after:h})}}),St.current=F,lt.push(()=>F.cancel());let _i=null;if(F.onReadAloudChange((l,m)=>{var A;eo=l,to=m,no();let h=l!=null?l:_i;l&&(_i=l);let x=h&&(A=F.getMessages().find(W=>W.id===h))!=null?A:null;i.emit("message:read-aloud",{messageId:h,message:x,state:m,timestamp:Date.now()}),m==="idle"&&(_i=null)}),cs=!0,((kd=(Md=r.voiceRecognition)==null?void 0:Md.provider)==null?void 0:kd.type)==="runtype")try{F.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&F.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(V||r.onSSEEvent)&&F.setSSEEventCallback((l,m)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,m),Q==null||Q.processEvent(l,m),V==null||V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})});let fc=()=>{r.resume&&typeof r.reconnectStream=="function"&&F.resumeFromHandle(r.resume)};u?u.then(l=>{var m,h,x;if(l){if(l.metadata&&(p=Kl(l.metadata),L.syncFromMetadata()),(m=l.messages)!=null&&m.length){Do=!0;try{F.hydrateMessages(l.messages)}finally{Do=!1}}(h=l.artifacts)!=null&&h.length&&F.hydrateArtifacts(l.artifacts,(x=l.selectedArtifactId)!=null?x:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>fc()):fc();let hc=()=>{var m,h,x;!R()||O||!((x=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.expandOnSubmit)==null||x)||_t(!0,"auto")},yc=l=>{var A;if(l.preventDefault(),F.isStreaming()){F.cancel(),Q==null||Q.reset(),Me==null||Me.update();return}let m=be.value.trim(),h=(A=At==null?void 0:At.hasAttachments())!=null?A:!1;if(!m&&!h)return;hc();let x;h&&(x=[],x.push(...At.getContentParts()),m&&x.push(Ka(m))),be.value="",be.style.height="auto",ka(),F.sendMessage(m,{contentParts:x}),h&&At.clearAttachments()},Qf=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},$i={...ti},ji=!1,ka=()=>{$i={...ti}},Yf=()=>F.getMessages().filter(l=>l.role==="user").map(l=>{var m;return(m=l.content)!=null?m:""}).filter(l=>l.length>0),Zf=l=>{if(!be)return;ji=!0,be.value=l,be.dispatchEvent(new Event("input",{bubbles:!0})),ji=!1;let m=be.value.length;be.setSelectionRange(m,m)},bc=()=>{ji||ka()},xc=l=>{if(be){if(Qf()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let m=be.selectionStart===0&&be.selectionEnd===0,h=sg({direction:l.key==="ArrowUp"?"up":"down",history:Yf(),currentValue:be.value,atStart:m,state:$i});if($i=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Zf(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(F.isStreaming()){l.preventDefault();return}ka(),l.preventDefault(),pe.click()}}},vc=l=>{l.key!=="Escape"||l.isComposing||F.isStreaming()&&l.composedPath().includes(Se)&&(F.cancel(),Q==null||Q.reset(),Me==null||Me.update(),ka(),l.preventDefault(),l.stopImmediatePropagation())},wc=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!At)return;let m=Iw(l.clipboardData);m.length!==0&&(l.preventDefault(),await At.handleFiles(m))},Qn=null,Pr=!1,us=null,pt=null,Cc=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,La=(l="user")=>{var W,U,_,D,ie,oe,Y;if(Pr||F.isStreaming())return;let m=Cc();if(!m)return;Qn=new m;let x=(U=((W=r.voiceRecognition)!=null?W:{}).pauseDuration)!=null?U:2e3;Qn.continuous=!0,Qn.interimResults=!0,Qn.lang="en-US";let A=be.value;Qn.onresult=ve=>{let Oe="",Fe="";for(let qe=0;qe<ve.results.length;qe++){let ut=ve.results[qe],st=ut[0].transcript;ut.isFinal?Oe+=st+" ":Fe=st}let je=A+Oe+Fe;be.value=je,us&&clearTimeout(us),(Oe||Fe)&&(us=window.setTimeout(()=>{let qe=be.value.trim();qe&&Qn&&Pr&&(uo(),be.value="",be.style.height="auto",F.sendMessage(qe,{viaVoice:!0}))},x))},Qn.onerror=ve=>{ve.error!=="no-speech"&&uo()},Qn.onend=()=>{if(Pr){let ve=be.value.trim();ve&&ve!==A.trim()&&(be.value="",be.style.height="auto",F.sendMessage(ve,{viaVoice:!0})),uo()}};try{if(Qn.start(),Pr=!0,K.active=!0,l!=="system"&&(K.manuallyDeactivated=!1),rt(l),ct(),B){let ve=(_=r.voiceRecognition)!=null?_:{};pt={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(D=ve.iconName)!=null?D:"mic",iconSize:parseFloat((Y=(oe=ve.iconSize)!=null?oe:(ie=r.sendButton)==null?void 0:ie.size)!=null?Y:"40")||24};let Oe=ve.recordingBackgroundColor,Fe=ve.recordingIconColor,je=ve.recordingBorderColor;if(B.classList.add("persona-voice-recording"),B.style.backgroundColor=Oe!=null?Oe:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=Fe!=null?Fe:"var(--persona-voice-recording-indicator, #ffffff)",Fe){let qe=B.querySelector("svg");qe&&qe.setAttribute("stroke",Fe)}je&&(B.style.borderColor=je),B.setAttribute("aria-label","Stop voice recognition")}}catch{uo("system")}},uo=(l="user")=>{if(Pr){if(Pr=!1,us&&(clearTimeout(us),us=null),Qn){try{Qn.stop()}catch{}Qn=null}if(K.active=!1,rt(l),ct(),B){if(B.classList.remove("persona-voice-recording"),pt){B.style.backgroundColor=pt.backgroundColor,B.style.color=pt.color,B.style.borderColor=pt.borderColor;let m=B.querySelector("svg");m&&m.setAttribute("stroke",pt.color||"currentColor"),pt=null}B.setAttribute("aria-label","Start voice recognition")}}},eh=(l,m)=>{var st,Be,Re,ze,Xe,bt,H,De,We;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),x=((st=l==null?void 0:l.provider)==null?void 0:st.type)==="runtype",A=((Be=l==null?void 0:l.provider)==null?void 0:Be.type)==="custom";if(!(h||x||A))return null;let U=y("div","persona-send-button-wrapper"),_=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");_.type="button",_.setAttribute("aria-label","Start voice recognition");let D=(Re=l==null?void 0:l.iconName)!=null?Re:"mic",ie=(ze=m==null?void 0:m.size)!=null?ze:"40px",oe=(Xe=l==null?void 0:l.iconSize)!=null?Xe:ie,Y=parseFloat(oe)||24,ve=(bt=l==null?void 0:l.backgroundColor)!=null?bt:m==null?void 0:m.backgroundColor,Oe=(H=l==null?void 0:l.iconColor)!=null?H:m==null?void 0:m.textColor;_.style.width=oe,_.style.height=oe,_.style.minWidth=oe,_.style.minHeight=oe,_.style.fontSize="18px",_.style.lineHeight="1",Oe?_.style.color=Oe:_.style.color="var(--persona-text, #111827)";let je=ye(D,Y,Oe||"currentColor",1.5);je?_.appendChild(je):_.textContent="\u{1F3A4}",ve?_.style.backgroundColor=ve:_.style.backgroundColor="",l!=null&&l.borderWidth&&(_.style.borderWidth=l.borderWidth,_.style.borderStyle="solid"),l!=null&&l.borderColor&&(_.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(_.style.paddingLeft=l.paddingX,_.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(_.style.paddingTop=l.paddingY,_.style.paddingBottom=l.paddingY),U.appendChild(_);let qe=(De=l==null?void 0:l.tooltipText)!=null?De:"Start voice recognition";if(((We=l==null?void 0:l.showTooltip)!=null?We:!1)&&qe){let Ye=y("div","persona-send-button-tooltip");Ye.textContent=qe,U.appendChild(Ye)}return{micButton:_,micButtonWrapper:U}},Ui=()=>{var m,h,x,A,W;if(!B||pt)return;let l=(m=r.voiceRecognition)!=null?m:{};pt={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((W=(A=l.iconSize)!=null?A:(x=r.sendButton)==null?void 0:x.size)!=null?W:"40")||24}},qi=(l,m)=>{var W,U,_,D,ie;if(!B)return;let h=B.querySelector("svg");h&&h.remove();let x=(ie=pt==null?void 0:pt.iconSize)!=null?ie:parseFloat((D=(_=(W=r.voiceRecognition)==null?void 0:W.iconSize)!=null?_:(U=r.sendButton)==null?void 0:U.size)!=null?D:"40")||24,A=ye(l,x,m,1.5);A&&B.appendChild(A)},Pa=()=>{B&&B.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ms=()=>{var A;if(!B)return;Ui();let l=(A=r.voiceRecognition)!=null?A:{},m=l.recordingBackgroundColor,h=l.recordingIconColor,x=l.recordingBorderColor;if(Pa(),B.classList.add("persona-voice-recording"),B.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let W=B.querySelector("svg");W&&W.setAttribute("stroke",h)}x&&(B.style.borderColor=x),B.setAttribute("aria-label","Stop voice recognition")},th=()=>{var _,D,ie,oe,Y,ve,Oe,Fe;if(!B)return;Ui();let l=(_=r.voiceRecognition)!=null?_:{},m=F.getVoiceInterruptionMode(),h=(D=l.processingIconName)!=null?D:"loader",x=(oe=(ie=l.processingIconColor)!=null?ie:pt==null?void 0:pt.color)!=null?oe:"",A=(ve=(Y=l.processingBackgroundColor)!=null?Y:pt==null?void 0:pt.backgroundColor)!=null?ve:"",W=(Fe=(Oe=l.processingBorderColor)!=null?Oe:pt==null?void 0:pt.borderColor)!=null?Fe:"";Pa(),B.classList.add("persona-voice-processing"),B.style.backgroundColor=A,B.style.borderColor=W;let U=x||"currentColor";B.style.color=U,qi(h,U),B.setAttribute("aria-label","Processing voice input"),m==="none"&&(B.style.cursor="default")},nh=()=>{var ie,oe,Y,ve,Oe,Fe,je,qe,ut,st,Be,Re;if(!B)return;Ui();let l=(ie=r.voiceRecognition)!=null?ie:{},m=F.getVoiceInterruptionMode(),h=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",x=(oe=l.speakingIconName)!=null?oe:h,A=(Fe=l.speakingIconColor)!=null?Fe:m==="barge-in"?(ve=(Y=l.recordingIconColor)!=null?Y:pt==null?void 0:pt.color)!=null?ve:"":(Oe=pt==null?void 0:pt.color)!=null?Oe:"",W=(ut=l.speakingBackgroundColor)!=null?ut:m==="barge-in"?(je=l.recordingBackgroundColor)!=null?je:"var(--persona-voice-recording-bg, #ef4444)":(qe=pt==null?void 0:pt.backgroundColor)!=null?qe:"",U=(Re=l.speakingBorderColor)!=null?Re:m==="barge-in"?(st=l.recordingBorderColor)!=null?st:"":(Be=pt==null?void 0:pt.borderColor)!=null?Be:"";Pa(),B.classList.add("persona-voice-speaking"),B.style.backgroundColor=W,B.style.borderColor=U;let _=A||"currentColor";B.style.color=_,qi(x,_);let D=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";B.setAttribute("aria-label",D),m==="none"&&(B.style.cursor="default"),m==="barge-in"&&B.classList.add("persona-voice-recording")},zr=()=>{var l,m,h;B&&(Pa(),pt&&(B.style.backgroundColor=(l=pt.backgroundColor)!=null?l:"",B.style.color=(m=pt.color)!=null?m:"",B.style.borderColor=(h=pt.borderColor)!=null?h:"",qi(pt.iconName,pt.color||"currentColor"),pt=null),B.style.cursor="",B.setAttribute("aria-label","Start voice recognition"))},Ia=()=>{var l,m;if(((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let h=F.getVoiceStatus(),x=F.getVoiceInterruptionMode();if(x==="none"&&(h==="processing"||h==="speaking"))return;if(x==="cancel"&&(h==="processing"||h==="speaking")){F.stopVoicePlayback();return}if(F.isBargeInActive()){F.stopVoicePlayback(),F.deactivateBargeIn().then(()=>{K.active=!1,K.manuallyDeactivated=!0,ct(),rt("user"),zr()});return}F.toggleVoice().then(()=>{K.active=F.isVoiceActive(),K.manuallyDeactivated=!F.isVoiceActive(),ct(),rt("user"),F.isVoiceActive()?ms():zr()});return}if(Pr){let h=be.value.trim();K.manuallyDeactivated=!0,ct(),uo("user"),h&&(be.value="",be.style.height="auto",F.sendMessage(h))}else K.manuallyDeactivated=!1,ct(),La("user")};wr=Ia,B&&(B.addEventListener("click",Ia),lt.push(()=>{var l,m;((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?(F.isVoiceActive()&&F.toggleVoice(),zr()):uo("system"),B&&B.removeEventListener("click",Ia)}));let rh=i.on("assistant:complete",()=>{Ne&&(K.active||K.manuallyDeactivated||Ne==="assistant"&&!K.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!K.active&&!K.manuallyDeactivated&&(((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?F.toggleVoice().then(()=>{K.active=F.isVoiceActive(),rt("auto"),F.isVoiceActive()&&ms()}):La("auto"))},600))});lt.push(rh);let oh=i.on("action:resubmit",()=>{setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)});lt.push(oh);let Ac=()=>{_t(!O,"user")},Zt=null,sn=null;if(P&&!R()){let{instance:l,element:m}=Ml({config:r,plugins:o,onToggle:Ac});Zt=l,l||(sn=m)}Zt?e.appendChild(Zt.element):sn&&e.appendChild(sn),zs(),is(),gc(),Oi(F.isStreaming()),cc()||(Ot()==="follow"?po(!0):ic()),Di(),k&&(!P||R()?setTimeout(()=>Fi(),0):O&&setTimeout(()=>Fi(),200));let Vs=()=>{var D,ie,oe,Y,ve,Oe,Fe,je,qe,ut,st,Be,Re,ze,Xe,bt,H,De,We,Ye,Pt,_e;if(R()){zn(),zs();return}let l=dn(r),m=(ie=(D=r.launcher)==null?void 0:D.sidebarMode)!=null?ie:!1,h=l||m||((Y=(oe=r.launcher)==null?void 0:oe.fullHeight)!=null?Y:!1),x=(ve=e.ownerDocument.defaultView)!=null?ve:window,A=(Fe=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?Fe:!0,W=(qe=(je=r.launcher)==null?void 0:je.mobileBreakpoint)!=null?qe:640,U=x.innerWidth<=W,_=A&&U&&P;try{if(_){oo(),es(e,r);return}if($&&($=!1,oo(),es(e,r)),!P&&!l){X.style.height="",X.style.width="";return}if(!m&&!l){let Kt=(st=(ut=r==null?void 0:r.launcher)==null?void 0:ut.width)!=null?st:r==null?void 0:r.launcherWidth,wt=Kt!=null?Kt:tr;X.style.width=wt,X.style.maxWidth=wt}if(Wo(),!h){let Kt=x.innerHeight,wt=64,an=(Re=(Be=r.launcher)==null?void 0:Be.heightOffset)!=null?Re:0,Rn=Math.max(200,Kt-wt),Ht=Math.min(640,Rn),mn=Math.max(200,Ht-an);X.style.height=`${mn}px`}}finally{if(zn(),zs(),O&&P){let wt=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((bt=(Xe=r.launcher)==null?void 0:Xe.mobileBreakpoint)!=null?bt:640),an=(De=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?De:!1,Rn=(Ye=(We=r.launcher)==null?void 0:We.mobileFullscreen)!=null?Ye:!0,Ht=dn(r)&&Rn&&wt,mn=an||Rn&&wt&&P||Ht;if(mn&&!on){let _n=e.getRootNode(),Ge=_n instanceof ShadowRoot?_n.host:e.closest(".persona-host");Ge&&!rn&&(rn=Cl(Ge,(_e=(Pt=r.launcher)==null?void 0:Pt.zIndex)!=null?_e:xn)),on=Al(e.ownerDocument)}else mn||(rn==null||rn(),rn=null,on==null||on(),on=null)}}};Vs();let Sc=(Ld=e.ownerDocument.defaultView)!=null?Ld:window;if(Sc.addEventListener("resize",Vs),lt.push(()=>Sc.removeEventListener("resize",Vs)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{zn()});l.observe(He),lt.push(()=>l.disconnect())}Cn=we.scrollTop;let Tc=Br(we),sh=()=>{let l=we.getRootNode(),m=typeof l.getSelection=="function"?l.getSelection():null;return m!=null?m:we.ownerDocument.getSelection()},zi=()=>pg(sh(),we),Ec=()=>{let l=we.scrollTop,m=Br(we),h=m<Tc;if(Tc=m,!en()){Cn=l,Fn();return}let{action:x,nextLastScrollTop:A}=ri({following:hn.isFollowing(),currentScrollTop:l,lastScrollTop:Cn,nearBottom:Co(we,z),userScrollThreshold:w,isAutoScrolling:An||Bo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Cn=A,x==="resume"){zi()||co();return}x==="pause"&&Fs()};if(we.addEventListener("scroll",Ec,{passive:!0}),lt.push(()=>we.removeEventListener("scroll",Ec)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{$f()});l.observe(Ze),l.observe(we),lt.push(()=>l.disconnect())}let Mc=()=>{en()&&hn.isFollowing()&&zi()&&Fs()},kc=we.ownerDocument;kc.addEventListener("selectionchange",Mc),lt.push(()=>{kc.removeEventListener("selectionchange",Mc)});let ah=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Lc=l=>{or()&&en()&&hn.isFollowing()&&ah.has(l.key)&&Fs()},Pc=l=>{if(!or()||!en()||!hn.isFollowing())return;let m=l.target;m&&m.closest("a, button, [tabindex], input, textarea, select")&&Fs()};we.addEventListener("keydown",Lc),we.addEventListener("focusin",Pc),lt.push(()=>{we.removeEventListener("keydown",Lc),we.removeEventListener("focusin",Pc)});let Ic=l=>{if(!en())return;let m=oi({following:hn.isFollowing(),deltaY:l.deltaY,nearBottom:Co(we,z),resumeWhenNearBottom:!0});m==="pause"?Fs():m==="resume"&&!zi()&&co()};we.addEventListener("wheel",Ic,{passive:!0}),lt.push(()=>we.removeEventListener("wheel",Ic)),zt.addEventListener("click",()=>{_s(),we.scrollTop=we.scrollHeight,Cn=we.scrollTop,co(),po(!0),Fn()}),lt.push(()=>zt.remove()),lt.push(()=>{Sn(),_s()});let Rc=()=>{Ue&&(Er&&(Ue.removeEventListener("click",Er),Er=null),N()?(Ue.style.display="",Er=()=>{_t(!1,"user")},Ue.addEventListener("click",Er)):Ue.style.display="none")};Rc(),(()=>{let{clearChatButton:l}=Ve;l&&l.addEventListener("click",()=>{F.clearMessages(),Mr.clear(),co(),Jo(Ve.composerOverlay);try{localStorage.removeItem(Bs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Bs}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Bs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),c!=null&&c.clear)try{let h=c.clear();h instanceof Promise&&h.catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",x)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}p={},L.syncFromMetadata(),V==null||V.clear(),Q==null||Q.reset(),Me==null||Me.update()})})(),Ct&&Ct.addEventListener("submit",yc),be==null||be.addEventListener("keydown",xc),be==null||be.addEventListener("input",bc),be==null||be.addEventListener("paste",wc);let Wc=(Pd=e.ownerDocument)!=null?Pd:document;Wc.addEventListener("keydown",vc,!0);let Hc="persona-attachment-drop-active",Ks=0,Vi=()=>{Ks=0,Se.classList.remove(Hc)},gs=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&At!==null},Bc=l=>{!Mi(l.dataTransfer)||!gs()||(Ks++,Ks===1&&Se.classList.add(Hc))},Dc=l=>{!Mi(l.dataTransfer)||!gs()||(Ks--,Ks<=0&&Vi())},Nc=l=>{!Mi(l.dataTransfer)||!gs()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Oc=l=>{var h;if(!Mi(l.dataTransfer)||!gs())return;l.preventDefault(),l.stopPropagation(),Vi();let m=Array.from((h=l.dataTransfer.files)!=null?h:[]);m.length!==0&&At.handleFiles(m)},mo=!0;Se.addEventListener("dragenter",Bc,mo),Se.addEventListener("dragleave",Dc,mo),e.addEventListener("dragover",Nc,mo),e.addEventListener("drop",Oc,mo);let Ra=e.ownerDocument,Fc=l=>{gs()&&l.preventDefault()},_c=l=>{gs()&&l.preventDefault()};Ra.addEventListener("dragover",Fc),Ra.addEventListener("drop",_c),lt.push(()=>{Ct&&Ct.removeEventListener("submit",yc),be==null||be.removeEventListener("keydown",xc),be==null||be.removeEventListener("input",bc),be==null||be.removeEventListener("paste",wc),Wc.removeEventListener("keydown",vc,!0)}),lt.push(()=>{Se.removeEventListener("dragenter",Bc,mo),Se.removeEventListener("dragleave",Dc,mo),e.removeEventListener("dragover",Nc,mo),e.removeEventListener("drop",Oc,mo),Ra.removeEventListener("dragover",Fc),Ra.removeEventListener("drop",_c),Vi()}),lt.push(()=>{F.cancel()}),Zt?lt.push(()=>{Zt==null||Zt.destroy()}):sn&<.push(()=>{sn==null||sn.remove()});let tn={update(l){var jn,Ir,pn,un,Zn,ho,Nd,Od,Fd,_d,$d,jd,Ud,qd,zd,Vd,Kd,Gd,Jd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,xp,vp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Np,Op,Fp,_p,$p,jp,Up,qp,zp,Vp,Kp,Gp,Jp,Xp,Qp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,yu,bu,xu,vu,wu,Cu,Au,Su,Tu,Eu,Mu,ku,Lu,Pu,Iu,Ru,Wu,Hu,Bu,Du,Nu,Ou,Fu,_u,$u,ju,Uu;let m=r.toolCall,h=r.messageActions,x=(jn=r.layout)==null?void 0:jn.messages,A=r.colorScheme,W=r.loadingIndicator,U=r.iterationDisplay,_=(Ir=r.features)==null?void 0:Ir.showReasoning,D=(pn=r.features)==null?void 0:pn.showToolCalls,ie=(un=r.features)==null?void 0:un.toolCallDisplay,oe=(Zn=r.features)==null?void 0:Zn.reasoningDisplay,Y=(Nd=(ho=r.features)==null?void 0:ho.streamAnimation)==null?void 0:Nd.type;r={...r,...l},oo(),es(e,r),Ci(e,r),Ai(e,r),Sr(),r.colorScheme!==A&&Os();let ve=Si.getForInstance(r.plugins);o.length=0,o.push(...ve),P=(Fd=(Od=r.launcher)==null?void 0:Od.enabled)!=null?Fd:!0,E=($d=(_d=r.launcher)==null?void 0:_d.autoExpand)!=null?$d:!1,Le=(Ud=(jd=r.features)==null?void 0:jd.showReasoning)!=null?Ud:!0,Pe=(zd=(qd=r.features)==null?void 0:qd.showToolCalls)!=null?zd:!0,Ae=(Kd=(Vd=r.features)==null?void 0:Vd.scrollToBottom)!=null?Kd:{};let Oe=Ot();re=(Jd=(Gd=r.features)==null?void 0:Gd.scrollBehavior)!=null?Jd:{},Oe!==Ot()&&(_s(),co()),Yr(),Fn();let Fe=ne;if(ne=(Qd=(Xd=r.features)==null?void 0:Xd.showEventStreamToggle)!=null?Qd:!1,ne&&!Fe){if(V||(fe=new Sa(ae),V=new Aa($e,fe),Q=Q!=null?Q:new Ta,fe.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),F.setSSEEventCallback((te,Tt)=>{var Ut;(Ut=r.onSSEEvent)==null||Ut.call(r,te,Tt),Q==null||Q.processEvent(te,Tt),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!yt&&ke){let te=(Zd=(Yd=r.features)==null?void 0:Yd.eventStream)==null?void 0:Zd.classNames,Tt="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"+(te!=null&&te.toggleButton?" "+te.toggleButton:"");yt=y("button",Tt),yt.style.width="28px",yt.style.height="28px",yt.style.color=Mn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let Ut=ye("activity","18px","currentColor",1.5);Ut&&yt.appendChild(Ut);let at=Ve.clearChatButtonWrapper,kt=Ve.closeButtonWrapper,ln=at||kt;ln&&ln.parentNode===ke?ke.insertBefore(yt,ln):ke.appendChild(yt),yt.addEventListener("click",()=>{J?lr():Fr()})}}else!ne&&Fe&&(lr(),yt&&(yt.remove(),yt=null),V==null||V.clear(),fe==null||fe.destroy(),V=null,fe=null,Q==null||Q.reset(),Q=null);if(((ep=r.launcher)==null?void 0:ep.enabled)===!1&&Zt&&(Zt.destroy(),Zt=null),((tp=r.launcher)==null?void 0:tp.enabled)===!1&&sn&&(sn.remove(),sn=null),((np=r.launcher)==null?void 0:np.enabled)!==!1&&!Zt&&!sn){let{instance:te,element:Tt}=Ml({config:r,plugins:o,onToggle:Ac});Zt=te,te||(sn=Tt),e.appendChild(Tt)}Zt&&Zt.update(r),ue&&((rp=r.launcher)==null?void 0:rp.title)!==void 0&&(ue.textContent=r.launcher.title),Te&&((op=r.launcher)==null?void 0:op.subtitle)!==void 0&&(Te.textContent=r.launcher.subtitle);let je=(sp=r.layout)==null?void 0:sp.header;if((je==null?void 0:je.layout)!==j&&ke){let te=je?va(r,je,{showClose:N(),onClose:()=>_t(!1,"user")}):Eo({config:r,showClose:N(),onClose:()=>_t(!1,"user")});tt.replaceHeader(te),ke=tt.header.element,M=tt.header.iconHolder,ue=tt.header.headerTitle,Te=tt.header.headerSubtitle,Ue=tt.header.closeButton,j=je==null?void 0:je.layout}else if(je&&(M&&(M.style.display=je.showIcon===!1?"none":""),ue&&(ue.style.display=je.showTitle===!1?"none":""),Te&&(Te.style.display=je.showSubtitle===!1?"none":""),Ue&&(Ue.style.display=je.showCloseButton===!1?"none":""),Ve.clearChatButtonWrapper)){let te=je.showClearChat;if(te!==void 0){Ve.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Tt}=Ve;Tt&&!Tt.classList.contains("persona-absolute")&&(te?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let ut=((ap=r.layout)==null?void 0:ap.showHeader)!==!1;ke&&(ke.style.display=ut?"":"none");let st=((ip=r.layout)==null?void 0:ip.showFooter)!==!1;He&&(He.style.display=st?"":"none"),zn(),Fn(),P!==I?P?_t(E,"auto"):(O=!0,zs()):E!==C&&_t(E,"auto"),C=E,I=P,Vs(),Rc();let ze=JSON.stringify(l.toolCall)!==JSON.stringify(m),Xe=JSON.stringify(r.messageActions)!==JSON.stringify(h),bt=JSON.stringify((lp=r.layout)==null?void 0:lp.messages)!==JSON.stringify(x),H=((cp=r.loadingIndicator)==null?void 0:cp.render)!==(W==null?void 0:W.render)||((dp=r.loadingIndicator)==null?void 0:dp.renderIdle)!==(W==null?void 0:W.renderIdle)||((pp=r.loadingIndicator)==null?void 0:pp.showBubble)!==(W==null?void 0:W.showBubble),De=r.iterationDisplay!==U,We=((mp=(up=r.features)==null?void 0:up.showReasoning)!=null?mp:!0)!==(_!=null?_:!0)||((fp=(gp=r.features)==null?void 0:gp.showToolCalls)!=null?fp:!0)!==(D!=null?D:!0)||JSON.stringify((hp=r.features)==null?void 0:hp.toolCallDisplay)!==JSON.stringify(ie)||JSON.stringify((yp=r.features)==null?void 0:yp.reasoningDisplay)!==JSON.stringify(oe);(ze||Xe||bt||H||De||We)&&F&&(ls++,$s(Ze,F.getMessages(),ee));let Pt=(xp=(bp=r.features)==null?void 0:bp.streamAnimation)==null?void 0:xp.type;if(Pt!==Y&&Pt&&Pt!=="none"){let te=ks(Pt,(wp=(vp=r.features)==null?void 0:vp.streamAnimation)==null?void 0:wp.plugins);te&&li(te,e)}let _e=(Cp=r.launcher)!=null?Cp:{},Kt=(Ap=_e.headerIconHidden)!=null?Ap:!1,wt=(Tp=(Sp=r.layout)==null?void 0:Sp.header)==null?void 0:Tp.showIcon,an=Kt||wt===!1,Rn=_e.headerIconName,Ht=(Ep=_e.headerIconSize)!=null?Ep:"48px";if(M){let te=Se.querySelector(".persona-border-b-persona-divider"),Tt=te==null?void 0:te.querySelector(".persona-flex-col");if(an)M.style.display="none",te&&Tt&&!te.contains(Tt)&&te.insertBefore(Tt,te.firstChild);else{if(M.style.display="",M.style.height=Ht,M.style.width=Ht,te&&Tt&&(te.contains(M)?M.nextSibling!==Tt&&(M.remove(),te.insertBefore(M,Tt)):te.insertBefore(M,Tt)),Rn){let at=parseFloat(Ht)||24,kt=ye(Rn,at*.6,"currentColor",1);kt?M.replaceChildren(kt):M.textContent=(Mp=_e.agentIconText)!=null?Mp:"\u{1F4AC}"}else if(_e.iconUrl){let at=M.querySelector("img");if(at)at.src=_e.iconUrl,at.style.height=Ht,at.style.width=Ht;else{let kt=document.createElement("img");kt.src=_e.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=Ht,kt.style.width=Ht,M.replaceChildren(kt)}}else{let at=M.querySelector("svg"),kt=M.querySelector("img");(at||kt)&&M.replaceChildren(),M.textContent=(kp=_e.agentIconText)!=null?kp:"\u{1F4AC}"}let Ut=M.querySelector("img");Ut&&(Ut.style.height=Ht,Ut.style.width=Ht)}}let mn=(Pp=(Lp=r.layout)==null?void 0:Lp.header)==null?void 0:Pp.showTitle,_n=(Rp=(Ip=r.layout)==null?void 0:Ip.header)==null?void 0:Rp.showSubtitle;if(ue&&(ue.style.display=mn===!1?"none":""),Te&&(Te.style.display=_n===!1?"none":""),Ue){((Hp=(Wp=r.layout)==null?void 0:Wp.header)==null?void 0:Hp.showCloseButton)===!1?Ue.style.display="none":Ue.style.display="";let Tt=(Bp=_e.closeButtonSize)!=null?Bp:"32px",Ut=(Dp=_e.closeButtonPlacement)!=null?Dp:"inline";Ue.style.height=Tt,Ue.style.width=Tt;let{closeButtonWrapper:at}=Ve,kt=Ut==="top-right",ln=at==null?void 0:at.classList.contains("persona-absolute");if(at&&kt!==ln)if(at.remove(),kt)at.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Se.style.position="relative",Se.appendChild(at);else{let dt=(Op=(Np=_e.clearChat)==null?void 0:Np.placement)!=null?Op:"inline",cn=(_p=(Fp=_e.clearChat)==null?void 0:Fp.enabled)!=null?_p:!0;at.className=cn&&dt==="inline"?"":"persona-ml-auto";let Wn=Se.querySelector(".persona-border-b-persona-divider");Wn&&Wn.appendChild(at)}if(Ue.style.color=_e.closeButtonColor||Mn.actionIconColor,_e.closeButtonBackgroundColor?(Ue.style.backgroundColor=_e.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),_e.closeButtonBorderWidth||_e.closeButtonBorderColor){let dt=_e.closeButtonBorderWidth||"0px",cn=_e.closeButtonBorderColor||"transparent";Ue.style.border=`${dt} solid ${cn}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");_e.closeButtonBorderRadius?(Ue.style.borderRadius=_e.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),_e.closeButtonPaddingX?(Ue.style.paddingLeft=_e.closeButtonPaddingX,Ue.style.paddingRight=_e.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),_e.closeButtonPaddingY?(Ue.style.paddingTop=_e.closeButtonPaddingY,Ue.style.paddingBottom=_e.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let bn=($p=_e.closeButtonIconName)!=null?$p:"x",mr=(jp=_e.closeButtonIconText)!=null?jp:"\xD7";Ue.innerHTML="";let En=ye(bn,"28px","currentColor",1);En?Ue.appendChild(En):Ue.textContent=mr;let Yt=(Up=_e.closeButtonTooltipText)!=null?Up:"Close chat",Un=(qp=_e.closeButtonShowTooltip)!=null?qp:!0;if(Ue.setAttribute("aria-label",Yt),at&&(at._cleanupTooltip&&(at._cleanupTooltip(),delete at._cleanupTooltip),Un&&Yt)){let dt=null,cn=()=>{if(dt||!Ue)return;let qo=Ue.ownerDocument,Gs=qo.body;if(!Gs)return;dt=Wr(qo,"div","persona-clear-chat-tooltip"),dt.textContent=Yt;let Js=Wr(qo,"div");Js.className="persona-clear-chat-tooltip-arrow",dt.appendChild(Js);let zo=Ue.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(Ao),dt.style.left=`${zo.left+zo.width/2}px`,dt.style.top=`${zo.top-8}px`,dt.style.transform="translate(-50%, -100%)",Gs.appendChild(dt)},Wn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};at.addEventListener("mouseenter",cn),at.addEventListener("mouseleave",Wn),Ue.addEventListener("focus",cn),Ue.addEventListener("blur",Wn),at._cleanupTooltip=()=>{Wn(),at&&(at.removeEventListener("mouseenter",cn),at.removeEventListener("mouseleave",Wn)),Ue&&(Ue.removeEventListener("focus",cn),Ue.removeEventListener("blur",Wn))}}}let{clearChatButton:Ge,clearChatButtonWrapper:It}=Ve;if(Ge){let te=(zp=_e.clearChat)!=null?zp:{},Tt=(Vp=te.enabled)!=null?Vp:!0,Ut=(Gp=(Kp=r.layout)==null?void 0:Kp.header)==null?void 0:Gp.showClearChat,at=Ut!==void 0?Ut:Tt,kt=(Jp=te.placement)!=null?Jp:"inline";if(It){It.style.display=at?"":"none";let{closeButtonWrapper:ln}=Ve;!R()&&ln&&!ln.classList.contains("persona-absolute")&&(at?ln.classList.remove("persona-ml-auto"):ln.classList.add("persona-ml-auto"));let bn=kt==="top-right",mr=It.classList.contains("persona-absolute");if(!R()&&bn!==mr&&at){if(It.remove(),bn)It.className="persona-absolute persona-top-4 persona-z-50",It.style.right="48px",Se.style.position="relative",Se.appendChild(It);else{It.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",It.style.right="";let Yt=Se.querySelector(".persona-border-b-persona-divider"),Un=Ve.closeButtonWrapper;Yt&&Un&&Un.parentElement===Yt?Yt.insertBefore(It,Un):Yt&&Yt.appendChild(It)}let En=Ve.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(bn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(at){if(!R()){let dt=(Xp=te.size)!=null?Xp:"32px";Ge.style.height=dt,Ge.style.width=dt}let ln=(Qp=te.iconName)!=null?Qp:"refresh-cw",bn=(Yp=te.iconColor)!=null?Yp:"";Ge.style.color=bn||Mn.actionIconColor,Ge.innerHTML="";let mr=R()?"14px":"20px",En=ye(ln,mr,"currentColor",2);if(En&&Ge.appendChild(En),te.backgroundColor?(Ge.style.backgroundColor=te.backgroundColor,Ge.classList.remove("hover:persona-bg-gray-100")):(Ge.style.backgroundColor="",Ge.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let dt=te.borderWidth||"0px",cn=te.borderColor||"transparent";Ge.style.border=`${dt} solid ${cn}`,Ge.classList.remove("persona-border-none")}else Ge.style.border="",Ge.classList.add("persona-border-none");te.borderRadius?(Ge.style.borderRadius=te.borderRadius,Ge.classList.remove("persona-rounded-full")):(Ge.style.borderRadius="",Ge.classList.add("persona-rounded-full")),te.paddingX?(Ge.style.paddingLeft=te.paddingX,Ge.style.paddingRight=te.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),te.paddingY?(Ge.style.paddingTop=te.paddingY,Ge.style.paddingBottom=te.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let Yt=(Zp=te.tooltipText)!=null?Zp:"Clear chat",Un=(eu=te.showTooltip)!=null?eu:!0;if(Ge.setAttribute("aria-label",Yt),It&&(It._cleanupTooltip&&(It._cleanupTooltip(),delete It._cleanupTooltip),Un&&Yt)){let dt=null,cn=()=>{if(dt||!Ge)return;let qo=Ge.ownerDocument,Gs=qo.body;if(!Gs)return;dt=Wr(qo,"div","persona-clear-chat-tooltip"),dt.textContent=Yt;let Js=Wr(qo,"div");Js.className="persona-clear-chat-tooltip-arrow",dt.appendChild(Js);let zo=Ge.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(Ao),dt.style.left=`${zo.left+zo.width/2}px`,dt.style.top=`${zo.top-8}px`,dt.style.transform="translate(-50%, -100%)",Gs.appendChild(dt)},Wn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};It.addEventListener("mouseenter",cn),It.addEventListener("mouseleave",Wn),Ge.addEventListener("focus",cn),Ge.addEventListener("blur",Wn),It._cleanupTooltip=()=>{Wn(),It&&(It.removeEventListener("mouseenter",cn),It.removeEventListener("mouseleave",Wn)),Ge&&(Ge.removeEventListener("focus",cn),Ge.removeEventListener("blur",Wn))}}}}let $n=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ti],Oo=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Hs.message,Hs.messageAndClick];L=Ei({parsers:$n,handlers:Oo,getSessionMetadata:b,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),ee=rf(r,L,de),F.updateConfig(r),$s(Ze,F.getMessages(),ee),is(),gc(),Oi(F.isStreaming());let Fo=((tu=r.voiceRecognition)==null?void 0:tu.enabled)===!0,_o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),$o=((ru=(nu=r.voiceRecognition)==null?void 0:nu.provider)==null?void 0:ru.type)==="runtype";if(Fo&&(_o||$o))if(!B||!xe){let te=eh(r.voiceRecognition,r.sendButton);te&&(B=te.micButton,xe=te.micButtonWrapper,ht.insertBefore(xe,vn),B.addEventListener("click",Ia),B.disabled=F.isStreaming())}else{let te=(ou=r.voiceRecognition)!=null?ou:{},Tt=(su=r.sendButton)!=null?su:{},Ut=(au=te.iconName)!=null?au:"mic",at=(iu=Tt.size)!=null?iu:"40px",kt=(lu=te.iconSize)!=null?lu:at,ln=parseFloat(kt)||24;B.style.width=kt,B.style.height=kt,B.style.minWidth=kt,B.style.minHeight=kt;let bn=(du=(cu=te.iconColor)!=null?cu:Tt.textColor)!=null?du:"currentColor";B.innerHTML="";let mr=ye(Ut,ln,bn,2);mr?B.appendChild(mr):B.textContent="\u{1F3A4}";let En=(pu=te.backgroundColor)!=null?pu:Tt.backgroundColor;En?B.style.backgroundColor=En:B.style.backgroundColor="",bn?B.style.color=bn:B.style.color="var(--persona-text, #111827)",te.borderWidth?(B.style.borderWidth=te.borderWidth,B.style.borderStyle="solid"):(B.style.borderWidth="",B.style.borderStyle=""),te.borderColor?B.style.borderColor=te.borderColor:B.style.borderColor="",te.paddingX?(B.style.paddingLeft=te.paddingX,B.style.paddingRight=te.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),te.paddingY?(B.style.paddingTop=te.paddingY,B.style.paddingBottom=te.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let Yt=xe==null?void 0:xe.querySelector(".persona-send-button-tooltip"),Un=(uu=te.tooltipText)!=null?uu:"Start voice recognition";if(((mu=te.showTooltip)!=null?mu:!1)&&Un)if(Yt)Yt.textContent=Un,Yt.style.display="";else{let cn=document.createElement("div");cn.className="persona-send-button-tooltip",cn.textContent=Un,xe==null||xe.insertBefore(cn,B)}else Yt&&(Yt.style.display="none");xe.style.display="",B.disabled=F.isStreaming()}else B&&xe&&(xe.style.display="none",((fu=(gu=r.voiceRecognition)==null?void 0:gu.provider)==null?void 0:fu.type)==="runtype"?F.isVoiceActive()&&F.toggleVoice():Pr&&uo());if(((hu=r.attachments)==null?void 0:hu.enabled)===!0)if(!ft||!ce){let te=(yu=r.attachments)!=null?yu:{},Ut=(xu=((bu=r.sendButton)!=null?bu:{}).size)!=null?xu:"40px";Lt||(Lt=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Lt.style.display="none",Ct.insertBefore(Lt,be)),Je||(Je=document.createElement("input"),Je.type="file",Je.accept=((vu=te.allowedTypes)!=null?vu:Gr).join(","),Je.multiple=((wu=te.maxFiles)!=null?wu:4)>1,Je.style.display="none",Je.setAttribute("aria-label","Attach files"),Ct.insertBefore(Je,be)),ft=y("div","persona-send-button-wrapper"),ce=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ce.type="button",ce.setAttribute("aria-label",(Cu=te.buttonTooltipText)!=null?Cu:"Attach file");let at=(Au=te.buttonIconName)!=null?Au:"paperclip",kt=Ut,ln=parseFloat(kt)||40,bn=Math.round(ln*.6);ce.style.width=kt,ce.style.height=kt,ce.style.minWidth=kt,ce.style.minHeight=kt,ce.style.fontSize="18px",ce.style.lineHeight="1",ce.style.backgroundColor="transparent",ce.style.color="var(--persona-primary, #111827)",ce.style.border="none",ce.style.borderRadius="6px",ce.style.transition="background-color 0.15s ease",ce.addEventListener("mouseenter",()=>{ce.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ce.addEventListener("mouseleave",()=>{ce.style.backgroundColor="transparent"});let mr=ye(at,bn,"currentColor",1.5);mr?ce.appendChild(mr):ce.textContent="\u{1F4CE}",ce.addEventListener("click",Un=>{Un.preventDefault(),Je==null||Je.click()}),ft.appendChild(ce);let En=(Su=te.buttonTooltipText)!=null?Su:"Attach file",Yt=y("div","persona-send-button-tooltip");Yt.textContent=En,ft.appendChild(Yt),Qe.append(ft),!At&&Je&&Lt&&(At=Es.fromConfig(te),At.setPreviewsContainer(Lt),Je.addEventListener("change",async()=>{At&&(Je!=null&&Je.files)&&(await At.handleFileSelect(Je.files),Je.value="")})),Se.querySelector(".persona-attachment-drop-overlay")||Se.appendChild(of(te.dropOverlay))}else{ft.style.display="";let te=(Tu=r.attachments)!=null?Tu:{};Je&&(Je.accept=((Eu=te.allowedTypes)!=null?Eu:Gr).join(","),Je.multiple=((Mu=te.maxFiles)!=null?Mu:4)>1),At&&At.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}else ft&&(ft.style.display="none"),At&&At.clearAttachments(),(ku=Se.querySelector(".persona-attachment-drop-overlay"))==null||ku.remove();let Jt=(Lu=r.sendButton)!=null?Lu:{},jo=(Pu=Jt.useIcon)!=null?Pu:!1,go=(Iu=Jt.iconText)!=null?Iu:"\u2191",fo=Jt.iconName,Vr=(Ru=Jt.tooltipText)!=null?Ru:"Send message",Uo=(Wu=Jt.showTooltip)!=null?Wu:!1,et=(Hu=Jt.size)!=null?Hu:"40px",Nt=Jt.backgroundColor,Bt=Jt.textColor;if(jo){if(pe.style.width=et,pe.style.height=et,pe.style.minWidth=et,pe.style.minHeight=et,pe.style.fontSize="18px",pe.style.lineHeight="1",pe.innerHTML="",Bt?pe.style.color=Bt:pe.style.color="var(--persona-button-primary-fg, #ffffff)",fo){let te=parseFloat(et)||24,Tt=(Bt==null?void 0:Bt.trim())||"currentColor",Ut=ye(fo,te,Tt,2);Ut?pe.appendChild(Ut):pe.textContent=go}else pe.textContent=go;pe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Nt?(pe.style.backgroundColor=Nt,pe.classList.remove("persona-bg-persona-primary")):(pe.style.backgroundColor="",pe.classList.add("persona-bg-persona-primary"))}else pe.textContent=(Du=(Bu=r.copy)==null?void 0:Bu.sendButtonLabel)!=null?Du:"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",Nt?(pe.style.backgroundColor=Nt,pe.classList.remove("persona-bg-persona-accent")):pe.classList.add("persona-bg-persona-accent"),Bt?pe.style.color=Bt:pe.classList.add("persona-text-white");Jt.borderWidth?(pe.style.borderWidth=Jt.borderWidth,pe.style.borderStyle="solid"):(pe.style.borderWidth="",pe.style.borderStyle=""),Jt.borderColor?pe.style.borderColor=Jt.borderColor:pe.style.borderColor="",Jt.paddingX?(pe.style.paddingLeft=Jt.paddingX,pe.style.paddingRight=Jt.paddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),Jt.paddingY?(pe.style.paddingTop=Jt.paddingY,pe.style.paddingBottom=Jt.paddingY):(pe.style.paddingTop="",pe.style.paddingBottom="");let Vt=vn==null?void 0:vn.querySelector(".persona-send-button-tooltip");if(Uo&&Vr)if(Vt)Vt.textContent=Vr,Vt.style.display="";else{let te=document.createElement("div");te.className="persona-send-button-tooltip",te.textContent=Vr,vn==null||vn.insertBefore(te,pe)}else Vt&&(Vt.style.display="none");let $t=($u=(Nu=r.layout)==null?void 0:Nu.contentMaxWidth)!=null?$u:R()?(_u=(Fu=(Ou=r.launcher)==null?void 0:Ou.composerBar)==null?void 0:Fu.contentMaxWidth)!=null?_u:"720px":void 0;$t?(Ze.style.maxWidth=$t,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%",Ct&&(Ct.style.maxWidth=$t,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),qt&&(qt.style.maxWidth=$t,qt.style.marginLeft="auto",qt.style.marginRight="auto")):(Ze.style.maxWidth="",Ze.style.marginLeft="",Ze.style.marginRight="",Ze.style.width="",Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""),qt&&(qt.style.maxWidth="",qt.style.marginLeft="",qt.style.marginRight=""));let mt=(ju=r.statusIndicator)!=null?ju:{},jt=(Uu=mt.visible)!=null?Uu:!0;if(fn.style.display=jt?"":"none",F){let te=F.getStatus();Wt(fn,(Ut=>{var at,kt,ln,bn;return Ut==="idle"?(at=mt.idleText)!=null?at:nn.idle:Ut==="connecting"?(kt=mt.connectingText)!=null?kt:nn.connecting:Ut==="connected"?(ln=mt.connectedText)!=null?ln:nn.connected:Ut==="error"?(bn=mt.errorText)!=null?bn:nn.error:nn[Ut]})(te),mt,te)}fn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let gn=mt.align==="left"?"persona-text-left":mt.align==="center"?"persona-text-center":"persona-text-right";fn.classList.add(gn)},open(){N()&&_t(!0,"api")},close(){N()&&_t(!1,"api")},toggle(){N()&&_t(!O,"api")},reconnect(){F.reconnectNow()},clearChat(){wn=!1,F.clearMessages(),Mr.clear(),co();try{localStorage.removeItem(Bs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Bs}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Bs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),c!=null&&c.clear)try{let m=c.clear();m instanceof Promise&&m.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}p={},L.syncFromMetadata(),V==null||V.clear(),Q==null||Q.reset(),Me==null||Me.update()},setMessage(l){return!be||F.isStreaming()?!1:(!O&&N()&&_t(!0,"system"),be.value=l,be.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(F.isStreaming())return!1;let m=(l==null?void 0:l.trim())||be.value.trim();return m?(!O&&N()&&_t(!0,"system"),be.value="",be.style.height="auto",F.sendMessage(m),!0):!1},startVoiceRecognition(){var m,h;return F.isStreaming()?!1:((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype"?(F.isVoiceActive()||(!O&&N()&&_t(!0,"system"),K.manuallyDeactivated=!1,ct(),F.toggleVoice().then(()=>{K.active=F.isVoiceActive(),rt("user"),F.isVoiceActive()&&ms()})),!0):Pr?!0:Cc()?(!O&&N()&&_t(!0,"system"),K.manuallyDeactivated=!1,ct(),La("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?F.isVoiceActive()?(F.toggleVoice().then(()=>{K.active=!1,K.manuallyDeactivated=!0,ct(),rt("user"),zr()}),!0):!1:Pr?(K.manuallyDeactivated=!0,ct(),uo("user"),!0):!1},injectMessage(l){return!O&&N()&&_t(!0,"system"),F.injectMessage(l)},injectAssistantMessage(l){!O&&N()&&_t(!0,"system");let m=F.injectAssistantMessage(l);return Z&&(Z=!1,Ee&&(clearTimeout(Ee),Ee=null),setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)),m},injectUserMessage(l){return!O&&N()&&_t(!0,"system"),F.injectUserMessage(l)},injectSystemMessage(l){return!O&&N()&&_t(!0,"system"),F.injectSystemMessage(l)},injectMessageBatch(l){return!O&&N()&&_t(!0,"system"),F.injectMessageBatch(l)},injectComponentDirective(l){return!O&&N()&&_t(!0,"system"),F.injectComponentDirective(l)},injectTestMessage(l){!O&&N()&&_t(!0,"system"),F.injectTestEvent(l)},async connectStream(l,m){return F.connectStream(l,m)},__pushEventStreamEvent(l){V&&(Q==null||Q.processEvent(l.type,l.payload),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!ne||!V||Fr()},hideEventStream(){J&&lr()},isEventStreamVisible(){return J},showArtifacts(){rr(r)&&(wn=!1,Sr(),vt==null||vt.setMobileOpen(!0))},hideArtifacts(){rr(r)&&(wn=!0,Sr())},upsertArtifact(l){return rr(r)?(wn=!1,F.upsertArtifact(l)):null},selectArtifact(l){rr(r)&&F.selectArtifact(l)},clearArtifacts(){rr(r)&&F.clearArtifacts()},getArtifacts(){var l;return(l=F==null?void 0:F.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=F==null?void 0:F.getSelectedArtifactId())!=null?l:null},focusInput(){return P&&!O&&!R()||!be?!1:(be.focus(),!0)},async resolveApproval(l,m,h){let A=F.getMessages().find(W=>{var U;return W.variant==="approval"&&((U=W.approval)==null?void 0:U.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);if(A.approval.toolType==="webmcp"){F.resolveWebMcpApproval(A.id,m);return}return F.resolveApproval(A.approval,m,h)},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(l){v(l)},on(l,m){return i.on(l,m)},off(l,m){i.off(l,m)},isOpen(){return N()&&O},isVoiceActive(){return K.active},toggleReadAloud(l){F.toggleReadAloud(l)},stopReadAloud(){F.stopSpeaking()},getReadAloudState(l){return F.getReadAloudState(l)},onReadAloudChange(l){return F.onReadAloudChange(l)},getState(){return{open:N()&&O,launcherEnabled:P,voiceActive:K.active,streaming:F.isStreaming()}},showCSATFeedback(l){!O&&N()&&_t(!0,"system");let m=Ze.querySelector(".persona-feedback-container");m&&m.remove();let h=zl({onSubmit:async(x,A)=>{var W;F.isClientTokenMode()&&await F.submitCSATFeedback(x,A),(W=l==null?void 0:l.onSubmit)==null||W.call(l,x,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!O&&N()&&_t(!0,"system");let m=Ze.querySelector(".persona-feedback-container");m&&m.remove();let h=Vl({onSubmit:async(x,A)=>{var W;F.isClientTokenMode()&&await F.submitNPSFeedback(x,A),(W=l==null?void 0:l.onSubmit)==null||W.call(l,x,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,m){return F.submitCSATFeedback(l,m)},async submitNPSFeedback(l,m){return F.submitNPSFeedback(l,m)},destroy(){No!=null&&(clearInterval(No),No=null),lt.forEach(l=>l()),ge.remove(),it==null||it.remove(),Zt==null||Zt.destroy(),sn==null||sn.remove(),Er&&Ue.removeEventListener("click",Er)}};if((((Id=n==null?void 0:n.debugTools)!=null?Id:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:h=>h?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=m,lt.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",m),lt.push(()=>{window.removeEventListener("persona:focusInput",m)}),ne){let _=ie=>{let oe=ie.detail;(!(oe!=null&&oe.instanceId)||oe.instanceId===l)&&tn.showEventStream()},D=ie=>{let oe=ie.detail;(!(oe!=null&&oe.instanceId)||oe.instanceId===l)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",_),window.addEventListener("persona:hideEventStream",D),lt.push(()=>{window.removeEventListener("persona:showEventStream",_),window.removeEventListener("persona:hideEventStream",D)})}let h=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&tn.showArtifacts()},x=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&tn.hideArtifacts()},A=_=>{let D=_.detail;D!=null&&D.instanceId&&D.instanceId!==l||D!=null&&D.artifact&&tn.upsertArtifact(D.artifact)},W=_=>{let D=_.detail;D!=null&&D.instanceId&&D.instanceId!==l||typeof(D==null?void 0:D.id)=="string"&&tn.selectArtifact(D.id)},U=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",U),lt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",U)})}let Yn=Rw(r.persistState);if(Yn&&N()){let l=Ww(Yn.storage),m=`${Yn.keyPrefix}widget-open`,h=`${Yn.keyPrefix}widget-voice`,x=`${Yn.keyPrefix}widget-voice-mode`;if(l){let A=((Rd=Yn.persist)==null?void 0:Rd.openState)&&l.getItem(m)==="true",W=((Wd=Yn.persist)==null?void 0:Wd.voiceState)&&l.getItem(h)==="true",U=((Hd=Yn.persist)==null?void 0:Hd.voiceState)&&l.getItem(x)==="true";if(A&&setTimeout(()=>{tn.open(),setTimeout(()=>{var _;if(W||U)tn.startVoiceRecognition();else if((_=Yn.persist)!=null&&_.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(Bd=Yn.persist)!=null&&Bd.openState&&(i.on("widget:opened",()=>{l.setItem(m,"true")}),i.on("widget:closed",()=>{l.setItem(m,"false")})),(Dd=Yn.persist)!=null&&Dd.voiceState&&(i.on("voice:state",_=>{l.setItem(h,_.active?"true":"false")}),i.on("user:message",_=>{l.setItem(x,_.viaVoice?"true":"false")})),Yn.clearOnChatClear){let _=()=>{l.removeItem(m),l.removeItem(h),l.removeItem(x)},D=()=>_();window.addEventListener("persona:clear-chat",D),lt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return f&&N()&&setTimeout(()=>{tn.open()},0),ps(),Ma||Gu().then(()=>{F&&(ls++,Mr.clear(),$s(Ze,F.getMessages(),ee))}).catch(()=>{}),tn};var Hw=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(n);return o?Math.max(0,t*parseFloat(o[1])/100):420},Bw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Dw=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Nw=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(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.")},sf=(e,t)=>{var r,o;let n=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!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"},Yl=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=""},af=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Yl(e)},Jl=e=>{e.style.transition=""},Xl=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=""},Ql=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ki=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Ow=(e,t,n,r,o)=>{o?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Fw=(e,t,n,r,o,s)=>{let a=s?t:e;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},lf=(e,t,n,r,o,s,a)=>{var b,v,S,T,L,P;let i=nr(s),d=i.reveal==="push";Ow(e,t,n,r,d),Fw(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.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",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,p=(v=(b=s==null?void 0:s.launcher)==null?void 0:b.mobileFullscreen)!=null?v:!0,u=(T=(S=s==null?void 0:s.launcher)==null?void 0:S.mobileBreakpoint)!=null?T:640,f=c!=null?c.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Xl(t),Jl(r),af(r),Ql(n),ki(o,r),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",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((P=(L=s==null?void 0:s.launcher)==null?void 0:L.zIndex)!=null?P:xn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.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"),af(r),Bw(r,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Xl(t),Jl(r),Ql(n),ki(o,r);let E=i.animate?"transform 180ms ease":"none",k=i.side==="right"?"translateX(100%)":"translateX(-100%)",C=a?"translateX(0)":k;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=E,r.style.transform=C,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Jl(r),Yl(r),ki(o,r);let E=Hw(i.width,e.clientWidth),k=Math.max(0,e.clientWidth),C=i.animate?"margin-left 180ms ease":"none",I=i.side==="right"?a?-E:0:a?0:-E;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=`${k+E}px`,t.style.transition=C,t.style.marginLeft=`${I}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${k}px`,n.style.maxWidth=`${k}px`,n.style.minWidth=`${k}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Xl(t),Yl(r),Ql(n),ki(o,r);let E=i.reveal==="emerge";E?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let k=a?i.width:"0px",C=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",I=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${k}`,r.style.width=k,r.style.maxWidth=k,r.style.minWidth=k,r.style.minHeight="0",Dw(r,i.maxHeight),r.style.overflow=E||I?"hidden":"visible",r.style.transition=C,E&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},_w=(e,t)=>{let n=e.ownerDocument.createElement("div");return sf(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){sf(n,r)},destroy(){n.remove()}}},$w=(e,t)=>{var P,E,k,C;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),c=n.createElement("aside"),p=n.createElement("div"),u=(E=(P=t==null?void 0:t.launcher)==null?void 0:P.enabled)==null||E?(C=(k=t==null?void 0:t.launcher)==null?void 0:k.autoExpand)!=null?C:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},b=()=>{g(),nr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{lf(a,i,d,c,p,t,u)}),f.observe(a))},v=!1,S=()=>{lf(a,i,d,c,p,t,u),b(),u&&!v&&a.dataset.personaDockMobileFullscreen!=="true"&&(v=!0,Nw(a,nr(t)))},T=a.ownerDocument.defaultView,L=()=>{S()};return T==null||T.addEventListener("resize",L),nr(t).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),S(),{mode:"docked",host:p,shell:a,syncWidgetState(I){let j=I.launcherEnabled?I.open:!0;u!==j&&(u=j,S())},updateConfig(I){var j,$;t=I,(($=(j=t==null?void 0:t.launcher)==null?void 0:j.enabled)!=null?$:!0)===!1&&(u=!0),S()},destroy(){T==null||T.removeEventListener("resize",L),g(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Li=(e,t)=>dn(t)?$w(e,t):_w(e,t);var Zl={},jw=e=>{if(typeof window=="undefined"||typeof document=="undefined")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},Uw=()=>{try{if(typeof Zl!="undefined"&&Zl.url)return new URL("../widget.css",Zl.url).href}catch{}return null},cf=(e,t)=>{let n=Uw(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),t.head.appendChild(s)}},df=e=>{var S;let t=jw(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=Li(t,o),a,i=[],d=(T,L)=>{var C,I;let E=!((I=(C=L==null?void 0:L.launcher)==null?void 0:C.enabled)!=null?I:!0)||dn(L),k=r.createElement("div");if(k.setAttribute("data-persona-root","true"),E&&(k.style.height="100%",k.style.display="flex",k.style.flexDirection="column",k.style.flex="1",k.style.minHeight="0"),n){let j=T.attachShadow({mode:"open"});j.appendChild(k),cf(j,r)}else T.appendChild(k),cf(T,r);return t.id&&k.setAttribute("data-persona-instance",t.id),k},c=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(T=>T()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},u=()=>{let T=d(s.host,o);a=Gl(T,o,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(T=>T()),i=[],a.destroy()};u(),(S=e.onChatReady)==null||S.call(e);let g=T=>{f(),s.destroy(),s=Li(t,T),o=T,u()},b={update(T){var I,j,$,R,N,O;let L={...o,...T,launcher:{...(I=o==null?void 0:o.launcher)!=null?I:{},...(j=T==null?void 0:T.launcher)!=null?j:{},dock:{...(R=($=o==null?void 0:o.launcher)==null?void 0:$.dock)!=null?R:{},...(O=(N=T==null?void 0:T.launcher)==null?void 0:N.dock)!=null?O:{}}}},P=dn(o),E=dn(L),k=To(o),C=To(L);if(P!==E||k!==C){g(L);return}o=L,s.updateConfig(o),a.update(T),c()},destroy(){f(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(b,{get(T,L,P){if(L==="host")return s.host;if(L in T)return Reflect.get(T,L,P);let E=a[L];return typeof E=="function"?E.bind(a):E}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var ff=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),qw=new Set(["button","a","input","select","textarea","details","summary"]),zw=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ec=/\b(product|card|item|listing|result)\b/i,nc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Vw=3e3,Kw=100;function hf(e){let t=typeof e.className=="string"?e.className:"";if(ec.test(t)||e.id&&ec.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&ec.test(r.value))return!0}return!1}function yf(e){var t;return nc.test(((t=e.textContent)!=null?t:"").trim())}function bf(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let o=(n=t[r].getAttribute("href"))!=null?n:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function Gw(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function pf(e){let t=e.match(nc);return t?t[0]:null}function uf(e){var r,o,s;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((o=t.textContent)!=null&&o.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(s=n==null?void 0:n.textContent)!=null&&s.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Jw(e){let t=[],n=r=>{let o=r.trim();o&&!t.includes(o)&&t.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;n((o=r.value)!=null?o:"")}),t.slice(0,6)}var Xw="commerce-card",Qw="result-card";function mf(e){return!hf(e)||!yf(e)||!bf(e)&&!Gw(e)?0:5200}function gf(e){var r;return!hf(e)||yf(e)||!bf(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var xf=[{id:Xw,scoreElement(e){return mf(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||nc.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,c,p;if(mf(e)===0)return null;let{title:n,href:r}=uf(e),o=(p=(c=pf(((d=e.textContent)!=null?d:"").trim()))!=null?c:pf(t.text))!=null?p:"",s=Jw(e);return[r&&n?`[${n}](${r})${o?`: ${o}`:""}`:n?`${n}${o?`: ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
112
|
-
`)}},{id:
|
|
113
|
-
`)}}];function
|
|
111
|
+
`}if(!x&&!l){let Nt="max-height: -moz-available !important; max-height: stretch !important;",Bt=m?"":"padding-top: 1.25em !important;",Vt=m?"":`z-index: ${(et=(zo=r.launcher)==null?void 0:zo.zIndex)!=null?et:wn} !important;`;ge.style.cssText+=Nt+Bt+Vt}Xe()};io(),ns(e,r),Ei(e,r),Mi(e,r);let lt=[];lt.push(()=>{document.removeEventListener("keydown",$r)}),lt.push(()=>{ir!==null&&clearTimeout(ir)});let nn=null,rn=null;lt.push(()=>{nn==null||nn(),nn=null,rn==null||rn(),rn=null}),Dn&<.push(()=>{Dn==null||Dn.disconnect(),Dn=null}),lt.push(()=>{Jn==null||Jn(),Jn=null,ls(),Ft&&(Ft.remove(),Ft=null),vt==null||vt.element.style.removeProperty("width"),vt==null||vt.element.style.removeProperty("maxWidth")}),ne&<.push(()=>{le!==null&&(cancelAnimationFrame(le),le=null),Me==null||Me.destroy(),Me=null,V==null||V.destroy(),V=null,fe=null});let Sr=null,$s=()=>{Sr&&(Sr(),Sr=null),r.colorScheme==="auto"&&(Sr=kl(()=>{ns(e,r)}))};$s(),lt.push(()=>{Sr&&(Sr(),Sr=null)}),lt.push(a);let Ur=(Dd=r.features)==null?void 0:Dd.streamAnimation;if(Ur!=null&&Ur.type&&Ur.type!=="none"){let l=Is(Ur.type,Ur.plugins);l&&(ui(l,e),lt.push(()=>kg(e)))}let Do=Qg(qt),Tr=null,_,cs=l=>{var x,C;if(!_)return;let m=l!=null?l:_.getMessages(),h=((C=(x=r.features)==null?void 0:x.suggestReplies)==null?void 0:C.enabled)!==!1?ul(m):null;h?Do.render(h,_,be,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(M=>M.role==="user")?Do.render([],_,be,m):Do.render(r.suggestionChips,_,be,m,r.suggestionChipsConfig)},Xn=!1,Er=xg(),qr=new Map,Mr=new Map,cr=new Map,ds=0,Ia=Go()!==null,bn=ai(),Sn=0,dr=null,Tn=!1,No=!1,pr=0,xn=null,kr=null,ps=!1,Oo=!1,us=null,lo=!0,co=!1,ot=null,w=4,z=24,q=80,G=new Map,K={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ne=(Od=(Nd=r.voiceRecognition)==null?void 0:Nd.autoResume)!=null?Od:!1,rt=l=>{i.emit("voice:state",{active:K.active,source:l,timestamp:Date.now()})},ct=()=>{v(l=>({...l,voiceState:{active:K.active,timestamp:Date.now(),manuallyDeactivated:K.manuallyDeactivated}}))},$i=()=>{var x,C;if(((x=r.voiceRecognition)==null?void 0:x.enabled)===!1)return;let l=tc(p.voiceState),m=!!l.active,h=Number((C=l.timestamp)!=null?C:0);K.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-h<qw&&setTimeout(()=>{var M,$;K.active||(K.manuallyDeactivated=!1,(($=(M=r.voiceRecognition)==null?void 0:M.provider)==null?void 0:$.type)==="runtype"?_.toggleVoice().then(()=>{K.active=_.isVoiceActive(),rt("restore"),_.isVoiceActive()&&hs()}):Ha("restore"))},1e3)},po=()=>_?ff(_.getMessages()).filter(l=>!l.__skipPersist):[],En=null,pn=(l,m)=>{typeof console!="undefined"&&console.error(l,m)},zr=(l,m)=>{let h=()=>{try{let $=l();return!$||typeof $.then!="function"?null:Promise.resolve($).catch(N=>{pn(m,N)})}catch($){return pn(m,$),null}},x=En,C=x?x.then(()=>{var $;return($=h())!=null?$:void 0}):h();if(!C)return;let M=C.finally(()=>{En===M&&(En=null)});En=M};function Lr(l){if(!(c!=null&&c.save))return;let h={messages:l?ff(l):_?po():[],metadata:p,artifacts:Nn.artifacts,selectedArtifactId:Nn.selectedId};zr(()=>c.save(h),"[AgentWidget] Failed to persist state:")}let on=null,Mn=()=>ge.querySelector("#persona-scroll-container")||we,gn=()=>{on!==null&&(cancelAnimationFrame(on),on=null),Tn=!1},mc=()=>{dr!==null&&(cancelAnimationFrame(dr),dr=null),No=!1,gn()},Qf=()=>Xn&&Ui()&&(Ot()!=="anchor-top"||sr()),ji=()=>{let l=xt()||"Jump to latest",m=Qf();zt.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),pr>0?(Hn.textContent=String(pr),Hn.style.display="",zt.setAttribute("aria-label",`${l} (${pr} new)`)):(Hn.textContent="",Hn.style.display="none",zt.setAttribute("aria-label",m?`${l} (response streaming below)`:l))},gc=()=>{pr!==0&&(pr=0,ji())},Ui=()=>Zt()?!bn.isFollowing():!So(we,z),Fn=()=>{if(!Xt()||J){zt.parentNode&&zt.remove(),zt.style.display="none";return}zt.parentNode!==Se&&Se.appendChild(zt),zn();let m=Br(we)>0&&Ui();m?ji():gc(),zt.style.display=m?"":"none"},js=()=>{bn.pause()&&(mc(),Fn())},uo=()=>{bn.resume(),gc(),Fn()},mo=(l=!1)=>{Zt()&&bn.isFollowing()&&(!l&&!Xn||(dr!==null&&(cancelAnimationFrame(dr),dr=null),No=!0,dr=requestAnimationFrame(()=>{dr=null,No=!1,bn.isFollowing()&&Yf(Mn(),l?220:140)})))},fc=(l,m,h,x=()=>!0)=>{let C=l.scrollTop,M=m(),$=M-C;if(gn(),Math.abs($)<1){Tn=!0,l.scrollTop=M,Sn=l.scrollTop,Tn=!1;return}let N=performance.now();Tn=!0;let D=oe=>1-Math.pow(1-oe,3),ie=oe=>{if(!x()){gn();return}let Y=m();Y!==M&&(M=Y,$=M-C);let ve=oe-N,Oe=Math.min(ve/h,1),Fe=D(Oe),je=C+$*Fe;l.scrollTop=je,Sn=l.scrollTop,Oe<1?on=requestAnimationFrame(ie):(l.scrollTop=M,Sn=l.scrollTop,on=null,Tn=!1)};on=requestAnimationFrame(ie)},Yf=(l,m=500)=>{let h=Br(l)-l.scrollTop;if(Math.abs(h)<1){Sn=l.scrollTop;return}if(Math.abs(h)>=q){gn(),Tn=!0,l.scrollTop=Br(l),Sn=l.scrollTop,Tn=!1;return}fc(l,()=>Br(l),m,()=>bn.isFollowing())},hc=()=>{let l=Mn();Tn=!0,l.scrollTop=Br(l),Sn=l.scrollTop,Tn=!1,Fn()},yc=l=>{let m=0,h=l;for(;h&&h!==we;)m+=h.offsetTop,h=h.offsetParent;return m},bc=()=>{var M;if(Nr()!=="last-user-turn")return!1;let l=(M=_==null?void 0:_.getMessages())!=null?M:[];if(l.length<2)return!1;let m=[...l].reverse().find($=>$.role==="user");if(!m)return!1;let h=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(m.id):m.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=we.querySelector(`[data-message-id="${h}"]`);if(!x)return!1;let C=Math.min(Math.max(0,yc(x)-br()),Br(we));return Tn=!0,we.scrollTop=C,Sn=we.scrollTop,Tn=!1,Ot()==="follow"&&!So(we,z)&&bn.pause(),Fn(),!0},xc=l=>{Pn.style.height=`${Math.max(0,Math.round(l))}px`,xn&&(xn.spacerHeight=Math.max(0,l))},Us=()=>{kr!==null&&(cancelAnimationFrame(kr),kr=null),gn(),xn=null,Pn.style.height="0px"},Zf=l=>{kr!==null&&cancelAnimationFrame(kr),kr=requestAnimationFrame(()=>{var D;kr=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=we.querySelector(`[data-message-id="${m}"]`);if(!h)return;let x=yc(h),C=(D=xn==null?void 0:xn.spacerHeight)!=null?D:0,M=we.scrollHeight-C,{targetScrollTop:$,spacerHeight:N}=Sg({anchorOffsetTop:x,topOffset:br(),viewportHeight:we.clientHeight,contentHeight:M});xn={initialSpacerHeight:N,contentHeightAtAnchor:M,spacerHeight:N},xc(N),fc(we,()=>$,220)})},eh=()=>{if(Zt()){if(!bn.isFollowing()||So(we,1))return;mo(!Xn);return}if(xn&&xn.initialSpacerHeight>0){let l=we.scrollHeight-xn.spacerHeight,m=Tg({initialSpacerHeight:xn.initialSpacerHeight,contentHeightAtAnchor:xn.contentHeightAtAnchor,currentContentHeight:l});m!==xn.spacerHeight&&xc(m)}Fn()},th=l=>{let m=Ot();m==="follow"?(uo(),mo(!0)):m==="anchor-top"&&(lo=!1,co=!0,Zf(l))},nh=()=>{if(Ot()==="anchor-top"){if(co){lo=!1;return}lo=!0,Us(),uo(),mo(!0)}},rh=l=>{let m=new Map;l.forEach(h=>{let x=G.get(h.id);m.set(h.id,{streaming:h.streaming,role:h.role}),!x&&h.role==="assistant"&&(i.emit("assistant:message",h),!Oo&&(Ot()!=="anchor-top"||sr())&&Ui()&&(pr+=1,ji(),Fn(),eo(pr===1?"1 new message below.":`${pr} new messages below.`))),h.role==="assistant"&&(x!=null&&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}))}),G.clear(),m.forEach((h,x)=>{G.set(x,h)})},oh=(l,m,h)=>{var st,Be,Re,ze,Xe,bt;let x=document.createElement("div"),M=(()=>{var De;let I=o.find(We=>We.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((De=r.loadingIndicator)!=null&&De.render)return r.loadingIndicator.render})(),$=(I,De)=>De==null?!1:typeof De=="string"?(I.textContent=De,!0):(I.appendChild(De),!0),N=new Set,D=new Set,ie=o.some(I=>I.renderAskUserQuestion),oe=[],Y=[],ve=r.enableComponentStreaming!==!1,Oe=r.approval!==!1,Fe=[];if(m.forEach(I=>{var fn,_n,Ge,It,$n,_o,$o,jo,Uo,bs,xs,Jt,qo,ho,yo,Jr,zo;N.add(I.id);let De=ie&&xo(I),We=Oe&&I.variant==="approval"&&!!I.approval,Ye=!De&&I.role==="assistant"&&!I.variant&&ve&&Ii(I);if(!We&&cr.has(I.id)){let et=l.querySelector(`#wrapper-${I.id}`);et==null||et.removeAttribute("data-preserve-runtime"),cr.delete(I.id)}if(!Ye&&Mr.has(I.id)){let et=l.querySelector(`#wrapper-${I.id}`);et==null||et.removeAttribute("data-preserve-runtime"),Mr.delete(I.id)}let Pt=xo(I)?`:${(fn=I.agentMetadata)!=null&&fn.askUserQuestionAnswered?"a":"u"}:${(_n=I.agentMetadata)!=null&&_n.askUserQuestionAnswers?Object.keys(I.agentMetadata.askUserQuestionAnswers).length:0}`:"",_e=bg(I,ds)+Pt,Kt=De||We||Ye?null:vg(Er,I.id,_e);if(Kt){x.appendChild(Kt.cloneNode(!0)),xo(I)&&((Ge=I.toolCall)!=null&&Ge.id)&&((It=I.agentMetadata)==null?void 0:It.awaitingLocalTool)===!0&&!(($n=I.agentMetadata)!=null&&$n.askUserQuestionAnswered)&&(D.add(I.toolCall.id),sa(I,r,Ve.composerOverlay));return}let wt=null,an=o.find(et=>!!(I.variant==="reasoning"&&et.renderReasoning||I.variant==="tool"&&et.renderToolCall||!I.variant&&et.renderMessage)),Rn=(_o=r.layout)==null?void 0:_o.messages;if(xo(I)&&(($o=I.agentMetadata)==null?void 0:$o.askUserQuestionAnswered)===!0){qr.delete(I.id);let et=l.querySelector(`#wrapper-${I.id}`);et==null||et.removeAttribute("data-preserve-runtime");return}if(qa(I)&&((Uo=(jo=r.features)==null?void 0:jo.suggestReplies)==null?void 0:Uo.enabled)!==!1)return;if(xo(I)&&((xs=(bs=r.features)==null?void 0:bs.askUserQuestion)==null?void 0:xs.enabled)!==!1){let et=o.find(Nt=>typeof Nt.renderAskUserQuestion=="function");if(et&&St.current){let Nt=qr.get(I.id),Bt=Nt!==_e,Vt=null;if(Bt){let{payload:jt,complete:hn}=vo(I),jn=I.id,Ir=()=>{var un;return(un=St.current)==null?void 0:un.getMessages().find(mn=>mn.id===jn)};Vt=et.renderAskUserQuestion({message:I,payload:jt,complete:hn,resolve:un=>{var Zn;let mn=Ir();mn&&((Zn=St.current)==null||Zn.resolveAskUserQuestion(mn,un))},dismiss:()=>{var mn,Zn,bo;let un=Ir();(mn=un==null?void 0:un.agentMetadata)!=null&&mn.awaitingLocalTool&&((Zn=St.current)==null||Zn.markAskUserQuestionResolved(un),(bo=St.current)==null||bo.resolveAskUserQuestion(un,"(dismissed)"))},config:r})}let $t=Nt!=null;if(Bt&&Vt===null&&!$t){((Jt=I.agentMetadata)==null?void 0:Jt.awaitingLocalTool)===!0&&!((qo=I.agentMetadata)!=null&&qo.askUserQuestionAnswered)&&(D.add(I.toolCall.id),sa(I,r,Ve.composerOverlay));return}let mt=document.createElement("div");mt.className="persona-flex",mt.id=`wrapper-${I.id}`,mt.setAttribute("data-wrapper-id",I.id),mt.setAttribute("data-ask-plugin-stub","true"),mt.setAttribute("data-preserve-runtime","true"),x.appendChild(mt),oe.push({messageId:I.id,fingerprint:_e,bubble:Vt});return}else{((ho=I.agentMetadata)==null?void 0:ho.awaitingLocalTool)===!0&&!((yo=I.agentMetadata)!=null&&yo.askUserQuestionAnswered)&&(D.add(I.toolCall.id),sa(I,r,Ve.composerOverlay));return}}else if(We){let et=(Jr=o.find($t=>typeof $t.renderApproval=="function"))!=null?Jr:s,Bt=cr.get(I.id)!==_e,Vt=null;if(Bt&&(et!=null&&et.renderApproval)){let $t=I.id,mt=(jt,hn)=>{var Ir,un,mn;let jn=(Ir=St.current)==null?void 0:Ir.getMessages().find(Zn=>Zn.id===$t);jn!=null&&jn.approval&&(jn.approval.toolType==="webmcp"?(un=St.current)==null||un.resolveWebMcpApproval(jn.id,jt):(mn=St.current)==null||mn.resolveApproval(jn.approval,jt,hn))};Vt=et.renderApproval({message:I,defaultRenderer:()=>Si(I,r),config:r,approve:jt=>mt("approved",jt),deny:jt=>mt("denied",jt)})}if(Bt&&Vt===null){let $t=l.querySelector(`#wrapper-${I.id}`);$t==null||$t.removeAttribute("data-preserve-runtime"),cr.delete(I.id),wt=Si(I,r)}else{let $t=document.createElement("div");$t.className="persona-flex",$t.id=`wrapper-${I.id}`,$t.setAttribute("data-wrapper-id",I.id),$t.setAttribute("data-approval-plugin-stub","true"),$t.setAttribute("data-preserve-runtime","true"),x.appendChild($t),Fe.push({messageId:I.id,fingerprint:_e,bubble:Vt});return}}else if(an)if(I.variant==="reasoning"&&I.reasoning&&an.renderReasoning){if(!Le)return;wt=an.renderReasoning({message:I,defaultRenderer:()=>Fl(I,r),config:r})}else if(I.variant==="tool"&&I.toolCall&&an.renderToolCall){if(!Pe)return;wt=an.renderToolCall({message:I,defaultRenderer:()=>$l(I,r),config:r})}else an.renderMessage&&(wt=an.renderMessage({message:I,defaultRenderer:()=>{let et=Ea(I,h,Rn,r.messageActions,he,{loadingIndicatorRenderer:M,widgetConfig:r});return I.role!=="user"&&Vl(et,I,r,_),et},config:r}));if(!wt&&Ye){let et=Yl(I);if(et){let Nt=Mr.get(I.id),Bt=Nt!==_e,Vt=r.wrapComponentDirectiveInBubble!==!1,$t=null;if(Bt){let mt=Ql(et,{config:r,message:I,transform:h});if(mt)if(Vt){let jt=document.createElement("div");if(jt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),jt.id=`bubble-${I.id}`,jt.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let hn=document.createElement("div");hn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",hn.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),jt.appendChild(hn)}jt.appendChild(mt),$t=jt}else{let jt=document.createElement("div");if(jt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",jt.id=`bubble-${I.id}`,jt.setAttribute("data-message-id",I.id),jt.setAttribute("data-persona-component-directive","true"),I.content&&I.content.trim()){let hn=document.createElement("div");hn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",hn.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),jt.appendChild(hn)}jt.appendChild(mt),$t=jt}}if($t||Nt!=null){let mt=document.createElement("div");mt.className="persona-flex",mt.id=`wrapper-${I.id}`,mt.setAttribute("data-wrapper-id",I.id),mt.setAttribute("data-component-directive-stub","true"),mt.setAttribute("data-preserve-runtime","true"),Vt||mt.classList.add("persona-w-full"),x.appendChild(mt),Y.push({messageId:I.id,fingerprint:_e,bubble:$t});return}}}if(!wt)if(I.variant==="reasoning"&&I.reasoning){if(!Le)return;wt=Fl(I,r)}else if(I.variant==="tool"&&I.toolCall){if(!Pe)return;wt=$l(I,r)}else if(I.variant==="approval"&&I.approval){if(r.approval===!1)return;wt=Si(I,r)}else{let et=(zo=r.layout)==null?void 0:zo.messages;et!=null&&et.renderUserMessage&&I.role==="user"?wt=et.renderUserMessage({message:I,config:r,streaming:!!I.streaming}):et!=null&&et.renderAssistantMessage&&I.role==="assistant"?wt=et.renderAssistantMessage({message:I,config:r,streaming:!!I.streaming}):wt=Ea(I,h,et,r.messageActions,he,{loadingIndicatorRenderer:M,widgetConfig:r}),I.role!=="user"&&wt&&Vl(wt,I,r,_)}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${I.id}`,Ht.setAttribute("data-wrapper-id",I.id),I.role==="user"&&Ht.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&Ht.classList.add("persona-w-full"),Ht.appendChild(wt),wg(Er,I.id,_e,Ht),x.appendChild(Ht)}),Ve.composerOverlay&&Ve.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let We=De.getAttribute("data-persona-ask-sheet-for");We&&!D.has(We)&&Qo(Ve.composerOverlay,We)}),(Be=(st=r.features)==null?void 0:st.toolCallDisplay)!=null&&Be.grouped){let I=[],De=[];m.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&Pe){De.push(We);return}De.length>1&&I.push(De),De=[]}),De.length>1&&I.push(De),I.forEach((We,Ye)=>{var fn,_n;let Pt=We.map(Ge=>Array.from(x.children).find(It=>It instanceof HTMLElement&&It.getAttribute("data-wrapper-id")===Ge.id)).filter(Ge=>!!Ge);if(Pt.length<2)return;let _e=document.createElement("div");_e.className="persona-flex",_e.id=`wrapper-tool-group-${Ye}-${We[0].id}`,_e.setAttribute("data-wrapper-id",`tool-group-${Ye}-${We[0].id}`);let Kt=document.createElement("div");Kt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Kt.setAttribute("data-persona-tool-group","true");let wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let an=`Called ${We.length} tools`,Rn=(_n=(fn=r.toolCall)==null?void 0:fn.renderGroupedSummary)==null?void 0:_n.call(fn,{messages:We,toolCalls:We.map(Ge=>Ge.toolCall).filter(Ge=>!!Ge),defaultSummary:an,config:r});$(wt,Rn)||(wt.textContent=an);let Ht=document.createElement("div");Ht.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(wt,Ht),_e.appendChild(Kt),Pt[0].before(_e),Pt.forEach((Ge,It)=>{let $n=document.createElement("div");$n.className="persona-tool-group-item persona-relative",$n.setAttribute("data-persona-tool-group-item","true"),It<Pt.length-1&&$n.setAttribute("data-persona-tool-group-connector","true"),$n.appendChild(Ge),Ht.appendChild($n)})})}Cg(Er,N);let je=m.some(I=>I.role==="assistant"&&I.streaming),qe=m[m.length-1],ut=(qe==null?void 0:qe.role)==="assistant"&&!qe.streaming&&qe.variant!=="approval";if(Xn&&m.some(I=>I.role==="user")&&!je&&!ut){let I={config:r,streaming:!0,location:"standalone",defaultRenderer:Ws},De=o.find(Ye=>Ye.renderLoadingIndicator),We=null;if(De!=null&&De.renderLoadingIndicator&&(We=De.renderLoadingIndicator(I)),We===null&&((Re=r.loadingIndicator)!=null&&Re.render)&&(We=r.loadingIndicator.render(I)),We===null&&(We=Ws()),We){let Ye=document.createElement("div"),Pt=((ze=r.loadingIndicator)==null?void 0:ze.showBubble)!==!1;Ye.className=Pt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ye.setAttribute("data-typing-indicator","true"),Ye.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ye.appendChild(We);let _e=document.createElement("div");_e.className="persona-flex",_e.id="wrapper-typing-indicator",_e.setAttribute("data-wrapper-id","typing-indicator"),_e.appendChild(Ye),x.appendChild(_e)}}if(!Xn&&m.length>0){let I=m[m.length-1],De={config:r,lastMessage:I,messageCount:m.length},We=o.find(Pt=>Pt.renderIdleIndicator),Ye=null;if(We!=null&&We.renderIdleIndicator&&(Ye=We.renderIdleIndicator(De)),Ye===null&&((Xe=r.loadingIndicator)!=null&&Xe.renderIdle)&&(Ye=r.loadingIndicator.renderIdle(De)),Ye){let Pt=document.createElement("div"),_e=((bt=r.loadingIndicator)==null?void 0:bt.showBubble)!==!1;Pt.className=_e?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Pt.setAttribute("data-idle-indicator","true"),Pt.appendChild(Ye);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-idle-indicator",Kt.setAttribute("data-wrapper-id","idle-indicator"),Kt.appendChild(Pt),x.appendChild(Kt)}}if(oi(l,x),oe.length>0)for(let{messageId:I,fingerprint:De,bubble:We}of oe){let Ye=l.querySelector(`#wrapper-${I}`);Ye&&We!==null&&(Ye.replaceChildren(We),Ye.setAttribute("data-bubble-fp",De),qr.set(I,De))}if(qr.size>0)for(let I of qr.keys())N.has(I)||qr.delete(I);if(Y.length>0)for(let{messageId:I,fingerprint:De,bubble:We}of Y){let Ye=l.querySelector(`#wrapper-${I}`);Ye&&We!==null&&(Ye.replaceChildren(We),Ye.setAttribute("data-bubble-fp",De),Mr.set(I,De))}if(Mr.size>0)for(let I of Mr.keys())N.has(I)||Mr.delete(I);if(Fe.length>0)for(let{messageId:I,fingerprint:De,bubble:We}of Fe){let Ye=l.querySelector(`#wrapper-${I}`);Ye&&We!==null&&(Ye.replaceChildren(We),Ye.setAttribute("data-bubble-fp",De),cr.set(I,De))}if(cr.size>0)for(let I of cr.keys())N.has(I)||cr.delete(I)},qs=(l,m,h)=>{oh(l,m,h),so()},zs=null,sh=()=>{var h;if(zs)return;let l=x=>{let C=x.composedPath();C.includes(ge)||it&&C.includes(it)||_t(!1,"user")};zs=l,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},vc=()=>{var m;if(!zs)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",zs,!0),zs=null};lt.push(()=>vc());let Vs=null,ah=()=>{var h;if(Vs)return;let l=x=>{x.key==="Escape"&&(x.isComposing||_t(!1,"user"))};Vs=l,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},wc=()=>{var m;if(!Vs)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",Vs,!0),Vs=null};lt.push(()=>wc());let Ks=!1,Cc=new Set,ih=()=>{var m,h,x,C;let l=(x=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.peek)==null?void 0:x.streamAnimation;return l||((C=r.features)==null?void 0:C.streamAnimation)},ms=()=>{var ut,st,Be,Re;if(!k())return;let l=Ve.peekBanner,m=Ve.peekTextNode;if(!l||!m)return;if(F){l.classList.remove("persona-pill-peek--visible");return}let h=(ut=_==null?void 0:_.getMessages())!=null?ut:[],x;for(let ze=h.length-1;ze>=0;ze--){let Xe=h[ze];if(Xe.role==="assistant"&&Xe.content){x=Xe;break}}if(!x){l.classList.remove("persona-pill-peek--visible");return}let C=x.content,M=!!x.streaming,$=ih(),N=ci($),D=N.type!=="none"?Is(N.type,$==null?void 0:$.plugins):null,ie=((st=D==null?void 0:D.isAnimating)==null?void 0:st.call(D,x))===!0,oe=D!==null&&(M||ie);oe&&D&&!Cc.has(D.name)&&(ui(D,e),Cc.add(D.name));let Y=oe&&(D!=null&&D.containerClass)?D.containerClass:null,ve=(Be=m.dataset.personaPeekStreamClass)!=null?Be:null;ve&&ve!==Y&&(m.classList.remove(ve),delete m.dataset.personaPeekStreamClass),Y&&ve!==Y&&(m.classList.add(Y),m.dataset.personaPeekStreamClass=Y),oe?(m.style.setProperty("--persona-stream-step",`${N.speed}ms`),m.style.setProperty("--persona-stream-duration",`${N.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let Oe=oe?di(C,N.buffer,D,x,M):C;if(oe&&N.placeholder==="skeleton"&&M&&(!Oe||!Oe.trim())){let ze=document.createElement("div"),Xe=wa();Xe.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Xe),oi(m,ze)}else{let ze=Math.max(0,Oe.length-100),Xe=Oe.length>100?Oe.slice(-100):Oe,bt=Xr(Xe);if(!oe||!D){let I=Oe.length>100?`\u2026${Xe}`:Xe;m.textContent!==I&&(m.textContent=I)}else{let I=bt;(D.wrap==="char"||D.wrap==="word")&&(I=va(bt,D.wrap,`peek-${x.id}`,{skipTags:D.skipTags,startIndex:ze}));let De=document.createElement("div");if(De.innerHTML=I,D.useCaret&&Xe.length>0){let We=pi(),Ye=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),Pt=Ye[Ye.length-1];Pt!=null&&Pt.parentNode?Pt.parentNode.insertBefore(We,Pt.nextSibling):De.appendChild(We)}oi(m,De),(Re=D.onAfterRender)==null||Re.call(D,{container:m,bubble:l,messageId:x.id,message:x,speed:N.speed,duration:N.duration})}}let qe=Xn||Ks;l.classList.toggle("persona-pill-peek--visible",qe)};if(k()){let l=Ve.peekBanner;if(l){let x=C=>{C.preventDefault(),C.stopPropagation(),_t(!0,"user")};l.addEventListener("pointerdown",x),lt.push(()=>{l.removeEventListener("pointerdown",x)})}let m=()=>{Ks||(Ks=!0,ms())},h=()=>{Ks&&(Ks=!1,ms())};X.addEventListener("pointerenter",m),X.addEventListener("pointerleave",h),lt.push(()=>{X.removeEventListener("pointerenter",m),X.removeEventListener("pointerleave",h)}),it&&(it.addEventListener("pointerenter",m),it.addEventListener("pointerleave",h),lt.push(()=>{it.removeEventListener("pointerenter",m),it.removeEventListener("pointerleave",h)}))}let lh=l=>{var ve,Oe,Fe,je,qe,ut,st,Be;let m=(Oe=(ve=r.launcher)==null?void 0:ve.composerBar)!=null?Oe:{},h=(Fe=m.expandedSize)!=null?Fe:"anchored",x=(je=m.bottomOffset)!=null?je:"16px",C=m.collapsedMaxWidth,M=(qe=m.expandedMaxWidth)!=null?qe:"880px",$=(ut=m.expandedTopOffset)!=null?ut:"5vh",N=(st=m.modalMaxWidth)!=null?st:"880px",D=(Be=m.modalMaxHeight)!=null?Be:"min(90vh, 800px)",ie="calc(100vw - 32px)",oe="var(--persona-pill-area-height, 80px)",Y=ge.style;if(Y.left="",Y.right="",Y.top="",Y.bottom="",Y.transform="",Y.width="",Y.maxWidth="",Y.height="",Y.maxHeight="",it){let Re=it.style;Re.bottom=x,Re.width=C!=null?C:""}if(l&&h!=="fullscreen"){if(h==="modal"){Y.top="50%",Y.left="50%",Y.transform="translate(-50%, -50%)",Y.bottom="auto",Y.right="auto",Y.width=N,Y.maxWidth=ie,Y.maxHeight=D,Y.height=D;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${x} + ${oe})`,Y.top=$,Y.width=M,Y.maxWidth=ie}},Gs=()=>{var D,ie,oe,Y,ve,Oe,Fe,je;if(!O())return;if(k()){let ut=(oe=((ie=(D=r.launcher)==null?void 0:D.composerBar)!=null?ie:{}).expandedSize)!=null?oe:"anchored",st=F?"expanded":"collapsed";ge.dataset.state=st,ge.dataset.expandedSize=ut,it&&(it.dataset.state=st,it.dataset.expandedSize=ut),ge.style.removeProperty("display"),ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),lh(F),Se.style.display=F?"flex":"none",io(),F?(sh(),ah()):(vc(),wc()),ms();return}let l=dn(r),m=(Y=e.ownerDocument.defaultView)!=null?Y:window,h=(Oe=(ve=r.launcher)==null?void 0:ve.mobileBreakpoint)!=null?Oe:640,x=(je=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?je:!0,C=m.innerWidth<=h,M=x&&C&&W,$=nr(r).reveal;F?(ge.style.removeProperty("display"),ge.style.display=l?"flex":"",ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0"),X.classList.add("persona-scale-100","persona-opacity-100"),Yt?Yt.element.style.display="none":sn&&(sn.style.display="none")):(l?l&&($==="overlay"||$==="push")&&!M?(ge.style.removeProperty("display"),ge.style.display="flex",ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ge.style.setProperty("display","none","important"),ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ge.style.display="",ge.classList.add("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100"),X.classList.add("persona-scale-95","persona-opacity-0")),Yt?Yt.element.style.display=l?"none":"":sn&&(sn.style.display=l?"none":""))},_t=(l,m="user")=>{var M,$;if(!O()||F===l)return;let h=F;F=l,Gs();let x=(()=>{var Fe,je,qe,ut,st,Be,Re,ze,Xe,bt;let N=(je=(Fe=r.launcher)==null?void 0:Fe.sidebarMode)!=null?je:!1,D=(qe=e.ownerDocument.defaultView)!=null?qe:window,ie=(st=(ut=r.launcher)==null?void 0:ut.mobileFullscreen)!=null?st:!0,oe=(Re=(Be=r.launcher)==null?void 0:Be.mobileBreakpoint)!=null?Re:640,Y=D.innerWidth<=oe,ve=dn(r)&&ie&&Y,Oe=k()&&((bt=(Xe=(ze=r.launcher)==null?void 0:ze.composerBar)==null?void 0:Xe.expandedSize)!=null?bt:"fullscreen")==="fullscreen";return N||ie&&Y&&W||ve||Oe})();if(F&&x){if(!nn){let N=e.getRootNode(),D=N instanceof ShadowRoot?N.host:e.closest(".persona-host");D&&(nn=Il(D,($=(M=r.launcher)==null?void 0:M.zIndex)!=null?$:wn))}rn||(rn=Rl(e.ownerDocument))}else F||(nn==null||nn(),nn=null,rn==null||rn(),rn=null);F&&(Js(),bc()||(Ot()==="follow"?mo(!0):hc()));let C={open:F,source:m,timestamp:Date.now()};F&&!h?i.emit("widget:opened",C):!F&&h&&i.emit("widget:closed",C),i.emit("widget:state",{open:F,launcherEnabled:W,voiceActive:K.active,streaming:_.isStreaming()})},qi=l=>{me(l?"stop":"send"),B&&(B.disabled=l),Do.buttons.forEach(m=>{m.disabled=l}),He.dataset.personaComposerStreaming=l?"true":"false",He.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},zi=()=>{K.active||be&&be.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>zi(),200)});let Ac=()=>{var h,x,C,M,$,N,D,ie,oe,Y,ve;hr.textContent=(x=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?x:"Hello \u{1F44B}",yr.textContent=(M=(C=r.copy)==null?void 0:C.welcomeSubtitle)!=null?M:"Ask anything about your account or products.",be.placeholder=(N=($=r.copy)==null?void 0:$.inputPlaceholder)!=null?N:"How can I help...";let l=we.querySelector("[data-persona-intro-card]");if(l){let Oe=((D=r.copy)==null?void 0:D.showWelcomeCard)!==!1;l.style.display=Oe?"":"none",Oe?(we.classList.remove("persona-gap-3"),we.classList.add("persona-gap-6")):(we.classList.remove("persona-gap-6"),we.classList.add("persona-gap-3"))}!((oe=(ie=r.sendButton)==null?void 0:ie.useIcon)!=null&&oe)&&!(_!=null&&_.isStreaming())&&(pe.textContent=(ve=(Y=r.copy)==null?void 0:Y.sendButtonLabel)!=null?ve:"Send"),be.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',be.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=p.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{v(m=>({...m,sessionId:l}))}});let Fo=null,ch=()=>{Fo==null&&(Fo=setInterval(()=>{let l=Ze.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Fo),Fo=null;return}let m=Date.now();l.forEach(h=>{let x=Number(h.getAttribute("data-tool-elapsed"));x&&(h.textContent=Va(m-x))})},100))},Vi=(l,m)=>{if(Object.is(l,m))return!0;if(l===null||m===null||typeof l!="object"||typeof m!="object")return!1;if(Array.isArray(l)||Array.isArray(m))return!Array.isArray(l)||!Array.isArray(m)||l.length!==m.length?!1:l.every(($,N)=>Vi($,m[N]));let h=l,x=m,C=Object.keys(h),M=Object.keys(x);return C.length===M.length&&C.every($=>Object.prototype.hasOwnProperty.call(x,$)&&Vi(h[$],x[$]))},Sc=l=>{let{content:m,rawContent:h,llmContent:x,...C}=l;return C},Ki=l=>l.role==="assistant"&&l.streaming===!0&&!l.variant&&!l.toolCall&&!l.tools&&!l.approval&&!l.reasoning&&!l.contentParts&&!l.stopReason&&!Ii(l),dh=(l,m,h)=>{if(l.length!==m.length)return!1;let x=l[h.index],C=m[h.index];return!x||!C||x.id!==h.id||C.id!==h.id?!1:(!Object.is(x.content,C.content)||!Object.is(x.rawContent,C.rawContent)||!Object.is(x.llmContent,C.llmContent))&&Ki(x)&&Ki(C)&&Vi(Sc(x),Sc(C))},Tc=null,gs=null,Vr=null,Kr=null,Ra=l=>{var C,M;Tc=l;let m,h;gs=null;for(let $=l.length-1;$>=0;$-=1){let N=l[$];if(!m&&N.role==="user"&&(m=N),!h&&N.role==="assistant"&&(h=N),!gs&&Ki(N)&&(gs={index:$,id:N.id}),m&&h&&gs)break}qs(Ze,l,ee),ch(),cs(l),mo(!Xn),rh(l),l.length===0&&(Us(),lo=!0,co=!1),!ps||Oo?(ps=!0,us=(C=m==null?void 0:m.id)!=null?C:null,ot=(M=h==null?void 0:h.id)!=null?M:null):m&&m.id!==us?(us=m.id,th(m.id)):h&&h.id!==ot&&nh(),h&&(ot=h.id);let x=K.lastUserMessageId;m&&m.id!==x&&(K.lastUserMessageId=m.id,i.emit("user:message",m)),K.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Lr(l),ms()},Gi=()=>{Kr!==null&&(cancelAnimationFrame(Kr),Kr=null);let l=Vr;Vr=null,l&&Ra(l)},Ec=()=>{Kr!==null&&cancelAnimationFrame(Kr),Kr=null,Vr=null},ph=l=>{let m=Vr!=null?Vr:Tc;if(Xn&&m&&gs&&dh(m,l,gs)){Vr=l,Kr===null&&(Kr=requestAnimationFrame(()=>{Kr=null;let h=Vr;Vr=null,h&&Ra(h)}));return}if(l.length===0){Ec(),Ra(l);return}Gi(),Ra(l)};_=new ga(r,{onMessagesChanged(l){ph(l)},onStatusChanged(l){var x;let m=(x=r.statusIndicator)!=null?x:{};Wt(yn,(C=>{var M,$,N,D,ie,oe;return C==="idle"?(M=m.idleText)!=null?M:tn.idle:C==="connecting"?($=m.connectingText)!=null?$:tn.connecting:C==="connected"?(N=m.connectedText)!=null?N:tn.connected:C==="error"?(D=m.errorText)!=null?D:tn.error:C==="paused"?(ie=m.pausedText)!=null?ie:tn.paused:C==="resuming"?(oe=m.resumingText)!=null?oe:tn.resuming:tn[C]})(l),m,l)},onStreamingChanged(l){l||((_==null?void 0:_.getMessages().length)===0?Ec():Gi()),Xn=l,qi(l),_&&qs(Ze,_.getMessages(),ee),l||mo(!0),Fn(),eo(l?"Responding\u2026":"Response complete."),ms()},onVoiceStatusChanged(l){var m,h;if(i.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":Gr(),hs();break;case"processing":Gr(),hh();break;case"speaking":Gr(),yh();break;default:l==="idle"&&_.isBargeInActive()?(Gr(),hs(),B==null||B.setAttribute("aria-label","End voice session")):(K.active=!1,Gr(),rt("system"),ct());break}},onArtifactsState(l){Nn=l,Ar(),Lr()},onReconnect(l){var x;let{executionId:m,lastEventId:h}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:m,after:h}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:m,after:h,attempt:(x=l.attempt)!=null?x:1}):i.emit("stream:resumed",{executionId:m,after:h})}}),St.current=_,lt.push(()=>_.cancel());let Ji=null;if(_.onReadAloudChange((l,m)=>{var C;ro=l,oo=m,so();let h=l!=null?l:Ji;l&&(Ji=l);let x=h&&(C=_.getMessages().find(M=>M.id===h))!=null?C:null;i.emit("message:read-aloud",{messageId:h,message:x,state:m,timestamp:Date.now()}),m==="idle"&&(Ji=null)}),ps=!0,((_d=(Fd=r.voiceRecognition)==null?void 0:Fd.provider)==null?void 0:_d.type)==="runtype")try{_.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&_.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(V||r.onSSEEvent)&&_.setSSEEventCallback((l,m)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,m),Q==null||Q.processEvent(l,m),V==null||V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})});let Mc=()=>{r.resume&&typeof r.reconnectStream=="function"&&_.resumeFromHandle(r.resume)};u?u.then(l=>{var m,h,x;if(l){if(l.metadata&&(p=tc(l.metadata),L.syncFromMetadata()),(m=l.messages)!=null&&m.length){Oo=!0;try{_.hydrateMessages(l.messages)}finally{Oo=!1}}(h=l.artifacts)!=null&&h.length&&_.hydrateArtifacts(l.artifacts,(x=l.selectedArtifactId)!=null?x:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>Mc()):Mc();let kc=()=>{var m,h,x;!k()||F||!((x=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.expandOnSubmit)==null||x)||_t(!0,"auto")},Lc=l=>{var C;if(l.preventDefault(),_.isStreaming()){_.cancel(),Q==null||Q.reset(),Me==null||Me.update();return}let m=be.value.trim(),h=(C=At==null?void 0:At.hasAttachments())!=null?C:!1;if(!m&&!h)return;kc();let x;h&&(x=[],x.push(...At.getContentParts()),m&&x.push(Qa(m))),be.value="",be.style.height="auto",Wa(),_.sendMessage(m,{contentParts:x}),h&&At.clearAttachments()},uh=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},Xi={...si},Qi=!1,Wa=()=>{Xi={...si}},mh=()=>_.getMessages().filter(l=>l.role==="user").map(l=>{var m;return(m=l.content)!=null?m:""}).filter(l=>l.length>0),gh=l=>{if(!be)return;Qi=!0,be.value=l,be.dispatchEvent(new Event("input",{bubbles:!0})),Qi=!1;let m=be.value.length;be.setSelectionRange(m,m)},Pc=()=>{Qi||Wa()},Ic=l=>{if(be){if(uh()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let m=be.selectionStart===0&&be.selectionEnd===0,h=yg({direction:l.key==="ArrowUp"?"up":"down",history:mh(),currentValue:be.value,atStart:m,state:Xi});if(Xi=h.state,h.handled){l.preventDefault(),h.value!==void 0&&gh(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(_.isStreaming()){l.preventDefault();return}Wa(),l.preventDefault(),pe.click()}}},Rc=l=>{l.key!=="Escape"||l.isComposing||_.isStreaming()&&l.composedPath().includes(Se)&&(_.cancel(),Q==null||Q.reset(),Me==null||Me.update(),Wa(),l.preventDefault(),l.stopImmediatePropagation())},Wc=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!At)return;let m=Vw(l.clipboardData);m.length!==0&&(l.preventDefault(),await At.handleFiles(m))},Qn=null,Pr=!1,fs=null,pt=null,Hc=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Ha=(l="user")=>{var M,$,N,D,ie,oe,Y;if(Pr||_.isStreaming())return;let m=Hc();if(!m)return;Qn=new m;let x=($=((M=r.voiceRecognition)!=null?M:{}).pauseDuration)!=null?$:2e3;Qn.continuous=!0,Qn.interimResults=!0,Qn.lang="en-US";let C=be.value;Qn.onresult=ve=>{let Oe="",Fe="";for(let qe=0;qe<ve.results.length;qe++){let ut=ve.results[qe],st=ut[0].transcript;ut.isFinal?Oe+=st+" ":Fe=st}let je=C+Oe+Fe;be.value=je,fs&&clearTimeout(fs),(Oe||Fe)&&(fs=window.setTimeout(()=>{let qe=be.value.trim();qe&&Qn&&Pr&&(go(),be.value="",be.style.height="auto",_.sendMessage(qe,{viaVoice:!0}))},x))},Qn.onerror=ve=>{ve.error!=="no-speech"&&go()},Qn.onend=()=>{if(Pr){let ve=be.value.trim();ve&&ve!==C.trim()&&(be.value="",be.style.height="auto",_.sendMessage(ve,{viaVoice:!0})),go()}};try{if(Qn.start(),Pr=!0,K.active=!0,l!=="system"&&(K.manuallyDeactivated=!1),rt(l),ct(),B){let ve=(N=r.voiceRecognition)!=null?N:{};pt={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(D=ve.iconName)!=null?D:"mic",iconSize:parseFloat((Y=(oe=ve.iconSize)!=null?oe:(ie=r.sendButton)==null?void 0:ie.size)!=null?Y:"40")||24};let Oe=ve.recordingBackgroundColor,Fe=ve.recordingIconColor,je=ve.recordingBorderColor;if(B.classList.add("persona-voice-recording"),B.style.backgroundColor=Oe!=null?Oe:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=Fe!=null?Fe:"var(--persona-voice-recording-indicator, #ffffff)",Fe){let qe=B.querySelector("svg");qe&&qe.setAttribute("stroke",Fe)}je&&(B.style.borderColor=je),B.setAttribute("aria-label","Stop voice recognition")}}catch{go("system")}},go=(l="user")=>{if(Pr){if(Pr=!1,fs&&(clearTimeout(fs),fs=null),Qn){try{Qn.stop()}catch{}Qn=null}if(K.active=!1,rt(l),ct(),B){if(B.classList.remove("persona-voice-recording"),pt){B.style.backgroundColor=pt.backgroundColor,B.style.color=pt.color,B.style.borderColor=pt.borderColor;let m=B.querySelector("svg");m&&m.setAttribute("stroke",pt.color||"currentColor"),pt=null}B.setAttribute("aria-label","Start voice recognition")}}},fh=(l,m)=>{var st,Be,Re,ze,Xe,bt,I,De,We;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),x=((st=l==null?void 0:l.provider)==null?void 0:st.type)==="runtype",C=((Be=l==null?void 0:l.provider)==null?void 0:Be.type)==="custom";if(!(h||x||C))return null;let $=b("div","persona-send-button-wrapper"),N=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button",N.setAttribute("aria-label","Start voice recognition");let D=(Re=l==null?void 0:l.iconName)!=null?Re:"mic",ie=(ze=m==null?void 0:m.size)!=null?ze:"40px",oe=(Xe=l==null?void 0:l.iconSize)!=null?Xe:ie,Y=parseFloat(oe)||24,ve=(bt=l==null?void 0:l.backgroundColor)!=null?bt:m==null?void 0:m.backgroundColor,Oe=(I=l==null?void 0:l.iconColor)!=null?I:m==null?void 0:m.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",Oe?N.style.color=Oe:N.style.color="var(--persona-text, #111827)";let je=ye(D,Y,Oe||"currentColor",1.5);je?N.appendChild(je):N.textContent="\u{1F3A4}",ve?N.style.backgroundColor=ve:N.style.backgroundColor="",l!=null&&l.borderWidth&&(N.style.borderWidth=l.borderWidth,N.style.borderStyle="solid"),l!=null&&l.borderColor&&(N.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(N.style.paddingLeft=l.paddingX,N.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(N.style.paddingTop=l.paddingY,N.style.paddingBottom=l.paddingY),$.appendChild(N);let qe=(De=l==null?void 0:l.tooltipText)!=null?De:"Start voice recognition";if(((We=l==null?void 0:l.showTooltip)!=null?We:!1)&&qe){let Ye=b("div","persona-send-button-tooltip");Ye.textContent=qe,$.appendChild(Ye)}return{micButton:N,micButtonWrapper:$}},Yi=()=>{var m,h,x,C,M;if(!B||pt)return;let l=(m=r.voiceRecognition)!=null?m:{};pt={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((M=(C=l.iconSize)!=null?C:(x=r.sendButton)==null?void 0:x.size)!=null?M:"40")||24}},Zi=(l,m)=>{var M,$,N,D,ie;if(!B)return;let h=B.querySelector("svg");h&&h.remove();let x=(ie=pt==null?void 0:pt.iconSize)!=null?ie:parseFloat((D=(N=(M=r.voiceRecognition)==null?void 0:M.iconSize)!=null?N:($=r.sendButton)==null?void 0:$.size)!=null?D:"40")||24,C=ye(l,x,m,1.5);C&&B.appendChild(C)},Ba=()=>{B&&B.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},hs=()=>{var C;if(!B)return;Yi();let l=(C=r.voiceRecognition)!=null?C:{},m=l.recordingBackgroundColor,h=l.recordingIconColor,x=l.recordingBorderColor;if(Ba(),B.classList.add("persona-voice-recording"),B.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let M=B.querySelector("svg");M&&M.setAttribute("stroke",h)}x&&(B.style.borderColor=x),B.setAttribute("aria-label","Stop voice recognition")},hh=()=>{var N,D,ie,oe,Y,ve,Oe,Fe;if(!B)return;Yi();let l=(N=r.voiceRecognition)!=null?N:{},m=_.getVoiceInterruptionMode(),h=(D=l.processingIconName)!=null?D:"loader",x=(oe=(ie=l.processingIconColor)!=null?ie:pt==null?void 0:pt.color)!=null?oe:"",C=(ve=(Y=l.processingBackgroundColor)!=null?Y:pt==null?void 0:pt.backgroundColor)!=null?ve:"",M=(Fe=(Oe=l.processingBorderColor)!=null?Oe:pt==null?void 0:pt.borderColor)!=null?Fe:"";Ba(),B.classList.add("persona-voice-processing"),B.style.backgroundColor=C,B.style.borderColor=M;let $=x||"currentColor";B.style.color=$,Zi(h,$),B.setAttribute("aria-label","Processing voice input"),m==="none"&&(B.style.cursor="default")},yh=()=>{var ie,oe,Y,ve,Oe,Fe,je,qe,ut,st,Be,Re;if(!B)return;Yi();let l=(ie=r.voiceRecognition)!=null?ie:{},m=_.getVoiceInterruptionMode(),h=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",x=(oe=l.speakingIconName)!=null?oe:h,C=(Fe=l.speakingIconColor)!=null?Fe:m==="barge-in"?(ve=(Y=l.recordingIconColor)!=null?Y:pt==null?void 0:pt.color)!=null?ve:"":(Oe=pt==null?void 0:pt.color)!=null?Oe:"",M=(ut=l.speakingBackgroundColor)!=null?ut:m==="barge-in"?(je=l.recordingBackgroundColor)!=null?je:"var(--persona-voice-recording-bg, #ef4444)":(qe=pt==null?void 0:pt.backgroundColor)!=null?qe:"",$=(Re=l.speakingBorderColor)!=null?Re:m==="barge-in"?(st=l.recordingBorderColor)!=null?st:"":(Be=pt==null?void 0:pt.borderColor)!=null?Be:"";Ba(),B.classList.add("persona-voice-speaking"),B.style.backgroundColor=M,B.style.borderColor=$;let N=C||"currentColor";B.style.color=N,Zi(x,N);let D=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";B.setAttribute("aria-label",D),m==="none"&&(B.style.cursor="default"),m==="barge-in"&&B.classList.add("persona-voice-recording")},Gr=()=>{var l,m,h;B&&(Ba(),pt&&(B.style.backgroundColor=(l=pt.backgroundColor)!=null?l:"",B.style.color=(m=pt.color)!=null?m:"",B.style.borderColor=(h=pt.borderColor)!=null?h:"",Zi(pt.iconName,pt.color||"currentColor"),pt=null),B.style.cursor="",B.setAttribute("aria-label","Start voice recognition"))},Da=()=>{var l,m;if(((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let h=_.getVoiceStatus(),x=_.getVoiceInterruptionMode();if(x==="none"&&(h==="processing"||h==="speaking"))return;if(x==="cancel"&&(h==="processing"||h==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{K.active=!1,K.manuallyDeactivated=!0,ct(),rt("user"),Gr()});return}_.toggleVoice().then(()=>{K.active=_.isVoiceActive(),K.manuallyDeactivated=!_.isVoiceActive(),ct(),rt("user"),_.isVoiceActive()?hs():Gr()});return}if(Pr){let h=be.value.trim();K.manuallyDeactivated=!0,ct(),go("user"),h&&(be.value="",be.style.height="auto",_.sendMessage(h))}else K.manuallyDeactivated=!1,ct(),Ha("user")};vr=Da,B&&(B.addEventListener("click",Da),lt.push(()=>{var l,m;((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),Gr()):go("system"),B&&B.removeEventListener("click",Da)}));let bh=i.on("assistant:complete",()=>{Ne&&(K.active||K.manuallyDeactivated||Ne==="assistant"&&!K.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!K.active&&!K.manuallyDeactivated&&(((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?_.toggleVoice().then(()=>{K.active=_.isVoiceActive(),rt("auto"),_.isVoiceActive()&&hs()}):Ha("auto"))},600))});lt.push(bh);let xh=i.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});lt.push(xh);let Bc=()=>{_t(!F,"user")},Yt=null,sn=null;if(W&&!k()){let{instance:l,element:m}=Dl({config:r,plugins:o,onToggle:Bc});Yt=l,l||(sn=m)}Yt?e.appendChild(Yt.element):sn&&e.appendChild(sn),Gs(),cs(),Ac(),qi(_.isStreaming()),bc()||(Ot()==="follow"?mo(!0):hc()),$i(),P&&(!W||k()?setTimeout(()=>zi(),0):F&&setTimeout(()=>zi(),200));let Js=()=>{var D,ie,oe,Y,ve,Oe,Fe,je,qe,ut,st,Be,Re,ze,Xe,bt,I,De,We,Ye,Pt,_e;if(k()){zn(),Gs();return}let l=dn(r),m=(ie=(D=r.launcher)==null?void 0:D.sidebarMode)!=null?ie:!1,h=l||m||((Y=(oe=r.launcher)==null?void 0:oe.fullHeight)!=null?Y:!1),x=(ve=e.ownerDocument.defaultView)!=null?ve:window,C=(Fe=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?Fe:!0,M=(qe=(je=r.launcher)==null?void 0:je.mobileBreakpoint)!=null?qe:640,$=x.innerWidth<=M,N=C&&$&&W;try{if(N){io(),ns(e,r);return}if(j&&(j=!1,io(),ns(e,r)),!W&&!l){X.style.height="",X.style.width="";return}if(!m&&!l){let Kt=(st=(ut=r==null?void 0:r.launcher)==null?void 0:ut.width)!=null?st:r==null?void 0:r.launcherWidth,wt=Kt!=null?Kt:tr;X.style.width=wt,X.style.maxWidth=wt}if(Bo(),!h){let Kt=x.innerHeight,wt=64,an=(Re=(Be=r.launcher)==null?void 0:Be.heightOffset)!=null?Re:0,Rn=Math.max(200,Kt-wt),Ht=Math.min(640,Rn),fn=Math.max(200,Ht-an);X.style.height=`${fn}px`}}finally{if(zn(),Gs(),F&&W){let wt=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((bt=(Xe=r.launcher)==null?void 0:Xe.mobileBreakpoint)!=null?bt:640),an=(De=(I=r.launcher)==null?void 0:I.sidebarMode)!=null?De:!1,Rn=(Ye=(We=r.launcher)==null?void 0:We.mobileFullscreen)!=null?Ye:!0,Ht=dn(r)&&Rn&&wt,fn=an||Rn&&wt&&W||Ht;if(fn&&!rn){let _n=e.getRootNode(),Ge=_n instanceof ShadowRoot?_n.host:e.closest(".persona-host");Ge&&!nn&&(nn=Il(Ge,(_e=(Pt=r.launcher)==null?void 0:Pt.zIndex)!=null?_e:wn)),rn=Rl(e.ownerDocument)}else fn||(nn==null||nn(),nn=null,rn==null||rn(),rn=null)}}};Js();let Dc=($d=e.ownerDocument.defaultView)!=null?$d:window;if(Dc.addEventListener("resize",Js),lt.push(()=>Dc.removeEventListener("resize",Js)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{zn()});l.observe(He),lt.push(()=>l.disconnect())}Sn=we.scrollTop;let Nc=Br(we),vh=()=>{let l=we.getRootNode(),m=typeof l.getSelection=="function"?l.getSelection():null;return m!=null?m:we.ownerDocument.getSelection()},el=()=>Ag(vh(),we),Oc=()=>{let l=we.scrollTop,m=Br(we),h=m<Nc;if(Nc=m,!Zt()){Sn=l,Fn();return}let{action:x,nextLastScrollTop:C}=ii({following:bn.isFollowing(),currentScrollTop:l,lastScrollTop:Sn,nearBottom:So(we,z),userScrollThreshold:w,isAutoScrolling:Tn||No||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Sn=C,x==="resume"){el()||uo();return}x==="pause"&&js()};if(we.addEventListener("scroll",Oc,{passive:!0}),lt.push(()=>we.removeEventListener("scroll",Oc)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{eh()});l.observe(Ze),l.observe(we),lt.push(()=>l.disconnect())}let Fc=()=>{Zt()&&bn.isFollowing()&&el()&&js()},_c=we.ownerDocument;_c.addEventListener("selectionchange",Fc),lt.push(()=>{_c.removeEventListener("selectionchange",Fc)});let wh=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),$c=l=>{or()&&Zt()&&bn.isFollowing()&&wh.has(l.key)&&js()},jc=l=>{if(!or()||!Zt()||!bn.isFollowing())return;let m=l.target;m&&m.closest("a, button, [tabindex], input, textarea, select")&&js()};we.addEventListener("keydown",$c),we.addEventListener("focusin",jc),lt.push(()=>{we.removeEventListener("keydown",$c),we.removeEventListener("focusin",jc)});let Uc=l=>{if(!Zt())return;let m=li({following:bn.isFollowing(),deltaY:l.deltaY,nearBottom:So(we,z),resumeWhenNearBottom:!0});m==="pause"?js():m==="resume"&&!el()&&uo()};we.addEventListener("wheel",Uc,{passive:!0}),lt.push(()=>we.removeEventListener("wheel",Uc)),zt.addEventListener("click",()=>{Us(),we.scrollTop=we.scrollHeight,Sn=we.scrollTop,uo(),mo(!0),Fn()}),lt.push(()=>zt.remove()),lt.push(()=>{mc(),Us()});let qc=()=>{Ue&&(Tr&&(Ue.removeEventListener("click",Tr),Tr=null),O()?(Ue.style.display="",Tr=()=>{_t(!1,"user")},Ue.addEventListener("click",Tr)):Ue.style.display="none")};qc(),(()=>{let{clearChatButton:l}=Ve;l&&l.addEventListener("click",()=>{_.clearMessages(),Er.clear(),uo(),Qo(Ve.composerOverlay);try{localStorage.removeItem(Os),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Os}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Os)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(m),c!=null&&c.clear&&zr(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),p={},L.syncFromMetadata(),V==null||V.clear(),Q==null||Q.reset(),Me==null||Me.update()})})(),Ct&&Ct.addEventListener("submit",Lc),be==null||be.addEventListener("keydown",Ic),be==null||be.addEventListener("input",Pc),be==null||be.addEventListener("paste",Wc);let zc=(jd=e.ownerDocument)!=null?jd:document;zc.addEventListener("keydown",Rc,!0);let Vc="persona-attachment-drop-active",Xs=0,tl=()=>{Xs=0,Se.classList.remove(Vc)},ys=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&At!==null},Kc=l=>{!Ri(l.dataTransfer)||!ys()||(Xs++,Xs===1&&Se.classList.add(Vc))},Gc=l=>{!Ri(l.dataTransfer)||!ys()||(Xs--,Xs<=0&&tl())},Jc=l=>{!Ri(l.dataTransfer)||!ys()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Xc=l=>{var h;if(!Ri(l.dataTransfer)||!ys())return;l.preventDefault(),l.stopPropagation(),tl();let m=Array.from((h=l.dataTransfer.files)!=null?h:[]);m.length!==0&&At.handleFiles(m)},fo=!0;Se.addEventListener("dragenter",Kc,fo),Se.addEventListener("dragleave",Gc,fo),e.addEventListener("dragover",Jc,fo),e.addEventListener("drop",Xc,fo);let Na=e.ownerDocument,Qc=l=>{ys()&&l.preventDefault()},Yc=l=>{ys()&&l.preventDefault()};Na.addEventListener("dragover",Qc),Na.addEventListener("drop",Yc),lt.push(()=>{Ct&&Ct.removeEventListener("submit",Lc),be==null||be.removeEventListener("keydown",Ic),be==null||be.removeEventListener("input",Pc),be==null||be.removeEventListener("paste",Wc),zc.removeEventListener("keydown",Rc,!0)}),lt.push(()=>{Se.removeEventListener("dragenter",Kc,fo),Se.removeEventListener("dragleave",Gc,fo),e.removeEventListener("dragover",Jc,fo),e.removeEventListener("drop",Xc,fo),Na.removeEventListener("dragover",Qc),Na.removeEventListener("drop",Yc),tl()}),lt.push(()=>{_.cancel()}),Yt?lt.push(()=>{Yt==null||Yt.destroy()}):sn&<.push(()=>{sn==null||sn.remove()});let en={update(l){var jn,Ir,un,mn,Zn,bo,Jd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,xp,vp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Np,Op,Fp,_p,$p,jp,Up,qp,zp,Vp,Kp,Gp,Jp,Xp,Qp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,yu,bu,xu,vu,wu,Cu,Au,Su,Tu,Eu,Mu,ku,Lu,Pu,Iu,Ru,Wu,Hu,Bu,Du,Nu,Ou,Fu,_u,$u,ju,Uu,qu,zu,Vu,Ku,Gu,Ju,Xu,Qu,Yu,Zu,em,tm;let m=r.toolCall,h=r.messageActions,x=(jn=r.layout)==null?void 0:jn.messages,C=r.colorScheme,M=r.loadingIndicator,$=r.iterationDisplay,N=(Ir=r.features)==null?void 0:Ir.showReasoning,D=(un=r.features)==null?void 0:un.showToolCalls,ie=(mn=r.features)==null?void 0:mn.toolCallDisplay,oe=(Zn=r.features)==null?void 0:Zn.reasoningDisplay,Y=(Jd=(bo=r.features)==null?void 0:bo.streamAnimation)==null?void 0:Jd.type;r={...r,...l},io(),ns(e,r),Ei(e,r),Mi(e,r),Ar(),r.colorScheme!==C&&$s();let ve=ki.getForInstance(r.plugins);o.length=0,o.push(...ve),W=(Qd=(Xd=r.launcher)==null?void 0:Xd.enabled)!=null?Qd:!0,R=(Zd=(Yd=r.launcher)==null?void 0:Yd.autoExpand)!=null?Zd:!1,Le=(tp=(ep=r.features)==null?void 0:ep.showReasoning)!=null?tp:!0,Pe=(rp=(np=r.features)==null?void 0:np.showToolCalls)!=null?rp:!0,Ae=(sp=(op=r.features)==null?void 0:op.scrollToBottom)!=null?sp:{};let Oe=Ot();re=(ip=(ap=r.features)==null?void 0:ap.scrollBehavior)!=null?ip:{},Oe!==Ot()&&(Us(),uo()),to(),Fn();let Fe=ne;if(ne=(cp=(lp=r.features)==null?void 0:lp.showEventStreamToggle)!=null?cp:!1,ne&&!Fe){if(V||(fe=new ka(ae),V=new Ma($e,fe),Q=Q!=null?Q:new La,fe.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),_.setSSEEventCallback((te,Tt)=>{var Ut;(Ut=r.onSSEEvent)==null||Ut.call(r,te,Tt),Q==null||Q.processEvent(te,Tt),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!yt&&ke){let te=(pp=(dp=r.features)==null?void 0:dp.eventStream)==null?void 0:pp.classNames,Tt="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"+(te!=null&&te.toggleButton?" "+te.toggleButton:"");yt=b("button",Tt),yt.style.width="28px",yt.style.height="28px",yt.style.color=Ln.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let Ut=ye("activity","18px","currentColor",1.5);Ut&&yt.appendChild(Ut);let at=Ve.clearChatButtonWrapper,kt=Ve.closeButtonWrapper,ln=at||kt;ln&&ln.parentNode===ke?ke.insertBefore(yt,ln):ke.appendChild(yt),yt.addEventListener("click",()=>{J?lr():Fr()})}}else!ne&&Fe&&(lr(),yt&&(yt.remove(),yt=null),V==null||V.clear(),fe==null||fe.destroy(),V=null,fe=null,Q==null||Q.reset(),Q=null);if(((up=r.launcher)==null?void 0:up.enabled)===!1&&Yt&&(Yt.destroy(),Yt=null),((mp=r.launcher)==null?void 0:mp.enabled)===!1&&sn&&(sn.remove(),sn=null),((gp=r.launcher)==null?void 0:gp.enabled)!==!1&&!Yt&&!sn){let{instance:te,element:Tt}=Dl({config:r,plugins:o,onToggle:Bc});Yt=te,te||(sn=Tt),e.appendChild(Tt)}Yt&&Yt.update(r),ue&&((fp=r.launcher)==null?void 0:fp.title)!==void 0&&(ue.textContent=r.launcher.title),Te&&((hp=r.launcher)==null?void 0:hp.subtitle)!==void 0&&(Te.textContent=r.launcher.subtitle);let je=(yp=r.layout)==null?void 0:yp.header;if((je==null?void 0:je.layout)!==U&&ke){let te=je?Sa(r,je,{showClose:O(),onClose:()=>_t(!1,"user")}):ko({config:r,showClose:O(),onClose:()=>_t(!1,"user")});tt.replaceHeader(te),ke=tt.header.element,E=tt.header.iconHolder,ue=tt.header.headerTitle,Te=tt.header.headerSubtitle,Ue=tt.header.closeButton,U=je==null?void 0:je.layout}else if(je&&(E&&(E.style.display=je.showIcon===!1?"none":""),ue&&(ue.style.display=je.showTitle===!1?"none":""),Te&&(Te.style.display=je.showSubtitle===!1?"none":""),Ue&&(Ue.style.display=je.showCloseButton===!1?"none":""),Ve.clearChatButtonWrapper)){let te=je.showClearChat;if(te!==void 0){Ve.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Tt}=Ve;Tt&&!Tt.classList.contains("persona-absolute")&&(te?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let ut=((bp=r.layout)==null?void 0:bp.showHeader)!==!1;ke&&(ke.style.display=ut?"":"none");let st=((xp=r.layout)==null?void 0:xp.showFooter)!==!1;He&&(He.style.display=st?"":"none"),zn(),Fn(),W!==H?W?_t(R,"auto"):(F=!0,Gs()):R!==S&&_t(R,"auto"),S=R,H=W,Js(),qc();let ze=JSON.stringify(l.toolCall)!==JSON.stringify(m),Xe=JSON.stringify(r.messageActions)!==JSON.stringify(h),bt=JSON.stringify((vp=r.layout)==null?void 0:vp.messages)!==JSON.stringify(x),I=((wp=r.loadingIndicator)==null?void 0:wp.render)!==(M==null?void 0:M.render)||((Cp=r.loadingIndicator)==null?void 0:Cp.renderIdle)!==(M==null?void 0:M.renderIdle)||((Ap=r.loadingIndicator)==null?void 0:Ap.showBubble)!==(M==null?void 0:M.showBubble),De=r.iterationDisplay!==$,We=((Tp=(Sp=r.features)==null?void 0:Sp.showReasoning)!=null?Tp:!0)!==(N!=null?N:!0)||((Mp=(Ep=r.features)==null?void 0:Ep.showToolCalls)!=null?Mp:!0)!==(D!=null?D:!0)||JSON.stringify((kp=r.features)==null?void 0:kp.toolCallDisplay)!==JSON.stringify(ie)||JSON.stringify((Lp=r.features)==null?void 0:Lp.reasoningDisplay)!==JSON.stringify(oe);(ze||Xe||bt||I||De||We)&&_&&(ds++,qs(Ze,_.getMessages(),ee));let Pt=(Ip=(Pp=r.features)==null?void 0:Pp.streamAnimation)==null?void 0:Ip.type;if(Pt!==Y&&Pt&&Pt!=="none"){let te=Is(Pt,(Wp=(Rp=r.features)==null?void 0:Rp.streamAnimation)==null?void 0:Wp.plugins);te&&ui(te,e)}let _e=(Hp=r.launcher)!=null?Hp:{},Kt=(Bp=_e.headerIconHidden)!=null?Bp:!1,wt=(Np=(Dp=r.layout)==null?void 0:Dp.header)==null?void 0:Np.showIcon,an=Kt||wt===!1,Rn=_e.headerIconName,Ht=(Op=_e.headerIconSize)!=null?Op:"48px";if(E){let te=Se.querySelector(".persona-border-b-persona-divider"),Tt=te==null?void 0:te.querySelector(".persona-flex-col");if(an)E.style.display="none",te&&Tt&&!te.contains(Tt)&&te.insertBefore(Tt,te.firstChild);else{if(E.style.display="",E.style.height=Ht,E.style.width=Ht,te&&Tt&&(te.contains(E)?E.nextSibling!==Tt&&(E.remove(),te.insertBefore(E,Tt)):te.insertBefore(E,Tt)),Rn){let at=parseFloat(Ht)||24,kt=ye(Rn,at*.6,"currentColor",1);kt?E.replaceChildren(kt):E.textContent=(Fp=_e.agentIconText)!=null?Fp:"\u{1F4AC}"}else if(_e.iconUrl){let at=E.querySelector("img");if(at)at.src=_e.iconUrl,at.style.height=Ht,at.style.width=Ht;else{let kt=document.createElement("img");kt.src=_e.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=Ht,kt.style.width=Ht,E.replaceChildren(kt)}}else{let at=E.querySelector("svg"),kt=E.querySelector("img");(at||kt)&&E.replaceChildren(),E.textContent=(_p=_e.agentIconText)!=null?_p:"\u{1F4AC}"}let Ut=E.querySelector("img");Ut&&(Ut.style.height=Ht,Ut.style.width=Ht)}}let fn=(jp=($p=r.layout)==null?void 0:$p.header)==null?void 0:jp.showTitle,_n=(qp=(Up=r.layout)==null?void 0:Up.header)==null?void 0:qp.showSubtitle;if(ue&&(ue.style.display=fn===!1?"none":""),Te&&(Te.style.display=_n===!1?"none":""),Ue){((Vp=(zp=r.layout)==null?void 0:zp.header)==null?void 0:Vp.showCloseButton)===!1?Ue.style.display="none":Ue.style.display="";let Tt=(Kp=_e.closeButtonSize)!=null?Kp:"32px",Ut=(Gp=_e.closeButtonPlacement)!=null?Gp:"inline";Ue.style.height=Tt,Ue.style.width=Tt;let{closeButtonWrapper:at}=Ve,kt=Ut==="top-right",ln=at==null?void 0:at.classList.contains("persona-absolute");if(at&&kt!==ln)if(at.remove(),kt)at.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Se.style.position="relative",Se.appendChild(at);else{let dt=(Xp=(Jp=_e.clearChat)==null?void 0:Jp.placement)!=null?Xp:"inline",cn=(Yp=(Qp=_e.clearChat)==null?void 0:Qp.enabled)!=null?Yp:!0;at.className=cn&&dt==="inline"?"":"persona-ml-auto";let Wn=Se.querySelector(".persona-border-b-persona-divider");Wn&&Wn.appendChild(at)}if(Ue.style.color=_e.closeButtonColor||Ln.actionIconColor,_e.closeButtonBackgroundColor?(Ue.style.backgroundColor=_e.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),_e.closeButtonBorderWidth||_e.closeButtonBorderColor){let dt=_e.closeButtonBorderWidth||"0px",cn=_e.closeButtonBorderColor||"transparent";Ue.style.border=`${dt} solid ${cn}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");_e.closeButtonBorderRadius?(Ue.style.borderRadius=_e.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),_e.closeButtonPaddingX?(Ue.style.paddingLeft=_e.closeButtonPaddingX,Ue.style.paddingRight=_e.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),_e.closeButtonPaddingY?(Ue.style.paddingTop=_e.closeButtonPaddingY,Ue.style.paddingBottom=_e.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let vn=(Zp=_e.closeButtonIconName)!=null?Zp:"x",ur=(eu=_e.closeButtonIconText)!=null?eu:"\xD7";Ue.innerHTML="";let kn=ye(vn,"28px","currentColor",1);kn?Ue.appendChild(kn):Ue.textContent=ur;let Qt=(tu=_e.closeButtonTooltipText)!=null?tu:"Close chat",Un=(nu=_e.closeButtonShowTooltip)!=null?nu:!0;if(Ue.setAttribute("aria-label",Qt),at&&(at._cleanupTooltip&&(at._cleanupTooltip(),delete at._cleanupTooltip),Un&&Qt)){let dt=null,cn=()=>{if(dt||!Ue)return;let Vo=Ue.ownerDocument,Qs=Vo.body;if(!Qs)return;dt=Wr(Vo,"div","persona-clear-chat-tooltip"),dt.textContent=Qt;let Ys=Wr(Vo,"div");Ys.className="persona-clear-chat-tooltip-arrow",dt.appendChild(Ys);let Ko=Ue.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(To),dt.style.left=`${Ko.left+Ko.width/2}px`,dt.style.top=`${Ko.top-8}px`,dt.style.transform="translate(-50%, -100%)",Qs.appendChild(dt)},Wn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};at.addEventListener("mouseenter",cn),at.addEventListener("mouseleave",Wn),Ue.addEventListener("focus",cn),Ue.addEventListener("blur",Wn),at._cleanupTooltip=()=>{Wn(),at&&(at.removeEventListener("mouseenter",cn),at.removeEventListener("mouseleave",Wn)),Ue&&(Ue.removeEventListener("focus",cn),Ue.removeEventListener("blur",Wn))}}}let{clearChatButton:Ge,clearChatButtonWrapper:It}=Ve;if(Ge){let te=(ru=_e.clearChat)!=null?ru:{},Tt=(ou=te.enabled)!=null?ou:!0,Ut=(au=(su=r.layout)==null?void 0:su.header)==null?void 0:au.showClearChat,at=Ut!==void 0?Ut:Tt,kt=(iu=te.placement)!=null?iu:"inline";if(It){It.style.display=at?"":"none";let{closeButtonWrapper:ln}=Ve;!k()&&ln&&!ln.classList.contains("persona-absolute")&&(at?ln.classList.remove("persona-ml-auto"):ln.classList.add("persona-ml-auto"));let vn=kt==="top-right",ur=It.classList.contains("persona-absolute");if(!k()&&vn!==ur&&at){if(It.remove(),vn)It.className="persona-absolute persona-top-4 persona-z-50",It.style.right="48px",Se.style.position="relative",Se.appendChild(It);else{It.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",It.style.right="";let Qt=Se.querySelector(".persona-border-b-persona-divider"),Un=Ve.closeButtonWrapper;Qt&&Un&&Un.parentElement===Qt?Qt.insertBefore(It,Un):Qt&&Qt.appendChild(It)}let kn=Ve.closeButtonWrapper;kn&&!kn.classList.contains("persona-absolute")&&(vn?kn.classList.add("persona-ml-auto"):kn.classList.remove("persona-ml-auto"))}}if(at){if(!k()){let dt=(lu=te.size)!=null?lu:"32px";Ge.style.height=dt,Ge.style.width=dt}let ln=(cu=te.iconName)!=null?cu:"refresh-cw",vn=(du=te.iconColor)!=null?du:"";Ge.style.color=vn||Ln.actionIconColor,Ge.innerHTML="";let ur=k()?"14px":"20px",kn=ye(ln,ur,"currentColor",2);if(kn&&Ge.appendChild(kn),te.backgroundColor?(Ge.style.backgroundColor=te.backgroundColor,Ge.classList.remove("hover:persona-bg-gray-100")):(Ge.style.backgroundColor="",Ge.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let dt=te.borderWidth||"0px",cn=te.borderColor||"transparent";Ge.style.border=`${dt} solid ${cn}`,Ge.classList.remove("persona-border-none")}else Ge.style.border="",Ge.classList.add("persona-border-none");te.borderRadius?(Ge.style.borderRadius=te.borderRadius,Ge.classList.remove("persona-rounded-full")):(Ge.style.borderRadius="",Ge.classList.add("persona-rounded-full")),te.paddingX?(Ge.style.paddingLeft=te.paddingX,Ge.style.paddingRight=te.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),te.paddingY?(Ge.style.paddingTop=te.paddingY,Ge.style.paddingBottom=te.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let Qt=(pu=te.tooltipText)!=null?pu:"Clear chat",Un=(uu=te.showTooltip)!=null?uu:!0;if(Ge.setAttribute("aria-label",Qt),It&&(It._cleanupTooltip&&(It._cleanupTooltip(),delete It._cleanupTooltip),Un&&Qt)){let dt=null,cn=()=>{if(dt||!Ge)return;let Vo=Ge.ownerDocument,Qs=Vo.body;if(!Qs)return;dt=Wr(Vo,"div","persona-clear-chat-tooltip"),dt.textContent=Qt;let Ys=Wr(Vo,"div");Ys.className="persona-clear-chat-tooltip-arrow",dt.appendChild(Ys);let Ko=Ge.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(To),dt.style.left=`${Ko.left+Ko.width/2}px`,dt.style.top=`${Ko.top-8}px`,dt.style.transform="translate(-50%, -100%)",Qs.appendChild(dt)},Wn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};It.addEventListener("mouseenter",cn),It.addEventListener("mouseleave",Wn),Ge.addEventListener("focus",cn),Ge.addEventListener("blur",Wn),It._cleanupTooltip=()=>{Wn(),It&&(It.removeEventListener("mouseenter",cn),It.removeEventListener("mouseleave",Wn)),Ge&&(Ge.removeEventListener("focus",cn),Ge.removeEventListener("blur",Wn))}}}}let $n=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Li],_o=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Ns.message,Ns.messageAndClick];L=Pi({parsers:$n,handlers:_o,getSessionMetadata:y,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),ee=hf(r,L,de),_.updateConfig(r),qs(Ze,_.getMessages(),ee),cs(),Ac(),qi(_.isStreaming());let $o=((mu=r.voiceRecognition)==null?void 0:mu.enabled)===!0,jo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Uo=((fu=(gu=r.voiceRecognition)==null?void 0:gu.provider)==null?void 0:fu.type)==="runtype";if($o&&(jo||Uo))if(!B||!xe){let te=fh(r.voiceRecognition,r.sendButton);te&&(B=te.micButton,xe=te.micButtonWrapper,ht.insertBefore(xe,Cn),B.addEventListener("click",Da),B.disabled=_.isStreaming())}else{let te=(hu=r.voiceRecognition)!=null?hu:{},Tt=(yu=r.sendButton)!=null?yu:{},Ut=(bu=te.iconName)!=null?bu:"mic",at=(xu=Tt.size)!=null?xu:"40px",kt=(vu=te.iconSize)!=null?vu:at,ln=parseFloat(kt)||24;B.style.width=kt,B.style.height=kt,B.style.minWidth=kt,B.style.minHeight=kt;let vn=(Cu=(wu=te.iconColor)!=null?wu:Tt.textColor)!=null?Cu:"currentColor";B.innerHTML="";let ur=ye(Ut,ln,vn,2);ur?B.appendChild(ur):B.textContent="\u{1F3A4}";let kn=(Au=te.backgroundColor)!=null?Au:Tt.backgroundColor;kn?B.style.backgroundColor=kn:B.style.backgroundColor="",vn?B.style.color=vn:B.style.color="var(--persona-text, #111827)",te.borderWidth?(B.style.borderWidth=te.borderWidth,B.style.borderStyle="solid"):(B.style.borderWidth="",B.style.borderStyle=""),te.borderColor?B.style.borderColor=te.borderColor:B.style.borderColor="",te.paddingX?(B.style.paddingLeft=te.paddingX,B.style.paddingRight=te.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),te.paddingY?(B.style.paddingTop=te.paddingY,B.style.paddingBottom=te.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let Qt=xe==null?void 0:xe.querySelector(".persona-send-button-tooltip"),Un=(Su=te.tooltipText)!=null?Su:"Start voice recognition";if(((Tu=te.showTooltip)!=null?Tu:!1)&&Un)if(Qt)Qt.textContent=Un,Qt.style.display="";else{let cn=document.createElement("div");cn.className="persona-send-button-tooltip",cn.textContent=Un,xe==null||xe.insertBefore(cn,B)}else Qt&&(Qt.style.display="none");xe.style.display="",B.disabled=_.isStreaming()}else B&&xe&&(xe.style.display="none",((Mu=(Eu=r.voiceRecognition)==null?void 0:Eu.provider)==null?void 0:Mu.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():Pr&&go());if(((ku=r.attachments)==null?void 0:ku.enabled)===!0)if(!ft||!ce){let te=(Lu=r.attachments)!=null?Lu:{},Ut=(Iu=((Pu=r.sendButton)!=null?Pu:{}).size)!=null?Iu:"40px";Lt||(Lt=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Lt.style.display="none",Ct.insertBefore(Lt,be)),Je||(Je=document.createElement("input"),Je.type="file",Je.accept=((Ru=te.allowedTypes)!=null?Ru:Qr).join(","),Je.multiple=((Wu=te.maxFiles)!=null?Wu:4)>1,Je.style.display="none",Je.setAttribute("aria-label","Attach files"),Ct.insertBefore(Je,be)),ft=b("div","persona-send-button-wrapper"),ce=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ce.type="button",ce.setAttribute("aria-label",(Hu=te.buttonTooltipText)!=null?Hu:"Attach file");let at=(Bu=te.buttonIconName)!=null?Bu:"paperclip",kt=Ut,ln=parseFloat(kt)||40,vn=Math.round(ln*.6);ce.style.width=kt,ce.style.height=kt,ce.style.minWidth=kt,ce.style.minHeight=kt,ce.style.fontSize="18px",ce.style.lineHeight="1",ce.style.backgroundColor="transparent",ce.style.color="var(--persona-primary, #111827)",ce.style.border="none",ce.style.borderRadius="6px",ce.style.transition="background-color 0.15s ease",ce.addEventListener("mouseenter",()=>{ce.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ce.addEventListener("mouseleave",()=>{ce.style.backgroundColor="transparent"});let ur=ye(at,vn,"currentColor",1.5);ur?ce.appendChild(ur):ce.textContent="\u{1F4CE}",ce.addEventListener("click",Un=>{Un.preventDefault(),Je==null||Je.click()}),ft.appendChild(ce);let kn=(Du=te.buttonTooltipText)!=null?Du:"Attach file",Qt=b("div","persona-send-button-tooltip");Qt.textContent=kn,ft.appendChild(Qt),Qe.append(ft),!At&&Je&&Lt&&(At=Ls.fromConfig(te),At.setPreviewsContainer(Lt),Je.addEventListener("change",async()=>{At&&(Je!=null&&Je.files)&&(await At.handleFileSelect(Je.files),Je.value="")})),Se.querySelector(".persona-attachment-drop-overlay")||Se.appendChild(yf(te.dropOverlay))}else{ft.style.display="";let te=(Nu=r.attachments)!=null?Nu:{};Je&&(Je.accept=((Ou=te.allowedTypes)!=null?Ou:Qr).join(","),Je.multiple=((Fu=te.maxFiles)!=null?Fu:4)>1),At&&At.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}else ft&&(ft.style.display="none"),At&&At.clearAttachments(),(_u=Se.querySelector(".persona-attachment-drop-overlay"))==null||_u.remove();let Jt=($u=r.sendButton)!=null?$u:{},qo=(ju=Jt.useIcon)!=null?ju:!1,ho=(Uu=Jt.iconText)!=null?Uu:"\u2191",yo=Jt.iconName,Jr=(qu=Jt.tooltipText)!=null?qu:"Send message",zo=(zu=Jt.showTooltip)!=null?zu:!1,et=(Vu=Jt.size)!=null?Vu:"40px",Nt=Jt.backgroundColor,Bt=Jt.textColor;if(qo){if(pe.style.width=et,pe.style.height=et,pe.style.minWidth=et,pe.style.minHeight=et,pe.style.fontSize="18px",pe.style.lineHeight="1",pe.innerHTML="",Bt?pe.style.color=Bt:pe.style.color="var(--persona-button-primary-fg, #ffffff)",yo){let te=parseFloat(et)||24,Tt=(Bt==null?void 0:Bt.trim())||"currentColor",Ut=ye(yo,te,Tt,2);Ut?pe.appendChild(Ut):pe.textContent=ho}else pe.textContent=ho;pe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Nt?(pe.style.backgroundColor=Nt,pe.classList.remove("persona-bg-persona-primary")):(pe.style.backgroundColor="",pe.classList.add("persona-bg-persona-primary"))}else pe.textContent=(Gu=(Ku=r.copy)==null?void 0:Ku.sendButtonLabel)!=null?Gu:"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",Nt?(pe.style.backgroundColor=Nt,pe.classList.remove("persona-bg-persona-accent")):pe.classList.add("persona-bg-persona-accent"),Bt?pe.style.color=Bt:pe.classList.add("persona-text-white");Jt.borderWidth?(pe.style.borderWidth=Jt.borderWidth,pe.style.borderStyle="solid"):(pe.style.borderWidth="",pe.style.borderStyle=""),Jt.borderColor?pe.style.borderColor=Jt.borderColor:pe.style.borderColor="",Jt.paddingX?(pe.style.paddingLeft=Jt.paddingX,pe.style.paddingRight=Jt.paddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),Jt.paddingY?(pe.style.paddingTop=Jt.paddingY,pe.style.paddingBottom=Jt.paddingY):(pe.style.paddingTop="",pe.style.paddingBottom="");let Vt=Cn==null?void 0:Cn.querySelector(".persona-send-button-tooltip");if(zo&&Jr)if(Vt)Vt.textContent=Jr,Vt.style.display="";else{let te=document.createElement("div");te.className="persona-send-button-tooltip",te.textContent=Jr,Cn==null||Cn.insertBefore(te,pe)}else Vt&&(Vt.style.display="none");let $t=(Zu=(Ju=r.layout)==null?void 0:Ju.contentMaxWidth)!=null?Zu:k()?(Yu=(Qu=(Xu=r.launcher)==null?void 0:Xu.composerBar)==null?void 0:Qu.contentMaxWidth)!=null?Yu:"720px":void 0;$t?(Ze.style.maxWidth=$t,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%",Ct&&(Ct.style.maxWidth=$t,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),qt&&(qt.style.maxWidth=$t,qt.style.marginLeft="auto",qt.style.marginRight="auto")):(Ze.style.maxWidth="",Ze.style.marginLeft="",Ze.style.marginRight="",Ze.style.width="",Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""),qt&&(qt.style.maxWidth="",qt.style.marginLeft="",qt.style.marginRight=""));let mt=(em=r.statusIndicator)!=null?em:{},jt=(tm=mt.visible)!=null?tm:!0;if(yn.style.display=jt?"":"none",_){let te=_.getStatus();Wt(yn,(Ut=>{var at,kt,ln,vn;return Ut==="idle"?(at=mt.idleText)!=null?at:tn.idle:Ut==="connecting"?(kt=mt.connectingText)!=null?kt:tn.connecting:Ut==="connected"?(ln=mt.connectedText)!=null?ln:tn.connected:Ut==="error"?(vn=mt.errorText)!=null?vn:tn.error:tn[Ut]})(te),mt,te)}yn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let hn=mt.align==="left"?"persona-text-left":mt.align==="center"?"persona-text-center":"persona-text-right";yn.classList.add(hn)},open(){O()&&_t(!0,"api")},close(){O()&&_t(!1,"api")},toggle(){O()&&_t(!F,"api")},reconnect(){_.reconnectNow()},clearChat(){An=!1,_.clearMessages(),Er.clear(),uo();try{localStorage.removeItem(Os),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Os}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Os)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});window.dispatchEvent(l),c!=null&&c.clear&&zr(()=>c.clear(),"[AgentWidget] Failed to clear storage adapter:"),p={},L.syncFromMetadata(),V==null||V.clear(),Q==null||Q.reset(),Me==null||Me.update()},setMessage(l){return!be||_.isStreaming()?!1:(!F&&O()&&_t(!0,"system"),be.value=l,be.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(_.isStreaming())return!1;let m=(l==null?void 0:l.trim())||be.value.trim();return m?(!F&&O()&&_t(!0,"system"),be.value="",be.style.height="auto",_.sendMessage(m),!0):!1},startVoiceRecognition(){var m,h;return _.isStreaming()?!1:((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype"?(_.isVoiceActive()||(!F&&O()&&_t(!0,"system"),K.manuallyDeactivated=!1,ct(),_.toggleVoice().then(()=>{K.active=_.isVoiceActive(),rt("user"),_.isVoiceActive()&&hs()})),!0):Pr?!0:Hc()?(!F&&O()&&_t(!0,"system"),K.manuallyDeactivated=!1,ct(),Ha("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{K.active=!1,K.manuallyDeactivated=!0,ct(),rt("user"),Gr()}),!0):!1:Pr?(K.manuallyDeactivated=!0,ct(),go("user"),!0):!1},injectMessage(l){return!F&&O()&&_t(!0,"system"),_.injectMessage(l)},injectAssistantMessage(l){!F&&O()&&_t(!0,"system");let m=_.injectAssistantMessage(l);return Z&&(Z=!1,Ee&&(clearTimeout(Ee),Ee=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),m},injectUserMessage(l){return!F&&O()&&_t(!0,"system"),_.injectUserMessage(l)},injectSystemMessage(l){return!F&&O()&&_t(!0,"system"),_.injectSystemMessage(l)},injectMessageBatch(l){return!F&&O()&&_t(!0,"system"),_.injectMessageBatch(l)},injectComponentDirective(l){return!F&&O()&&_t(!0,"system"),_.injectComponentDirective(l)},injectTestMessage(l){!F&&O()&&_t(!0,"system"),_.injectTestEvent(l)},async connectStream(l,m){return _.connectStream(l,m)},__pushEventStreamEvent(l){V&&(Q==null||Q.processEvent(l.type,l.payload),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!ne||!V||Fr()},hideEventStream(){J&&lr()},isEventStreamVisible(){return J},showArtifacts(){rr(r)&&(An=!1,Ar(),vt==null||vt.setMobileOpen(!0))},hideArtifacts(){rr(r)&&(An=!0,Ar())},upsertArtifact(l){return rr(r)?(An=!1,_.upsertArtifact(l)):null},selectArtifact(l){rr(r)&&_.selectArtifact(l)},clearArtifacts(){rr(r)&&_.clearArtifacts()},getArtifacts(){var l;return(l=_==null?void 0:_.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=_==null?void 0:_.getSelectedArtifactId())!=null?l:null},focusInput(){return W&&!F&&!k()||!be?!1:(be.focus(),!0)},async resolveApproval(l,m,h){let C=_.getMessages().find(M=>{var $;return M.variant==="approval"&&(($=M.approval)==null?void 0:$.id)===l});if(!(C!=null&&C.approval))throw new Error(`Approval not found: ${l}`);if(C.approval.toolType==="webmcp"){_.resolveWebMcpApproval(C.id,m);return}return _.resolveApproval(C.approval,m,h)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(l){v(l)},on(l,m){return i.on(l,m)},off(l,m){i.off(l,m)},isOpen(){return O()&&F},isVoiceActive(){return K.active},toggleReadAloud(l){_.toggleReadAloud(l)},stopReadAloud(){_.stopSpeaking()},getReadAloudState(l){return _.getReadAloudState(l)},onReadAloudChange(l){return _.onReadAloudChange(l)},getState(){return{open:O()&&F,launcherEnabled:W,voiceActive:K.active,streaming:_.isStreaming()}},showCSATFeedback(l){!F&&O()&&_t(!0,"system");let m=Ze.querySelector(".persona-feedback-container");m&&m.remove();let h=Zl({onSubmit:async(x,C)=>{var M;_.isClientTokenMode()&&await _.submitCSATFeedback(x,C),(M=l==null?void 0:l.onSubmit)==null||M.call(l,x,C)},onDismiss:l==null?void 0:l.onDismiss,...l});Ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!F&&O()&&_t(!0,"system");let m=Ze.querySelector(".persona-feedback-container");m&&m.remove();let h=ec({onSubmit:async(x,C)=>{var M;_.isClientTokenMode()&&await _.submitNPSFeedback(x,C),(M=l==null?void 0:l.onSubmit)==null||M.call(l,x,C)},onDismiss:l==null?void 0:l.onDismiss,...l});Ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,m){return _.submitCSATFeedback(l,m)},async submitNPSFeedback(l,m){return _.submitNPSFeedback(l,m)},destroy(){Gi(),Fo!=null&&(clearInterval(Fo),Fo=null),lt.forEach(l=>l()),ge.remove(),it==null||it.remove(),Yt==null||Yt.destroy(),sn==null||sn.remove(),Tr&&Ue.removeEventListener("click",Tr)}};if((((Ud=n==null?void 0:n.debugTools)!=null?Ud:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:en,getMessages:en.getMessages,getStatus:en.getStatus,getMetadata:en.getPersistentMetadata,updateMetadata:en.updatePersistentMetadata,clearHistory:()=>en.clearChat(),setVoiceActive:h=>h?en.startVoiceRecognition():en.stopVoiceRecognition()};window.AgentWidgetBrowser=m,lt.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=N=>{let D=N.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&en.focusInput()};if(window.addEventListener("persona:focusInput",m),lt.push(()=>{window.removeEventListener("persona:focusInput",m)}),ne){let N=ie=>{let oe=ie.detail;(!(oe!=null&&oe.instanceId)||oe.instanceId===l)&&en.showEventStream()},D=ie=>{let oe=ie.detail;(!(oe!=null&&oe.instanceId)||oe.instanceId===l)&&en.hideEventStream()};window.addEventListener("persona:showEventStream",N),window.addEventListener("persona:hideEventStream",D),lt.push(()=>{window.removeEventListener("persona:showEventStream",N),window.removeEventListener("persona:hideEventStream",D)})}let h=N=>{let D=N.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&en.showArtifacts()},x=N=>{let D=N.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&en.hideArtifacts()},C=N=>{let D=N.detail;D!=null&&D.instanceId&&D.instanceId!==l||D!=null&&D.artifact&&en.upsertArtifact(D.artifact)},M=N=>{let D=N.detail;D!=null&&D.instanceId&&D.instanceId!==l||typeof(D==null?void 0:D.id)=="string"&&en.selectArtifact(D.id)},$=N=>{let D=N.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&en.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",C),window.addEventListener("persona:selectArtifact",M),window.addEventListener("persona:clearArtifacts",$),lt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",C),window.removeEventListener("persona:selectArtifact",M),window.removeEventListener("persona:clearArtifacts",$)})}let Yn=Kw(r.persistState);if(Yn&&O()){let l=Gw(Yn.storage),m=`${Yn.keyPrefix}widget-open`,h=`${Yn.keyPrefix}widget-voice`,x=`${Yn.keyPrefix}widget-voice-mode`;if(l){let C=((qd=Yn.persist)==null?void 0:qd.openState)&&l.getItem(m)==="true",M=((zd=Yn.persist)==null?void 0:zd.voiceState)&&l.getItem(h)==="true",$=((Vd=Yn.persist)==null?void 0:Vd.voiceState)&&l.getItem(x)==="true";if(C&&setTimeout(()=>{en.open(),setTimeout(()=>{var N;if(M||$)en.startVoiceRecognition();else if((N=Yn.persist)!=null&&N.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(Kd=Yn.persist)!=null&&Kd.openState&&(i.on("widget:opened",()=>{l.setItem(m,"true")}),i.on("widget:closed",()=>{l.setItem(m,"false")})),(Gd=Yn.persist)!=null&&Gd.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")})),Yn.clearOnChatClear){let N=()=>{l.removeItem(m),l.removeItem(h),l.removeItem(x)},D=()=>N();window.addEventListener("persona:clear-chat",D),lt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return f&&O()&&setTimeout(()=>{en.open()},0),ms(),Ia||am().then(()=>{_&&(ds++,Er.clear(),qs(Ze,_.getMessages(),ee))}).catch(()=>{}),en};var Jw=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(n);return o?Math.max(0,t*parseFloat(o[1])/100):420},Xw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Qw=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Yw=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(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.")},bf=(e,t)=>{var r,o;let n=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!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"},ac=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=""},xf=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",ac(e)},rc=e=>{e.style.transition=""},oc=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=""},sc=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Wi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Zw=(e,t,n,r,o)=>{o?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},eC=(e,t,n,r,o,s)=>{let a=s?t:e;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},vf=(e,t,n,r,o,s,a)=>{var y,v,A,T,L,W;let i=nr(s),d=i.reveal==="push";Zw(e,t,n,r,d),eC(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.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",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,p=(v=(y=s==null?void 0:s.launcher)==null?void 0:y.mobileFullscreen)!=null?v:!0,u=(T=(A=s==null?void 0:s.launcher)==null?void 0:A.mobileBreakpoint)!=null?T:640,f=c!=null?c.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),oc(t),rc(r),xf(r),sc(n),Wi(o,r),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",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((W=(L=s==null?void 0:s.launcher)==null?void 0:L.zIndex)!=null?W:wn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.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"),xf(r),Xw(r,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",oc(t),rc(r),sc(n),Wi(o,r);let R=i.animate?"transform 180ms ease":"none",P=i.side==="right"?"translateX(100%)":"translateX(-100%)",S=a?"translateX(0)":P;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=R,r.style.transform=S,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",rc(r),ac(r),Wi(o,r);let R=Jw(i.width,e.clientWidth),P=Math.max(0,e.clientWidth),S=i.animate?"margin-left 180ms ease":"none",H=i.side==="right"?a?-R:0:a?0:-R;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=`${P+R}px`,t.style.transition=S,t.style.marginLeft=`${H}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${P}px`,n.style.maxWidth=`${P}px`,n.style.minWidth=`${P}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",oc(t),ac(r),sc(n),Wi(o,r);let R=i.reveal==="emerge";R?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let P=a?i.width:"0px",S=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",H=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${P}`,r.style.width=P,r.style.maxWidth=P,r.style.minWidth=P,r.style.minHeight="0",Qw(r,i.maxHeight),r.style.overflow=R||H?"hidden":"visible",r.style.transition=S,R&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},tC=(e,t)=>{let n=e.ownerDocument.createElement("div");return bf(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){bf(n,r)},destroy(){n.remove()}}},nC=(e,t)=>{var W,R,P,S;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),c=n.createElement("aside"),p=n.createElement("div"),u=(R=(W=t==null?void 0:t.launcher)==null?void 0:W.enabled)==null||R?(S=(P=t==null?void 0:t.launcher)==null?void 0:P.autoExpand)!=null?S:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},y=()=>{g(),nr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{vf(a,i,d,c,p,t,u)}),f.observe(a))},v=!1,A=()=>{vf(a,i,d,c,p,t,u),y(),u&&!v&&a.dataset.personaDockMobileFullscreen!=="true"&&(v=!0,Yw(a,nr(t)))},T=a.ownerDocument.defaultView,L=()=>{A()};return T==null||T.addEventListener("resize",L),nr(t).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),A(),{mode:"docked",host:p,shell:a,syncWidgetState(H){let U=H.launcherEnabled?H.open:!0;u!==U&&(u=U,A())},updateConfig(H){var U,j;t=H,((j=(U=t==null?void 0:t.launcher)==null?void 0:U.enabled)!=null?j:!0)===!1&&(u=!0),A()},destroy(){T==null||T.removeEventListener("resize",L),g(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Hi=(e,t)=>dn(t)?nC(e,t):tC(e,t);var ic={},rC=e=>{if(typeof window=="undefined"||typeof document=="undefined")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},oC=()=>{try{if(typeof ic!="undefined"&&ic.url)return new URL("../widget.css",ic.url).href}catch{}return null},wf=(e,t)=>{let n=oC(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),t.head.appendChild(s)}},Cf=e=>{var A;let t=rC(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=Hi(t,o),a,i=[],d=(T,L)=>{var S,H;let R=!((H=(S=L==null?void 0:L.launcher)==null?void 0:S.enabled)!=null?H:!0)||dn(L),P=r.createElement("div");if(P.setAttribute("data-persona-root","true"),R&&(P.style.height="100%",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1",P.style.minHeight="0"),n){let U=T.attachShadow({mode:"open"});U.appendChild(P),wf(U,r)}else T.appendChild(P),wf(T,r);return t.id&&P.setAttribute("data-persona-instance",t.id),P},c=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(T=>T()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},u=()=>{let T=d(s.host,o);a=nc(T,o,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(T=>T()),i=[],a.destroy()};u(),(A=e.onChatReady)==null||A.call(e);let g=T=>{f(),s.destroy(),s=Hi(t,T),o=T,u()},y={update(T){var H,U,j,k,O,F;let L={...o,...T,launcher:{...(H=o==null?void 0:o.launcher)!=null?H:{},...(U=T==null?void 0:T.launcher)!=null?U:{},dock:{...(k=(j=o==null?void 0:o.launcher)==null?void 0:j.dock)!=null?k:{},...(F=(O=T==null?void 0:T.launcher)==null?void 0:O.dock)!=null?F:{}}}},W=dn(o),R=dn(L),P=Mo(o),S=Mo(L);if(W!==R||P!==S){g(L);return}o=L,s.updateConfig(o),a.update(T),c()},destroy(){f(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(y,{get(T,L,W){if(L==="host")return s.host;if(L in T)return Reflect.get(T,L,W);let R=a[L];return typeof R=="function"?R.bind(a):R}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var Mf=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),sC=new Set(["button","a","input","select","textarea","details","summary"]),aC=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),lc=/\b(product|card|item|listing|result)\b/i,dc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,iC=3e3,lC=100;function kf(e){let t=typeof e.className=="string"?e.className:"";if(lc.test(t)||e.id&&lc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&lc.test(r.value))return!0}return!1}function Lf(e){var t;return dc.test(((t=e.textContent)!=null?t:"").trim())}function Pf(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let o=(n=t[r].getAttribute("href"))!=null?n:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function cC(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Af(e){let t=e.match(dc);return t?t[0]:null}function Sf(e){var r,o,s;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((o=t.textContent)!=null&&o.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(s=n==null?void 0:n.textContent)!=null&&s.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function dC(e){let t=[],n=r=>{let o=r.trim();o&&!t.includes(o)&&t.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;n((o=r.value)!=null?o:"")}),t.slice(0,6)}var pC="commerce-card",uC="result-card";function Tf(e){return!kf(e)||!Lf(e)||!Pf(e)&&!cC(e)?0:5200}function Ef(e){var r;return!kf(e)||Lf(e)||!Pf(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var If=[{id:pC,scoreElement(e){return Tf(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||dc.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,c,p;if(Tf(e)===0)return null;let{title:n,href:r}=Sf(e),o=(p=(c=Af(((d=e.textContent)!=null?d:"").trim()))!=null?c:Af(t.text))!=null?p:"",s=dC(e);return[r&&n?`[${n}](${r})${o?`: ${o}`:""}`:n?`${n}${o?`: ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
112
|
+
`)}},{id:uC,scoreElement(e){return Ef(e)},formatSummary(e,t){if(Ef(e)===0)return null;let{title:n,href:r}=Sf(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
113
|
+
`)}}];function mC(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function gC(e){var p,u,f,g,y,v,A,T,L,W,R,P,S;let t=(p=e.options)!=null?p:{},n=(f=(u=t.maxElements)!=null?u:e.maxElements)!=null?f:80,r=(y=(g=t.excludeSelector)!=null?g:e.excludeSelector)!=null?y:".persona-host",o=(A=(v=t.maxTextLength)!=null?v:e.maxTextLength)!=null?A:200,s=(L=(T=t.visibleOnly)!=null?T:e.visibleOnly)!=null?L:!0,a=(W=t.root)!=null?W:e.root,i=(R=t.mode)!=null?R:"structured",d=(P=t.maxCandidates)!=null?P:Math.max(500,n*10),c=(S=e.rules)!=null?S:If;return i==="simple"&&e.rules&&e.rules.length>0?(mC(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:c}}function cc(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var fC=["data-testid","data-product","data-action","data-id","data-name","data-type"];function hC(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"||sC.has(t)||n&&aC.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Rf(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 yC(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);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 d=e.getAttribute("role");d&&(t.role=d);for(let c=0;c<e.attributes.length;c++){let p=e.attributes[c];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function Wf(e){let t=e.tagName.toLowerCase();if(e.id){let o=`#${cc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of fC){let s=e.getAttribute(o);if(s){let a=`${t}[${o}="${cc(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(n.length>0){let o=`${t}.${n.map(a=>cc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let s=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function bC(e){return e==="static"?lC:iC}function Hf(e,t){var o;let n=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,t);return{selector:Wf(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:hC(e),attributes:yC(e)}}function xC(e,t,n,r){let o=bC(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function vC(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function wC(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,p=c.tagName.toLowerCase();if(Mf.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Rf(c)){i=a.nextNode();continue}let u=Hf(c,e.maxTextLength),f=u.text.length>0,g=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(A=>A==="role");if(!f&&!g){i=a.nextNode();continue}if(r.has(u.selector)){i=a.nextNode();continue}r.add(u.selector);let{score:y,formattingRule:v}=xC(c,u,e.rules,n);o.push({el:c,domIndex:s,enriched:u,score:y,formattingRule:v}),s+=1}i=a.nextNode()}o.sort((c,p)=>{let u=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex});let d=[];for(let c of o){if(d.length>=e.maxElements)break;vC(d,c)||d.push(c)}return d.sort((c,p)=>{let u=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:u===1&&p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex}),d.map(c=>{var f;let p;if((f=c.formattingRule)!=null&&f.formatSummary){let g=c.formattingRule.formatSummary(c.el,c.enriched,n);g&&(p=g)}let u={...c.enriched};return p&&(u.formattedSummary=p),u})}function CC(e,t){let n=[],r=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,c=d.tagName.toLowerCase();if(Mf.has(c)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!Rf(d)){s=o.nextNode();continue}let p=Hf(d,e.maxTextLength),u=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(g=>g==="role");if(!u&&!f){s=o.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}s=o.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function AC(e={}){var r;let t=gC(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?CC(t,n):wC(t,n):[]}var Bi=100;function SC(e,t={}){var s;if(e.length===0)return"No page elements found.";let n=(s=t.mode)!=null?s:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
|
|
114
114
|
${a.map(i=>`- ${i.split(`
|
|
115
115
|
`).join(`
|
|
116
116
|
`)}`).join(`
|
|
117
|
-
`)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,
|
|
117
|
+
`)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Bi)}" (clickable)`);r.push(`Interactive elements:
|
|
118
118
|
${a.join(`
|
|
119
|
-
`)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,
|
|
119
|
+
`)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Bi)}" (navigable)`);r.push(`Navigation links:
|
|
120
120
|
${a.join(`
|
|
121
|
-
`)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,
|
|
121
|
+
`)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Bi)}" (input)`);r.push(`Form inputs:
|
|
122
122
|
${a.join(`
|
|
123
|
-
`)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,
|
|
123
|
+
`)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Bi)}"`);r.push(`Content:
|
|
124
124
|
${a.join(`
|
|
125
125
|
`)}`)}return r.join(`
|
|
126
126
|
|
|
127
|
-
`)}function
|
|
127
|
+
`)}function TC(){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 EC(){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 MC(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Dr(e.colors.primary,.95),100:Dr(e.colors.primary,.9),200:Dr(e.colors.primary,.8),300:Dr(e.colors.primary,.7),400:Dr(e.colors.primary,.6),500:e.colors.primary,600:Dr(e.colors.primary,.8),700:Dr(e.colors.primary,.7),800:Dr(e.colors.primary,.6),900:Dr(e.colors.primary,.5),950:Dr(e.colors.primary,.45)}}),{...t,palette:n}}}}function kC(){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 LC(){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 Dr(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(o+(255-o)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function PC(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var IC={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"}}},Bf={components:{panel:{borderRadius:"0",shadow:"none"}}},Df={id:"shop",label:"Shopping Assistant",config:{theme:IC,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:tr},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?"]}},Nf={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Bf}},Of={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Bf}},Ff={shop:Df,minimal:Nf,fullscreen:Of};function RC(e){return Ff[e]}var WC=Cf;function Yr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function HC(e){if(e)return{getHeaders:Yr(e.getHeaders),onFeedback:Yr(e.onFeedback),onCopy:Yr(e.onCopy),requestMiddleware:Yr(e.requestMiddleware),actionHandlers:Yr(e.actionHandlers),actionParsers:Yr(e.actionParsers),postprocessMessage:Yr(e.postprocessMessage),contextProviders:Yr(e.contextProviders),streamParser:Yr(e.streamParser)}}var _f=`({ text, message }: any) => {
|
|
128
128
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
129
129
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
130
130
|
let cleanJson = jsonSource
|
|
@@ -137,7 +137,7 @@ ${a.join(`
|
|
|
137
137
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
138
138
|
} catch (e) { return null; }
|
|
139
139
|
return null;
|
|
140
|
-
}
|
|
140
|
+
}`,$f=`function(ctx) {
|
|
141
141
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
142
142
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
143
143
|
var cleanJson = jsonSource
|
|
@@ -150,7 +150,7 @@ ${a.join(`
|
|
|
150
150
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
151
151
|
} catch (e) { return null; }
|
|
152
152
|
return null;
|
|
153
|
-
}`,
|
|
153
|
+
}`,jf=`(action: any, context: any) => {
|
|
154
154
|
if (action.type !== 'nav_then_click') return;
|
|
155
155
|
const payload = action.payload || action.raw || {};
|
|
156
156
|
const url = payload?.page;
|
|
@@ -167,7 +167,7 @@ ${a.join(`
|
|
|
167
167
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
168
168
|
window.location.href = targetUrl;
|
|
169
169
|
return { handled: true, displayText: text };
|
|
170
|
-
}`,
|
|
170
|
+
}`,Uf=`function(action, context) {
|
|
171
171
|
if (action.type !== 'nav_then_click') return;
|
|
172
172
|
var payload = action.payload || action.raw || {};
|
|
173
173
|
var url = payload.page;
|
|
@@ -184,26 +184,26 @@ ${a.join(`
|
|
|
184
184
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
185
185
|
window.location.href = targetUrl;
|
|
186
186
|
return { handled: true, displayText: text };
|
|
187
|
-
}`,
|
|
187
|
+
}`,BC=`(parsed: any) => {
|
|
188
188
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
189
189
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
190
190
|
if (parsed.action === 'message') return parsed.text || '';
|
|
191
191
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
192
192
|
return parsed.text || null;
|
|
193
|
-
}`,
|
|
193
|
+
}`,DC=`function(parsed) {
|
|
194
194
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
195
195
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
196
196
|
if (parsed.action === 'message') return parsed.text || '';
|
|
197
197
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
198
198
|
return parsed.text || null;
|
|
199
|
-
}`;function
|
|
200
|
-
`)}function
|
|
201
|
-
`)}function EC(e,t){let n=t==null?void 0:t.hooks,r=["// 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: '${Ea(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(r,"theme",e.theme," "),e.launcher&&ko(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"?r.push(` ${o}: ${s},`):typeof s=="number"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{r.push(` ${o}: ${s},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{r.push(` "${o}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Ri(e," ")),r.push(...Wi(e," ",n)),r.push(...Hi(e," ")),r.push(...Bi(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${vC}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${kf}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${kf}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${Pf}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${Pf}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
|
|
202
|
-
`)}function
|
|
203
|
-
`)}function
|
|
199
|
+
}`;function NC(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 Di(e){var t,n;return(n=(t=e.parserType)!=null?t:NC(e.streamParser))!=null?n:"plain"}function Ni(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,o])=>{typeof o=="string"&&n.push(`${t} ${r}: "${o}",`)}),n.push(`${t}},`)),n}function Oi(e,t,n){let r=[],o=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(o||s)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function Fi(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(r||o)&&(n.push(`${t}markdown: {`),r&&(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} },`)),o&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function _i(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(r||o)&&(n.push(`${t}layout: {`),r&&(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} },`)),o&&(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,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?n.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&n.push(`${t} ${d}: ${c},`))}),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 pc(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 qf(e,t,n){Object.entries(t).forEach(([r,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${r}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${r}: {`),qf(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(o)},`)}})}function Po(e,t,n,r){n&&(e.push(`${r}${t}: {`),qf(e,n,`${r} `),e.push(`${r}},`))}function Pa(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function OC(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let o=n?{...n,hooks:HC(n.hooks)}:void 0;return t==="esm"?FC(r,o):t==="script-installer"?jC(r,o):t==="script-advanced"?qC(r,o):t==="react-component"?_C(r,o):t==="react-advanced"?$C(r,o):UC(r,o)}function FC(e,t){let n=t==null?void 0:t.hooks,r=Di(e),o=r!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Pa(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}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Po(s,"theme",e.theme," "),e.launcher&&Po(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(...Ni(e," ")),s.push(...Oi(e," ",n)),s.push(...Fi(e," ")),s.push(..._i(e," ")),s.push(...pc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
|
|
200
|
+
`)}function _C(e,t){let n=t==null?void 0:t.hooks,r=Di(e),o=r!=="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: '${Pa(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}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Po(s,"theme",e.theme," "),e.launcher&&Po(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(...Ni(e," ")),s.push(...Oi(e," ",n)),s.push(...Fi(e," ")),s.push(..._i(e," ")),s.push(...pc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&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(`
|
|
201
|
+
`)}function $C(e,t){let n=t==null?void 0:t.hooks,r=["// 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: '${Pa(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Po(r,"theme",e.theme," "),e.launcher&&Po(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"?r.push(` ${o}: ${s},`):typeof s=="number"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{r.push(` ${o}: ${s},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{r.push(` "${o}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Ni(e," ")),r.push(...Oi(e," ",n)),r.push(...Fi(e," ")),r.push(..._i(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${BC}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${_f}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${_f}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${jf}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${jf}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
|
|
202
|
+
`)}function zf(e){var o;let t=Di(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.agentId&&(r.agentId=e.agentId),e.target&&(r.target=e.target),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((o=e.suggestionChips)==null?void 0:o.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(s[a]=i)}),Object.keys(s).length>0&&(r.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(r.markdown=s)}if(e.layout){let s={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([p,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(c[p]=u)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.messages=a)}Object.keys(s).length>0&&(r.layout=s)}return r}function jC(e,t){let n=zf(e),o=!!(t!=null&&t.windowKey||t!=null&&t.target)?{config:n,...t!=null&&t.windowKey?{windowKey:t.windowKey}:{},...t!=null&&t.target?{target:t.target}:{}}:n,s=JSON.stringify(o,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${gr}/dist/install.global.js" data-config='${s}'></script>`}function UC(e,t){let n=t==null?void 0:t.hooks,r=Di(e),o=r!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${gr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${gr}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Pa(t)}',`,...t!=null&&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}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Po(s,"theme",e.theme," "),e.launcher&&Po(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(...Ni(e," ")),s.push(...Oi(e," ",n)),s.push(...Fi(e," ")),s.push(..._i(e," ")),s.push(...pc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
|
|
203
|
+
`)}function qC(e,t){let n=t==null?void 0:t.hooks,r=zf(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
|
|
204
204
|
`).map((a,i)=>i===0?a:" "+a).join(`
|
|
205
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${
|
|
206
|
-
`)}var
|
|
205
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${gr}/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!=null&&n.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n!=null&&n.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n!=null&&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(${DC});`),s.push(" };")),s.push(""),n!=null&&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(` ${$f}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${$f}`),s.push(" ];")),s.push(""),n!=null&&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(` ${Uf}`),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(` ${Uf}`),s.push(" ];")),s.push(""),n!=null&&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!=null&&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!=null&&n.onFeedback||n!=null&&n.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&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: '${Pa(t)}',`," useShadowDom: false,",...t!=null&&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(`
|
|
206
|
+
`)}var Vf={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Kf=.1,Gf=.15,Jf=1.5,uc=24,Xf=40,zC=`
|
|
207
207
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
208
208
|
.persona-dc-root {
|
|
209
209
|
display: flex;
|
|
@@ -354,7 +354,7 @@ ${a.join(`
|
|
|
354
354
|
.persona-dc-stage {
|
|
355
355
|
height: 550px;
|
|
356
356
|
min-height: 400px;
|
|
357
|
-
padding: ${
|
|
357
|
+
padding: ${uc}px;
|
|
358
358
|
overflow: auto;
|
|
359
359
|
background: #f0f1f3;
|
|
360
360
|
background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
|
|
@@ -444,5 +444,5 @@ ${a.join(`
|
|
|
444
444
|
min-height: 300px;
|
|
445
445
|
}
|
|
446
446
|
}
|
|
447
|
-
`;function
|
|
447
|
+
`;function VC(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=zC,document.head.appendChild(e)}function KC(e,t){let n=e.clientWidth-uc*2-Xf,r=e.clientHeight-uc*2-Xf;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function GC(e,t,n,r,o){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=o==="mobile"?`${32*r}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${r})`}function JC(e,t){let{items:n,initialIndex:r=0,initialDevice:o="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:c}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");VC();let p=Math.max(0,Math.min(r,n.length-1)),u=o,f=s,g=null,y=1,v=!1,A=b("div","persona-dc-root"),T=b("div","persona-dc-toolbar"),L=b("div","persona-dc-toolbar-lead"),W=b("div","persona-dc-toolbar-trail"),R=Gt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Q(-1)}),P=b("div");P.style.position="relative";let S=b("button","persona-dc-title-btn");S.type="button",S.setAttribute("aria-expanded","false"),S.setAttribute("aria-haspopup","listbox");let H=b("span","persona-dc-title-text"),U=b("span","persona-dc-title-chevron"),j=ye("chevron-down",12,"currentColor",2);j&&U.appendChild(j),S.append(H,U);let k=b("div","persona-dc-dropdown");k.setAttribute("role","listbox"),k.style.display="none";let O=!1;function F(){k.innerHTML="";for(let he=0;he<n.length;he++){let Ke=n[he],gt=b("button","persona-dc-dropdown-item");gt.type="button",gt.setAttribute("role","option"),gt.setAttribute("aria-current",he===p?"true":"false");let Wt=b("span");if(Wt.textContent=Ke.title,gt.appendChild(Wt),Ke.description){let tt=b("span","persona-dc-dropdown-desc");tt.textContent=Ke.description,gt.appendChild(tt)}gt.addEventListener("click",()=>{Ee(),Me(he)}),k.appendChild(gt)}}function Z(){O=!O,k.style.display=O?"":"none",S.setAttribute("aria-expanded",O?"true":"false"),O&&F()}function Ee(){O&&(O=!1,k.style.display="none",S.setAttribute("aria-expanded","false"))}S.addEventListener("click",he=>{he.stopPropagation(),Z()});let de=()=>Ee();document.addEventListener("click",de),P.append(S,k);let ee=Gt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Q(1)}),Le=b("span","persona-dc-counter");L.append(R,P,ee,Le);let Pe=null;i&&(Pe=hi({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:he=>{u=he,ae.dataset.device=u,g=null,J()}}),W.appendChild(Pe.element));let ne=null;if(a){let he=b("div","persona-dc-zoom-controls"),Ke=Gt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let tt=g!=null?g:y;g=Math.max(Gf,tt-Kf),J()}});ne=b("span","persona-dc-zoom-level"),ne.title="Reset to 100%",ne.style.cursor="pointer",ne.addEventListener("click",()=>{g=1,J()});let gt=Gt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let tt=g!=null?g:y;g=Math.min(Jf,tt+Kf),J()}}),Wt=Gt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,J()}});he.append(Ke,ne,gt,Wt),W.appendChild(he)}if(d){let he=b("div","persona-dc-separator");W.appendChild(he);let Ke=hi({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:gt=>{f=gt,ae.dataset.colorScheme=f,$e()}});W.appendChild(Ke.element)}let Ae=b("div","persona-dc-separator");W.appendChild(Ae);let re=Gt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});W.appendChild(re),T.append(L,W);let se=b("div","persona-dc-stage"),ae=b("div","persona-dc-iframe-wrapper");ae.dataset.device=u,ae.dataset.colorScheme=f;let fe=b("iframe","persona-dc-iframe");fe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),fe.setAttribute("loading","lazy"),fe.title=n[p].title,ae.appendChild(fe),se.appendChild(ae),A.append(T,se),e.appendChild(A);function $e(){var he;try{let Ke=(he=fe.contentDocument)==null?void 0:he.body;if(!Ke)return;f==="dark"?Ke.classList.add("theme-dark"):Ke.classList.remove("theme-dark")}catch{}}fe.addEventListener("load",()=>$e());function V(){let he=n[p];H.textContent=he.title,Le.textContent=`${p+1} / ${n.length}`,fe.title=he.title}function Q(he){let Ke=((p+he)%n.length+n.length)%n.length;Me(Ke)}function Me(he){he<0||he>=n.length||(p=he,fe.src=n[p].url,V(),c==null||c(p,n[p]))}function J(){var gt;if(v)return;let he=(gt=Vf[u])!=null?gt:Vf.desktop;y=KC(se,he);let Ke=Math.max(Gf,Math.min(Jf,g!=null?g:y));GC(ae,fe,he,Ke,u),ne&&(ne.textContent=`${Math.round(Ke*100)}%`)}let le=new ResizeObserver(()=>J());le.observe(se),V(),fe.src=n[p].url,requestAnimationFrame(()=>J());function Ie(){v||(v=!0,le.disconnect(),document.removeEventListener("click",de),A.remove())}return{element:A,goTo:Me,next:()=>Q(1),prev:()=>Q(-1),getIndex:()=>p,setDevice(he){u=he,ae.dataset.device=he,Pe==null||Pe.setSelected(he),g=null,J()},setColorScheme(he){f=he,ae.dataset.colorScheme=he},setZoom(he){g=he,J()},destroy:Ie}}export{Om as ASK_USER_QUESTION_CLIENT_TOOL,Nm as ASK_USER_QUESTION_PARAMETERS_SCHEMA,_a as ASK_USER_QUESTION_TOOL_NAME,Es as AgentWidgetClient,ga as AgentWidgetSession,Ls as AttachmentManager,ts as BrowserSpeechEngine,pg as DEFAULT_COMPONENTS,Sl as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,tr as DEFAULT_FLOATING_LAUNCHER_WIDTH,cg as DEFAULT_PALETTE,dg as DEFAULT_SEMANTIC,Dt as DEFAULT_WIDGET_CONFIG,Ff as PRESETS,Of as PRESET_FULLSCREEN,Nf as PRESET_MINIMAL,Df as PRESET_SHOP,ks as ReadAloudController,dl as SUGGEST_REPLIES_CLIENT_TOOL,Hm as SUGGEST_REPLIES_PARAMETERS_SCHEMA,Hr as SUGGEST_REPLIES_TOOL_NAME,iv as THEME_ZONES,gr as VERSION,Rr as WEBMCP_TOOL_PREFIX,ea as WebMcpBridge,TC as accessibilityPlugin,EC as animationsPlugin,ns as applyThemeVariables,Rs as attachHeaderToContainer,MC as brandPlugin,Ta as buildComposer,Lg as buildDefaultHeader,ko as buildHeader,Sa as buildHeaderWithLayout,Pg as buildMinimalHeader,aa as builtInClientToolsForDispatch,AC as collectEnrichedPageContext,Lo as componentRegistry,Pi as createActionManager,nc as createAgentExperience,yy as createAskUserQuestionBubble,vl as createBestAvailableVoiceProvider,Uv as createBubbleWithLayout,Zl as createCSATFeedback,Wl as createComboButton,jw as createComponentMiddleware,Xl as createComponentStreamParser,pm as createDefaultSanitizer,JC as createDemoCarousel,Lh as createDirectivePostprocessor,rs as createDropdownMenu,wy as createFlexibleJsonStreamParser,Gt as createIconButton,Ry as createImagePart,hl as createJsonStreamParser,fi as createLabelButton,Jl as createLocalStorageAdapter,Oa as createMarkdownProcessor,As as createMarkdownProcessorFromConfig,_g as createMessageActions,ec as createNPSFeedback,gl as createPlainTextParser,PC as createPlugin,fl as createRegexJsonParser,Ea as createStandardBubble,Qa as createTextPart,ha as createTheme,kl as createThemeObserver,hi as createToggleGroup,Ws as createTypingIndicator,es as createVoiceProvider,Hi as createWidgetHostLayout,yl as createXmlParser,WC as default,Ns as defaultActionHandlers,Li as defaultJsonActionParser,If as defaultParseRules,ri as detectColorScheme,Ph as directivePostprocessor,sa as ensureAskUserQuestionSheet,Xr as escapeHtml,Yl as extractComponentDirectiveFromMessage,Wy as fileToImagePart,SC as formatEnrichedContext,Yo as generateAssistantMessageId,OC as generateCodeSnippet,My as generateMessageId,Wf as generateStableSelector,da as generateUserMessageId,ya as getActiveTheme,fg as getColorScheme,Ly as getDisplayText,Ig as getHeaderLayout,Iy as getImageParts,RC as getPreset,Ii as hasComponentDirective,Py as hasImages,Hl as headerLayouts,LC as highContrastPlugin,Cf as initAgentWidget,xo as isAskUserQuestionMessage,$w as isComponentDirectiveType,dn as isDockedMountMode,qa as isSuggestRepliesMessage,Za as isVoiceSupported,Jo as isWebMcpToolName,ul as latestAgentSuggestions,yv as listRegisteredStreamAnimations,lm as markdownPostprocessor,Tl as mergeWithDefaults,ky as normalizeContent,vo as parseAskUserQuestionPayload,Bm as parseSuggestRepliesPayload,ua as pickBestVoice,ki as pluginRegistry,kC as reducedMotionPlugin,fv as registerStreamAnimationPlugin,Qo as removeAskUserQuestionSheet,Ql as renderComponentDirective,Fg as renderLoadingIndicatorWithFallback,ye as renderLucideIcon,nr as resolveDockConfig,Zs as resolveSanitizer,El as resolveTokens,ol as stripWebMcpPrefix,Ml as themeToCssVariables,hv as unregisterStreamAnimationPlugin,Hy as validateImageFile,ug as validateTheme};
|
|
448
448
|
//# sourceMappingURL=index.js.map
|