@runtypelabs/persona 4.4.2 → 4.6.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-C6tFDxKy.d.cts → types-8RICZWQe.d.cts} +6 -0
- package/dist/animations/{types-C6tFDxKy.d.ts → types-8RICZWQe.d.ts} +6 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/chunk-DFBSCFYN.js +1 -0
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/index.cjs +50 -50
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +286 -11
- package/dist/index.d.ts +286 -11
- package/dist/index.global.js +39 -39
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +51 -51
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js.map +1 -1
- package/dist/markdown-parsers-entry-NVFT3TE6.js +1 -0
- package/dist/runtype-tts-entry-HFUV2UF7.js +1 -0
- package/dist/session-reconnect-U77QFUR7.js +1 -0
- package/dist/smart-dom-reader.d.cts +147 -8
- package/dist/smart-dom-reader.d.ts +147 -8
- package/dist/theme-editor-preview.cjs +48 -48
- package/dist/theme-editor-preview.d.cts +187 -9
- package/dist/theme-editor-preview.d.ts +187 -9
- package/dist/theme-editor-preview.js +48 -48
- package/dist/theme-editor.cjs +1 -1
- package/dist/theme-editor.d.cts +147 -8
- package/dist/theme-editor.d.ts +147 -8
- package/dist/theme-editor.js +1 -1
- package/package.json +2 -2
- package/src/client.ts +48 -7
- package/src/defaults.ts +9 -1
- package/src/generated/runtype-openapi-contract.ts +6 -0
- package/src/index-core.ts +5 -0
- package/src/reconnect-wake.test.ts +162 -0
- package/src/reconnect.test.ts +430 -0
- package/src/session-reconnect.ts +282 -0
- package/src/session.ts +408 -5
- package/src/types.ts +165 -9
- package/src/ui.scroll-additive.test.ts +451 -0
- package/src/ui.scroll.test.ts +8 -2
- package/src/ui.stream-animation-update.test.ts +99 -0
- package/src/ui.ts +371 -41
- package/src/utils/constants.ts +3 -1
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
"use strict";var Wg=Object.create;var ya=Object.defineProperty;var Rg=Object.getOwnPropertyDescriptor;var Hg=Object.getOwnPropertyNames;var Bg=Object.getPrototypeOf,Dg=Object.prototype.hasOwnProperty;var Is=(t,e)=>()=>(t&&(e=t(t=0)),e);var bi=(t,e)=>{for(var n in e)ya(t,n,{get:e[n],enumerable:!0})},Op=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Hg(e))!Dg.call(t,o)&&o!==n&&ya(t,o,{get:()=>e[o],enumerable:!(r=Rg(e,o))||r.enumerable});return t};var _p=(t,e,n)=>(n=t!=null?Wg(Bg(t)):{},Op(e||!t||!t.__esModule?ya(n,"default",{value:t,enumerable:!0}):n,t)),Ng=t=>Op(ya({},"__esModule",{value:!0}),t);var zp={};bi(zp,{DOMPurify:()=>Up.default,Marked:()=>$p.Marked});var $p,Up,qp=Is(()=>{"use strict";$p=require("marked"),Up=_p(require("dompurify"),1)});var ls,Hi=Is(()=>{"use strict";ls=class{constructor(e=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var o;this.sampleRate=e;let r=Math.max(0,(o=n.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(e*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 e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let n=e;if(this.remainder){let o=new Uint8Array(this.remainder.length+e.length);o.set(this.remainder),o.set(e,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 e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of e)this.scheduleSamples(n)}scheduleSamples(e){if(e.length===0)return;let n=this.ensureContext(),r=n.createBuffer(1,e.length,this.sampleRate);r.getChannelData(0).set(e);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 e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of e)n()}}pcmToFloat32(e){let n=Math.floor(e.length/2),r=new Float32Array(n),o=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function jf(t){return t.replace(/\/+$/,"")}async function Vf(t){var e,n;try{let r=await t.json();return r.detail?`${(e=r.error)!=null?e:`Runtype TTS ${t.status}`}: ${r.detail}`:(n=r.error)!=null?n:`Runtype TTS request failed (${t.status})`}catch{return`Runtype TTS request failed (${t.status})`}}var Ra,Hu=Is(()=>{"use strict";Hi();Ra=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var e,n;return(n=this.playerPromise)!=null?n:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new ls(24e3,{prebufferMs:(e=this.opts.prebufferMs)!=null?e:200})).then(r=>this.player=r)}speak(e,n){let r=++this.generation;this.run(r,e,n)}async run(e,n,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(e!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var g;e===this.generation&&((g=r.onStart)==null||g.call(r))}),d.onFinished(()=>{var g;e===this.generation&&((g=r.onEnd)==null||g.call(r))});let c=`${jf(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,u=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(e!==this.generation)return;if(!u.ok||!u.body)throw new Error(await Vf(u));let m=u.body.getReader();for(;;){let{done:g,value:f}=await m.read();if(e!==this.generation){await m.cancel().catch(()=>{});return}if(g)break;f&&f.byteLength>0&&d.enqueue(f)}d.markStreamEnd()}catch(d){if(e!==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 e;(e=this.player)==null||e.pause()}resume(){var e;(e=this.player)==null||e.resume()}stop(){var e;this.generation++,(e=this.player)==null||e.flush()}destroy(){var e;this.generation++,(e=this.player)==null||e.destroy(),this.player=null,this.playerPromise=null}}});var Ha,Bu=Is(()=>{"use strict";Ha=class{constructor(e,n,r={}){this.primary=e;this.fallback=n;this.options=r;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,n){this.active=this.primary;let r=!1;this.primary.speak(e,{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(e,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var e,n,r,o;(n=(e=this.primary).destroy)==null||n.call(e),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var Du={};bi(Du,{FallbackSpeechEngine:()=>Ha,RuntypeSpeechEngine:()=>Ra});var Nu=Is(()=>{"use strict";Hu();Bu()});var sb={};bi(sb,{createThemePreview:()=>mg});module.exports=Ng(sb);var jp=null,Ws=null,ts=null;var Vp=()=>Ws?Promise.resolve(Ws):ts||(jp?(ts=jp().then(t=>(Ws=t,t)),ts):(ts=Promise.resolve().then(()=>(qp(),zp)).then(t=>(Ws=t,t)),ts)),Po=()=>Ws;var Fg=t=>{if(t)return t},vi=t=>{let e=null;return n=>{var o,s;let r=Po();if(!r)return io(n);if(!e){let{Marked:a}=r,i=t==null?void 0:t.markedOptions;e=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=Fg(t==null?void 0:t.renderer);d&&e.use({renderer:d})}return e.parse(n)}},ba=t=>t?vi({markedOptions:t.options,renderer:t.renderer}):vi(),pb=vi();var io=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var Og={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"]},_g=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,$g=()=>{let t=null;return e=>{let n=Po();if(!n)return io(e);if(!t){let{DOMPurify:r}=n;t=r(typeof window!="undefined"?window:void 0),t.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!_g.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return t.sanitize(e,Og)}},va=t=>t===!1?null:typeof t=="function"?t:$g();var Kp=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Gp=t=>t.includes("|"),Qp=t=>{let e=t.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(n=>n.trim())},Ug=t=>`| ${t.join(" | ")} |`,zg=t=>`| ${Array.from({length:t},()=>"---").join(" | ")} |`,qg=(t,e)=>t.length>=e?t.slice(0,e):t.concat(Array.from({length:e-t.length},()=>"")),Xp=t=>{if(!t||!t.includes("|"))return t;let e=t.split(`
|
|
2
|
-
`),
|
|
3
|
-
`):
|
|
1
|
+
"use strict";var cf=Object.create;var Ca=Object.defineProperty;var df=Object.getOwnPropertyDescriptor;var pf=Object.getOwnPropertyNames;var uf=Object.getPrototypeOf,mf=Object.prototype.hasOwnProperty;var is=(n,e)=>()=>(n&&(e=n(n=0)),e);var Aa=(n,e)=>{for(var t in e)Ca(n,t,{get:e[t],enumerable:!0})},du=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of pf(e))!mf.call(n,o)&&o!==t&&Ca(n,o,{get:()=>e[o],enumerable:!(r=df(e,o))||r.enumerable});return n};var pu=(n,e,t)=>(t=n!=null?cf(uf(n)):{},du(e||!n||!n.__esModule?Ca(t,"default",{value:n,enumerable:!0}):t,n)),gf=n=>du(Ca({},"__esModule",{value:!0}),n);var gu={};Aa(gu,{DOMPurify:()=>mu.default,Marked:()=>uu.Marked});var uu,mu,fu=is(()=>{"use strict";uu=require("marked"),mu=pu(require("dompurify"),1)});var hs,Ui=is(()=>{"use strict";hs=class{constructor(e=24e3,t={}){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=e;let r=Math.max(0,(o=t.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(e*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let e=this.ctx;return e.state==="suspended"&&!this.userPaused&&e.resume(),e}enqueue(e){if(e.length===0)return;let t=e;if(this.remainder){let o=new Uint8Array(this.remainder.length+e.length);o.set(this.remainder),o.set(e,this.remainder.length),t=o,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.pcmToFloat32(t);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 e of this.activeSources)try{e.stop(),e.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(e){this.finishedCallbacks.push(e)}onStarted(e){this.startedCallbacks.push(e)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let e=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let t of e)this.scheduleSamples(t)}scheduleSamples(e){if(e.length===0)return;let t=this.ensureContext(),r=t.createBuffer(1,e.length,this.sampleRate);r.getChannelData(0).set(e);let o=t.createBufferSource();o.buffer=r,o.connect(t.destination);let s=t.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 e=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of e)t()}}pcmToFloat32(e){let t=Math.floor(e.length/2),r=new Float32Array(t),o=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let s=0;s<t;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function xh(n){return n.replace(/\/+$/,"")}async function Ch(n){var e,t;try{let r=await n.json();return r.detail?`${(e=r.error)!=null?e:`Runtype TTS ${n.status}`}: ${r.detail}`:(t=r.error)!=null?t:`Runtype TTS request failed (${n.status})`}catch{return`Runtype TTS request failed (${n.status})`}}var Oa,sm=is(()=>{"use strict";Ui();Oa=class{constructor(e){this.opts=e;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var e,t;return(t=this.playerPromise)!=null?t:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new hs(24e3,{prebufferMs:(e=this.opts.prebufferMs)!=null?e:200})).then(r=>this.player=r)}speak(e,t){let r=++this.generation;this.run(r,e,t)}async run(e,t,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(e!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var h;e===this.generation&&((h=r.onStart)==null||h.call(r))}),d.onFinished(()=>{var h;e===this.generation&&((h=r.onEnd)==null||h.call(r))});let c=`${xh(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:t.text,voice:(o=t.voice)!=null?o:this.opts.voice,format:"pcm"})});if(e!==this.generation)return;if(!p.ok||!p.body)throw new Error(await Ch(p));let g=p.body.getReader();for(;;){let{done:h,value:m}=await g.read();if(e!==this.generation){await g.cancel().catch(()=>{});return}if(h)break;m&&m.byteLength>0&&d.enqueue(m)}d.markStreamEnd()}catch(d){if(e!==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 e;(e=this.player)==null||e.pause()}resume(){var e;(e=this.player)==null||e.resume()}stop(){var e;this.generation++,(e=this.player)==null||e.flush()}destroy(){var e;this.generation++,(e=this.player)==null||e.destroy(),this.player=null,this.playerPromise=null}}});var _a,am=is(()=>{"use strict";_a=class{constructor(e,t,r={}){this.primary=e;this.fallback=t;this.options=r;this.id="fallback";this.active=e}get supportsPause(){return this.active.supportsPause}speak(e,t){this.active=this.primary;let r=!1;this.primary.speak(e,{onStart:()=>{var o;r=!0,(o=t.onStart)==null||o.call(t)},onEnd:()=>{var o;return(o=t.onEnd)==null?void 0:o.call(t)},onError:o=>{var s,a,i;if(r){(s=t.onError)==null||s.call(t,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(e,t)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var e,t,r,o;(t=(e=this.primary).destroy)==null||t.call(e),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var im={};Aa(im,{FallbackSpeechEngine:()=>_a,RuntypeSpeechEngine:()=>Oa});var lm=is(()=>{"use strict";sm();am()});var dm={};Aa(dm,{createReconnectController:()=>Sh});function Sh(n){let e=0,t=null,r=null,o=!1,s=()=>{if(r&&(clearTimeout(r),r=null),t){let y=t;t=null,y()}},a=()=>{let y=n.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)},g=y=>new Promise(w=>{t=w,r=setTimeout(()=>{r=null,t=null,w()},y)}),h=()=>{var B;let y=n.getResumable();n.clearResumable(),n.setReconnecting(!1),e=0,p(),n.setAbortController(null);let w=!1;for(let T of n.getMessages())T.streaming&&(T.streaming=!1,w=!0);let E=n.buildErrorContent("Connection lost and the response could not be resumed.");E?n.appendMessage({id:`reconnect-failed-${(B=y==null?void 0:y.executionId)!=null?B:n.nextSequence()}`,role:"assistant",content:E,createdAt:new Date().toISOString(),streaming:!1,sequence:n.nextSequence()}):w&&n.notifyMessagesChanged(),n.setStreaming(!1),n.setStatus("idle"),n.onError(new Error("Durable session reconnect failed."))},m=async()=>{var B,T,I,M,P,C;let y=(T=(B=n.config.reconnect)==null?void 0:B.backoffMs)!=null?T:Ah,w=(M=(I=n.config.reconnect)==null?void 0:I.maxAttempts)!=null?M:y.length,E=n.config.reconnectStream;if(!E){n.setReconnecting(!1);return}for(;n.getResumable()&&e<w;){e+=1,n.setStatus("resuming");let k=n.getResumable(),q=k.lastEventId,_=new AbortController;n.setAbortController(_),n.emitReconnect({phase:"resuming",handle:k,attempt:e});let R=null;try{let O=await E({executionId:k.executionId,after:k.lastEventId,signal:_.signal});O&&O.ok&&O.body&&(R=O.body)}catch{R=null}if(_.signal.aborted)return;if(R){let O=(P=n.getMessages().find(Z=>Z.id===k.assistantMessageId))==null?void 0:P.content,F=typeof O=="string"?O:"";try{await n.resumeConnect(R,k.assistantMessageId,F)}catch{}if(_.signal.aborted)return;if(!n.getResumable()){n.setReconnecting(!1),e=0,p(),n.emitReconnect({phase:"resumed",handle:k});return}n.getResumable().lastEventId!==q&&(e=0)}if(n.getResumable()&&e<w&&(n.setStatus("paused"),await g((C=y[Math.min(e-1,y.length-1)])!=null?C:1e3),_.signal.aborted))return}n.getResumable()&&h()};return{begin(){e=0,c(),m()},teardown(){r&&(clearTimeout(r),r=null),t=null,e=0,p()},wake:s}}var Ah,pm=is(()=>{"use strict";Ah=[1e3,2e3,4e3,8e3,8e3]});var Nb={};Aa(Nb,{createThemePreview:()=>Og});module.exports=gf(Nb);var hu=null,Us=null,ls=null;var yu=()=>Us?Promise.resolve(Us):ls||(hu?(ls=hu().then(n=>(Us=n,n)),ls):(ls=Promise.resolve().then(()=>(fu(),gu)).then(n=>(Us=n,n)),ls)),Oo=()=>Us;var ff=n=>{if(n)return n},Mi=n=>{let e=null;return t=>{var o,s;let r=Oo();if(!r)return go(t);if(!e){let{Marked:a}=r,i=n==null?void 0:n.markedOptions;e=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=ff(n==null?void 0:n.renderer);d&&e.use({renderer:d})}return e.parse(t)}},Sa=n=>n?Mi({markedOptions:n.options,renderer:n.renderer}):Mi(),qb=Mi();var go=n=>n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");var hf={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"]},yf=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,bf=()=>{let n=null;return e=>{let t=Oo();if(!t)return go(e);if(!n){let{DOMPurify:r}=t;n=r(typeof window!="undefined"?window:void 0),n.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!yf.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return n.sanitize(e,hf)}},Ta=n=>n===!1?null:typeof n=="function"?n:bf();var bu=/^\s*\|?[\s:|-]*-[\s:|-]*$/,vu=n=>n.includes("|"),wu=n=>{let e=n.trim();return e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&(e=e.slice(0,-1)),e.split("|").map(t=>t.trim())},vf=n=>`| ${n.join(" | ")} |`,wf=n=>`| ${Array.from({length:n},()=>"---").join(" | ")} |`,xf=(n,e)=>n.length>=e?n.slice(0,e):n.concat(Array.from({length:e-n.length},()=>"")),xu=n=>{if(!n||!n.includes("|"))return n;let e=n.split(`
|
|
2
|
+
`),t=!1;for(let r=0;r<e.length-1;r++){let o=e[r],s=e[r+1];if(!vu(o)||bu.test(o)||!bu.test(s))continue;let a=wu(o).length;if(a<1)continue;let i=wf(a);e[r+1]!==i&&(e[r+1]=i,t=!0);let d=r+2;for(;d<e.length;d++){let c=e[d];if(c.trim()===""||!vu(c))break;let p=vf(xf(wu(c),a));e[d]!==p&&(e[d]=p,t=!0)}r=d-1}return t?e.join(`
|
|
3
|
+
`):n};var qr="webmcp:",ki=new Map,Cu=n=>{var e;ki.clear();for(let t of n){let r=(e=t.title)==null?void 0:e.trim();r&&ki.set(t.name,r)}},qs=n=>ki.get(Eu(n)),Ea={warn(n,...e){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${n}`,...e)}},Au=null;function Tu(n){if(n.length===0)return"0:empty";let e=n.map(t=>{var r,o;return[t.name,(r=t.description)!=null?r:"",t.parametersSchema?JSON.stringify(t.parametersSchema):"",(o=t.origin)!=null?o:"",t.annotations?JSON.stringify(t.annotations):""].join("")}).sort();return`${n.length}:${Cf(e.join(""))}`}function Su(n,e){let t=3735928559^e,r=1103547991^e;for(let o=0;o<n.length;o++){let s=n.charCodeAt(o);t=Math.imul(t^s,2654435761),r=Math.imul(r^s,1597334677)}return t=Math.imul(t^t>>>16,2246822507),t^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(t^t>>>13,3266489909),4294967296*(2097151&r)+(t>>>0)}function Cf(n){let e=Su(n,0).toString(36),t=Su(n,2654435761).toString(36);return`${e}.${t}`}var Ma=class{constructor(e){this.config=e;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var t;this.confirmHandler=(t=e.onConfirm)!=null?t:null,this.timeoutMs=3e4}setConfirmHandler(e){this.confirmHandler=e}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let e=this.getModelContext();if(!e)return[];let t;try{t=await e.getTools()}catch(o){return Ea.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}Cu(t);let r=typeof location!="undefined"?location.origin:"";return t.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Sf(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(e,t,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=Eu(e),a;try{a=await o.getTools()}catch(y){let w=y instanceof Error?y.message:String(y);return mr(`Failed to read WebMCP registry: ${w}`)}Cu(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=qs(s),c={toolName:s,args:t,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,g=!1,h=setTimeout(()=>{g=!0,p.abort()},this.timeoutMs),m=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",m,{once:!0}));try{let y=await o.executeTool(i,kf(t),{signal:p.signal});return Tf(y)}catch(y){if(g)return mr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return mr("Aborted by cancel()");let w=y instanceof Error?y.message:String(y);return mr(w)}finally{clearTimeout(h),r&&r.removeEventListener("abort",m)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Au?await Au():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(e){Ea.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",e),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let e=document.modelContext;if(!e||typeof e!="object")return null;let t=e;return typeof t.getTools!="function"||typeof t.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Ea.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):e}async requestConfirm(e){var r;let t=(r=this.confirmHandler)!=null?r:Ef;try{return await t(e)}catch(o){return Ea.warn(`Confirm handler threw for WebMCP tool '${e.toolName}'; declining.`,o),!1}}passesClientAllowlist(e){let t=this.config.allowlist;return!t||t.length===0?!0:t.some(r=>Af(e,r))}},Eu=n=>n.startsWith(qr)?n.slice(qr.length):n,cs=n=>n.startsWith(qr),Af=(n,e)=>{if(e==="*")return!0;let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*")+"$").test(n)},Sf=n=>{if(!(n===void 0||n===""))try{let e=JSON.parse(n);return e!==null&&typeof e=="object"?e:void 0}catch{return}},Tf=n=>{if(n==null)return{content:[{type:"text",text:""}]};let e;try{e=JSON.parse(n)}catch{return{content:[{type:"text",text:n}]}}return e!==null&&typeof e=="object"&&Array.isArray(e.content)?e:{content:[{type:"text",text:typeof e=="string"?e:Lf(e)}]}},mr=n=>({isError:!0,content:[{type:"text",text:n}]}),Ef=async n=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let e=Mf(n.args),t=`Allow the AI to call ${n.toolName}`+(e?`
|
|
4
4
|
|
|
5
5
|
Arguments:
|
|
6
|
-
${e}`:"")+(
|
|
6
|
+
${e}`:"")+(n.description?`
|
|
7
7
|
|
|
8
|
-
${t.description}`:"");return window.confirm(n)},Xg=t=>{if(t==null)return"";try{let e=JSON.stringify(t,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(t)}},Jg=t=>{if(t===void 0)return"{}";try{let e=JSON.stringify(t);return e===void 0?"{}":e}catch{return"{}"}},Yg=t=>{if(t===void 0)return"";try{return JSON.stringify(t)}catch{return String(t)}};var Zg="agent_",ef="flow_";function nu(t){return t.startsWith(Zg)?{kind:"agentId",agentId:t}:t.startsWith(ef)?{kind:"flowId",flowId:t}:null}function ru(t,e){let n=t.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=nu(i);if(c)return c;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=e==null?void 0:e[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(i).payload}}let o=nu(n);if(o)return o;let s=e==null?void 0:e.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var lo=require("partial-json");var b=(t,e)=>{let n=document.createElement(t);return e&&(n.className=e),n},Ir=(t,e,n)=>{let r=t.createElement(e);return n&&(r.className=n),r};var Et=(t,e={},...n)=>{let r=document.createElement(t);if(e.className&&(r.className=e.className),e.text!==void 0&&(r.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))r.setAttribute(s,a);if(e.style){let s=r.style,a=e.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},Hs=(...t)=>t.filter(Boolean).join(" ");var xi="ask_user_question",Bs=8,rs="data-persona-ask-sheet-for",tf="Other",nf="Other\u2026",su="Type your own answer here",au="Send",rf="Next",of="Back",sf="Submit all",af="Skip",lf=3,Ci="data-ask-current-index",Ai="data-ask-question-count",iu="data-ask-answers",Si="data-ask-grouped",lu="data-ask-layout",cf=t=>t.layout==="pills"?"pills":"rows",df=t=>t.getAttribute(lu)==="pills"?"pills":"rows",ou=!1,cu=t=>t.replace(/["\\]/g,"\\$&"),Io=t=>t.variant==="tool"&&!!t.toolCall&&t.toolCall.name===xi,Ti=t=>{var e,n;return(n=(e=t==null?void 0:t.features)==null?void 0:e.askUserQuestion)!=null?n:{}},os=t=>{let e=t.toolCall;if(!e)return{payload:null,complete:!1};let n=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:n};let r=e.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=(0,lo.parse)(o,lo.STR|lo.OBJ|lo.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Ds=t=>{let e=Array.isArray(t==null?void 0:t.questions)?t.questions:[];return e.length>Bs&&!ou&&(ou=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${Bs}.`)),e.slice(0,Bs)},pf=t=>{var e;return(e=Ds(t)[0])!=null?e:null},uf=(t,e)=>{var n;return(n=Ds(t)[e])!=null?n:null},mf=(t,e)=>{let n=e.styles;n&&(n.sheetBackground&&t.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&t.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&t.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&t.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&t.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&t.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&t.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&t.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&t.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},du=(t,e,n)=>{if(t!=="rows")return null;let r=b("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),e){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},gf=(t,e,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(e)),s.setAttribute("data-option-label",t.label),n==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=t.label,a.appendChild(i),t.description){let c=b("span","persona-ask-row-description");c.textContent=t.description,a.appendChild(c)}s.appendChild(a);let d=du(n,r,e);d&&s.appendChild(d)}else s.textContent=t.label,t.description&&(s.title=t.description);return s},ff=t=>{let n=b("span",t==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},hf=(t,e,n,r)=>{var u,m,g;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=!!(t!=null&&t.multiSelect),d=(Array.isArray(t==null?void 0:t.options)?t.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!n){for(let f=0;f<lf;f++)s.appendChild(ff(r));return s}if(d.forEach((f,w)=>{s.appendChild(gf(f,w,r,a))}),(t==null?void 0:t.allowFreeText)!==!1){let f=r==="rows"?tf:nf;if(r==="rows"){let w=b("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");w.setAttribute("data-ask-user-action","focus-free-text"),w.setAttribute("data-option-index",String(d.length)),w.setAttribute("data-ask-other-row","true");let v=b("span","persona-ask-row-content"),k=document.createElement("input");k.type="text",k.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",k.placeholder=(u=e.freeTextPlaceholder)!=null?u:su,k.setAttribute("data-ask-free-text-input","true"),k.setAttribute("aria-label",(m=e.freeTextLabel)!=null?m:f),v.appendChild(k),w.appendChild(v);let R=du(r,a,d.length);R&&w.appendChild(R),s.appendChild(w)}else{let w=b("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");w.type="button",w.setAttribute("data-ask-user-action","open-free-text"),w.textContent=(g=e.freeTextLabel)!=null?g:f,s.appendChild(w)}}return s},pu=(t,e)=>{var s,a;let r=b("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");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=t.freeTextPlaceholder)!=null?s:su,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),e!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=t.submitLabel)!=null?a:au,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},yf=t=>{var r;let e=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.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=t.submitLabel)!=null?r:au,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,e.appendChild(n),e},bf=(t,e,n)=>{var c,u,m,g;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:of,o.setAttribute("data-ask-user-action","back"),o.disabled=t===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=(u=n.skipLabel)!=null?u:af,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=t===e-1;return i.textContent=d?(m=n.submitAllLabel)!=null?m:sf:(g=n.nextLabel)!=null?g:rf,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Wo=t=>{let e=t.getAttribute(iu);if(!e)return{};try{let n=JSON.parse(e);return n&&typeof n=="object"?n:{}}catch{return{}}},uu=(t,e)=>{t.setAttribute(iu,JSON.stringify(e))},sr=t=>{var n;let e=Number((n=t.getAttribute(Ci))!=null?n:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},vf=(t,e)=>{t.setAttribute(Ci,String(Math.max(0,Math.floor(e))))},ss=t=>{var n;let e=Number((n=t.getAttribute(Ai))!=null?n:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},co=t=>t.getAttribute(Si)==="true",wf=(t,e)=>{var o;let n=(o=t.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return e.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},xf=(t,e)=>{var r;let n=(r=t.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(e-1,Math.floor(n)))},Ca=(t,e)=>{let{payload:n}=os(e),r=Ds(n),o=Wo(t),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},mu=t=>{let e=Wo(t),n=sr(t),r=e[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=t.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var m;let c=(m=d.getAttribute("data-option-label"))!=null?m:"",u=o.has(c);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=t.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=""},gu=t=>{if(!co(t))return;let e=Wo(t),n=sr(t),r=e[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=t.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=t.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Ei=(t,e,n)=>{let r=Ti(n),o=df(t),{payload:s,complete:a}=os(e),i=co(t),d=sr(t),c=ss(t),u=i?uf(s,d):pf(s),m=!!(u!=null&&u.multiSelect),g=t.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${c}`:"");let f=t.querySelector('[data-ask-stepper="true"]');f&&f.remove();let w=t.querySelector('[data-ask-question="true"]');if(w){let E=typeof(u==null?void 0:u.question)=="string"?u.question:"";w.textContent=E,w.classList.toggle("persona-ask-question-skeleton",!E&&!a)}let v=t.querySelector('[data-ask-pill-list="true"]');if(v){let E=hf(u,r,a,o);v.replaceWith(E)}if(o!=="rows"){let E=t.querySelector('[data-ask-free-text-row="true"]');E&&E.replaceWith(pu(r,o))}let k=t.querySelector('[data-ask-multi-actions="true"]');!i&&m&&!k?t.appendChild(yf(r)):(!m||i)&&k&&k.remove(),t.setAttribute("data-multi-select",m?"true":"false");let R=t.querySelector('[data-ask-nav-row="true"]');if(i){let E=bf(d,c,r);R?R.replaceWith(E):t.appendChild(E)}else R&&R.remove();mu(t),gu(t)},Cf=(t,e,n)=>{let r=Ti(e),o=cf(r),s=t.toolCall.id,a=Ds(n),i=Math.max(1,a.length),d=i>1,c=wf(t,a),u=d?xf(t,i):0,m=b("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));m.setAttribute(rs,s),m.setAttribute("data-tool-call-id",s),m.setAttribute("data-message-id",t.id),m.setAttribute(Ai,String(i)),m.setAttribute(Ci,String(u)),m.setAttribute(Si,d?"true":"false"),m.setAttribute(lu,o),uu(m,c),m.setAttribute("role","group"),m.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&m.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),mf(m,r);let g=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=b("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let w=b("span","persona-ask-sheet-step-inline");w.setAttribute("data-ask-step-inline","true"),w.textContent="",g.appendChild(w),m.appendChild(g);let k=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 k.setAttribute("data-ask-pill-list","true"),k.setAttribute("role","group"),m.appendChild(k),o!=="rows"&&m.appendChild(pu(r,o)),Ei(m,t,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>m.classList.remove("persona-ask-sheet-enter"))}),m},Af=(t,e,n)=>{let{payload:r}=os(e),o=Math.max(1,Ds(r).length);o>ss(t)&&(t.setAttribute(Ai,String(o)),o>1&&!co(t)&&t.setAttribute(Si,"true")),Ei(t,e,n)};var Aa=(t,e,n)=>{if(!n||!Io(t)||Ti(e).enabled===!1)return;let o=t.toolCall.id;n.querySelectorAll(`[${rs}]`).forEach(c=>{c.getAttribute(rs)!==o&&c.remove()});let a=n.querySelector(`[${rs}="${cu(o)}"]`);if(a){Af(a,t,e);return}let{payload:i}=os(t),d=Cf(t,e,i);n.appendChild(d)},as=(t,e)=>{if(!t)return;let n=e?`[${rs}="${cu(e)}"]`:`[${rs}]`;t.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)})},Mi=t=>Array.from(t.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),po=(t,e)=>{let n=Wo(t),r=sr(t);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete n[r]:n[r]=e,uu(t,n),mu(t),gu(t)},Sa=(t,e,n,r)=>{let o=ss(t),s=Math.max(0,Math.min(o-1,r));vf(t,s),Ei(t,e,n)};var zr="suggest_replies";var Sf={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},fu={name:zr,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:Sf,origin:"sdk",annotations:{readOnlyHint:!0}},ki=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Li=t=>{var e;return t.variant==="tool"&&((e=t.toolCall)==null?void 0:e.name)===zr},Tf=t=>{let e=t;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let n=e==null?void 0:e.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},hu=t=>{var e;for(let n=t.length-1;n>=0;n--){let r=t[n];if(r.role==="user")return null;if(!Li(r))continue;let o=Tf((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},yu=t=>{var n;let e=(n=t==null?void 0:t.features)==null?void 0:n.suggestReplies;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1};var Ef={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Bs,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},Mf={name:xi,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:Ef,origin:"sdk",annotations:{readOnlyHint:!0}},Pi=t=>{var r;let e=[],n=(r=t==null?void 0:t.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&e.push(Mf),yu(t)&&e.push(fu),e};var is=require("partial-json"),bu=t=>t.replace(/\\n/g,`
|
|
9
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
8
|
+
${n.description}`:"");return window.confirm(t)},Mf=n=>{if(n==null)return"";try{let e=JSON.stringify(n,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(n)}},kf=n=>{if(n===void 0)return"{}";try{let e=JSON.stringify(n);return e===void 0?"{}":e}catch{return"{}"}},Lf=n=>{if(n===void 0)return"";try{return JSON.stringify(n)}catch{return String(n)}};var Pf="agent_",If="flow_";function Mu(n){return n.startsWith(Pf)?{kind:"agentId",agentId:n}:n.startsWith(If)?{kind:"flowId",flowId:n}:null}function ku(n,e){let t=n.trim();if(!t)throw new Error("[Persona] `target` is empty.");let r=t.indexOf(":");if(r>0){let a=t.slice(0,r),i=t.slice(r+1);if(a==="runtype"){let c=Mu(i);if(c)return c;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=e==null?void 0:e[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(i).payload}}let o=Mu(t);if(o)return o;let s=e==null?void 0:e.default;if(s)return{kind:"payload",payload:s(t).payload};throw new Error(`[Persona] target "${t}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${t}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var fo=require("partial-json");var v=(n,e)=>{let t=document.createElement(n);return e&&(t.className=e),t},Ir=(n,e,t)=>{let r=n.createElement(e);return t&&(r.className=t),r};var Mt=(n,e={},...t)=>{let r=document.createElement(n);if(e.className&&(r.className=e.className),e.text!==void 0&&(r.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))r.setAttribute(s,a);if(e.style){let s=r.style,a=e.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=t.filter(s=>s!=null);return o.length>0&&r.append(...o),r},zs=(...n)=>n.filter(Boolean).join(" ");var Li="ask_user_question",js=8,ds="data-persona-ask-sheet-for",Rf="Other",Wf="Other\u2026",Pu="Type your own answer here",Iu="Send",Hf="Next",Bf="Back",Df="Submit all",Nf="Skip",Ff=3,Pi="data-ask-current-index",Ii="data-ask-question-count",Ru="data-ask-answers",Ri="data-ask-grouped",Wu="data-ask-layout",Of=n=>n.layout==="pills"?"pills":"rows",_f=n=>n.getAttribute(Wu)==="pills"?"pills":"rows",Lu=!1,Hu=n=>n.replace(/["\\]/g,"\\$&"),_o=n=>n.variant==="tool"&&!!n.toolCall&&n.toolCall.name===Li,Wi=n=>{var e,t;return(t=(e=n==null?void 0:n.features)==null?void 0:e.askUserQuestion)!=null?t:{}},ps=n=>{let e=n.toolCall;if(!e)return{payload:null,complete:!1};let t=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:t};let r=e.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let o=r.join(""),s=(0,fo.parse)(o,fo.STR|fo.OBJ|fo.ARR);if(s&&typeof s=="object")return{payload:s,complete:t}}catch{}return{payload:null,complete:t}},Vs=n=>{let e=Array.isArray(n==null?void 0:n.questions)?n.questions:[];return e.length>js&&!Lu&&(Lu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${js}.`)),e.slice(0,js)},$f=n=>{var e;return(e=Vs(n)[0])!=null?e:null},Uf=(n,e)=>{var t;return(t=Vs(n)[e])!=null?t:null},qf=(n,e)=>{let t=e.styles;t&&(t.sheetBackground&&n.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&n.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&n.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&n.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&n.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&n.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&n.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&n.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&n.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},Bu=(n,e,t)=>{if(n!=="rows")return null;let r=v("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),e){let o=v("span","persona-ask-row-check");r.appendChild(o)}else{let o=v("span","persona-ask-row-badge");o.textContent=String(t+1),r.appendChild(o)}return r},zf=(n,e,t,r)=>{let s=v("button",t==="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(e)),s.setAttribute("data-option-label",n.label),t==="rows"){let a=v("span","persona-ask-row-content"),i=v("span","persona-ask-row-label");if(i.textContent=n.label,a.appendChild(i),n.description){let c=v("span","persona-ask-row-description");c.textContent=n.description,a.appendChild(c)}s.appendChild(a);let d=Bu(t,r,e);d&&s.appendChild(d)}else s.textContent=n.label,n.description&&(s.title=n.description);return s},jf=n=>{let t=v("span",n==="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 t.setAttribute("aria-hidden","true"),t},Vf=(n,e,t,r)=>{var p,g,h;let s=v("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(n!=null&&n.multiSelect),d=(Array.isArray(n==null?void 0:n.options)?n.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!t){for(let m=0;m<Ff;m++)s.appendChild(jf(r));return s}if(d.forEach((m,y)=>{s.appendChild(zf(m,y,r,a))}),(n==null?void 0:n.allowFreeText)!==!1){let m=r==="rows"?Rf:Wf;if(r==="rows"){let y=v("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 w=v("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(p=e.freeTextPlaceholder)!=null?p:Pu,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(g=e.freeTextLabel)!=null?g:m),w.appendChild(E),y.appendChild(w);let B=Bu(r,a,d.length);B&&y.appendChild(B),s.appendChild(y)}else{let y=v("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=(h=e.freeTextLabel)!=null?h:m,s.appendChild(y)}}return s},Du=(n,e)=>{var s,a;let r=v("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");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=n.freeTextPlaceholder)!=null?s:Pu,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),e!=="rows"){let i=v("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=n.submitLabel)!=null?a:Iu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Kf=n=>{var r;let e=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let t=v("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=n.submitLabel)!=null?r:Iu,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,e.appendChild(t),e},Gf=(n,e,t)=>{var c,p,g,h;let r=v("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=v("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=t.backLabel)!=null?c:Bf,o.setAttribute("data-ask-user-action","back"),o.disabled=n===0,r.appendChild(o);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=v("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=t.skipLabel)!=null?p:Nf,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=v("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=n===e-1;return i.textContent=d?(g=t.submitAllLabel)!=null?g:Df:(h=t.nextLabel)!=null?h:Hf,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},$o=n=>{let e=n.getAttribute(Ru);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Nu=(n,e)=>{n.setAttribute(Ru,JSON.stringify(e))},tr=n=>{var t;let e=Number((t=n.getAttribute(Pi))!=null?t:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Qf=(n,e)=>{n.setAttribute(Pi,String(Math.max(0,Math.floor(e))))},us=n=>{var t;let e=Number((t=n.getAttribute(Ii))!=null?t:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},ho=n=>n.getAttribute(Ri)==="true",Xf=(n,e)=>{var o;let t=(o=n.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return e.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Jf=(n,e)=>{var r;let t=(r=n.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(e-1,Math.floor(t)))},ka=(n,e)=>{let{payload:t}=ps(e),r=Vs(t),o=$o(n),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},Fu=n=>{let e=$o(n),t=tr(n),r=e[t],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=n.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var g;let c=(g=d.getAttribute("data-option-label"))!=null?g:"",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=n.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=""},Ou=n=>{if(!ho(n))return;let e=$o(n),t=tr(n),r=e[t],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=n.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=n.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Hi=(n,e,t)=>{let r=Wi(t),o=_f(n),{payload:s,complete:a}=ps(e),i=ho(n),d=tr(n),c=us(n),p=i?Uf(s,d):$f(s),g=!!(p!=null&&p.multiSelect),h=n.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=i?`${d+1}/${c}`:"");let m=n.querySelector('[data-ask-stepper="true"]');m&&m.remove();let y=n.querySelector('[data-ask-question="true"]');if(y){let T=typeof(p==null?void 0:p.question)=="string"?p.question:"";y.textContent=T,y.classList.toggle("persona-ask-question-skeleton",!T&&!a)}let w=n.querySelector('[data-ask-pill-list="true"]');if(w){let T=Vf(p,r,a,o);w.replaceWith(T)}if(o!=="rows"){let T=n.querySelector('[data-ask-free-text-row="true"]');T&&T.replaceWith(Du(r,o))}let E=n.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!E?n.appendChild(Kf(r)):(!g||i)&&E&&E.remove(),n.setAttribute("data-multi-select",g?"true":"false");let B=n.querySelector('[data-ask-nav-row="true"]');if(i){let T=Gf(d,c,r);B?B.replaceWith(T):n.appendChild(T)}else B&&B.remove();Fu(n),Ou(n)},Yf=(n,e,t)=>{let r=Wi(e),o=Of(r),s=n.toolCall.id,a=Vs(t),i=Math.max(1,a.length),d=i>1,c=Xf(n,a),p=d?Jf(n,i):0,g=v("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(ds,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",n.id),g.setAttribute(Ii,String(i)),g.setAttribute(Pi,String(p)),g.setAttribute(Ri,d?"true":"false"),g.setAttribute(Wu,o),Nu(g,c),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),qf(g,r);let h=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=v("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",h.appendChild(m);let y=v("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",h.appendChild(y),g.appendChild(h);let E=v("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),g.appendChild(E),o!=="rows"&&g.appendChild(Du(r,o)),Hi(g,n,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},Zf=(n,e,t)=>{let{payload:r}=ps(e),o=Math.max(1,Vs(r).length);o>us(n)&&(n.setAttribute(Ii,String(o)),o>1&&!ho(n)&&n.setAttribute(Ri,"true")),Hi(n,e,t)};var La=(n,e,t)=>{if(!t||!_o(n)||Wi(e).enabled===!1)return;let o=n.toolCall.id;t.querySelectorAll(`[${ds}]`).forEach(c=>{c.getAttribute(ds)!==o&&c.remove()});let a=t.querySelector(`[${ds}="${Hu(o)}"]`);if(a){Zf(a,n,e);return}let{payload:i}=ps(n),d=Yf(n,e,i);t.appendChild(d)},ms=(n,e)=>{if(!n)return;let t=e?`[${ds}="${Hu(e)}"]`:`[${ds}]`;n.querySelectorAll(t).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)})},Bi=n=>Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),yo=(n,e)=>{let t=$o(n),r=tr(n);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete t[r]:t[r]=e,Nu(n,t),Fu(n),Ou(n)},Pa=(n,e,t,r)=>{let o=us(n),s=Math.max(0,Math.min(o-1,r));Qf(n,s),Hi(n,e,t)};var zr="suggest_replies";var eh={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},_u={name:zr,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:eh,origin:"sdk",annotations:{readOnlyHint:!0}},Di=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ni=n=>{var e;return n.variant==="tool"&&((e=n.toolCall)==null?void 0:e.name)===zr},th=n=>{let e=n;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let t=e==null?void 0:e.suggestions;if(!Array.isArray(t))return[];let r=t.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},$u=n=>{var e;for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.role==="user")return null;if(!Ni(r))continue;let o=th((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},Uu=n=>{var t;let e=(t=n==null?void 0:n.features)==null?void 0:t.suggestReplies;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1};var nh={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:js,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},rh={name:Li,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:nh,origin:"sdk",annotations:{readOnlyHint:!0}},Fi=n=>{var r;let e=[],t=(r=n==null?void 0:n.features)==null?void 0:r.askUserQuestion;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1&&e.push(rh),Uu(n)&&e.push(_u),e};var gs=require("partial-json"),qu=n=>n.replace(/\\n/g,`
|
|
9
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),bo=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},oh=n=>{var a,i;let e=(a=n.completedAt)!=null?a:Date.now(),t=(i=n.startedAt)!=null?i:e,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-t))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},zu=n=>n.status==="complete"?oh(n):n.status==="pending"?"Waiting":"",sh=n=>{var o,s,a;let t=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((a=(s=n.startedAt)!=null?s:n.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var ju=n=>n.status==="complete"?sh(n):"Using tool...",Ia=n=>{let e=n/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Gs=n=>{var t,r,o;let e=typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((t=n.completedAt)!=null?t:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return Ia(e)},Ra=n=>{var t,r,o;let e=n.durationMs!==void 0?n.durationMs:Math.max(0,((t=n.completedAt)!=null?t:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return Ia(e)},Oi=(n,e,t)=>{var s;if(!e)return t;let r=((s=n.name)==null?void 0:s.trim())||"tool",o=Gs(n);return e.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Wa=(n,e)=>{let t=n.replace(/\{toolName\}/g,e),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(t))!==null;)a.index>s&&Ks(r,t.slice(s,a.index),[]),a[1]!==void 0?Ks(r,a[1],["bold"]):a[2]!==void 0?Ks(r,a[2],["italic"]):a[3]!==void 0&&Ks(r,a[3],["dim"]),s=a.index+a[0].length;return s<t.length&&Ks(r,t.slice(s),[]),r},Ks=(n,e,t)=>{let r=e.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&n.push({text:r[o],styles:t}),o<r.length-1&&n.push({text:"{duration}",styles:t,isDuration:!0})},ah=()=>{let n=null,e=0,t=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:()=>t,processChunk:async r=>{if(r.length<=e)return t!==null?{text:t,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(t=s),e=r.length,t!==null?{text:t,raw:r}:null},close:async()=>{}}},Os=t=>{try{let e=JSON.parse(t);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},xu=()=>{let t={processChunk:e=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},Cu=()=>{var e;let t=Pf();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:t.processChunk(n)},getExtractedText:t.getExtractedText.bind(t),close:(e=t.close)==null?void 0:e.bind(t)}},Au=()=>{let t=null,e=0;return{getExtractedText:()=>t,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=e)return t!==null||t===""?{text:t||"",raw:n}:null;try{let o=(0,is.parse)(n,is.STR|is.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?t=typeof o.text=="string"?bu(o.text):"":o.type==="init"&&o.form?t="":typeof o.text=="string"&&(t=bu(o.text)))}catch{}return e=n.length,t!==null?{text:t,raw:n}:null},close:()=>{}}};var Su=()=>{let t=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let r=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(t=r[1],{text:t,raw:e}):null},getExtractedText:()=>t}};var Tu="4.4.2";var _s=Tu;var Wf="https://api.runtype.com/v1/dispatch",ka="https://api.runtype.com";function Rf(t){var s,a;let e=t.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(r)return`attachment.${r}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.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 Wi=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function Hf(t){switch(t){case"json":return Au;case"regex-json":return Cu;case"xml":return Su;default:return xu}}var Eu=t=>t.startsWith("{")||t.startsWith("[")||t.startsWith("<");function Bf(t,e){if(!t)return e;let n=t.trim(),r=e.trim();if(n.length===0)return e;if(r.length===0)return t;let o=Eu(n);if(!Eu(r))return t;if(!o||r===n||r.startsWith(n))return e;let a=Os(t);return Os(e)!==null&&a===null?e:t}var $s=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=e.apiUrl)!=null?n:Wf,this.headers={"Content-Type":"application/json","X-Persona-Version":_s,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:Hf(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new xa(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:e,flowId:n};let s=ru(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(e){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ka}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,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=(e=this.config).onSessionInit)==null||n.call(e,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let e=((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},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":_s},body:JSON.stringify(o)});if(!s.ok){let u=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${u.hint||u.error}`):s.status===403?new Error(`Origin not allowed: ${u.hint||u.error}`):new Error(u.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$/,""))||ka}/v1/client/feedback`}async sendFeedback(e){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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":_s},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(e,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:n})}async submitCSATFeedback(e,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:e,comment:n})}async submitNPSFeedback(e,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:e,comment:n})}async dispatch(e,n){return this.isClientTokenMode()?this.dispatchClientToken(e,n):this.isAgentMode()?this.dispatchAgent(e,n):this.dispatchProxy(e,n)}async dispatchClientToken(e,n){var o,s,a,i;let r=new AbortController;e.signal&&e.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 M=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:M}),M}let c=await this.buildPayload(e.messages),u=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,m={sessionId:d.sessionId,messages:e.messages.filter(Wi).map(M=>{var I,A,P;return{id:M.id,role:M.role,content:(P=(A=(I=M.contentParts)!=null?I:M.llmContent)!=null?A:M.rawContent)!=null?P:M.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},g=c.clientTools,f=!!(g&&g.length>0),w=f?eu(g):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,k=f&&v&&this.lastSentClientToolsFingerprint===w,R=!1,E=null,L;for(let M=0;;M++){let A={...m,...f&&(R||!k)&&g?{clientTools:g}:{},...w?{clientToolsFingerprint:w}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",A),L=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":_s},body:JSON.stringify(A),signal:r.signal}),L.status===409&&M===0&&f){let P=await L.json().catch(()=>null);if((P==null?void 0:P.error)==="client_tools_resend_required"){R=!0,this.lastSentClientToolsFingerprint=null;continue}E=P!=null?P:{error:"Chat request failed"}}break}if(!L.ok){let M=E!=null?E:await L.json().catch(()=>({error:"Chat request failed"}));if(L.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let A=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:A}),A}if(L.status===429){let A=new Error(M.hint||"Message limit reached for this session.");throw n({type:"error",error:A}),A}let I=new Error(M.error||"Failed to send message");throw n({type:"error",error:I}),I}if(!L.body){let M=new Error("No response body received");throw n({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=w!=null?w:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(L.body,n,e.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(e,n){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(e.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(e,n){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.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,e.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(e,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(e,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(e,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ka}/v1/agents/${e.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:e.executionId,approvalId:e.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(e,n,r){var c,u;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||ka}/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:e,toolOutputs:n,streamResponse:(u=r==null?void 0:r.streamResponse)!=null?u:!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(e){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=e.slice().filter(Wi).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,u)=>{let m=new Date(c.createdAt).getTime(),g=new Date(u.createdAt).getTime();return m-g}).map(c=>{var u,m,g;return{role:c.role,content:(g=(m=(u=c.contentParts)!=null?u:c.llmContent)!=null?m:c.rawContent)!=null?g: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=[...Pi(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 u=>{try{let m=await u({messages:e,config:this.config});m&&typeof m=="object"&&Object.assign(c,m)}catch(m){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",m)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(e){var a,i;let n=e.slice().filter(Wi).sort((d,c)=>{let u=new Date(d.createdAt).getTime(),m=new Date(c.createdAt).getTime();return u-m}).map(d=>{var c,u,m;return{role:d.role,content:(m=(u=(c=d.contentParts)!=null?c:d.llmContent)!=null?u:d.rawContent)!=null?m: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=[...Pi(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 u=await c({messages:e,config:this.config});u&&typeof u=="object"&&Object.assign(d,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),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(e,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=u=>{let m={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return r.current=m,o(m),m},c=u=>r.current?r.current:d(u);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 u=c(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,o(u)}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(e,n,r){var xt,hn,hr,yr;let o=e.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,u=S=>{let ne=S.reasoning?{...S.reasoning,chunks:[...S.reasoning.chunks]}:void 0,Se=S.toolCall?{...S.toolCall,chunks:S.toolCall.chunks?[...S.toolCall.chunks]:void 0}:void 0,Ne=S.tools?S.tools.map(Pe=>({...Pe,chunks:Pe.chunks?[...Pe.chunks]:void 0})):void 0;return{...S,reasoning:ne,toolCall:Se,tools:Ne}},m=S=>{if(S.role!=="assistant"||S.variant)return!0;let ne=Array.isArray(S.contentParts)&&S.contentParts.length>0,Se=typeof S.rawContent=="string"&&S.rawContent.trim()!=="";return typeof S.content=="string"&&S.content.trim()!==""||ne||Se||!!S.stopReason},g=S=>{m(S)&&n({type:"message",message:u(S)})},f=null,w=null,v={current:null},k={current:null},R=null,E="",L=new Map,M=new Map,I=new Map,A=new Map,P=new Map,O={lastId:null,byStep:new Map},_={lastId:null,byCall:new Map},H=S=>{if(S==null)return null;try{return String(S)}catch{return null}},U=S=>{var ne,Se,Ne,Pe,Fe;return H((Fe=(Pe=(Ne=(Se=(ne=S.stepId)!=null?ne:S.step_id)!=null?Se:S.step)!=null?Ne:S.parentId)!=null?Pe:S.flowStepId)!=null?Fe:S.flow_step_id)},F=S=>{var ne,Se,Ne,Pe,Fe,Ke,it;return H((it=(Ke=(Fe=(Pe=(Ne=(Se=(ne=S.callId)!=null?ne:S.call_id)!=null?Se:S.requestId)!=null?Ne:S.request_id)!=null?Pe:S.toolCallId)!=null?Fe:S.tool_call_id)!=null?Ke:S.stepId)!=null?it:S.step_id)},Z=r,Te=!1,pe=()=>{if(f)return f;let S,ne=R;return!Te&&Z?(S=Z,Te=!0):Z&&ne?S=`${Z}_${ne}`:S=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:S,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},g(f),f},ee=(S,ne)=>{O.lastId=ne,S&&O.byStep.set(S,ne)},xe=(S,ne)=>{var Fe;let Se=(Fe=S.reasoningId)!=null?Fe:S.id,Ne=U(S);if(Se){let Ke=String(Se);return ee(Ne,Ke),Ke}if(Ne){let Ke=O.byStep.get(Ne);if(Ke)return O.lastId=Ke,Ke}if(O.lastId&&!ne)return O.lastId;if(!ne)return null;let Pe=`reason-${c()}`;return ee(Ne,Pe),Pe},Re=S=>{let ne=A.get(S);if(ne)return ne;let Se={id:`reason-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:S,status:"streaming",chunks:[]}};return A.set(S,Se),g(Se),Se},le=(S,ne)=>{_.lastId=ne,S&&_.byCall.set(S,ne)},me=new Set,oe=new Map,se=new Set,de=new Map,Ee=S=>{if(!S)return!1;let ne=S.replace(/_+/g,"_").replace(/^_|_$/g,"");return ne==="emit_artifact_markdown"||ne==="emit_artifact_component"},He=(S,ne)=>{var Fe;let Se=(Fe=S.toolId)!=null?Fe:S.id,Ne=F(S);if(Se){let Ke=String(Se);return le(Ne,Ke),Ke}if(Ne){let Ke=_.byCall.get(Ne);if(Ke)return _.lastId=Ke,Ke}if(_.lastId&&!ne)return _.lastId;if(!ne)return null;let Pe=`tool-${c()}`;return le(Ne,Pe),Pe},K=S=>{let ne=P.get(S);if(ne)return ne;let Se={id:`tool-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:S,status:"pending"}};return P.set(S,Se),g(Se),Se},J=S=>{if(typeof S=="number"&&Number.isFinite(S))return S;if(typeof S=="string"){let ne=Number(S);if(!Number.isNaN(ne)&&Number.isFinite(ne))return ne;let Se=Date.parse(S);if(!Number.isNaN(Se))return Se}return Date.now()},Le=S=>{if(typeof S=="string")return S;if(S==null)return"";try{return JSON.stringify(S)}catch{return String(S)}},G=new Map,ue=new Map,De=new Map,Xe=(S,ne,Se)=>{var it;let Ne=De.get(S);Ne||(Ne=[],De.set(S,Ne));let Pe=0,Fe=Ne.length;for(;Pe<Fe;){let Rt=Pe+Fe>>>1;Ne[Rt].seq<ne?Pe=Rt+1:Fe=Rt}((it=Ne[Pe])==null?void 0:it.seq)===ne?Ne[Pe]={seq:ne,text:Se}:Ne.splice(Pe,0,{seq:ne,text:Se});let Ke="";for(let Rt=0;Rt<Ne.length;Rt++)Ke+=Ne[Rt].text;return Ke},et=(S,ne)=>{let Se=Le(ne),Ne=ue.get(S.id),Pe=Bf(Ne,Se);S.rawContent=Pe;let Fe=G.get(S.id),Ke=he=>{var Ct;let _e=(Ct=S.content)!=null?Ct:"";he.trim()!==""&&(_e.trim().length===0||he.startsWith(_e)||he.trimStart().startsWith(_e.trim()))&&(S.content=he)},it=()=>{var he;if(Fe){let _e=(he=Fe.close)==null?void 0:he.call(Fe);_e instanceof Promise&&_e.catch(()=>{})}G.delete(S.id),ue.delete(S.id),S.streaming=!1,g(S)};if(!Fe){Ke(Se),it();return}let Rt=Os(Pe);if(Rt!==null&&Rt.trim()!==""){Ke(Rt),it();return}let ce=he=>{var Ye;let _e=typeof he=="string"?he:(Ye=he==null?void 0:he.text)!=null?Ye:null;if(_e!==null&&_e.trim()!=="")return _e;let Ct=Fe.getExtractedText();return Ct!==null&&Ct.trim()!==""?Ct:Se},B;try{B=Fe.processChunk(Pe)}catch{Ke(Se),it();return}if(B instanceof Promise){B.then(he=>{Ke(ce(he)),it()}).catch(()=>{Ke(Se),it()});return}Ke(ce(B)),it()},vt=null,wt=(S,ne,Se,Ne)=>{var Rt;S.rawContent=ne,G.has(S.id)||G.set(S.id,this.createStreamParser());let Pe=G.get(S.id),Fe=ne.trim().startsWith("{")||ne.trim().startsWith("[");if(Fe&&ue.set(S.id,ne),Pe.__isPlainTextParser===!0){S.content=Ne!==void 0?ne:S.content+Se,ue.delete(S.id),G.delete(S.id),S.rawContent=void 0,g(S);return}let it=Pe.processChunk(ne);if(it instanceof Promise)it.then(ce=>{var he;let B=typeof ce=="string"?ce:(he=ce==null?void 0:ce.text)!=null?he:null;B!==null&&B.trim()!==""?(S.content=B,g(S)):!Fe&&!ne.trim().startsWith("<")&&(S.content=Ne!==void 0?ne:S.content+Se,ue.delete(S.id),G.delete(S.id),S.rawContent=void 0,g(S))}).catch(()=>{S.content=Ne!==void 0?ne:S.content+Se,ue.delete(S.id),G.delete(S.id),S.rawContent=void 0,g(S)});else{let ce=typeof it=="string"?it:(Rt=it==null?void 0:it.text)!=null?Rt:null;ce!==null&&ce.trim()!==""?(S.content=ce,g(S)):!Fe&&!ne.trim().startsWith("<")&&(S.content=Ne!==void 0?ne:S.content+Se,ue.delete(S.id),G.delete(S.id),S.rawContent=void 0,g(S))}},Je=(S,ne)=>{var Rt,ce;let Se=ne!=null?ne:S.content;if(Se==null||Se===""){S.streaming=!1,g(S);return}let Ne=ue.get(S.id),Pe=Ne!=null?Ne:Le(Se);S.rawContent=Pe;let Fe=G.get(S.id),Ke=null,it=!1;if(Fe&&(Ke=Fe.getExtractedText(),Ke===null&&(Ke=Os(Pe)),Ke===null)){let B=Fe.processChunk(Pe);B instanceof Promise?(it=!0,B.then(he=>{var Ct;let _e=typeof he=="string"?he:(Ct=he==null?void 0:he.text)!=null?Ct:null;_e!==null&&(S.content=_e,S.streaming=!1,G.delete(S.id),ue.delete(S.id),g(S))}).catch(()=>{})):Ke=typeof B=="string"?B:(Rt=B==null?void 0:B.text)!=null?Rt:null}if(!it){Ke!==null&&Ke.trim()!==""?S.content=Ke:ue.has(S.id)||(S.content=Le(Se));let B=G.get(S.id);if(B){let he=(ce=B.close)==null?void 0:ce.call(B);he instanceof Promise&&he.catch(()=>{}),G.delete(S.id)}ue.delete(S.id),S.streaming=!1,g(S)}},fe=(S,ne,Se)=>{let Ne=M.get(S);if(Ne)return Ne;let Pe={id:`nested-${ne}-${S}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...Se?{variant:Se}:{},...Se==="reasoning"?{reasoning:{id:S,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ne}};return M.set(S,Pe),g(Pe),Pe},Q=[],dt,qe=new Map,Ce=0,Me="agent",nt=!1,Wt=null,te=null,Ue=new Map,An=(xt=this.config.iterationDisplay)!=null?xt:"separate";for(dt=()=>{var S,ne,Se,Ne,Pe,Fe,Ke,it,Rt,ce,B,he,_e,Ct,Ye,Nt,Mt,ht,It,Jt,$t,Bn,zt,Dn,Qn,yn,Ln,Xn,Kr,At,br,vr,Wr,ir,ut,fo,wr,ho,Pn,$o,Gr,Rr,Qr,Xr,yo,bo,Jr,bt,Nn,Fn,Sn,St,Jn,Yn,On,Yr,Hr,Zr,_n,Ht,Tn,Zn,eo,Br,to,ve,In,xr,mt,rn,on,Cr,vs,Dr,vo,Ar,z,Uo,Sr,Tr,Nr,Er,lr,zo,la,$n,Un,cr,dr,wo,Fr,bn,Mr,qo,xo,jo,ca,Vo,da,Ko,pt,ws,er,Wn,pa;for(let Go=0;Go<Q.length;Go++){let tt=Q[Go].payloadType,x=Q[Go].payload;if(!nt&&Me!=="flow"&&typeof x.stepType=="string"&&(Me="flow"),tt==="reasoning_start"){let V=typeof x.id=="string"?x.id:null,q=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(V&&q){L.set(V,q),fe(V,q,"reasoning");continue}let X=(S=xe(x,!0))!=null?S:`reason-${c()}`,ye=Re(X);ye.reasoning=(ne=ye.reasoning)!=null?ne:{id:X,status:"streaming",chunks:[]},ye.reasoning.startedAt=(Ne=ye.reasoning.startedAt)!=null?Ne:J((Se=x.startedAt)!=null?Se:x.timestamp),ye.reasoning.completedAt=void 0,ye.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(ye.reasoning.scope=x.scope),ye.streaming=!0,ye.reasoning.status="streaming",g(ye)}else if(tt==="reasoning_delta"){let V=typeof x.id=="string"?x.id:null;if(V&&L.has(V)&&M.has(V)){let $e=M.get(V),gt=(Ke=(Fe=(Pe=x.reasoningText)!=null?Pe:x.text)!=null?Fe:x.delta)!=null?Ke:"";gt&&x.hidden!==!0&&$e.reasoning&&($e.reasoning.chunks.push(String(gt)),g($e));continue}let q=(Rt=(it=xe(x,!1))!=null?it:xe(x,!0))!=null?Rt:`reason-${c()}`,X=Re(q);X.reasoning=(ce=X.reasoning)!=null?ce:{id:q,status:"streaming",chunks:[]},X.reasoning.startedAt=(he=X.reasoning.startedAt)!=null?he:J((B=x.startedAt)!=null?B:x.timestamp);let ye=(Ye=(Ct=(_e=x.reasoningText)!=null?_e:x.text)!=null?Ct:x.delta)!=null?Ye:"";if(ye&&x.hidden!==!0){let $e=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if($e!==void 0){let gt=Xe(q,$e,String(ye));X.reasoning.chunks=[gt]}else X.reasoning.chunks.push(String(ye))}if(X.reasoning.status=x.done?"complete":"streaming",x.done){X.reasoning.completedAt=J((Nt=x.completedAt)!=null?Nt:x.timestamp);let $e=(Mt=X.reasoning.startedAt)!=null?Mt:Date.now();X.reasoning.durationMs=Math.max(0,((ht=X.reasoning.completedAt)!=null?ht:Date.now())-$e)}X.streaming=X.reasoning.status!=="complete",g(X)}else if(tt==="reasoning_complete"){let V=typeof x.id=="string"?x.id:null;if(V&&L.has(V)&&M.has(V)){let gt=M.get(V);if(gt.reasoning){let st=typeof x.text=="string"?x.text:"";st&>.reasoning.chunks.length===0&>.reasoning.chunks.push(st),gt.reasoning.status="complete",gt.streaming=!1,g(gt)}L.delete(V),M.delete(V);continue}let q=(Jt=(It=xe(x,!1))!=null?It:xe(x,!0))!=null?Jt:`reason-${c()}`,X=typeof x.text=="string"?x.text:"";!A.get(q)&&(X||x.scope==="loop")&&Re(q);let ye=A.get(q);if(ye!=null&&ye.reasoning){(x.scope==="loop"||x.scope==="turn")&&(ye.reasoning.scope=x.scope),X&&ye.reasoning.chunks.length===0&&ye.reasoning.chunks.push(X),ye.reasoning.status="complete",ye.reasoning.completedAt=J(($t=x.completedAt)!=null?$t:x.timestamp);let gt=(Bn=ye.reasoning.startedAt)!=null?Bn:Date.now();ye.reasoning.durationMs=Math.max(0,((zt=ye.reasoning.completedAt)!=null?zt:Date.now())-gt),ye.streaming=!1,g(ye)}let $e=U(x);$e&&O.byStep.delete($e)}else if(tt==="tool_start"){f&&(f.streaming=!1,g(f),f=null),typeof x.iteration=="number"&&(Ce=x.iteration);let V=(Qn=(Dn=typeof x.toolCallId=="string"?x.toolCallId:void 0)!=null?Dn:He(x,!0))!=null?Qn:`tool-${c()}`,q=(yn=x.toolName)!=null?yn:x.name;if(Ee(q)){me.add(V);continue}le(F(x),V);let X=K(V),ye=(Ln=X.toolCall)!=null?Ln:{id:V,status:"pending"};ye.name=q!=null?q:ye.name,ye.status="running",x.parameters!==void 0?ye.args=x.parameters:x.args!==void 0&&(ye.args=x.args),ye.startedAt=(Kr=ye.startedAt)!=null?Kr:J((Xn=x.startedAt)!=null?Xn:x.timestamp),ye.completedAt=void 0,ye.durationMs=void 0,X.toolCall=ye,X.streaming=!0,x.executionId&&(X.agentMetadata={executionId:x.executionId,iteration:x.iteration}),g(X)}else if(tt==="tool_output_delta"){let V=(br=(At=He(x,!1))!=null?At:He(x,!0))!=null?br:`tool-${c()}`;if(me.has(V))continue;let q=K(V),X=(vr=q.toolCall)!=null?vr:{id:V,status:"running"};X.startedAt=(ir=X.startedAt)!=null?ir:J((Wr=x.startedAt)!=null?Wr:x.timestamp);let ye=(wr=(fo=(ut=x.text)!=null?ut:x.delta)!=null?fo:x.message)!=null?wr:"";ye&&(X.chunks=(ho=X.chunks)!=null?ho:[],X.chunks.push(String(ye))),X.status="running",q.toolCall=X,q.streaming=!0;let $e=x.agentContext;($e||x.executionId)&&(q.agentMetadata=(Gr=q.agentMetadata)!=null?Gr:{executionId:(Pn=$e==null?void 0:$e.executionId)!=null?Pn:x.executionId,iteration:($o=$e==null?void 0:$e.iteration)!=null?$o:x.iteration}),g(q)}else if(tt==="tool_complete"){let V=(Qr=(Rr=He(x,!1))!=null?Rr:He(x,!0))!=null?Qr:`tool-${c()}`;if(me.has(V)){me.delete(V);continue}let q=K(V),X=(Xr=q.toolCall)!=null?Xr:{id:V,status:"running"};X.status="complete",x.result!==void 0&&(X.result=x.result),typeof x.duration=="number"&&(X.duration=x.duration),X.completedAt=J((yo=x.completedAt)!=null?yo:x.timestamp);let ye=(bo=x.duration)!=null?bo:x.executionTime;if(typeof ye=="number")X.durationMs=ye;else{let st=(Jr=X.startedAt)!=null?Jr:Date.now();X.durationMs=Math.max(0,((bt=X.completedAt)!=null?bt:Date.now())-st)}q.toolCall=X,q.streaming=!1;let $e=x.agentContext;($e||x.executionId)&&(q.agentMetadata=(Sn=q.agentMetadata)!=null?Sn:{executionId:(Nn=$e==null?void 0:$e.executionId)!=null?Nn:x.executionId,iteration:(Fn=$e==null?void 0:$e.iteration)!=null?Fn:x.iteration}),g(q);let gt=F(x);gt&&_.byCall.delete(gt)}else if(tt==="await"&&x.toolName){let V=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,q=(St=V!=null?V:x.toolId)!=null?St:`local-${c()}`,X=K(q),ye=x.toolName,$e=x.origin==="webmcp"&&!ns(ye)?`webmcp:${ye}`:ye,gt=ns($e),st=(Jn=X.toolCall)!=null?Jn:{id:q,status:"pending"};st.name=$e,st.args=x.parameters,st.status=gt?"running":"complete",st.chunks=(Yn=st.chunks)!=null?Yn:[],st.startedAt=(Hr=st.startedAt)!=null?Hr:J((Yr=(On=x.startedAt)!=null?On:x.timestamp)!=null?Yr:x.awaitedAt),gt?(st.completedAt=void 0,st.duration=void 0,st.durationMs=void 0):st.completedAt=(Zr=st.completedAt)!=null?Zr:st.startedAt,X.toolCall=st,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:(Ht=x.executionId)!=null?Ht:(_n=X.agentMetadata)==null?void 0:_n.executionId,awaitingLocalTool:!0,...V?{webMcpToolCallId:V}:{}},g(X)}else if(tt==="text_start"){let V=typeof x.id=="string"?x.id:null,q=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(V&&q){L.set(V,q);continue}let X=f;X&&(Me==="flow"?(Je(X),vt=X):(X.streaming=!1,g(X)),f=null),R=typeof x.id=="string"?x.id:R,E=""}else if(tt==="text_delta"){let V=typeof x.id=="string"?x.id:null,q=V?L.get(V):void 0;if(V&&q){let ye=typeof x.delta=="string"?x.delta:"",$e=((Tn=I.get(V))!=null?Tn:"")+ye;if(I.set(V,$e),$e.trim()==="")continue;let gt=fe(V,q);gt.agentMetadata={...gt.agentMetadata,executionId:x.executionId,parentToolId:q},wt(gt,$e,ye,void 0);continue}if(R=typeof x.id=="string"?x.id:R,Me==="flow"){let ye=typeof x.delta=="string"?x.delta:"";if(E+=ye,E.trim()==="")continue;let $e=pe();$e.agentMetadata={executionId:x.executionId,iteration:x.iteration},wt($e,E,ye,void 0),w=$e;continue}let X=pe();X.content+=(Zn=x.delta)!=null?Zn:"",X.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:Wt!=null?Wt:void 0,agentName:te==null?void 0:te.agentName},w=X,g(X)}else if(tt==="text_complete"){let V=typeof x.id=="string"?x.id:null;if(V&&L.has(V)){let X=M.get(V);X&&Je(X),L.delete(V),I.delete(V),M.delete(V);continue}let q=f;q&&(Me==="flow"?(Je(q),vt=q):(((eo=q.content)!=null?eo:"")===""&&typeof x.text=="string"&&(q.content=x.text),q.streaming=!1,g(q)),f=null),R=null,E=""}else if(tt==="step_complete"){let V=x.stepType,q=x.executionType;if(V==="tool"||q==="context")continue;if(x.success===!1){let X=x.error,ye=typeof X=="string"&&X!==""?X:X!=null&&typeof X=="object"&&"message"in X?String((Br=X.message)!=null?Br:"Step failed"):"Step failed";n({type:"error",error:new Error(ye)});let $e=f;$e&&$e.streaming&&($e.streaming=!1,g($e)),n({type:"status",status:"idle"});continue}{let X=vt;vt=null;let ye=x.stopReason,$e=(to=x.result)==null?void 0:to.response;if(X)ye&&(X.stopReason=ye),$e!=null?et(X,$e):X.streaming!==!1&&(G.delete(X.id),ue.delete(X.id),X.streaming=!1,g(X));else{let gt=$e!=null&&$e!=="";if(gt||ye){let st=pe();ye&&(st.stopReason=ye),gt?Je(st,$e):(st.streaming=!1,g(st))}}continue}}else if(tt==="execution_start")Me=x.kind==="flow"?"flow":"agent",nt=!0,Me==="agent"&&(te={executionId:x.executionId,agentId:(ve=x.agentId)!=null?ve:"virtual",agentName:(In=x.agentName)!=null?In:"",status:"running",currentIteration:0,maxTurns:(xr=x.maxTurns)!=null?xr:1,startedAt:J(x.startedAt)});else if(tt==="turn_start"){let V=typeof x.iteration=="number"?x.iteration:Ce;if(V!==Ce){if(te&&(te.currentIteration=V),An==="separate"&&V>1){let q=f;q&&(q.streaming=!1,g(q),Ue.set(V-1,q),f=null)}Ce=V}Wt=typeof x.id=="string"?x.id:null,w=null}else if(tt==="tool_input_delta"){let V=(mt=x.toolCallId)!=null?mt:_.lastId;if(V){let q=P.get(V);q!=null&&q.toolCall&&(q.toolCall.chunks=(rn=q.toolCall.chunks)!=null?rn:[],q.toolCall.chunks.push((on=x.delta)!=null?on:""),g(q))}}else{if(tt==="tool_input_complete")continue;if(tt==="turn_complete"){let V=x.stopReason,q=f!=null?f:w;if(V&&q!==null){let X=x.id;(!X||((Cr=q.agentMetadata)==null?void 0:Cr.turnId)===X)&&(q.stopReason=V,g(q))}Wt===x.id&&(Wt=null)}else if(tt==="media_start"){let V=String(x.id);qe.set(V,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(tt==="media_delta"){let V=qe.get(String(x.id));V&&typeof x.delta=="string"&&V.parts.push(x.delta)}else if(tt==="media_complete"){let V=String(x.id),q=qe.get(V);qe.delete(V);let X=(Dr=(vs=typeof x.mediaType=="string"?x.mediaType:void 0)!=null?vs:q==null?void 0:q.mediaType)!=null?Dr:"application/octet-stream",ye=typeof x.data=="string"?x.data:void 0,$e=typeof x.url=="string"?x.url:q&&q.parts.length>0?q.parts.join(""):void 0,gt=null;if(ye)gt={type:"media",data:ye,mediaType:X};else if($e){let cn=X.toLowerCase();gt={type:cn==="image"||cn.startsWith("image/")?"image-url":"file-url",url:$e,mediaType:X}}let st=(vo=x.toolCallId)!=null?vo:q==null?void 0:q.toolCallId,xs=gt?[gt]:[],Rn=[];for(let cn of xs){if(!cn||typeof cn!="object")continue;let dn=cn,Co=typeof dn.type=="string"?dn.type:void 0,Or=typeof dn.mediaType=="string"?dn.mediaType.toLowerCase():"",En=null,gn="";if(Co==="media"){let zn=typeof dn.data=="string"?dn.data:void 0;if(!zn)continue;gn=Or.length>0?Or:"application/octet-stream",En=`data:${gn};base64,${zn}`}else if(Co==="image-url"){let zn=typeof dn.url=="string"?dn.url:void 0;if(!zn)continue;gn=Or,En=zn}else if(Co==="file-url"){let zn=typeof dn.url=="string"?dn.url:void 0;if(!zn)continue;gn=Or,En=zn}else continue;if(En)if(Co==="image-url"||gn.startsWith("image/"))Rn.push({type:"image",image:En,...gn.includes("/")?{mimeType:gn}:{}});else if(gn.startsWith("audio/"))Rn.push({type:"audio",audio:En,mimeType:gn});else if(gn.startsWith("video/"))Rn.push({type:"video",video:En,mimeType:gn});else{let zn=gn||"application/octet-stream";Rn.push({type:"file",data:En,mimeType:zn,filename:Rf(zn)})}}if(Rn.length>0){let cn=c(),dn=st,Or={id:`agent-media-${typeof dn=="string"&&dn.length>0?`${dn}-${cn}`:String(cn)}`,role:"assistant",content:"",contentParts:Rn,createdAt:new Date().toISOString(),streaming:!1,sequence:cn,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:Ce}};g(Or);let En=f;En&&(En.streaming=!1,g(En)),f=null,v.current=null}}else if(tt==="execution_complete"){let V=(Ar=x.kind)!=null?Ar:Me;V==="agent"&&te&&(te.status=x.success?"complete":"error",te.completedAt=J(x.completedAt),te.stopReason=x.stopReason);let q=f;q&&(V==="flow"&&q.streaming!==!1?Je(q):(q.streaming=!1,g(q)),f=null),R=null,E="",vt=null,n({type:"status",status:"idle"})}else if(tt==="execution_error"){let V=typeof x.error=="string"?x.error:(Uo=(z=x.error)==null?void 0:z.message)!=null?Uo:"Execution error";n({type:"error",error:new Error(V)})}else if(tt!=="ping"){if(tt==="approval_start"){let V=(Sr=x.approvalId)!=null?Sr:`approval-${c()}`,q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:V,status:"pending",agentId:(Tr=te==null?void 0:te.agentId)!=null?Tr:"virtual",executionId:(Er=(Nr=x.executionId)!=null?Nr:te==null?void 0:te.executionId)!=null?Er:"",toolName:(lr=x.toolName)!=null?lr:"",toolType:x.toolType,description:(la=x.description)!=null?la:`Execute ${(zo=x.toolName)!=null?zo:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};g(q)}else if(tt==="step_await"&&x.awaitReason==="approval_required"){let V=($n=x.approvalId)!=null?$n:`approval-${c()}`,q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:V,status:"pending",agentId:(Un=te==null?void 0:te.agentId)!=null?Un:"virtual",executionId:(dr=(cr=x.executionId)!=null?cr:te==null?void 0:te.executionId)!=null?dr:"",toolName:(wo=x.toolName)!=null?wo:"",toolType:x.toolType,description:(bn=x.description)!=null?bn:`Execute ${(Fr=x.toolName)!=null?Fr:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};g(q)}else if(tt==="approval_complete"){let V=x.approvalId;if(V){let X={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:V,status:(Mr=x.decision)!=null?Mr:"approved",agentId:(qo=te==null?void 0:te.agentId)!=null?qo:"virtual",executionId:(jo=(xo=x.executionId)!=null?xo:te==null?void 0:te.executionId)!=null?jo:"",toolName:(ca=x.toolName)!=null?ca:"",description:(Vo=x.description)!=null?Vo:"",resolvedAt:Date.now()}};g(X)}}else if(tt==="artifact_start"||tt==="artifact_delta"||tt==="artifact_update"||tt==="artifact_complete"){if(tt==="artifact_start"){let V=x.artifactType,q=String(x.id),X=typeof x.title=="string"?x.title:void 0;if(n({type:"artifact_start",id:q,artifactType:V,title:X,component:typeof x.component=="string"?x.component:void 0}),de.set(q,{markdown:"",title:X}),!se.has(q)){se.add(q);let ye={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:X,artifactType:V,status:"streaming"}})};oe.set(q,ye),g(ye)}}else if(tt==="artifact_delta"){let V=String(x.id),q=typeof x.delta=="string"?x.delta:String((da=x.delta)!=null?da:"");n({type:"artifact_delta",id:V,artDelta:q});let X=de.get(V);X&&(X.markdown+=q)}else if(tt==="artifact_update"){let V=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};n({type:"artifact_update",id:String(x.id),props:V,component:typeof x.component=="string"?x.component:void 0})}else if(tt==="artifact_complete"){let V=String(x.id);n({type:"artifact_complete",id:V});let q=oe.get(V);if(q){q.streaming=!1;try{let X=JSON.parse((Ko=q.rawContent)!=null?Ko:"{}");if(X.props){X.props.status="complete";let ye=de.get(V);ye!=null&&ye.markdown&&(X.props.markdown=ye.markdown)}q.rawContent=JSON.stringify(X)}catch{}de.delete(V),g(q),oe.delete(V)}}}else if(tt==="transcript_insert"){let V=x.message;if(!V||typeof V!="object")continue;let q=String((pt=V.id)!=null?pt:`msg-${c()}`),X=V.role,$e={id:q,role:X==="user"?"user":X==="system"?"system":"assistant",content:typeof V.content=="string"?V.content:"",rawContent:typeof V.rawContent=="string"?V.rawContent:void 0,createdAt:typeof V.createdAt=="string"?V.createdAt:new Date().toISOString(),streaming:V.streaming===!0,...typeof V.variant=="string"?{variant:V.variant}:{},sequence:c()};if(g($e),$e.rawContent)try{let gt=JSON.parse($e.rawContent),st=(ws=gt==null?void 0:gt.props)==null?void 0:ws.artifactId;typeof st=="string"&&se.add(st)}catch{}f=null,v.current=null,G.delete(q),ue.delete(q)}else if(tt==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let V=typeof x.error=="string"?x.error:((er=x.error)==null?void 0:er.message)!=null?String(x.error.message):"Execution error";n({type:"error",error:new Error(V)});let q=f;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}else if(tt==="step_error"||tt==="dispatch_error"||tt==="flow_error"){let V=null;if(x.error instanceof Error)V=x.error;else if(tt==="dispatch_error"){let q=(Wn=x.message)!=null?Wn:x.error;q!=null&&q!==""&&(V=new Error(String(q)))}else{let q=x.error;typeof q=="string"&&q!==""?V=new Error(q):q!=null&&typeof q=="object"&&"message"in q&&(V=new Error(String((pa=q.message)!=null?pa:q)))}if(V){n({type:"error",error:V});let q=f;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}}}}Q.length=0};;){let{done:S,value:ne}=await o.read();if(S)break;a+=s.decode(ne,{stream:!0});let Se=a.split(`
|
|
11
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>n,processChunk:async r=>{if(r.length<=e)return n!==null?{text:n,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=t(r);return s!==null&&(n=s),e=r.length,n!==null?{text:n,raw:r}:null},close:async()=>{}}},Qs=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Vu=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Ku=()=>{var e;let n=ah();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:n.processChunk(t)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},Gu=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=e)return n!==null||n===""?{text:n||"",raw:t}:null;try{let o=(0,gs.parse)(t,gs.STR|gs.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?qu(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=qu(o.text)))}catch{}return e=t.length,n!==null?{text:n,raw:t}:null},close:()=>{}}};var Qu=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let r=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(n=r[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var Xu="4.6.0";var Xs=Xu;var lh="https://api.runtype.com/v1/dispatch",Ha="https://api.runtype.com";function ch(n){var s,a;let e=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(r)return`attachment.${r}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.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 _i=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function dh(n){switch(n){case"json":return Gu;case"regex-json":return Ku;case"xml":return Qu;default:return Vu}}var Ju=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function ph(n,e){if(!n)return e;let t=n.trim(),r=e.trim();if(t.length===0)return e;if(r.length===0)return n;let o=Ju(t);if(!Ju(r))return n;if(!o||r===t||r.startsWith(t))return e;let a=Qs(n);return Qs(e)!==null&&a===null?e:n}var Js=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,r,o,s;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(t=e.apiUrl)!=null?t:lh,this.headers={"Content-Type":"application/json","X-Persona-Version":Xs,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:dh(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new Ma(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,t,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,t,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:t,target:r,targetProviders:o}=this.config;if(!r)return{agentId:e,flowId:t};let s=ku(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(e){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ha}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,t;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(),(t=(e=this.config).onSessionInit)==null||t.call(e,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let e=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,t=this.routing(),r=(c=t.agentId)!=null?c:t.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xs},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 t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ha}/v1/client/feedback`}async sendFeedback(e){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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xs},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(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){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:e,comment:t})}async submitNPSFeedback(e,t){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:e,comment:t})}async dispatch(e,t){return this.isClientTokenMode()?this.dispatchClientToken(e,t):this.isAgentMode()?this.dispatchAgent(e,t):this.dispatchProxy(e,t)}async dispatchClientToken(e,t){var o,s,a,i;let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({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 M=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:M}),M}let c=await this.buildPayload(e.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,g={sessionId:d.sessionId,messages:e.messages.filter(_i).map(M=>{var P,C,k;return{id:M.id,role:M.role,content:(k=(C=(P=M.contentParts)!=null?P:M.llmContent)!=null?C:M.rawContent)!=null?k:M.content}}),...e.assistantMessageId&&{assistantMessageId:e.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}},h=c.clientTools,m=!!(h&&h.length>0),y=m?Tu(h):void 0,w=this.clientToolsFingerprintSessionId===d.sessionId,E=m&&w&&this.lastSentClientToolsFingerprint===y,B=!1,T=null,I;for(let M=0;;M++){let C={...g,...m&&(B||!E)&&h?{clientTools:h}:{},...y?{clientToolsFingerprint:y}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),I=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xs},body:JSON.stringify(C),signal:r.signal}),I.status===409&&M===0&&m){let k=await I.json().catch(()=>null);if((k==null?void 0:k.error)==="client_tools_resend_required"){B=!0,this.lastSentClientToolsFingerprint=null;continue}T=k!=null?k:{error:"Chat request failed"}}break}if(!I.ok){let M=T!=null?T:await I.json().catch(()=>({error:"Chat request failed"}));if(I.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:C}),C}if(I.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw t({type:"error",error:C}),C}let P=new Error(M.error||"Failed to send message");throw t({type:"error",error:P}),P}if(!I.body){let M=new Error("No response body received");throw t({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=y!=null?y:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(I.body,t,e.assistantMessageId)}finally{t({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")&&t({type:"error",error:c}),c}}async dispatchProxy(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildPayload(e.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 t({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 t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.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 t({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 t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r,o){t({type:"status",status:"connected"});try{await this.streamResponse(e,t,r,o)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ha}/v1/agents/${e.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:e.executionId,approvalId:e.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(e,t,r){var c,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Ha}/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:e,toolOutputs:t,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(e){var a,i,d;let t=this.routing().agentId;if(!this.config.agent&&!t)throw new Error("Agent configuration required for agent mode");let r=e.slice().filter(_i).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,p)=>{let g=new Date(c.createdAt).getTime(),h=new Date(p.createdAt).getTime();return g-h}).map(c=>{var p,g,h;return{role:c.role,content:(h=(g=(p=c.contentParts)!=null?p:c.llmContent)!=null?g:c.rawContent)!=null?h:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:t},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Fi(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 g=await p({messages:e,config:this.config});g&&typeof g=="object"&&Object.assign(c,g)}catch(g){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",g)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(e){var a,i;let t=e.slice().filter(_i).sort((d,c)=>{let p=new Date(d.createdAt).getTime(),g=new Date(c.createdAt).getTime();return p-g}).map(d=>{var c,p,g;return{role:d.role,content:(g=(p=(c=d.contentParts)!=null?c:d.llmContent)!=null?p:d.rawContent)!=null?g:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:t,...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=[...Fi(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:e,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(e,t,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=p=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=g,o(g),g},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,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,t,r,o){var fn,hr,yr,qe;let s=e.getReader(),a=new TextDecoder,i="",d=Date.now(),c=0,p=()=>d+c++,g=L=>{let ge=L.reasoning?{...L.reasoning,chunks:[...L.reasoning.chunks]}:void 0,Me=L.toolCall?{...L.toolCall,chunks:L.toolCall.chunks?[...L.toolCall.chunks]:void 0}:void 0,Le=L.tools?L.tools.map(He=>({...He,chunks:He.chunks?[...He.chunks]:void 0})):void 0;return{...L,reasoning:ge,toolCall:Me,tools:Le}},h=L=>{if(L.role!=="assistant"||L.variant)return!0;let ge=Array.isArray(L.contentParts)&&L.contentParts.length>0,Me=typeof L.rawContent=="string"&&L.rawContent.trim()!=="";return typeof L.content=="string"&&L.content.trim()!==""||ge||Me||!!L.stopReason},m=L=>{h(L)&&t({type:"message",message:g(L)})},y=null,w=null,E={current:null},B={current:null},T=null,I="",M=new Map,P=new Map,C=new Map,k=new Map,q=new Map,_={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},O=L=>{if(L==null)return null;try{return String(L)}catch{return null}},F=L=>{var ge,Me,Le,He,nt;return O((nt=(He=(Le=(Me=(ge=L.stepId)!=null?ge:L.step_id)!=null?Me:L.step)!=null?Le:L.parentId)!=null?He:L.flowStepId)!=null?nt:L.flow_step_id)},Z=L=>{var ge,Me,Le,He,nt,Xe,yt;return O((yt=(Xe=(nt=(He=(Le=(Me=(ge=L.callId)!=null?ge:L.call_id)!=null?Me:L.requestId)!=null?Le:L.request_id)!=null?He:L.toolCallId)!=null?nt:L.tool_call_id)!=null?Xe:L.stepId)!=null?yt:L.step_id)},ke=r,pe=!1,ee=()=>{if(y)return y;let L,ge="",Me=T;return!pe&&ke?(L=ke,pe=!0,ge=o!=null?o:""):ke&&Me?L=`${ke}_${Me}`:L=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:L,role:"assistant",content:ge,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},m(y),y},Pe=(L,ge)=>{_.lastId=ge,L&&_.byStep.set(L,ge)},Ie=(L,ge)=>{var nt;let Me=(nt=L.reasoningId)!=null?nt:L.id,Le=F(L);if(Me){let Xe=String(Me);return Pe(Le,Xe),Xe}if(Le){let Xe=_.byStep.get(Le);if(Xe)return _.lastId=Xe,Xe}if(_.lastId&&!ge)return _.lastId;if(!ge)return null;let He=`reason-${p()}`;return Pe(Le,He),He},ie=L=>{let ge=k.get(L);if(ge)return ge;let Me={id:`reason-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:L,status:"streaming",chunks:[]}};return k.set(L,Me),m(Me),Me},he=(L,ge)=>{R.lastId=ge,L&&R.byCall.set(L,ge)},re=new Set,oe=new Map,de=new Set,Ae=new Map,$e=L=>{if(!L)return!1;let ge=L.replace(/_+/g,"_").replace(/^_|_$/g,"");return ge==="emit_artifact_markdown"||ge==="emit_artifact_component"},K=(L,ge)=>{var nt;let Me=(nt=L.toolId)!=null?nt:L.id,Le=Z(L);if(Me){let Xe=String(Me);return he(Le,Xe),Xe}if(Le){let Xe=R.byCall.get(Le);if(Xe)return R.lastId=Xe,Xe}if(R.lastId&&!ge)return R.lastId;if(!ge)return null;let He=`tool-${p()}`;return he(Le,He),He},J=L=>{let ge=q.get(L);if(ge)return ge;let Me={id:`tool-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:L,status:"pending"}};return q.set(L,Me),m(Me),Me},Se=L=>{if(typeof L=="number"&&Number.isFinite(L))return L;if(typeof L=="string"){let ge=Number(L);if(!Number.isNaN(ge)&&Number.isFinite(ge))return ge;let Me=Date.parse(L);if(!Number.isNaN(Me))return Me}return Date.now()},Y=L=>{if(typeof L=="string")return L;if(L==null)return"";try{return JSON.stringify(L)}catch{return String(L)}},le=new Map,Te=new Map,Ye=new Map,tt=(L,ge,Me)=>{var yt;let Le=Ye.get(L);Le||(Le=[],Ye.set(L,Le));let He=0,nt=Le.length;for(;He<nt;){let fe=He+nt>>>1;Le[fe].seq<ge?He=fe+1:nt=fe}((yt=Le[He])==null?void 0:yt.seq)===ge?Le[He]={seq:ge,text:Me}:Le.splice(He,0,{seq:ge,text:Me});let Xe="";for(let fe=0;fe<Le.length;fe++)Xe+=Le[fe].text;return Xe},Wt=(L,ge)=>{let Me=Y(ge),Le=Te.get(L.id),He=ph(Le,Me);L.rawContent=He;let nt=le.get(L.id),Xe=ce=>{var Ge;let ft=(Ge=L.content)!=null?Ge:"";ce.trim()!==""&&(ft.trim().length===0||ce.startsWith(ft)||ce.trimStart().startsWith(ft.trim()))&&(L.content=ce)},yt=()=>{var ce;if(nt){let ft=(ce=nt.close)==null?void 0:ce.call(nt);ft instanceof Promise&&ft.catch(()=>{})}le.delete(L.id),Te.delete(L.id),L.streaming=!1,m(L)};if(!nt){Xe(Me),yt();return}let fe=Qs(He);if(fe!==null&&fe.trim()!==""){Xe(fe),yt();return}let D=ce=>{var Pt;let ft=typeof ce=="string"?ce:(Pt=ce==null?void 0:ce.text)!=null?Pt:null;if(ft!==null&&ft.trim()!=="")return ft;let Ge=nt.getExtractedText();return Ge!==null&&Ge.trim()!==""?Ge:Me},ve;try{ve=nt.processChunk(He)}catch{Xe(Me),yt();return}if(ve instanceof Promise){ve.then(ce=>{Xe(D(ce)),yt()}).catch(()=>{Xe(Me),yt()});return}Xe(D(ve)),yt()},ht=null,ot=(L,ge,Me,Le)=>{var fe;L.rawContent=ge,le.has(L.id)||le.set(L.id,this.createStreamParser());let He=le.get(L.id),nt=ge.trim().startsWith("{")||ge.trim().startsWith("[");if(nt&&Te.set(L.id,ge),He.__isPlainTextParser===!0){L.content=Le!==void 0?ge:L.content+Me,Te.delete(L.id),le.delete(L.id),L.rawContent=void 0,m(L);return}let yt=He.processChunk(ge);if(yt instanceof Promise)yt.then(D=>{var ce;let ve=typeof D=="string"?D:(ce=D==null?void 0:D.text)!=null?ce:null;ve!==null&&ve.trim()!==""?(L.content=ve,m(L)):!nt&&!ge.trim().startsWith("<")&&(L.content=Le!==void 0?ge:L.content+Me,Te.delete(L.id),le.delete(L.id),L.rawContent=void 0,m(L))}).catch(()=>{L.content=Le!==void 0?ge:L.content+Me,Te.delete(L.id),le.delete(L.id),L.rawContent=void 0,m(L)});else{let D=typeof yt=="string"?yt:(fe=yt==null?void 0:yt.text)!=null?fe:null;D!==null&&D.trim()!==""?(L.content=D,m(L)):!nt&&!ge.trim().startsWith("<")&&(L.content=Le!==void 0?ge:L.content+Me,Te.delete(L.id),le.delete(L.id),L.rawContent=void 0,m(L))}},me=(L,ge)=>{var fe,D;let Me=ge!=null?ge:L.content;if(Me==null||Me===""){L.streaming=!1,m(L);return}let Le=Te.get(L.id),He=Le!=null?Le:Y(Me);L.rawContent=He;let nt=le.get(L.id),Xe=null,yt=!1;if(nt&&(Xe=nt.getExtractedText(),Xe===null&&(Xe=Qs(He)),Xe===null)){let ve=nt.processChunk(He);ve instanceof Promise?(yt=!0,ve.then(ce=>{var Ge;let ft=typeof ce=="string"?ce:(Ge=ce==null?void 0:ce.text)!=null?Ge:null;ft!==null&&(L.content=ft,L.streaming=!1,le.delete(L.id),Te.delete(L.id),m(L))}).catch(()=>{})):Xe=typeof ve=="string"?ve:(fe=ve==null?void 0:ve.text)!=null?fe:null}if(!yt){Xe!==null&&Xe.trim()!==""?L.content=Xe:Te.has(L.id)||(L.content=Y(Me));let ve=le.get(L.id);if(ve){let ce=(D=ve.close)==null?void 0:D.call(ve);ce instanceof Promise&&ce.catch(()=>{}),le.delete(L.id)}Te.delete(L.id),L.streaming=!1,m(L)}},X=(L,ge,Me)=>{let Le=P.get(L);if(Le)return Le;let He={id:`nested-${ge}-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Me?{variant:Me}:{},...Me==="reasoning"?{reasoning:{id:L,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ge}};return P.set(L,He),m(He),He},lt=[],Ve,Ee=new Map,xe=0,Ze="agent",jt=!1,be=null,ue=null,xn=new Map,At=(fn=this.config.iterationDisplay)!=null?fn:"separate";for(Ve=()=>{var L,ge,Me,Le,He,nt,Xe,yt,fe,D,ve,ce,ft,Ge,Pt,kt,wt,Ht,Xt,Ot,en,br,Wr,rr,or,Kr,Vt,sr,Hr,Bn,Ln,Dn,ar,vr,Gr,Vn,Qr,St,wr,xr,Br,ir,bt,Co,Cr,Ao,Pn,Qo,Xr,Dr,Jr,Yr,So,To,Zr,xt,Nn,Fn,Cn,Tt,Kn,Gn,On,eo,Ce,Nr,Qn,_t,Xn,Fr,ks,Xo,Ls,Eo,Ar,to,ct,rn,on,Sr,Ps,Or,Mo,Tr,$,Jo,lr,Er,_r,Mr,cr,Yo,ha,hn,An,dr,Sn,ko,pr,yn,kr,Zo,Lo,es,no;for(let ro=0;ro<lt.length;ro++){let st=lt[ro].payloadType,x=lt[ro].payload;if(!jt&&Ze!=="flow"&&typeof x.stepType=="string"&&(Ze="flow"),st==="reasoning_start"){let V=typeof x.id=="string"?x.id:null,j=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(V&&j){M.set(V,j),X(V,j,"reasoning");continue}let Q=(L=Ie(x,!0))!=null?L:`reason-${p()}`,G=ie(Q);G.reasoning=(ge=G.reasoning)!=null?ge:{id:Q,status:"streaming",chunks:[]},G.reasoning.startedAt=(Le=G.reasoning.startedAt)!=null?Le:Se((Me=x.startedAt)!=null?Me:x.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(G.reasoning.scope=x.scope),G.streaming=!0,G.reasoning.status="streaming",m(G)}else if(st==="reasoning_delta"){let V=typeof x.id=="string"?x.id:null;if(V&&M.has(V)&&P.has(V)){let Ne=P.get(V),rt=(Xe=(nt=(He=x.reasoningText)!=null?He:x.text)!=null?nt:x.delta)!=null?Xe:"";rt&&x.hidden!==!0&&Ne.reasoning&&(Ne.reasoning.chunks.push(String(rt)),m(Ne));continue}let j=(fe=(yt=Ie(x,!1))!=null?yt:Ie(x,!0))!=null?fe:`reason-${p()}`,Q=ie(j);Q.reasoning=(D=Q.reasoning)!=null?D:{id:j,status:"streaming",chunks:[]},Q.reasoning.startedAt=(ce=Q.reasoning.startedAt)!=null?ce:Se((ve=x.startedAt)!=null?ve:x.timestamp);let G=(Pt=(Ge=(ft=x.reasoningText)!=null?ft:x.text)!=null?Ge:x.delta)!=null?Pt:"";if(G&&x.hidden!==!0){let Ne=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(Ne!==void 0){let rt=tt(j,Ne,String(G));Q.reasoning.chunks=[rt]}else Q.reasoning.chunks.push(String(G))}if(Q.reasoning.status=x.done?"complete":"streaming",x.done){Q.reasoning.completedAt=Se((kt=x.completedAt)!=null?kt:x.timestamp);let Ne=(wt=Q.reasoning.startedAt)!=null?wt:Date.now();Q.reasoning.durationMs=Math.max(0,((Ht=Q.reasoning.completedAt)!=null?Ht:Date.now())-Ne)}Q.streaming=Q.reasoning.status!=="complete",m(Q)}else if(st==="reasoning_complete"){let V=typeof x.id=="string"?x.id:null;if(V&&M.has(V)&&P.has(V)){let rt=P.get(V);if(rt.reasoning){let dt=typeof x.text=="string"?x.text:"";dt&&rt.reasoning.chunks.length===0&&rt.reasoning.chunks.push(dt),rt.reasoning.status="complete",rt.streaming=!1,m(rt)}M.delete(V),P.delete(V);continue}let j=(Ot=(Xt=Ie(x,!1))!=null?Xt:Ie(x,!0))!=null?Ot:`reason-${p()}`,Q=typeof x.text=="string"?x.text:"";!k.get(j)&&(Q||x.scope==="loop")&&ie(j);let G=k.get(j);if(G!=null&&G.reasoning){(x.scope==="loop"||x.scope==="turn")&&(G.reasoning.scope=x.scope),Q&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(Q),G.reasoning.status="complete",G.reasoning.completedAt=Se((en=x.completedAt)!=null?en:x.timestamp);let rt=(br=G.reasoning.startedAt)!=null?br:Date.now();G.reasoning.durationMs=Math.max(0,((Wr=G.reasoning.completedAt)!=null?Wr:Date.now())-rt),G.streaming=!1,m(G)}let Ne=F(x);Ne&&_.byStep.delete(Ne)}else if(st==="tool_start"){y&&(y.streaming=!1,m(y),y=null),typeof x.iteration=="number"&&(xe=x.iteration);let V=(or=(rr=typeof x.toolCallId=="string"?x.toolCallId:void 0)!=null?rr:K(x,!0))!=null?or:`tool-${p()}`,j=(Kr=x.toolName)!=null?Kr:x.name;if($e(j)){re.add(V);continue}he(Z(x),V);let Q=J(V),G=(Vt=Q.toolCall)!=null?Vt:{id:V,status:"pending"};G.name=j!=null?j:G.name,G.status="running",x.parameters!==void 0?G.args=x.parameters:x.args!==void 0&&(G.args=x.args),G.startedAt=(Hr=G.startedAt)!=null?Hr:Se((sr=x.startedAt)!=null?sr:x.timestamp),G.completedAt=void 0,G.durationMs=void 0,Q.toolCall=G,Q.streaming=!0,x.executionId&&(Q.agentMetadata={executionId:x.executionId,iteration:x.iteration}),m(Q)}else if(st==="tool_output_delta"){let V=(Ln=(Bn=K(x,!1))!=null?Bn:K(x,!0))!=null?Ln:`tool-${p()}`;if(re.has(V))continue;let j=J(V),Q=(Dn=j.toolCall)!=null?Dn:{id:V,status:"running"};Q.startedAt=(vr=Q.startedAt)!=null?vr:Se((ar=x.startedAt)!=null?ar:x.timestamp);let G=(Qr=(Vn=(Gr=x.text)!=null?Gr:x.delta)!=null?Vn:x.message)!=null?Qr:"";G&&(Q.chunks=(St=Q.chunks)!=null?St:[],Q.chunks.push(String(G))),Q.status="running",j.toolCall=Q,j.streaming=!0;let Ne=x.agentContext;(Ne||x.executionId)&&(j.agentMetadata=(Br=j.agentMetadata)!=null?Br:{executionId:(wr=Ne==null?void 0:Ne.executionId)!=null?wr:x.executionId,iteration:(xr=Ne==null?void 0:Ne.iteration)!=null?xr:x.iteration}),m(j)}else if(st==="tool_complete"){let V=(bt=(ir=K(x,!1))!=null?ir:K(x,!0))!=null?bt:`tool-${p()}`;if(re.has(V)){re.delete(V);continue}let j=J(V),Q=(Co=j.toolCall)!=null?Co:{id:V,status:"running"};Q.status="complete",x.result!==void 0&&(Q.result=x.result),typeof x.duration=="number"&&(Q.duration=x.duration),Q.completedAt=Se((Cr=x.completedAt)!=null?Cr:x.timestamp);let G=(Ao=x.duration)!=null?Ao:x.executionTime;if(typeof G=="number")Q.durationMs=G;else{let dt=(Pn=Q.startedAt)!=null?Pn:Date.now();Q.durationMs=Math.max(0,((Qo=Q.completedAt)!=null?Qo:Date.now())-dt)}j.toolCall=Q,j.streaming=!1;let Ne=x.agentContext;(Ne||x.executionId)&&(j.agentMetadata=(Jr=j.agentMetadata)!=null?Jr:{executionId:(Xr=Ne==null?void 0:Ne.executionId)!=null?Xr:x.executionId,iteration:(Dr=Ne==null?void 0:Ne.iteration)!=null?Dr:x.iteration}),m(j);let rt=Z(x);rt&&R.byCall.delete(rt)}else if(st==="await"&&x.toolName){let V=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,j=(Yr=V!=null?V:x.toolId)!=null?Yr:`local-${p()}`,Q=J(j),G=x.toolName,Ne=x.origin==="webmcp"&&!cs(G)?`webmcp:${G}`:G,rt=cs(Ne),dt=(So=Q.toolCall)!=null?So:{id:j,status:"pending"};dt.name=Ne,dt.args=x.parameters,dt.status=rt?"running":"complete",dt.chunks=(To=dt.chunks)!=null?To:[],dt.startedAt=(Nn=dt.startedAt)!=null?Nn:Se((xt=(Zr=x.startedAt)!=null?Zr:x.timestamp)!=null?xt:x.awaitedAt),rt?(dt.completedAt=void 0,dt.duration=void 0,dt.durationMs=void 0):dt.completedAt=(Fn=dt.completedAt)!=null?Fn:dt.startedAt,Q.toolCall=dt,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(Tt=x.executionId)!=null?Tt:(Cn=Q.agentMetadata)==null?void 0:Cn.executionId,awaitingLocalTool:!0,...V?{webMcpToolCallId:V}:{}},m(Q)}else if(st==="text_start"){let V=typeof x.id=="string"?x.id:null,j=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(V&&j){M.set(V,j);continue}let Q=y;Q&&(Ze==="flow"?(me(Q),ht=Q):(Q.streaming=!1,m(Q)),y=null),T=typeof x.id=="string"?x.id:T,I=""}else if(st==="text_delta"){let V=typeof x.id=="string"?x.id:null,j=V?M.get(V):void 0;if(V&&j){let G=typeof x.delta=="string"?x.delta:"",Ne=((Kn=C.get(V))!=null?Kn:"")+G;if(C.set(V,Ne),Ne.trim()==="")continue;let rt=X(V,j);rt.agentMetadata={...rt.agentMetadata,executionId:x.executionId,parentToolId:j},ot(rt,Ne,G,void 0);continue}if(T=typeof x.id=="string"?x.id:T,Ze==="flow"){let G=typeof x.delta=="string"?x.delta:"";if(I+=G,I.trim()==="")continue;let Ne=ee();Ne.agentMetadata={executionId:x.executionId,iteration:x.iteration},ot(Ne,I,G,void 0),w=Ne;continue}let Q=ee();Q.content+=(Gn=x.delta)!=null?Gn:"",Q.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:be!=null?be:void 0,agentName:ue==null?void 0:ue.agentName},w=Q,m(Q)}else if(st==="text_complete"){let V=typeof x.id=="string"?x.id:null;if(V&&M.has(V)){let Q=P.get(V);Q&&me(Q),M.delete(V),C.delete(V),P.delete(V);continue}let j=y;j&&(Ze==="flow"?(me(j),ht=j):(((On=j.content)!=null?On:"")===""&&typeof x.text=="string"&&(j.content=x.text),j.streaming=!1,m(j)),y=null),T=null,I=""}else if(st==="step_complete"){let V=x.stepType,j=x.executionType;if(V==="tool"||j==="context")continue;if(x.success===!1){let Q=x.error,G=typeof Q=="string"&&Q!==""?Q:Q!=null&&typeof Q=="object"&&"message"in Q?String((eo=Q.message)!=null?eo:"Step failed"):"Step failed";t({type:"error",error:new Error(G)});let Ne=y;Ne&&Ne.streaming&&(Ne.streaming=!1,m(Ne)),t({type:"status",status:"idle"});continue}{let Q=ht;ht=null;let G=x.stopReason,Ne=(Ce=x.result)==null?void 0:Ce.response;if(Q)G&&(Q.stopReason=G),Ne!=null?Wt(Q,Ne):Q.streaming!==!1&&(le.delete(Q.id),Te.delete(Q.id),Q.streaming=!1,m(Q));else{let rt=Ne!=null&&Ne!=="";if(rt||G){let dt=ee();G&&(dt.stopReason=G),rt?me(dt,Ne):(dt.streaming=!1,m(dt))}}continue}}else if(st==="execution_start")Ze=x.kind==="flow"?"flow":"agent",jt=!0,Ze==="agent"&&(ue={executionId:x.executionId,agentId:(Nr=x.agentId)!=null?Nr:"virtual",agentName:(Qn=x.agentName)!=null?Qn:"",status:"running",currentIteration:0,maxTurns:(_t=x.maxTurns)!=null?_t:1,startedAt:Se(x.startedAt)});else if(st==="turn_start"){let V=typeof x.iteration=="number"?x.iteration:xe;if(V!==xe){if(ue&&(ue.currentIteration=V),At==="separate"&&V>1){let j=y;j&&(j.streaming=!1,m(j),xn.set(V-1,j),y=null)}xe=V}be=typeof x.id=="string"?x.id:null,w=null}else if(st==="tool_input_delta"){let V=(Xn=x.toolCallId)!=null?Xn:R.lastId;if(V){let j=q.get(V);j!=null&&j.toolCall&&(j.toolCall.chunks=(Fr=j.toolCall.chunks)!=null?Fr:[],j.toolCall.chunks.push((ks=x.delta)!=null?ks:""),m(j))}}else{if(st==="tool_input_complete")continue;if(st==="turn_complete"){let V=x.stopReason,j=y!=null?y:w;if(V&&j!==null){let Q=x.id;(!Q||((Xo=j.agentMetadata)==null?void 0:Xo.turnId)===Q)&&(j.stopReason=V,m(j))}be===x.id&&(be=null)}else if(st==="media_start"){let V=String(x.id);Ee.set(V,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(st==="media_delta"){let V=Ee.get(String(x.id));V&&typeof x.delta=="string"&&V.parts.push(x.delta)}else if(st==="media_complete"){let V=String(x.id),j=Ee.get(V);Ee.delete(V);let Q=(Eo=(Ls=typeof x.mediaType=="string"?x.mediaType:void 0)!=null?Ls:j==null?void 0:j.mediaType)!=null?Eo:"application/octet-stream",G=typeof x.data=="string"?x.data:void 0,Ne=typeof x.url=="string"?x.url:j&&j.parts.length>0?j.parts.join(""):void 0,rt=null;if(G)rt={type:"media",data:G,mediaType:Q};else if(Ne){let In=Q.toLowerCase();rt={type:In==="image"||In.startsWith("image/")?"image-url":"file-url",url:Ne,mediaType:Q}}let dt=(Ar=x.toolCallId)!=null?Ar:j==null?void 0:j.toolCallId,hi=rt?[rt]:[],oo=[];for(let In of hi){if(!In||typeof In!="object")continue;let Jt=In,so=typeof Jt.type=="string"?Jt.type:void 0,Jn=typeof Jt.mediaType=="string"?Jt.mediaType.toLowerCase():"",Tn=null,Rn="";if(so==="media"){let En=typeof Jt.data=="string"?Jt.data:void 0;if(!En)continue;Rn=Jn.length>0?Jn:"application/octet-stream",Tn=`data:${Rn};base64,${En}`}else if(so==="image-url"){let En=typeof Jt.url=="string"?Jt.url:void 0;if(!En)continue;Rn=Jn,Tn=En}else if(so==="file-url"){let En=typeof Jt.url=="string"?Jt.url:void 0;if(!En)continue;Rn=Jn,Tn=En}else continue;if(Tn)if(so==="image-url"||Rn.startsWith("image/"))oo.push({type:"image",image:Tn,...Rn.includes("/")?{mimeType:Rn}:{}});else if(Rn.startsWith("audio/"))oo.push({type:"audio",audio:Tn,mimeType:Rn});else if(Rn.startsWith("video/"))oo.push({type:"video",video:Tn,mimeType:Rn});else{let En=Rn||"application/octet-stream";oo.push({type:"file",data:Tn,mimeType:En,filename:ch(En)})}}if(oo.length>0){let In=p(),Jt=dt,Jn={id:`agent-media-${typeof Jt=="string"&&Jt.length>0?`${Jt}-${In}`:String(In)}`,role:"assistant",content:"",contentParts:oo,createdAt:new Date().toISOString(),streaming:!1,sequence:In,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:xe}};m(Jn);let Tn=y;Tn&&(Tn.streaming=!1,m(Tn)),y=null,E.current=null}}else if(st==="execution_complete"){let V=(to=x.kind)!=null?to:Ze;V==="agent"&&ue&&(ue.status=x.success?"complete":"error",ue.completedAt=Se(x.completedAt),ue.stopReason=x.stopReason);let j=y;j&&(V==="flow"&&j.streaming!==!1?me(j):(j.streaming=!1,m(j)),y=null),T=null,I="",ht=null,t({type:"status",status:"idle",terminal:!0})}else if(st==="execution_error"){let V=typeof x.error=="string"?x.error:(rn=(ct=x.error)==null?void 0:ct.message)!=null?rn:"Execution error";t({type:"error",error:new Error(V)})}else if(st!=="ping"){if(st==="approval_start"){let V=(on=x.approvalId)!=null?on:`approval-${p()}`,j={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:"pending",agentId:(Sr=ue==null?void 0:ue.agentId)!=null?Sr:"virtual",executionId:(Or=(Ps=x.executionId)!=null?Ps:ue==null?void 0:ue.executionId)!=null?Or:"",toolName:(Mo=x.toolName)!=null?Mo:"",toolType:x.toolType,description:($=x.description)!=null?$:`Execute ${(Tr=x.toolName)!=null?Tr:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(j)}else if(st==="step_await"&&x.awaitReason==="approval_required"){let V=(Jo=x.approvalId)!=null?Jo:`approval-${p()}`,j={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:"pending",agentId:(lr=ue==null?void 0:ue.agentId)!=null?lr:"virtual",executionId:(_r=(Er=x.executionId)!=null?Er:ue==null?void 0:ue.executionId)!=null?_r:"",toolName:(Mr=x.toolName)!=null?Mr:"",toolType:x.toolType,description:(Yo=x.description)!=null?Yo:`Execute ${(cr=x.toolName)!=null?cr:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(j)}else if(st==="approval_complete"){let V=x.approvalId;if(V){let Q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:(ha=x.decision)!=null?ha:"approved",agentId:(hn=ue==null?void 0:ue.agentId)!=null?hn:"virtual",executionId:(dr=(An=x.executionId)!=null?An:ue==null?void 0:ue.executionId)!=null?dr:"",toolName:(Sn=x.toolName)!=null?Sn:"",description:(ko=x.description)!=null?ko:"",resolvedAt:Date.now()}};m(Q)}}else if(st==="artifact_start"||st==="artifact_delta"||st==="artifact_update"||st==="artifact_complete"){if(st==="artifact_start"){let V=x.artifactType,j=String(x.id),Q=typeof x.title=="string"?x.title:void 0;if(t({type:"artifact_start",id:j,artifactType:V,title:Q,component:typeof x.component=="string"?x.component:void 0}),Ae.set(j,{markdown:"",title:Q}),!de.has(j)){de.add(j);let G={id:`artifact-ref-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:j,title:Q,artifactType:V,status:"streaming"}})};oe.set(j,G),m(G)}}else if(st==="artifact_delta"){let V=String(x.id),j=typeof x.delta=="string"?x.delta:String((pr=x.delta)!=null?pr:"");t({type:"artifact_delta",id:V,artDelta:j});let Q=Ae.get(V);Q&&(Q.markdown+=j)}else if(st==="artifact_update"){let V=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};t({type:"artifact_update",id:String(x.id),props:V,component:typeof x.component=="string"?x.component:void 0})}else if(st==="artifact_complete"){let V=String(x.id);t({type:"artifact_complete",id:V});let j=oe.get(V);if(j){j.streaming=!1;try{let Q=JSON.parse((yn=j.rawContent)!=null?yn:"{}");if(Q.props){Q.props.status="complete";let G=Ae.get(V);G!=null&&G.markdown&&(Q.props.markdown=G.markdown)}j.rawContent=JSON.stringify(Q)}catch{}Ae.delete(V),m(j),oe.delete(V)}}}else if(st==="transcript_insert"){let V=x.message;if(!V||typeof V!="object")continue;let j=String((kr=V.id)!=null?kr:`msg-${p()}`),Q=V.role,Ne={id:j,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof V.content=="string"?V.content:"",rawContent:typeof V.rawContent=="string"?V.rawContent:void 0,createdAt:typeof V.createdAt=="string"?V.createdAt:new Date().toISOString(),streaming:V.streaming===!0,...typeof V.variant=="string"?{variant:V.variant}:{},sequence:p()};if(m(Ne),Ne.rawContent)try{let rt=JSON.parse(Ne.rawContent),dt=(Zo=rt==null?void 0:rt.props)==null?void 0:Zo.artifactId;typeof dt=="string"&&de.add(dt)}catch{}y=null,E.current=null,le.delete(j),Te.delete(j)}else if(st==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let V=typeof x.error=="string"?x.error:((Lo=x.error)==null?void 0:Lo.message)!=null?String(x.error.message):"Execution error";t({type:"error",error:new Error(V)});let j=y;j&&j.streaming&&(j.streaming=!1,m(j)),t({type:"status",status:"idle"})}}else if(st==="step_error"||st==="dispatch_error"||st==="flow_error"){let V=null;if(x.error instanceof Error)V=x.error;else if(st==="dispatch_error"){let j=(es=x.message)!=null?es:x.error;j!=null&&j!==""&&(V=new Error(String(j)))}else{let j=x.error;typeof j=="string"&&j!==""?V=new Error(j):j!=null&&typeof j=="object"&&"message"in j&&(V=new Error(String((no=j.message)!=null?no:j)))}if(V){t({type:"error",error:V});let j=y;j&&j.streaming&&(j.streaming=!1,m(j)),t({type:"status",status:"idle"})}}}}}lt.length=0};;){let{done:L,value:ge}=await s.read();if(L)break;i+=a.decode(ge,{stream:!0});let Me=i.split(`
|
|
12
12
|
|
|
13
|
-
`);
|
|
14
|
-
`),Fe="message",Ke="";for(let ce of Pe)ce.startsWith("event:")?Fe=ce.replace("event:","").trim():ce.startsWith("data:")&&(Ke+=ce.replace("data:","").trim());if(!Ke)continue;let it;try{it=JSON.parse(Ke)}catch(ce){n({type:"error",error:ce instanceof Error?ce:new Error("Failed to parse chat stream payload")});continue}let Rt=Fe!=="message"?Fe:(hr=it.type)!=null?hr:"message";if((yr=this.onSSEEvent)==null||yr.call(this,Rt,it),this.parseSSEEvent){v.current=f;let ce=await this.handleCustomSSEEvent(it,n,v,g,c,k);if(v.current&&v.current!==f&&(f=v.current),ce)continue}Q.push({payloadType:Rt,payload:it}),dt()}}dt()}};function La(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${t}_${e}`}function Us(){let t=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${t}_${e}`}var Pa="[Image]";function Ri(t){return{type:"text",text:t}}var Mu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Df=["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=[...Mu,...Df];function Nf(t){return Mu.includes(t)||t.startsWith("image/")}function Ia(t){return Nf(t.type)}async function ku(t){return new Promise((e,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ia(t)?e({type:"image",image:o,mimeType:t.type,alt:t.name}):e({type:"file",data:o,mimeType:t.type,filename:t.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(t)})}function Lu(t,e=qr,n=10*1024*1024){return e.includes(t.type)?t.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${e.join(", ")}`}}function Ff(t){let e=t.split(".");return e.length>1?e.pop().toLowerCase():""}function Pu(t,e){let n=Ff(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[t]||n||"FILE"}Hi();var Iu=16e3,Of=24e3,_f=4096,$f=1380533830;function Uf(t){return t.byteLength>=44&&new DataView(t).getUint32(0,!1)===$f?new Uint8Array(t,44):new Uint8Array(t)}function zf(t){var r;let e=t.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${e}`}var zs=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let e=(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(!e)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:Iu,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(v=>v.stop());return}this.mediaStream=c;let u=window.AudioContext||window.webkitAudioContext,m=new u({sampleRate:Iu});m.state==="suspended"&&await m.resume().catch(()=>{}),this.captureContext=m;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new ls(Of);if(o!==this.callGeneration){g.destroy(),c.getTracks().forEach(v=>v.stop()),m.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let f=`${zf(r)}/ws/agents/${encodeURIComponent(e)}/voice`,w=new WebSocket(f,["runtype.bearer",n]);w.binaryType="arraybuffer",this.ws=w,w.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(m,c,w,o))},w.onmessage=v=>this.handleMessage(v,o),w.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},w.onclose=v=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(v.code!==1e3){let k=v.code?` (code ${v.code})`:"";this.emitError(new Error(`Voice connection closed${k}`)),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(e,n,r,o){let s=e.createMediaStreamSource(n);this.sourceNode=s;let a=e.createScriptProcessor(_f,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 u=0;u<d.length;u++){let m=Math.max(-1,Math.min(1,d[u]));c[u]=m<0?m*32768:m*32767}r.send(c.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,n){var o,s;if(n!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,n);return}let r;try{r=JSON.parse(e.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(e,n){if(n!==this.callGeneration||!this.playback)return;let r=Uf(e);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(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(n=>n(e))}emitError(e){this.errorCallbacks.forEach(n=>n(e))}emitTranscript(e,n,r){this.transcriptCallbacks.forEach(o=>o(e,n,r))}emitMetrics(e){this.metricsCallbacks.forEach(n=>n(e))}};var Ro=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,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=((e=this.config)==null?void 0:e.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(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function cs(t){switch(t.type){case"runtype":if(!t.runtype)throw new Error("Runtype voice provider requires configuration");return new zs(t.runtype);case"browser":if(!Ro.isSupported())throw new Error("Browser speech recognition not supported");return new Ro(t.browser||{});case"custom":{let e=t.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof e=="function"?e():e;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${t.type}`)}}function Wu(t){if((t==null?void 0:t.type)==="custom"&&t.custom)return cs({type:"custom",custom:t.custom});if((t==null?void 0:t.type)==="runtype"&&t.runtype)return cs({type:"runtype",runtype:t.runtype});if(Ro.isSupported())return cs({type:"browser",browser:(t==null?void 0:t.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Bi(t){try{return Wu(t),!0}catch{return!1}}function Wa(t){var n;let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of e){let o=t.find(s=>s.name===r);if(o)return o}return(n=t.find(r=>r.lang.startsWith("en")))!=null?n:t[0]}var ds=class t{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(e,n){var a;if(!t.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(e.text),s=r.getVoices();if(e.voice){let i=s.find(d=>d.name===e.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):Wa(s));e.rate!==void 0&&(o.rate=e.rate),e.pitch!==void 0&&(o.pitch=e.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var c,u;let d=i.error;d==="canceled"||d==="interrupted"?(c=n.onEnd)==null||c.call(n):(u=n.onError)==null||u.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){t.isSupported()&&window.speechSynthesis.pause()}resume(){t.isSupported()&&window.speechSynthesis.resume()}stop(){t.isSupported()&&window.speechSynthesis.cancel()}};var qs=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var e,n;return(n=(e=this.engine)==null?void 0:e.supportsPause)!=null?n:!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,n){var r,o;if(this.activeId===e){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,n)}async play(e,n){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(e,"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(e,"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 e;this.generation++,(e=this.engine)==null||e.stop(),this.set(null,"idle")}destroy(){var e,n;this.stop(),(n=(e=this.engine)==null?void 0:e.destroy)==null||n.call(e),this.engine=null,this.listeners.clear()}set(e,n){this.activeId=n==="idle"?null:e,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function Di(t){if(!t)return"";let e=qf(t);return Ru(e!==null?e:t)}function qf(t){let e=t.trim(),n=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(e=n[1].trim()),!e.startsWith("{"))return null;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Ru(t){if(!t)return"";let e=t;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|
|
13
|
+
`);i=(hr=Me.pop())!=null?hr:"";for(let Le of Me){let He=Le.split(`
|
|
14
|
+
`),nt="message",Xe="",yt=null;for(let ce of He)ce.startsWith("event:")?nt=ce.replace("event:","").trim():ce.startsWith("data:")?Xe+=ce.replace("data:","").trim():ce.startsWith("id:")&&(yt=ce.slice(3).trim());let fe=()=>{yt!==null&&yt!==""&&t({type:"cursor",id:yt})};if(!Xe){fe();continue}let D;try{D=JSON.parse(Xe)}catch(ce){t({type:"error",error:ce instanceof Error?ce:new Error("Failed to parse chat stream payload")});continue}let ve=nt!=="message"?nt:(yr=D.type)!=null?yr:"message";if((qe=this.onSSEEvent)==null||qe.call(this,ve,D),this.parseSSEEvent){E.current=y;let ce=await this.handleCustomSSEEvent(D,t,E,m,p,B);if(E.current&&E.current!==y&&(y=E.current),ce){fe();continue}}lt.push({payloadType:ve,payload:D}),Ve(),fe()}}Ve()}};function Ba(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${n}_${e}`}function fs(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${n}_${e}`}var Da="[Image]";function $i(n){return{type:"text",text:n}}var Yu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],uh=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],jr=[...Yu,...uh];function mh(n){return Yu.includes(n)||n.startsWith("image/")}function Na(n){return mh(n.type)}async function Zu(n){return new Promise((e,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Na(n)?e({type:"image",image:o,mimeType:n.type,alt:n.name}):e({type:"file",data:o,mimeType:n.type,filename:n.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(n)})}function em(n,e=jr,t=10*1024*1024){return e.includes(n.type)?n.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${e.join(", ")}`}}function gh(n){let e=n.split(".");return e.length>1?e.pop().toLowerCase():""}function tm(n,e){let t=gh(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[n]||t||"FILE"}Ui();var nm=16e3,fh=24e3,hh=4096,yh=1380533830;function bh(n){return n.byteLength>=44&&new DataView(n).getUint32(0,!1)===yh?new Uint8Array(n,44):new Uint8Array(n)}function vh(n){var r;let e=n.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${e}`}var Ys=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let e=(s=this.config)==null?void 0:s.agentId,t=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!t)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:nm,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(w=>w.stop());return}this.mediaStream=c;let p=window.AudioContext||window.webkitAudioContext,g=new p({sampleRate:nm});g.state==="suspended"&&await g.resume().catch(()=>{}),this.captureContext=g;let h=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new hs(fh);if(o!==this.callGeneration){h.destroy(),c.getTracks().forEach(w=>w.stop()),g.close().catch(()=>{});return}this.playback=h,h.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${vh(r)}/ws/agents/${encodeURIComponent(e)}/voice`,y=new WebSocket(m,["runtype.bearer",t]);y.binaryType="arraybuffer",this.ws=y,y.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(g,c,y,o))},y.onmessage=w=>this.handleMessage(w,o),y.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},y.onclose=w=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(w.code!==1e3){let E=w.code?` (code ${w.code})`:"";this.emitError(new Error(`Voice connection closed${E}`)),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(e,t,r,o){let s=e.createMediaStreamSource(t);this.sourceNode=s;let a=e.createScriptProcessor(hh,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 g=Math.max(-1,Math.min(1,d[p]));c[p]=g<0?g*32768:g*32767}r.send(c.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,t){var o,s;if(t!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,t);return}let r;try{r=JSON.parse(e.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(e,t){if(t!==this.callGeneration||!this.playback)return;let r=bh(e);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(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(t=>t(e))}emitError(e){this.errorCallbacks.forEach(t=>t(e))}emitTranscript(e,t,r){this.transcriptCallbacks.forEach(o=>o(e,t,r))}emitMetrics(e){this.metricsCallbacks.forEach(t=>t(e))}};var Uo=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,t;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=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.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(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function ys(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new Ys(n.runtype);case"browser":if(!Uo.isSupported())throw new Error("Browser speech recognition not supported");return new Uo(n.browser||{});case"custom":{let e=n.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let t=typeof e=="function"?e():e;if(!t||typeof t.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return t}default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function rm(n){if((n==null?void 0:n.type)==="custom"&&n.custom)return ys({type:"custom",custom:n.custom});if((n==null?void 0:n.type)==="runtype"&&n.runtype)return ys({type:"runtype",runtype:n.runtype});if(Uo.isSupported())return ys({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function qi(n){try{return rm(n),!0}catch{return!1}}function Fa(n){var t;let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of e){let o=n.find(s=>s.name===r);if(o)return o}return(t=n.find(r=>r.lang.startsWith("en")))!=null?t:n[0]}var bs=class n{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(e,t){var a;if(!n.isSupported()){(a=t.onError)==null||a.call(t,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(e.text),s=r.getVoices();if(e.voice){let i=s.find(d=>d.name===e.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):Fa(s));e.rate!==void 0&&(o.rate=e.rate),e.pitch!==void 0&&(o.pitch=e.pitch),o.onend=()=>{var i;return(i=t.onEnd)==null?void 0:i.call(t)},o.onerror=i=>{var c,p;let d=i.error;d==="canceled"||d==="interrupted"?(c=t.onEnd)==null||c.call(t):(p=t.onError)==null||p.call(t,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=t.onStart)==null||i.call(t)},50)}pause(){n.isSupported()&&window.speechSynthesis.pause()}resume(){n.isSupported()&&window.speechSynthesis.resume()}stop(){n.isSupported()&&window.speechSynthesis.cancel()}};var Zs=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var e,t;return(t=(e=this.engine)==null?void 0:e.supportsPause)!=null?t:!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,t){var r,o;if(this.activeId===e){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,t)}async play(e,t){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(e,"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(t,{onStart:()=>{r===this.generation&&this.set(e,"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 e;this.generation++,(e=this.engine)==null||e.stop(),this.set(null,"idle")}destroy(){var e,t;this.stop(),(t=(e=this.engine)==null?void 0:e.destroy)==null||t.call(e),this.engine=null,this.listeners.clear()}set(e,t){this.activeId=t==="idle"?null:e,this.state=t;for(let r of this.listeners)r(this.activeId,this.state)}};function zi(n){if(!n)return"";let e=wh(n);return om(e!==null?e:n)}function wh(n){let e=n.trim(),t=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(t&&(e=t[1].trim()),!e.startsWith("{"))return null;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function om(n){if(!n)return"";let e=n;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|
|
15
15
|
`),e=e.replace(/\n{2,}/g,`
|
|
16
|
-
`),e.trim()}var
|
|
16
|
+
`),e.trim()}var cm=null;var ji=()=>cm?cm():Promise.resolve().then(()=>(lm(),im));var Th=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Eh(n,e){return Th.some(t=>n[t]!==e[t])}function Vi(n,e){let t=n instanceof Error?n:new Error(String(n));if(typeof e=="string")return e;if(typeof e=="function")return e(t);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 t.message?`${r}
|
|
17
17
|
|
|
18
|
-
_Details: ${n.message}_`:r}var js=t=>({isError:!0,content:[{type:"text",text:t}]}),_u=(t,e="WebMCP tool execution failed.")=>t instanceof Error&&t.message?t.message:typeof t=="string"&&t?t:e,$u=t=>ns(t)||t===zr,Ba=class{constructor(e={},n){this.config=e;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.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 qs(()=>this.createSpeechEngine());this.handleEvent=e=>{var n,r,o,s,a,i,d,c,u,m;if(e.type==="message"){this.upsertMessage(e.message);let g=e.message.toolCall,f=!!(g!=null&&g.name)&&(ns(g.name)||g.name===zr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&f&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(e.type==="status"){if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(m=(u=this.callbacks).onError)==null||m.call(u,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.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 $s(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d,c;let e=this.config.textToSpeech;if((e==null?void 0:e.provider)!=="runtype"||e.createEngine)return;let n=(o=e.host)!=null?o:this.config.apiUrl,r=(c=(d=e.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||Ni().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return Bi((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,n,r;return(r=(n=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:n.call(e))!=null?r:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let e=this.config.textToSpeech;if(e!=null&&e.createEngine)return e.createEngine();let n=ds.isSupported()?new ds({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let c=(r=e.host)!=null?r:this.config.apiUrl,u=(d=(i=e.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,m=this.config.clientToken,g=e.browserFallback!==!1;if(c&&u&&m)return Ni().then(({RuntypeSpeechEngine:f,FallbackSpeechEngine:w})=>{let v=new f({host:c,agentId:u,clientToken:m,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return g&&n?new w(v,n,{onFallback:k=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${k.message}`)}):v});if(g&&n)return m&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(e){var n,r;try{let o=e||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=cs(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 u=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=u.id}if(c){this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.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 u=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=u.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(e){console.error("Failed to start voice:",e)}}}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,u,m,g,f;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=e.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=e.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=e.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(u=e.runtype)==null?void 0:u.voiceId,createPlaybackEngine:(m=e.runtype)==null?void 0:m.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((g=e.browser)==null?void 0:g.language)||"en-US",continuous:(f=e.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){var e,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(e=this.callbacks).onError)==null||n.call(e,r instanceof Error?r:new Error(String(r))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,n){return this.client.submitMessageFeedback(e,n)}async submitCSATFeedback(e,n){return this.client.submitCSATFeedback(e,n)}async submitNPSFeedback(e,n){return this.client.submitNPSFeedback(e,n)}updateConfig(e){let n={...this.config,...e};if(!Gf(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 $s(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:u,rawContent:m}=e,f={id:a!=null?a:n==="user"?La():n==="assistant"?Us():`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},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};return this.upsertMessage(f),f}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let n=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:u,streaming:m=!1,voiceProcessing:g,rawContent:f}=r,v={id:d!=null?d:o==="user"?La():o==="assistant"?Us():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:m,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(e){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,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(e,n){var c,u,m,g,f;let r=e.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves();let o=La(),s=Us(),a={id:o,role:"user",content:r||Pa,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(w){let v=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));if(!v){let k=Ou(w,this.config.errorMessage);if(k){let R={id:s,role:"assistant",createdAt:new Date().toISOString(),content:k,sequence:this.nextSequence()};this.appendMessage(R)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(w instanceof Error?(m=(u=this.callbacks).onError)==null||m.call(u,w):(f=(g=this.callbacks).onError)==null||f.call(g,new Error(String(w))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=Us();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:e},this.handleEvent)}catch(c){let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let m=Ou(c,this.config.errorMessage);if(m){let g={id:e,role:"assistant",createdAt:new Date().toISOString(),content:m,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(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(e,n){var o,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.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(e,n){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(e,n,r){var u,m,g,f,w;let o=`approval-${e.id}`,s={...e,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===o),i={id:o,role:"assistant",content:"",createdAt:(u=a==null?void 0:a.createdAt)!=null?u:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(m=this.abortController)==null||m.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:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},n,r):v=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},n),v){let k=null;if(v instanceof Response){if(!v.ok){let R=await v.json().catch(()=>null);throw new Error((g=R==null?void 0:R.error)!=null?g:`Approval request failed: ${v.status}`)}k=v.body}else v instanceof ReadableStream&&(k=v);k?await this.connectStream(k,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let k=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,k||(w=(f=this.callbacks).onError)==null||w.call(f,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(e,n){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(e,n){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(e,n){var u,m,g,f,w,v,k,R,E,L,M,I;let r=this.messages.find(A=>A.id===e.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let o=(m=e.agentMetadata)==null?void 0:m.executionId,s=(g=e.toolCall)==null?void 0:g.name;if(!o||!s){(w=(f=this.callbacks).onError)==null||w.call(f,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 A=(v=e.toolCall)==null?void 0:v.args,P=Array.isArray(A==null?void 0:A.questions)?A.questions:[];if(P.length===1){let O=typeof((k=P[0])==null?void 0:k.question)=="string"?P[0].question:"";O&&(a={[O]:n})}}this.markAskUserQuestionResolved(e,a),(R=this.abortController)==null||R.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(E=e.toolCall)==null?void 0:E.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let A=typeof n=="string"?n:Object.entries(n).map(([P,O])=>`${P}: ${Array.isArray(O)?O.join(", "):O}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:A,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let A=a!=null?a:{};c.forEach((P,O)=>{let _=typeof(P==null?void 0:P.question)=="string"?P.question:"";if(!_)return;let H=A[_],U=Array.isArray(H)?H.join(", "):typeof H=="string"?H:"";this.appendMessage({id:`ask-user-q-${i}-${O}`,role:"assistant",content:_,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${O}`,role:"user",content:U||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let A=await this.client.resumeFlow(o,{[s]:n});if(!A.ok){let P=await A.json().catch(()=>null);throw new Error((L=P==null?void 0:P.error)!=null?L:`Resume failed: ${A.status}`)}A.body?await this.connectStream(A.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(A){let P=A instanceof Error&&(A.name==="AbortError"||A.message.includes("aborted")||A.message.includes("abort"));this.setStreaming(!1),this.abortController=null,P||(I=(M=this.callbacks).onError)==null||I.call(M,A instanceof Error?A:new Error(String(A)))}}enqueueWebMcpAwait(e){var s,a;let n=(s=e.agentMetadata)==null?void 0:s.executionId,r=(a=e.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});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(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(e){let n=this.webMcpAwaitBatches.get(e);if(!n)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(e,r)}resolveWebMcpToolStartedAt(e){var o,s;let n=this.messages.find(a=>a.id===e.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=e.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(e){var r,o;if(((r=e.toolCall)==null?void 0:r.name)!==zr)return!1;let n=this.messages.find(s=>s.id===e.id);return((o=(n!=null?n:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let n=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),n}markWebMcpToolComplete(e,n,r,o=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:n,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,n){var d,c,u,m;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async g=>{var I,A,P,O,_,H,U;let f=(I=g.toolCall)==null?void 0:I.name,w=(A=g.toolCall)==null?void 0:A.id;if(!f||!w)return null;let v=`${e}:${w}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(v),r.push(v);let k=this.markWebMcpToolRunning(g),R=(O=(P=g.agentMetadata)==null?void 0:P.webMcpToolCallId)!=null?O:f;if(f===zr)return{dedupeKey:v,resumeKey:R,output:ki(),toolMessage:g,startedAt:k,completedAt:Date.now()};let E=new AbortController;this.webMcpResolveControllers.add(E),o.push(E);let L=this.client.executeWebMcpToolCall(f,(_=g.toolCall)==null?void 0:_.args,E.signal),M;if(!L)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await L}catch(F){let Z=F instanceof Error&&(F.name==="AbortError"||F.message.includes("aborted")||F.message.includes("abort"));return Z||(U=(H=this.callbacks).onError)==null||U.call(H,F instanceof Error?F:new Error(String(F))),this.markWebMcpToolComplete(g,js(Z?"Aborted by cancel()":_u(F)),k),this.webMcpInflightKeys.delete(v),null}return E.signal.aborted?(this.markWebMcpToolComplete(g,js("Aborted by cancel()"),k),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:R,output:M,toolMessage:g,startedAt:k,completedAt:Date.now()}})),i=[];try{if(i=a.filter(w=>w!==null),i.length===0)return;let g={};for(let w of i)g[w.resumeKey]=w.output;let f=await this.client.resumeFlow(e,g,{signal:s.signal});if(!f.ok){let w=await f.json().catch(()=>null);throw new Error((d=w==null?void 0:w.error)!=null?d:`Resume failed: ${f.status}`)}for(let w of i)this.webMcpResolvedKeys.add(w.dedupeKey),this.markWebMcpToolComplete(w.toolMessage,w.output,w.startedAt,w.completedAt,((c=w.toolMessage.toolCall)==null?void 0:c.name)===zr?{suggestRepliesResolved:!0}:void 0);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(m=(u=this.callbacks).onError)==null||m.call(u,g instanceof Error?g:new Error(String(g)));else for(let w of i)this.markWebMcpToolComplete(w.toolMessage,js("Aborted by cancel()"),w.startedAt)}finally{for(let g of r)this.webMcpInflightKeys.delete(g);for(let g of o)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var w,v,k,R,E,L,M,I,A,P,O,_;let n=(w=e.agentMetadata)==null?void 0:w.executionId,r=(v=e.toolCall)==null?void 0:v.name,o=(k=e.toolCall)==null?void 0:k.id;if(!n){(E=(R=this.callbacks).onError)==null||E.call(R,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let H=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(H)||this.webMcpResolvedKeys.has(H))return;this.webMcpInflightKeys.add(H);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(H)}catch(U){(M=(L=this.callbacks).onError)==null||M.call(L,U instanceof Error?U:new Error(String(U)))}finally{this.webMcpInflightKeys.delete(H)}return}let s=`${n}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===zr,u=(I=e.toolCall)==null?void 0:I.args,m=c?null:this.client.executeWebMcpToolCall(r,u,d),g="execute",f=a;try{let H;if(c?H=ki():m?H=await m:H={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(e,js("Aborted by cancel()"),a);return}let U=(P=(A=e.agentMetadata)==null?void 0:A.webMcpToolCallId)!=null?P:r;g="resume",await this.resumeWithToolOutput(n,U,H,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,H,a,f,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(H){let U=H instanceof Error&&(H.name==="AbortError"||H.message.includes("aborted")||H.message.includes("abort"));(g==="execute"||U||d.aborted)&&this.markWebMcpToolComplete(e,js(U||d.aborted?"Aborted by cancel()":_u(H)),a),U||(_=(O=this.callbacks).onError)==null||_.call(O,H instanceof Error?H:new Error(String(H)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,n,r,o){var a,i;let s=await this.client.resumeFlow(e,{[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 e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let n=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.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 e,n;(n=(e=this.callbacks).onArtifactsState)==null||n.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var n,r;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(n=e.component)!=null?n:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.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(e,n=null){this.artifacts.clear();for(let r of e)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let n=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),n&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.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=Di(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Wa(e)}toggleReadAloud(e){let n=this.messages.find(s=>s.id===e);if(!n||n.role!=="assistant")return;let r=Di(n.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let n=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let n=this.ensureSequence(e),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var u,m,g,f,w,v,k,R,E,L,M,I,A,P,O;if(s!==r)return o;let a={...o,...n};if(((u=o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((m=o.agentMetadata)==null?void 0:m.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(g=a.agentMetadata)!=null?g:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let _=o.approval,H=n.approval;a.approval={..._,...H,executionId:H.executionId||_.executionId,toolName:H.toolName||_.toolName,description:H.description||_.description,toolType:(f=H.toolType)!=null?f:_.toolType,reason:(w=H.reason)!=null?w:_.reason,parameters:(v=H.parameters)!=null?v:_.parameters}}let i=(k=n.toolCall)==null?void 0:k.name,d=(R=n.agentMetadata)==null?void 0:R.executionId,c=(E=n.toolCall)==null?void 0:E.id;if(i&&$u(i)&&d&&c&&((L=n.agentMetadata)==null?void 0:L.awaitingLocalTool)===!0){let _=`${d}:${c}`,H=this.webMcpInflightKeys.has(_),U=this.webMcpResolvedKeys.has(_),F=(M=o.toolCall)==null?void 0:M.name,Z=((I=o.agentMetadata)==null?void 0:I.executionId)===d&&((A=o.toolCall)==null?void 0:A.id)===c&&F!==void 0&&$u(F)&&((P=o.toolCall)==null?void 0:P.status)==="complete";(H||U||Z)&&(a.agentMetadata={...(O=a.agentMetadata)!=null?O:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((n,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)})}};var C=require("lucide"),Qf={activity:C.Activity,"arrow-down":C.ArrowDown,"arrow-up":C.ArrowUp,"arrow-up-right":C.ArrowUpRight,bot:C.Bot,"chevron-down":C.ChevronDown,"chevron-up":C.ChevronUp,"chevron-right":C.ChevronRight,"chevron-left":C.ChevronLeft,check:C.Check,clipboard:C.Clipboard,"clipboard-copy":C.ClipboardCopy,copy:C.Copy,file:C.File,"file-code":C.FileCode,"file-spreadsheet":C.FileSpreadsheet,"file-text":C.FileText,"image-plus":C.ImagePlus,loader:C.Loader,"loader-circle":C.LoaderCircle,mic:C.Mic,paperclip:C.Paperclip,"refresh-cw":C.RefreshCw,search:C.Search,send:C.Send,"shield-alert":C.ShieldAlert,"shield-check":C.ShieldCheck,"shield-x":C.ShieldX,square:C.Square,"thumbs-down":C.ThumbsDown,"thumbs-up":C.ThumbsUp,upload:C.Upload,"volume-2":C.Volume2,x:C.X,user:C.User,mail:C.Mail,phone:C.Phone,calendar:C.Calendar,clock:C.Clock,building:C.Building,"map-pin":C.MapPin,lock:C.Lock,key:C.Key,"credit-card":C.CreditCard,"at-sign":C.AtSign,hash:C.Hash,globe:C.Globe,link:C.Link,"circle-check":C.CircleCheck,"circle-x":C.CircleX,"triangle-alert":C.TriangleAlert,info:C.Info,ban:C.Ban,shield:C.Shield,"arrow-left":C.ArrowLeft,"arrow-right":C.ArrowRight,"external-link":C.ExternalLink,ellipsis:C.Ellipsis,"ellipsis-vertical":C.EllipsisVertical,menu:C.Menu,house:C.House,plus:C.Plus,minus:C.Minus,pencil:C.Pencil,trash:C.Trash,"trash-2":C.Trash2,save:C.Save,download:C.Download,share:C.Share,funnel:C.Funnel,settings:C.Settings,"rotate-cw":C.RotateCw,maximize:C.Maximize,minimize:C.Minimize,"shopping-cart":C.ShoppingCart,"shopping-bag":C.ShoppingBag,package:C.Package,truck:C.Truck,tag:C.Tag,gift:C.Gift,receipt:C.Receipt,wallet:C.Wallet,store:C.Store,"dollar-sign":C.DollarSign,percent:C.Percent,play:C.Play,pause:C.Pause,"volume-x":C.VolumeX,camera:C.Camera,image:C.Image,film:C.Film,headphones:C.Headphones,"message-circle":C.MessageCircle,"message-square":C.MessageSquare,bell:C.Bell,heart:C.Heart,star:C.Star,eye:C.Eye,"eye-off":C.EyeOff,bookmark:C.Bookmark,"calendar-days":C.CalendarDays,history:C.History,timer:C.Timer,folder:C.Folder,"folder-open":C.FolderOpen,files:C.Files,sparkles:C.Sparkles,zap:C.Zap,sun:C.Sun,moon:C.Moon,flag:C.Flag,monitor:C.Monitor,smartphone:C.Smartphone},be=(t,e=24,n="currentColor",r=2)=>{let o=Qf[t];return o?Xf(o,e,n,r):(console.warn(`Lucide icon "${t}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Xf(t,e,n,r){if(!Array.isArray(t))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),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"),t.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,u])=>{c!=="stroke"&&d.setAttribute(c,String(u))}),o.appendChild(d)}),o}var Da={allowedTypes:qr,maxFileSize:10*1024*1024,maxFiles:4};function Jf(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Yf(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-code":"file"}var Vs=class t{constructor(e={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=e.allowedTypes)!=null?n:Da.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:Da.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:Da.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Da.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var n,r,o,s,a,i,d;if(e.length){for(let c of e){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let u=Lu(c,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let m=(o=u.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,m);continue}try{let m=await ku(c),g=Ia(c)?URL.createObjectURL(c):null,f={id:Jf(),file:c,previewUrl:g,contentPart:m};this.attachments.push(f),this.renderPreview(f)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let n=this.attachments.findIndex(d=>d.id===e);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="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(e=this.config).onAttachmentsChange)==null||n.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let n=Ia(e.file),r=b("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",n&&e.previewUrl){let a=b("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",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=Yf(e.file.type),d=be(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=b("span");c.textContent=Pu(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",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=be("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(e.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,n){return new t({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:n})}};var Uu=t=>typeof t=="object"&&t!==null&&!Array.isArray(t);function Ks(t,e){if(!t)return e;if(!e)return t;let n={...t};for(let[r,o]of Object.entries(e)){let s=n[r];Uu(s)&&Uu(o)?n[r]=Ks(s,o):n[r]=o}return n}var jr="min(440px, calc(100vw - 24px))",qu="440px",Zf={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:jr,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:Zf,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:"follow",anchorTopOffset:16},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 zu(t,e){if(!(!t&&!e))return t?e?Ks(t,e):t:e}function ju(t){var e,n,r,o,s,a,i,d,c,u,m,g,f,w,v,k,R,E,L,M,I;return t?{...Dt,...t,theme:zu(Dt.theme,t.theme),darkTheme:zu(Dt.darkTheme,t.darkTheme),launcher:{...Dt.launcher,...t.launcher,dock:{...(e=Dt.launcher)==null?void 0:e.dock,...(n=t.launcher)==null?void 0:n.dock},clearChat:{...(r=Dt.launcher)==null?void 0:r.clearChat,...(o=t.launcher)==null?void 0:o.clearChat}},copy:{...Dt.copy,...t.copy},sendButton:{...Dt.sendButton,...t.sendButton},statusIndicator:{...Dt.statusIndicator,...t.statusIndicator},voiceRecognition:{...Dt.voiceRecognition,...t.voiceRecognition},features:(()=>{var oe,se,de,Ee,He,K,J,Le,G,ue;let A=(oe=Dt.features)==null?void 0:oe.artifacts,P=(se=t.features)==null?void 0:se.artifacts,O=(de=Dt.features)==null?void 0:de.scrollToBottom,_=(Ee=t.features)==null?void 0:Ee.scrollToBottom,H=(He=Dt.features)==null?void 0:He.scrollBehavior,U=(K=t.features)==null?void 0:K.scrollBehavior,F=(J=Dt.features)==null?void 0:J.streamAnimation,Z=(Le=t.features)==null?void 0:Le.streamAnimation,Te=(G=Dt.features)==null?void 0:G.askUserQuestion,pe=(ue=t.features)==null?void 0:ue.askUserQuestion,ee=A===void 0&&P===void 0?void 0:{...A,...P,layout:{...A==null?void 0:A.layout,...P==null?void 0:P.layout}},xe=O===void 0&&_===void 0?void 0:{...O,..._},Re=H===void 0&&U===void 0?void 0:{...H,...U},le=F===void 0&&Z===void 0?void 0:{...F,...Z},me=Te===void 0&&pe===void 0?void 0:{...Te,...pe,styles:{...Te==null?void 0:Te.styles,...pe==null?void 0:pe.styles}};return{...Dt.features,...t.features,...xe!==void 0?{scrollToBottom:xe}:{},...Re!==void 0?{scrollBehavior:Re}:{},...ee!==void 0?{artifacts:ee}:{},...le!==void 0?{streamAnimation:le}:{},...me!==void 0?{askUserQuestion:me}:{}}})(),suggestionChips:(s=t.suggestionChips)!=null?s:Dt.suggestionChips,suggestionChipsConfig:{...Dt.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...Dt.layout,...t.layout,header:{...(a=Dt.layout)==null?void 0:a.header,...(i=t.layout)==null?void 0:i.header},messages:{...(d=Dt.layout)==null?void 0:d.messages,...(c=t.layout)==null?void 0:c.messages,avatar:{...(m=(u=Dt.layout)==null?void 0:u.messages)==null?void 0:m.avatar,...(f=(g=t.layout)==null?void 0:g.messages)==null?void 0:f.avatar},timestamp:{...(v=(w=Dt.layout)==null?void 0:w.messages)==null?void 0:v.timestamp,...(R=(k=t.layout)==null?void 0:k.messages)==null?void 0:R.timestamp}},slots:{...(E=Dt.layout)==null?void 0:E.slots,...(L=t.layout)==null?void 0:L.slots}},markdown:{...Dt.markdown,...t.markdown,options:{...(M=Dt.markdown)==null?void 0:M.options,...(I=t.markdown)==null?void 0:I.options}},messageActions:{...Dt.messageActions,...t.messageActions}}:Dt}var eh={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"}},th={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"}},nh={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:jr,maxWidth:qu,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(t,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let n=e.split("."),r=t;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(t,r):r}function Vu(t){let e={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=ps(t,a);d!==void 0&&(e[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(t.palette,"palette"),n(t.semantic,"semantic"),n(t.components,"components"),e}function rh(t){let e=[],n=[];return t.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),t.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),t.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:n}}function Ku(t,e){let n={...t};for(let[r,o]of Object.entries(e)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=Ku(s,o):n[r]=o}return n}function oh(t,e){return e?Ku(t,e):t}function Ho(t,e={}){var o,s,a,i,d,c,u,m,g,f,w,v,k;let n={palette:eh,semantic:th,components:nh},r={palette:{...n.palette,...t==null?void 0:t.palette,colors:{...n.palette.colors,...(o=t==null?void 0:t.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=t==null?void 0:t.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=t==null?void 0:t.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=t==null?void 0:t.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=t==null?void 0:t.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=t==null?void 0:t.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...t==null?void 0:t.semantic,colors:{...n.semantic.colors,...(u=t==null?void 0:t.semantic)==null?void 0:u.colors,interactive:{...n.semantic.colors.interactive,...(g=(m=t==null?void 0:t.semantic)==null?void 0:m.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(w=(f=t==null?void 0:t.semantic)==null?void 0:f.colors)==null?void 0:w.feedback}},spacing:{...n.semantic.spacing,...(v=t==null?void 0:t.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(k=t==null?void 0:t.semantic)==null?void 0:k.typography}},components:oh(n.components,t==null?void 0:t.components)};if(e.validate!==!1){let R=rh(r);if(!R.valid)throw new Error(`Theme validation failed: ${R.errors.map(E=>E.message).join(", ")}`)}if(e.plugins)for(let R of e.plugins)r=R.transform(r);return r}function Gu(t){var v,k,R,E,L,M,I,A,P,O,_,H,U,F,Z,Te,pe,ee,xe,Re,le,me,oe,se,de,Ee,He,K,J,Le,G,ue,De,Xe,et,vt,wt,Je,fe,Q,dt,qe,Ce,Me,nt,Wt,te,Ue,An,xt,hn,hr,yr,S,ne,Se,Ne,Pe,Fe,Ke,it,Rt,ce,B,he,_e,Ct,Ye,Nt,Mt,ht,It,Jt,$t,Bn,zt,Dn,Qn,yn,Ln,Xn,Kr,At,br,vr,Wr,ir,ut,fo,wr,ho,Pn,$o,Gr,Rr,Qr,Xr,yo,bo,Jr,bt,Nn,Fn,Sn,St,Jn,Yn,On,Yr,Hr,Zr,_n,Ht,Tn,Zn,eo,Br,to;let e=Vu(t),n={};for(let[ve,In]of Object.entries(e)){let xr=ve.replace(/\./g,"-");n[`--persona-${xr}`]=In.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(k=n["--persona-semantic-colors-secondary"])!=null?k:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(R=n["--persona-semantic-colors-accent"])!=null?R:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(E=n["--persona-semantic-colors-surface"])!=null?E:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(L=n["--persona-semantic-colors-background"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(M=n["--persona-semantic-colors-container"])!=null?M:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(I=n["--persona-semantic-colors-text"])!=null?I:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(A=n["--persona-semantic-colors-text-muted"])!=null?A:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(P=n["--persona-semantic-colors-text-inverse"])!=null?P:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(O=n["--persona-semantic-colors-border"])!=null?O: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"]=(H=n["--persona-components-voice-recording-indicator"])!=null?H:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(U=n["--persona-components-voice-recording-background"])!=null?U: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"]=(Te=n["--persona-components-approval-requested-background"])!=null?Te:n["--persona-surface"],n["--persona-approval-border"]=(pe=n["--persona-components-approval-requested-border"])!=null?pe: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"]=(xe=n["--persona-components-approval-requested-shadow"])!=null?xe:"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"]=(Re=n["--persona-components-approval-approve-background"])!=null?Re:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(le=n["--persona-components-approval-deny-background"])!=null?le:n["--persona-container"],n["--persona-attachment-image-bg"]=(me=n["--persona-components-attachment-image-background"])!=null?me:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(oe=n["--persona-components-attachment-image-border"])!=null?oe: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"]=(de=n["--persona-semantic-typography-fontSize"])!=null?de:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(Ee=n["--persona-semantic-typography-fontWeight"])!=null?Ee:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(He=n["--persona-semantic-typography-lineHeight"])!=null?He: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"]=(K=n["--persona-palette-radius-sm"])!=null?K:"0.125rem",n["--persona-radius-md"]=(J=n["--persona-palette-radius-md"])!=null?J:"0.375rem",n["--persona-radius-lg"]=(Le=n["--persona-palette-radius-lg"])!=null?Le:"0.5rem",n["--persona-radius-xl"]=(G=n["--persona-palette-radius-xl"])!=null?G:"0.75rem",n["--persona-radius-full"]=(ue=n["--persona-palette-radius-full"])!=null?ue:"9999px",n["--persona-launcher-radius"]=(Xe=(De=n["--persona-components-launcher-borderRadius"])!=null?De:n["--persona-palette-radius-full"])!=null?Xe:"9999px",n["--persona-launcher-bg"]=(et=n["--persona-components-launcher-background"])!=null?et:n["--persona-primary"],n["--persona-launcher-fg"]=(vt=n["--persona-components-launcher-foreground"])!=null?vt:n["--persona-text-inverse"],n["--persona-launcher-border"]=(wt=n["--persona-components-launcher-border"])!=null?wt:n["--persona-border"],n["--persona-button-primary-bg"]=(Je=n["--persona-components-button-primary-background"])!=null?Je:n["--persona-primary"],n["--persona-button-primary-fg"]=(fe=n["--persona-components-button-primary-foreground"])!=null?fe:n["--persona-text-inverse"],n["--persona-button-radius"]=(dt=(Q=n["--persona-components-button-primary-borderRadius"])!=null?Q:n["--persona-palette-radius-full"])!=null?dt:"9999px",n["--persona-panel-radius"]=(Ce=(qe=n["--persona-components-panel-borderRadius"])!=null?qe:n["--persona-radius-xl"])!=null?Ce:"0.75rem",n["--persona-panel-border"]=(Me=n["--persona-components-panel-border"])!=null?Me:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Wt=(nt=n["--persona-components-panel-shadow"])!=null?nt:n["--persona-palette-shadows-xl"])!=null?Wt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(te=n["--persona-components-launcher-shadow"])!=null?te:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(An=(Ue=n["--persona-components-input-borderRadius"])!=null?Ue:n["--persona-radius-lg"])!=null?An:"0.5rem",n["--persona-message-user-radius"]=(hn=(xt=n["--persona-components-message-user-borderRadius"])!=null?xt:n["--persona-radius-lg"])!=null?hn:"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"]=(S=n["--persona-components-header-background"])!=null?S:n["--persona-surface"],n["--persona-header-border"]=(ne=n["--persona-components-header-border"])!=null?ne:n["--persona-divider"],n["--persona-header-icon-bg"]=(Se=n["--persona-components-header-iconBackground"])!=null?Se:n["--persona-primary"],n["--persona-header-icon-fg"]=(Ne=n["--persona-components-header-iconForeground"])!=null?Ne:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Pe=n["--persona-components-header-titleForeground"])!=null?Pe:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Fe=n["--persona-components-header-subtitleForeground"])!=null?Fe:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Ke=n["--persona-components-header-actionIconForeground"])!=null?Ke:n["--persona-muted"];let r=(it=t.components)==null?void 0:it.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(Rt=t.components)==null?void 0:Rt.introCard;n["--persona-intro-card-bg"]=(ce=n["--persona-components-introCard-background"])!=null?ce:n["--persona-surface"],n["--persona-intro-card-radius"]=(B=n["--persona-components-introCard-borderRadius"])!=null?B:"1rem",n["--persona-intro-card-padding"]=(he=n["--persona-components-introCard-padding"])!=null?he:"1.5rem",n["--persona-intro-card-shadow"]=(Ct=(_e=o==null?void 0:o.shadow)!=null?_e:n["--persona-components-introCard-shadow"])!=null?Ct:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Ye=n["--persona-components-input-background"])!=null?Ye:n["--persona-surface"],n["--persona-input-placeholder"]=(Nt=n["--persona-components-input-placeholder"])!=null?Nt: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"]=(ht=n["--persona-components-message-user-text"])!=null?ht:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(It=n["--persona-components-message-user-shadow"])!=null?It:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Jt=n["--persona-components-message-assistant-background"])!=null?Jt:n["--persona-surface"],n["--persona-message-assistant-text"]=($t=n["--persona-components-message-assistant-text"])!=null?$t:n["--persona-text"],n["--persona-message-assistant-border"]=(Bn=n["--persona-components-message-assistant-border"])!=null?Bn:n["--persona-border"],n["--persona-message-assistant-shadow"]=(zt=n["--persona-components-message-assistant-shadow"])!=null?zt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Qn=(Dn=n["--persona-components-scrollToBottom-background"])!=null?Dn:n["--persona-button-primary-bg"])!=null?Qn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(Ln=(yn=n["--persona-components-scrollToBottom-foreground"])!=null?yn:n["--persona-button-primary-fg"])!=null?Ln:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Xn=n["--persona-components-scrollToBottom-border"])!=null?Xn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(Kr=n["--persona-components-scrollToBottom-size"])!=null?Kr:"40px",n["--persona-scroll-to-bottom-radius"]=(vr=(br=(At=n["--persona-components-scrollToBottom-borderRadius"])!=null?At:n["--persona-button-radius"])!=null?br:n["--persona-radius-full"])!=null?vr:"9999px",n["--persona-scroll-to-bottom-shadow"]=(ir=(Wr=n["--persona-components-scrollToBottom-shadow"])!=null?Wr:n["--persona-palette-shadows-sm"])!=null?ir:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(ut=n["--persona-components-scrollToBottom-padding"])!=null?ut:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(fo=n["--persona-components-scrollToBottom-gap"])!=null?fo:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(ho=(wr=n["--persona-components-scrollToBottom-fontSize"])!=null?wr:n["--persona-palette-typography-fontSize-sm"])!=null?ho:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Pn=n["--persona-components-scrollToBottom-iconSize"])!=null?Pn:"14px",n["--persona-tool-bubble-shadow"]=($o=n["--persona-components-toolBubble-shadow"])!=null?$o:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Gr=n["--persona-components-reasoningBubble-shadow"])!=null?Gr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Rr=n["--persona-components-composer-shadow"])!=null?Rr:"none",n["--persona-md-inline-code-bg"]=(Qr=n["--persona-components-markdown-inlineCode-background"])!=null?Qr:n["--persona-container"],n["--persona-md-inline-code-color"]=(Xr=n["--persona-components-markdown-inlineCode-foreground"])!=null?Xr:n["--persona-text"],n["--persona-md-link-color"]=(bo=(yo=n["--persona-components-markdown-link-foreground"])!=null?yo:n["--persona-accent"])!=null?bo:"#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"]=(Jr=n["--persona-components-markdown-codeBlock-background"])!=null?Jr:n["--persona-container"],n["--persona-md-code-block-border-color"]=(bt=n["--persona-components-markdown-codeBlock-borderColor"])!=null?bt:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Nn=n["--persona-components-markdown-codeBlock-textColor"])!=null?Nn:"inherit",n["--persona-md-table-header-bg"]=(Fn=n["--persona-components-markdown-table-headerBackground"])!=null?Fn:n["--persona-container"],n["--persona-md-table-border-color"]=(Sn=n["--persona-components-markdown-table-borderColor"])!=null?Sn:n["--persona-border"],n["--persona-md-hr-color"]=(St=n["--persona-components-markdown-hr-color"])!=null?St:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Jn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Jn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Yn=n["--persona-components-markdown-blockquote-background"])!=null?Yn:"transparent",n["--persona-md-blockquote-text-color"]=(On=n["--persona-components-markdown-blockquote-textColor"])!=null?On:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(Yr=n["--persona-components-collapsibleWidget-container"])!=null?Yr:n["--persona-surface"],n["--cw-surface"]=(Hr=n["--persona-components-collapsibleWidget-surface"])!=null?Hr:n["--persona-surface"],n["--cw-border"]=(Zr=n["--persona-components-collapsibleWidget-border"])!=null?Zr:n["--persona-border"],n["--persona-message-border"]=(_n=n["--persona-components-message-border"])!=null?_n:n["--persona-border"];let u=t.components,m=u==null?void 0:u.iconButton;m&&(m.background&&(n["--persona-icon-btn-bg"]=m.background),m.border&&(n["--persona-icon-btn-border"]=m.border),m.color&&(n["--persona-icon-btn-color"]=m.color),m.padding&&(n["--persona-icon-btn-padding"]=m.padding),m.borderRadius&&(n["--persona-icon-btn-radius"]=m.borderRadius),m.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=m.hoverBackground),m.hoverColor&&(n["--persona-icon-btn-hover-color"]=m.hoverColor),m.activeBackground&&(n["--persona-icon-btn-active-bg"]=m.activeBackground),m.activeBorder&&(n["--persona-icon-btn-active-border"]=m.activeBorder));let g=u==null?void 0:u.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let f=u==null?void 0:u.toggleGroup;f&&(f.gap&&(n["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(n["--persona-toggle-group-radius"]=f.borderRadius));let w=u==null?void 0:u.artifact;if(w!=null&&w.toolbar){let ve=w.toolbar;ve.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=ve.iconHoverColor),ve.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=ve.iconHoverBackground),ve.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=ve.iconPadding),ve.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=ve.iconBorderRadius),ve.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=ve.iconBorder),ve.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=ve.toggleGroupGap),ve.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=ve.toggleBorderRadius),ve.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=ve.copyBackground),ve.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=ve.copyBorder),ve.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=ve.copyColor),ve.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=ve.copyBorderRadius),ve.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=ve.copyPadding),ve.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=ve.copyMenuBackground,n["--persona-dropdown-bg"]=(Ht=n["--persona-dropdown-bg"])!=null?Ht:ve.copyMenuBackground),ve.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=ve.copyMenuBorder,n["--persona-dropdown-border"]=(Tn=n["--persona-dropdown-border"])!=null?Tn:ve.copyMenuBorder),ve.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=ve.copyMenuShadow,n["--persona-dropdown-shadow"]=(Zn=n["--persona-dropdown-shadow"])!=null?Zn:ve.copyMenuShadow),ve.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=ve.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(eo=n["--persona-dropdown-radius"])!=null?eo:ve.copyMenuBorderRadius),ve.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ve.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Br=n["--persona-dropdown-item-hover-bg"])!=null?Br:ve.copyMenuItemHoverBackground),ve.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=ve.iconBackground),ve.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=ve.toolbarBorder)}if(w!=null&&w.tab){let ve=w.tab;ve.background&&(n["--persona-artifact-tab-bg"]=ve.background),ve.activeBackground&&(n["--persona-artifact-tab-active-bg"]=ve.activeBackground),ve.activeBorder&&(n["--persona-artifact-tab-active-border"]=ve.activeBorder),ve.borderRadius&&(n["--persona-artifact-tab-radius"]=ve.borderRadius),ve.textColor&&(n["--persona-artifact-tab-color"]=ve.textColor),ve.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=ve.hoverBackground),ve.listBackground&&(n["--persona-artifact-tab-list-bg"]=ve.listBackground),ve.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=ve.listBorderColor),ve.listPadding&&(n["--persona-artifact-tab-list-padding"]=ve.listPadding)}if(w!=null&&w.pane){let ve=w.pane;if(ve.toolbarBackground){let In=(to=ps(t,ve.toolbarBackground))!=null?to:ve.toolbarBackground;n["--persona-artifact-toolbar-bg"]=In}}return n}var sh={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"}}},Qu=t=>{if(!(!t||typeof t!="object"||Array.isArray(t)))return t},Fi=()=>{var t;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},ah=t=>{var n;let e=(n=t==null?void 0:t.colorScheme)!=null?n:"light";return e==="light"?"light":e==="dark"?"dark":Fi()},ih=t=>ah(t),lh=t=>Ho(t),ch=t=>{var n;let e=Ho(void 0,{validate:!1});return Ho({...t,palette:{...e.palette,colors:{...sh.colors,...(n=t==null?void 0:t.palette)==null?void 0:n.colors}}},{validate:!1})},Na=t=>{let e=ih(t),n=Qu(t==null?void 0:t.theme),r=Qu(t==null?void 0:t.darkTheme);return e==="dark"?ch(Ks(n!=null?n:{},r!=null?r:{})):lh(n)},dh=t=>Gu(t),us=(t,e)=>{let n=Na(e),r=dh(n);for(let[o,s]of Object.entries(r))t.style.setProperty(o,s)},Xu=t=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{t(Fi())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>t(Fi());n.addEventListener?(n.addEventListener("change",r),e.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),e.push(()=>n.removeListener(r)))}return()=>{e.forEach(n=>n())}};var Ju=require("idiomorph"),Fa=(t,e,n={})=>{let{preserveTypingAnimation:r=!0}=n;Ju.Idiomorph.morph(t,e.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 Yu=t=>t.replace(/^\n+/,"").replace(/\s+$/,"");var Oa={index:-1,draft:""};function Zu(t){let{direction:e,history:n,currentValue:r,atStart:o,state:s}=t,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(e==="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:{...Oa}}}function em(t,e){var n,r,o,s,a,i,d,c,u,m,g,f,w,v,k,R,E,L,M,I,A,P,O,_,H,U,F,Z,Te,pe,ee,xe,Re,le,me,oe,se,de;return[t.id,t.role,(r=(n=t.content)==null?void 0:n.length)!=null?r:0,(s=(o=t.content)==null?void 0:o.slice(-32))!=null?s:"",t.streaming?"1":"0",t.voiceProcessing?"1":"0",(a=t.variant)!=null?a:"",(d=(i=t.rawContent)==null?void 0:i.length)!=null?d:0,(u=(c=t.llmContent)==null?void 0:c.length)!=null?u:0,(g=(m=t.approval)==null?void 0:m.status)!=null?g:"",(w=(f=t.toolCall)==null?void 0:f.status)!=null?w:"",(k=(v=t.toolCall)==null?void 0:v.name)!=null?k:"",(L=(E=(R=t.toolCall)==null?void 0:R.chunks)==null?void 0:E.length)!=null?L:0,(P=(A=(I=(M=t.toolCall)==null?void 0:M.chunks)==null?void 0:I[t.toolCall.chunks.length-1])==null?void 0:A.slice(-32))!=null?P:"",typeof((O=t.toolCall)==null?void 0:O.args)=="string"?t.toolCall.args.length:(_=t.toolCall)!=null&&_.args?JSON.stringify(t.toolCall.args).length:0,(F=(U=(H=t.reasoning)==null?void 0:H.chunks)==null?void 0:U.length)!=null?F:0,(ee=(pe=(Te=(Z=t.reasoning)==null?void 0:Z.chunks)==null?void 0:Te[t.reasoning.chunks.length-1])==null?void 0:pe.length)!=null?ee:0,(me=(le=(Re=(xe=t.reasoning)==null?void 0:xe.chunks)==null?void 0:Re[t.reasoning.chunks.length-1])==null?void 0:le.slice(-32))!=null?me:"",(se=(oe=t.contentParts)==null?void 0:oe.length)!=null?se:0,(de=t.stopReason)!=null?de:"",e].join("\0")}function tm(){return new Map}function nm(t,e,n){let r=t.get(e);return r&&r.fingerprint===n?r.wrapper:null}function rm(t,e,n,r){t.set(e,{fingerprint:n,wrapper:r})}function om(t,e){for(let n of t.keys())e.has(n)||t.delete(n)}function _a(t=!0){let e=t;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Vr(t){return Math.max(0,t.scrollHeight-t.clientHeight)}function Bo(t,e){return Vr(t)-t.scrollTop<=e}function $a(t){let{following:e,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=t,u=n-r;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:n}:!e&&o&&(!c||u>0)?{action:"resume",delta:u,nextLastScrollTop:n}:e&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:n}:e&&d&&!o?{action:"pause",delta:u,nextLastScrollTop:n}:{action:"none",delta:u,nextLastScrollTop:n}}function Ua(t){let{following:e,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=t;return e&&n<0?"pause":!e&&o&&n>0&&r?"resume":"none"}function sm(t,e){return!t||t.isCollapsed?!1:e.contains(t.anchorNode)||e.contains(t.focusNode)}function am(t){let e=Math.max(0,t.anchorOffsetTop-t.topOffset),n=Math.max(0,e+t.viewportHeight-t.contentHeight);return{targetScrollTop:e,spacerHeight:n}}function im(t){let e=Math.max(0,t.currentContentHeight-t.contentHeightAtAnchor);return Math.max(0,t.initialSpacerHeight-e)}var wn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},xn=1e5,mo=xn+1;var Gs={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},ph=["pre","code","a","script","style"],za=t=>{var e,n,r,o,s;return{type:(e=t==null?void 0:t.type)!=null?e:Gs.type,placeholder:(n=t==null?void 0:t.placeholder)!=null?n:Gs.placeholder,speed:(r=t==null?void 0:t.speed)!=null?r:Gs.speed,duration:(o=t==null?void 0:t.duration)!=null?o:Gs.duration,buffer:(s=t==null?void 0:t.buffer)!=null?s:Gs.buffer}},uh=[{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"}],cm=new Map;for(let t of uh)cm.set(t.name,t);var Qs=(t,e)=>{var n,r;return t==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,t)?(n=e[t])!=null?n:null:(r=cm.get(t))!=null?r:null},qa=(t,e,n,r,o)=>{if(!o)return t;if(n!=null&&n.bufferContent)return n.bufferContent(t,r);if(!t)return t;if(e==="word"){let s=t.search(/\s(?=\S*$)/);return s<0?"":t.slice(0,s)}if(e==="line"){let s=t.lastIndexOf(`
|
|
19
|
-
`);return s<0?"":t.slice(0,s)}return t},mh=(t,e,n,r)=>{let o=t.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=e,o},gh=(t,e,n,r)=>{let o=t.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=e,o},Oi=/\s/,fh=(t,e)=>{let n=t.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(e.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},hh=(t,e,n)=>{var d;let r=t.ownerDocument,o=t.parentNode;if(!r||!o)return;let s=(d=t.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(Oi.test(s[i])){let c=i;for(;c<s.length&&Oi.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 u=i;for(;u<s.length&&!Oi.test(s[u]);)c.appendChild(mh(r,s[u],e,n.value)),n.value+=1,u+=1;a.appendChild(c),i=u}o.replaceChild(a,t)},yh=(t,e,n)=>{var d;let r=t.ownerDocument,o=t.parentNode;if(!r||!o)return;let s=(d=t.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(gh(r,c,e,n.value)),n.value+=1));o.replaceChild(a,t)},Xs=(t,e,n,r)=>{var m,g;if(!t||typeof document=="undefined")return t;let o=document.createElement("div");o.innerHTML=t;let s=new Set(((m=r==null?void 0:r.skipTags)!=null?m:ph).map(f=>f.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)fh(d,s)||i.push(d),d=a.nextNode();let c={value:(g=r==null?void 0:r.startIndex)!=null?g:0},u=e==="char"?hh:yh;for(let f of i)u(f,n,c);return o.innerHTML},ja=(t=document)=>{let e=t.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},Js=(t=document)=>{let e=t.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let n=t.createElement("div");return n.className="persona-stream-skeleton-line",e.appendChild(n),e},lm=new WeakMap,bh=(t,e)=>{var s;if(!t.styles)return;let n=lm.get(e);if(n||(n=new Set,lm.set(e,n)),n.has(t.name)){let a=t.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(t.name)}n.add(t.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(s=e.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",t.name),o.textContent=t.styles,e.appendChild(o)},_i=new WeakMap,vh=(t,e)=>{if(!t.onAttach)return;let n=_i.get(e);if(n||(n=new Map,_i.set(e,n)),n.has(t.name))return;let r=t.onAttach(e);n.set(t.name,r)},dm=t=>{let e=_i.get(t);if(e){for(let n of e.values())typeof n=="function"&&n();e.clear()}},$i=(t,e)=>{bh(t,e),vh(t,e)};function Ui(t,e=xn){let n=t.style.position,r=t.style.zIndex,o=t.style.isolation,s=getComputedStyle(t),a=s.position==="static"||s.position==="";return a&&(t.style.position="relative"),t.style.zIndex=String(e),t.style.isolation="isolate",()=>{a&&(t.style.position=n),t.style.zIndex=r,t.style.isolation=o}}var Ys=0,go=null;function zi(t=document){var n;if(Ys++,Ys===1){let r=t.body,s=((n=t.defaultView)!=null?n:window).scrollY||t.documentElement.scrollTop;go={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 e=!1;return()=>{var r;if(!e&&(e=!0,Ys=Math.max(0,Ys-1),Ys===0&&go)){let o=t.body,s=(r=t.defaultView)!=null?r:window;o.style.overflow=go.originalOverflow,o.style.position=go.originalPosition,o.style.top=go.originalTop,o.style.width=go.originalWidth,s.scrollTo(0,go.scrollY),go=null}}}var Zs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},fn=t=>{var e,n;return((n=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?n:"floating")==="docked"},ea=t=>{var e,n;return((n=(e=t==null?void 0:t.launcher)==null?void 0:e.mountMode)!=null?n:"floating")==="composer-bar"},gr=t=>{var n,r,o,s,a,i;let e=(n=t==null?void 0:t.launcher)==null?void 0:n.dock;return{side:(r=e==null?void 0:e.side)!=null?r:Zs.side,width:(o=e==null?void 0:e.width)!=null?o:Zs.width,animate:(s=e==null?void 0:e.animate)!=null?s:Zs.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:Zs.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:Zs.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 wh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Va=(t,e={})=>{var k,R,E,L,M,I;let{showClose:n=!0,wrapperClassName:r=wh,buttonSize:o,iconSize:s="28px"}=e,a=(k=t==null?void 0:t.launcher)!=null?k:{},i=(R=o!=null?o:a.closeButtonSize)!=null?R:"32px",d=b("div",r),c=(E=a.closeButtonTooltipText)!=null?E:"Close chat",u=(L=a.closeButtonShowTooltip)!=null?L:!0,m=(M=a.closeButtonIconName)!=null?M:"x",g=(I=a.closeButtonIconText)!=null?I:"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),w=Et("button",{className:Hs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"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||kn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${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=be(m,s,"currentColor",1);if(v?(v.style.display="block",w.appendChild(v)):w.textContent=g,d.appendChild(w),u&&c){let A=null,P=()=>{if(A)return;let _=w.ownerDocument,H=_.body;if(!H)return;A=Ir(_,"div","persona-clear-chat-tooltip"),A.textContent=c;let U=Ir(_,"div");U.className="persona-clear-chat-tooltip-arrow",A.appendChild(U);let F=w.getBoundingClientRect();A.style.position="fixed",A.style.zIndex=String(mo),A.style.left=`${F.left+F.width/2}px`,A.style.top=`${F.top-8}px`,A.style.transform="translate(-50%, -100%)",H.appendChild(A)},O=()=>{A&&A.parentNode&&(A.parentNode.removeChild(A),A=null)};d.addEventListener("mouseenter",P),d.addEventListener("mouseleave",O),w.addEventListener("focus",P),w.addEventListener("blur",O),d._cleanupTooltip=()=>{O(),d.removeEventListener("mouseenter",P),d.removeEventListener("mouseleave",O),w.removeEventListener("focus",P),w.removeEventListener("blur",O)}}return{button:w,wrapper:d}},xh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ka=(t,e={})=>{var A,P,O,_,H,U,F,Z,Te,pe,ee,xe,Re;let{wrapperClassName:n=xh,buttonSize:r,iconSize:o="20px"}=e,a=(P=((A=t==null?void 0:t.launcher)!=null?A:{}).clearChat)!=null?P:{},i=(O=r!=null?r:a.size)!=null?O:"32px",d=(_=a.iconName)!=null?_:"refresh-cw",c=(H=a.iconColor)!=null?H:"",u=(U=a.backgroundColor)!=null?U:"",m=(F=a.borderWidth)!=null?F:"",g=(Z=a.borderColor)!=null?Z:"",f=(Te=a.borderRadius)!=null?Te:"",w=(pe=a.paddingX)!=null?pe:"",v=(ee=a.paddingY)!=null?ee:"",k=(xe=a.tooltipText)!=null?xe:"Clear chat",R=(Re=a.showTooltip)!=null?Re:!0,E=b("div",n),L=!!(m||g),M=Et("button",{className:Hs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"hover:persona-bg-gray-100",!L&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":k},style:{height:i,width:i,color:c||kn.actionIconColor,backgroundColor:u||void 0,border:L?`${m||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:w||void 0,paddingRight:w||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),I=be(d,o,"currentColor",1);if(I&&(I.style.display="block",M.appendChild(I)),E.appendChild(M),R&&k){let le=null,me=()=>{if(le)return;let se=M.ownerDocument,de=se.body;if(!de)return;le=Ir(se,"div","persona-clear-chat-tooltip"),le.textContent=k;let Ee=Ir(se,"div");Ee.className="persona-clear-chat-tooltip-arrow",le.appendChild(Ee);let He=M.getBoundingClientRect();le.style.position="fixed",le.style.zIndex=String(mo),le.style.left=`${He.left+He.width/2}px`,le.style.top=`${He.top-8}px`,le.style.transform="translate(-50%, -100%)",de.appendChild(le)},oe=()=>{le&&le.parentNode&&(le.parentNode.removeChild(le),le=null)};E.addEventListener("mouseenter",me),E.addEventListener("mouseleave",oe),M.addEventListener("focus",me),M.addEventListener("blur",oe),E._cleanupTooltip=()=>{oe(),E.removeEventListener("mouseenter",me),E.removeEventListener("mouseleave",oe),M.removeEventListener("focus",me),M.removeEventListener("blur",oe)}}return{button:M,wrapper:E}};var kn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Do=t=>{var I,A,P,O,_,H,U,F,Z,Te,pe,ee,xe,Re,le,me;let{config:e,showClose:n=!0}=t,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=(I=e==null?void 0:e.launcher)!=null?I:{},s=(A=o.headerIconSize)!=null?A:"48px",a=(P=o.closeButtonPlacement)!=null?P:"inline",i=(O=o.headerIconHidden)!=null?O:!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 oe=parseFloat(s)||24,se=be(d,oe*.6,"currentColor",1);se?c.replaceChildren(se):c.textContent=(H=(_=e==null?void 0:e.launcher)==null?void 0:_.agentIconText)!=null?H:"\u{1F4AC}"}else if((U=e==null?void 0:e.launcher)!=null&&U.iconUrl){let oe=b("img");oe.src=e.launcher.iconUrl,oe.alt="",oe.className="persona-rounded-xl persona-object-cover",oe.style.height=s,oe.style.width=s,c.replaceChildren(oe)}else c.textContent=(Z=(F=e==null?void 0:e.launcher)==null?void 0:F.agentIconText)!=null?Z:"\u{1F4AC}";let u=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),m=Et("span",{className:"persona-text-base persona-font-semibold",text:(pe=(Te=e==null?void 0:e.launcher)==null?void 0:Te.title)!=null?pe:"Chat Assistant",style:{color:kn.titleColor}}),g=Et("span",{className:"persona-text-xs",text:(xe=(ee=e==null?void 0:e.launcher)==null?void 0:ee.subtitle)!=null?xe:"Here to help you get answers fast",style:{color:kn.subtitleColor}});u.append(m,g),i?r.append(u):r.append(c,u);let f=(Re=o.clearChat)!=null?Re:{},w=(le=f.enabled)!=null?le:!0,v=(me=f.placement)!=null?me:"inline",k=null,R=null;if(w){let se=Ka(e,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});k=se.button,R=se.wrapper,v==="top-right"&&(R.style.right="48px"),v==="inline"&&r.appendChild(R)}let E=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":w&&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:L,wrapper:M}=Va(e,{showClose:n,wrapperClassName:E});return a!=="top-right"&&r.appendChild(M),{header:r,iconHolder:c,headerTitle:m,headerSubtitle:g,closeButton:L,closeButtonWrapper:M,clearChatButton:k,clearChatButtonWrapper:R}},ta=(t,e,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";t.appendChild(e.header),o==="top-right"&&(t.style.position="relative",t.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(e.clearChatButtonWrapper))};function ms(t){let{items:e,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=t,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(mo)):(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 f of e){if(f.dividerBefore){let k=document.createElement("hr");a.appendChild(k)}let w=document.createElement("button");if(w.type="button",w.setAttribute("role","menuitem"),w.setAttribute("data-dropdown-item-id",f.id),f.destructive&&w.setAttribute("data-destructive",""),f.icon){let k=be(f.icon,16,"currentColor",1.5);k&&w.appendChild(k)}let v=document.createElement("span");v.textContent=f.label,w.appendChild(v),w.addEventListener("click",k=>{k.stopPropagation(),u(),n(f.id)}),a.appendChild(w)}let i=null;function d(){if(!s)return;let f=r.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=w=>{!a.contains(w.target)&&!r.contains(w.target)&&u()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function m(){a.classList.contains("persona-hidden")?c():u()}function g(){u(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:u,toggle:m,destroy:g}}function Cn(t){let{icon:e,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=t,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=be(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[u,m]of Object.entries(i))d.setAttribute(u,m);return d}function qi(t){let{icon:e,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=t,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let u=b("button",c);if(u.type="button",u.setAttribute("aria-label",n),e){let g=be(e,s!=null?s:14,"currentColor",2);g&&u.appendChild(g)}let m=b("span");if(m.textContent=n,u.appendChild(m),i&&u.addEventListener("click",i),d)for(let[g,f]of Object.entries(d))u.setAttribute(g,f);return u}function pm(t){var f,w;let{label:e,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=t,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",e);let u=b("span","persona-combo-btn-label");u.textContent=e,c.appendChild(u);let m=be(n,14,"currentColor",2);m&&(m.style.marginLeft="4px",m.style.opacity="0.6",c.appendChild(m)),d&&(c.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",c.style.padding=(w=d.padding)!=null?w:"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,k;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(k=d.border)!=null?k:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let g=ms({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),o(v)},anchor:c,position:s,portal:a});return a||c.appendChild(g.element),c.addEventListener("click",v=>{v.stopPropagation();let k=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",k?"false":"true"),g.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{u.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),g.show()},close:()=>{c.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let v=!g.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),c.remove()}}}var Ch=t=>{var r;let e=Do({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),n=(r=t.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return e};function Ah(t,e,n){var r,o,s;if(e!=null&&e.length)for(let a of e){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=be(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=ms({items:a.menuItems,onSelect:u=>n==null?void 0:n(u),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",u=>{u.stopPropagation(),c.toggle()}),t.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),t.appendChild(i)}}var Sh=t=>{var E,L,M,I,A,P,O,_,H;let{config:e,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=t,a=(E=e==null?void 0:e.launcher)!=null?E:{},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,u;if(d)c=pm({label:(L=a.title)!=null?L:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=kn.titleColor,u=(M=c.querySelector(".persona-combo-btn-label"))!=null?M:c;else{if(c=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=b("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=kn.titleColor,u.textContent=(I=a.title)!=null?I:"Chat Assistant",c.appendChild(u),Ah(c,o==null?void 0:o.trailingActions,(A=o==null?void 0:o.onAction)!=null?A: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 U=o==null?void 0:o.titleRowHover;U&&(c.style.borderRadius=(P=U.borderRadius)!=null?P:"10px",c.style.padding=(O=U.padding)!=null?O:"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=U.background)!=null?F:"",c.style.borderColor=(Z=U.border)!=null?Z:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let m=(_=a.closeButtonSize)!=null?_:"32px",g=b("div",""),f=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");f.style.height=m,f.style.width=m,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||kn.actionIconColor;let w=(H=a.closeButtonIconName)!=null?H:"x",v=be(w,"28px","currentColor",1);v?f.appendChild(v):f.textContent="\xD7",r&&f.addEventListener("click",r),g.appendChild(f),i.appendChild(g);let k=b("div");k.style.display="none";let R=b("span");return R.style.display="none",{header:i,iconHolder:k,headerTitle:u,headerSubtitle:R,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},um={default:Ch,minimal:Sh},Th=t=>{var e;return(e=um[t])!=null?e:um.default},Ga=(t,e,n)=>{var a,i,d;if(e!=null&&e.render){let c=e.render({config:t,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),u=b("div");u.style.display="none";let m=b("span"),g=b("span"),f=b("button");f.style.display="none";let w=b("div");return w.style.display="none",{header:c,iconHolder:u,headerTitle:m,headerSubtitle:g,closeButton:f,closeButtonWrapper:w,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=Th(r)({config:t,showClose:(d=(i=e==null?void 0:e.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:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Qa=t=>{var a,i;let e=b("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(a=t==null?void 0:t.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;e.style.maxHeight=`${n*r}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Xa=t=>{var I,A,P,O,_,H,U,F,Z,Te,pe,ee;let e=(I=t==null?void 0:t.sendButton)!=null?I:{},n=(A=e.useIcon)!=null?A:!1,r=(P=e.iconText)!=null?P:"\u2191",o=e.iconName,s=(O=e.stopIconName)!=null?O:"square",a=(_=e.tooltipText)!=null?_:"Send message",i=(H=e.stopTooltipText)!=null?H:"Stop generating",d=(F=(U=t==null?void 0:t.copy)==null?void 0:U.sendButtonLabel)!=null?F:"Send",c=(Te=(Z=t==null?void 0:t.copy)==null?void 0:Z.stopButtonLabel)!=null?Te:"Stop",u=(pe=e.showTooltip)!=null?pe:!1,m=(ee=e.size)!=null?ee:"40px",g=e.backgroundColor,f=e.textColor,w=b("div","persona-send-button-wrapper"),v=Et("button",{className:Hs("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&&!g&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?m:void 0,height:n?m:void 0,minWidth:n?m:void 0,minHeight:n?m:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&g||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),k=null,R=null;if(n){let xe=parseFloat(m)||24,Re=(f==null?void 0:f.trim())||"currentColor";o?(k=be(o,xe,Re,2),k?v.appendChild(k):v.textContent=r):v.textContent=r,R=be(s,xe,Re,2)}else v.textContent=d;let E=null;u&&a&&(E=b("div","persona-send-button-tooltip"),E.textContent=a,w.appendChild(E)),v.setAttribute("aria-label",a),w.appendChild(v);let L="send";return{button:v,wrapper:w,setMode:xe=>{if(xe===L)return;L=xe;let Re=xe==="stop"?i:a;if(v.setAttribute("aria-label",Re),E&&(E.textContent=Re),n){if(k&&R){let le=xe==="stop"?R:k;v.replaceChildren(le)}}else v.textContent=xe==="stop"?c:d}}},Ja=t=>{var E,L,M,I,A,P,O,_,H,U,F,Z;let e=(E=t==null?void 0:t.voiceRecognition)!=null?E:{};if(!(e.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((L=e.provider)==null?void 0:L.type)==="runtype";if(!(r||o))return null;let a=(I=(M=t==null?void 0:t.sendButton)==null?void 0:M.size)!=null?I:"40px",i=(A=e.iconName)!=null?A:"mic",d=(P=e.iconSize)!=null?P:a,c=parseFloat(d)||24,u=(_=e.backgroundColor)!=null?_:(O=t==null?void 0:t.sendButton)==null?void 0:O.backgroundColor,m=(U=e.iconColor)!=null?U:(H=t==null?void 0:t.sendButton)==null?void 0:H.textColor,g=b("div","persona-send-button-wrapper"),f=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:m||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),v=be(i,c,m||"currentColor",1.5);v?f.appendChild(v):f.textContent="\u{1F3A4}",g.appendChild(f);let k=(F=e.tooltipText)!=null?F:"Start voice recognition";if(((Z=e.showTooltip)!=null?Z:!1)&&k){let Te=b("div","persona-send-button-tooltip");Te.textContent=k,g.appendChild(Te)}return{button:f,wrapper:g}},Ya=t=>{var w,v,k,R,E,L,M,I;let e=(w=t==null?void 0:t.attachments)!=null?w:{};if(e.enabled!==!0)return null;let n=(k=(v=t==null?void 0:t.sendButton)==null?void 0:v.size)!=null?k:"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=((R=e.allowedTypes)!=null?R:qr).join(","),o.multiple=((E=e.maxFiles)!=null?E:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(L=e.buttonIconName)!=null?L:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=b("div","persona-send-button-wrapper"),u=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":(M=e.buttonTooltipText)!=null?M:"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"}});u.addEventListener("mouseenter",()=>{u.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="transparent"});let m=be(s,d,"currentColor",1.5);m?u.appendChild(m):u.textContent="\u{1F4CE}",u.addEventListener("click",A=>{A.preventDefault(),o.click()}),c.appendChild(u);let g=(I=e.buttonTooltipText)!=null?I:"Attach file",f=b("div","persona-send-button-tooltip");return f.textContent=g,c.appendChild(f),{button:u,wrapper:c,input:o,previewsContainer:r}},Za=t=>{var a,i,d;let e=(a=t==null?void 0:t.statusIndicator)!=null?a:{},n=e.align==="left"?"persona-text-left":e.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=e.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let c=b("a");c.href=e.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},ei=()=>Et("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ti=t=>{var w,v,k,R,E,L;let{config:e}=t,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=ei(),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}=Qa(e);a();let i=Xa(e),d=Ja(e),c=Ya(e),u=Za(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let m=Et("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&g.append(c.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),m.append(g,f),o.append(m),o.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(c==null?void 0:c.button)&&M.target!==(c==null?void 0:c.wrapper)&&s.focus()}),n.append(r,o,u),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:u,attachmentButton:(k=c==null?void 0:c.button)!=null?k:null,attachmentButtonWrapper:(R=c==null?void 0:c.wrapper)!=null?R:null,attachmentInput:(E=c==null?void 0:c.input)!=null?E:null,attachmentPreviewsContainer:(L=c==null?void 0:c.previewsContainer)!=null?L:null,actionsRow:m,leftActions:g,rightActions:f,setSendButtonMode:i.setMode}};var mm=()=>{let t=Et("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=b("span","persona-pill-peek__icon"),n=be("message-square",16,"currentColor",1.5);n&&e.appendChild(n);let r=b("span","persona-pill-peek__text"),o=b("span","persona-pill-peek__caret"),s=be("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),t.append(e,r,o),{root:t,textNode:r}},gm=t=>{var w,v,k,R,E,L;let{config:e}=t,n=Et("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=ei();r.style.display="none";let o=Za(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=Qa(e);s.style.maxHeight="100px",a();let i=Xa(e),d=Ja(e),c=Ya(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let u=Et("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),m=b("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&m.append(c.wrapper);let g=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),u.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(c==null?void 0:c.button)&&M.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&u.append(c.input),u.append(m,s,g),c&&n.append(c.previewsContainer),n.append(u,r,o);let f=u;return{footer:n,suggestions:r,composerForm:u,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(w=d==null?void 0:d.button)!=null?w:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:o,attachmentButton:(k=c==null?void 0:c.button)!=null?k:null,attachmentButtonWrapper:(R=c==null?void 0:c.wrapper)!=null?R:null,attachmentInput:(E=c==null?void 0:c.input)!=null?E:null,attachmentPreviewsContainer:(L=c==null?void 0:c.previewsContainer)!=null?L:null,actionsRow:f,leftActions:m,rightActions:g,setSendButtonMode:i.setMode}};var fm=t=>{var u,m,g,f,w,v,k,R,E,L,M,I,A,P,O,_,H;let e=(m=(u=t==null?void 0:t.launcher)==null?void 0:u.enabled)!=null?m:!0,n=fn(t);if(ea(t)){let U=(f=(g=t==null?void 0:t.launcher)==null?void 0:g.composerBar)!=null?f:{},F=b("div","persona-widget-wrapper persona-fixed persona-transition");F.setAttribute("data-persona-composer-bar",""),F.dataset.state="collapsed",F.dataset.expandedSize=(w=U.expandedSize)!=null?w:"anchored",F.style.zIndex=String((k=(v=t==null?void 0:t.launcher)==null?void 0:v.zIndex)!=null?k:xn);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 Te=b("div","persona-widget-pill-root");return Te.setAttribute("data-persona-composer-bar",""),Te.dataset.state="collapsed",Te.dataset.expandedSize=(R=U.expandedSize)!=null?R:"anchored",Te.style.zIndex=String((L=(E=t==null?void 0:t.launcher)==null?void 0:E.zIndex)!=null?L:xn),{wrapper:F,panel:Z,pillRoot:Te}}if(n){let U=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 U.appendChild(F),{wrapper:U,panel:F}}if(!e){let U=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=(I=(M=t==null?void 0:t.launcher)==null?void 0:M.width)!=null?I:"100%";return U.style.width=Z,F.style.width="100%",U.appendChild(F),{wrapper:U,panel:F}}let o=(A=t==null?void 0:t.launcher)!=null?A:{},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((O=(P=t==null?void 0:t.launcher)==null?void 0:P.zIndex)!=null?O:xn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(H=(_=t==null?void 0:t.launcher)==null?void 0:_.width)!=null?H:t==null?void 0:t.launcherWidth,c=d!=null?d:jr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},Eh=(t,e)=>{var M,I,A,P,O,_,H,U,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}=Va(t,{showClose:e,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=(A=(I=(M=t==null?void 0:t.launcher)==null?void 0:M.clearChat)==null?void 0:I.enabled)!=null?A:!0,a=null,i=null;if(s){let Z=Ka(t,{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 u=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(O=(P=t==null?void 0:t.copy)==null?void 0:P.welcomeTitle)!=null?O:"Hello \u{1F44B}"}),m=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(H=(_=t==null?void 0:t.copy)==null?void 0:_.welcomeSubtitle)!=null?H:"Ask anything about your account or products."}),g=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))"}},u,m),f=b("div","persona-flex persona-flex-col persona-gap-3"),w=(U=t==null?void 0:t.layout)==null?void 0:U.contentMaxWidth;w&&(f.style.maxWidth=w,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((F=t==null?void 0:t.copy)==null?void 0:F.showWelcomeCard)!==!1||(g.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(g,f);let k=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"}}),R=gm({config:t}),{root:E,textNode:L}=mm();return n.append(d,o,c,k),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:f,composerOverlay:k,suggestions:R.suggestions,textarea:R.textarea,sendButton:R.sendButton,sendButtonWrapper:R.sendButtonWrapper,micButton:R.micButton,micButtonWrapper:R.micButtonWrapper,composerForm:R.composerForm,statusText:R.statusText,introTitle:u,introSubtitle:m,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:R.footer,attachmentButton:R.attachmentButton,attachmentButtonWrapper:R.attachmentButtonWrapper,attachmentInput:R.attachmentInput,attachmentPreviewsContainer:R.attachmentPreviewsContainer,actionsRow:R.actionsRow,leftActions:R.leftActions,rightActions:R.rightActions,setSendButtonMode:R.setSendButtonMode,peekBanner:E,peekTextNode:L}},hm=(t,e=!0)=>{var k,R,E,L,M,I,A,P,O;if(ea(t))return Eh(t,e);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=(k=t==null?void 0:t.layout)==null?void 0:k.header,o=((R=t==null?void 0:t.layout)==null?void 0:R.showHeader)!==!1,s=r?Ga(t,r,{showClose:e}):Do({config:t,showClose:e}),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:(L=(E=t==null?void 0:t.copy)==null?void 0:E.welcomeTitle)!=null?L:"Hello \u{1F44B}"}),d=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(I=(M=t==null?void 0:t.copy)==null?void 0:M.welcomeSubtitle)!=null?I:"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:fn(t)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),u=b("div","persona-flex persona-flex-col persona-gap-3"),m=(A=t==null?void 0:t.layout)==null?void 0:A.contentMaxWidth;m&&(u.style.maxWidth=m,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((P=t==null?void 0:t.copy)==null?void 0:P.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,u);let f=ti({config:t}),w=((O=t==null?void 0:t.layout)==null?void 0:O.showFooter)!==!1;o?ta(n,s,t):(s.header.style.display="none",ta(n,s,t)),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 w||(f.footer.style.display="none"),n.append(f.footer),n.append(v),{container:n,body:a,messagesWrapper:u,composerOverlay:v,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle: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:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var ji=(t,e)=>{let n=b("button");n.type="button",n.innerHTML=`
|
|
18
|
+
_Details: ${t.message}_`:r}var ea=n=>({isError:!0,content:[{type:"text",text:n}]}),um=(n,e="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:e,mm=n=>cs(n)||n===zr,$a=class{constructor(e={},t){this.config=e;this.callbacks=t;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 Zs(()=>this.createSpeechEngine());this.handleEvent=e=>{var t,r,o,s,a,i,d,c,p,g;if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let h=e.message.toolCall,m=!!(h!=null&&h.name)&&(cs(h.name)||h.name===zr&&((r=(t=this.config.features)==null?void 0:t.suggestReplies)==null?void 0:r.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let h=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":h||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(g=(p=this.callbacks).onError)==null||g.call(p,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.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 Js(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d,c;let e=this.config.textToSpeech;if((e==null?void 0:e.provider)!=="runtype"||e.createEngine)return;let t=(o=e.host)!=null?o:this.config.apiUrl,r=(c=(d=e.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;!t||!r||!this.config.clientToken||ji().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return qi((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,t,r;return(r=(t=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:t.call(e))!=null?r:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let e=this.config.textToSpeech;if(e!=null&&e.createEngine)return e.createEngine();let t=bs.isSupported()?new bs({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let c=(r=e.host)!=null?r:this.config.apiUrl,p=(d=(i=e.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,g=this.config.clientToken,h=e.browserFallback!==!1;if(c&&p&&g)return ji().then(({RuntypeSpeechEngine:m,FallbackSpeechEngine:y})=>{let w=new m({host:c,agentId:p,clientToken:g,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return h&&t?new y(w,t,{onFallback:E=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${E.message}`)}):w});if(h&&t)return g&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),t}return t}setupVoice(e){var t,r;try{let o=e||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=ys(o);let a=(r=((t=this.config.voiceRecognition)!=null?t:{}).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(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,o,s,a,i,d,c,p,g,h,m;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=e.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=e.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=e.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(p=e.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(g=e.runtype)==null?void 0:g.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((h=e.browser)==null?void 0:h.language)||"en-US",continuous:(m=e.browser)==null?void 0:m.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){var e,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(e=this.callbacks).onError)==null||t.call(e,r instanceof Error?r:new Error(String(r))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}updateConfig(e){let t={...this.config,...e};if(!Eh(this.config,t)){this.config=t,this.client.updateConfig(t);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=t,this.client=new Js(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:g}=e,m={id:a!=null?a:t==="user"?Ba():t==="assistant"?fs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,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},...g!==void 0&&{rawContent:g}};return this.upsertMessage(m),m}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let t=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:g=!1,voiceProcessing:h,rawContent:m}=r,w={id:d!=null?d:o==="user"?Ba():o==="assistant"?fs():`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:g,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...h!==void 0&&{voiceProcessing:h},...m!==void 0&&{rawContent:m}};t.push(w)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,c={text:o,component:t,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(e,t){var c,p,g,h,m;let r=e.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let o=Ba(),s=fs();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||Da,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.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 w=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));if(!w){let E=Vi(y,this.config.errorMessage);if(E){let B={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(B)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,w||(y instanceof Error?(g=(p=this.callbacks).onError)==null||g.call(p,y):(m=(h=this.callbacks).onError)==null||m.call(h,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 e=fs();this.activeAssistantMessageId=null,this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},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 g=Vi(c,this.config.errorMessage);if(g){let h={id:e,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(h)}}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(e,t){var s,a,i;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(s=this.abortController)==null||s.abort(),t!=null&&t.preserveAssistantId&&t.assistantMessageId&&(this.activeAssistantMessageId=t.assistantMessageId);let r=t!=null&&t.preserveAssistantId?t.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(e,this.handleEvent,t==null?void 0:t.assistantMessageId,t==null?void 0:t.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 e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(e,t,r){var p,g,h,m,y;let o=`approval-${e.id}`,s={...e,status:t,resolvedAt:Date.now()},a=this.messages.find(w=>w.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),(g=this.abortController)==null||g.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let w;if(c?w=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},t,r):w=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},t),w){let E=null;if(w instanceof Response){if(!w.ok){let B=await w.json().catch(()=>null);throw new Error((h=B==null?void 0:B.error)!=null?h:`Approval request failed: ${w.status}`)}E=w.body}else w instanceof ReadableStream&&(E=w);E?await this.connectStream(E,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(w){let E=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(y=(m=this.callbacks).onError)==null||y.call(m,w instanceof Error?w:new Error(String(w)))}}persistAskUserQuestionProgress(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(e,t){var p,g,h,m,y,w,E,B,T,I,M,P;let r=this.messages.find(C=>C.id===e.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(g=e.agentMetadata)==null?void 0:g.executionId,s=(h=e.toolCall)==null?void 0:h.name;if(!o||!s){(y=(m=this.callbacks).onError)==null||y.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let C=(w=e.toolCall)==null?void 0:w.args,k=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(k.length===1){let q=typeof((E=k[0])==null?void 0:E.question)=="string"?k[0].question:"";q&&(a={[q]:t})}}this.markAskUserQuestionResolved(e,a),(B=this.abortController)==null||B.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(T=e.toolCall)==null?void 0:T.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let C=typeof t=="string"?t:Object.entries(t).map(([k,q])=>`${k}: ${Array.isArray(q)?q.join(", "):q}`).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((k,q)=>{let _=typeof(k==null?void 0:k.question)=="string"?k.question:"";if(!_)return;let R=C[_],O=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${q}`,role:"assistant",content:_,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${q}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:t});if(!C.ok){let k=await C.json().catch(()=>null);throw new Error((I=k==null?void 0:k.error)!=null?I:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let k=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,k||(P=(M=this.callbacks).onError)==null||P.call(M,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(e){var s,a;let t=(s=e.agentMetadata)==null?void 0:s.executionId,r=(a=e.toolCall)==null?void 0:a.id;if(!t||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(t);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=t;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(e,r)}resolveWebMcpToolStartedAt(e){var o,s;let t=this.messages.find(a=>a.id===e.id),r=[(o=t==null?void 0:t.toolCall)==null?void 0:o.startedAt,(s=e.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(e){var r,o;if(((r=e.toolCall)==null?void 0:r.name)!==zr)return!1;let t=this.messages.find(s=>s.id===e.id);return((o=(t!=null?t:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let t=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:t,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),t}markWebMcpToolComplete(e,t,r,o=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:t,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,t){var d,c,p,g;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(t.map(async h=>{var P,C,k,q,_,R,O;let m=(P=h.toolCall)==null?void 0:P.name,y=(C=h.toolCall)==null?void 0:C.id;if(!m||!y)return null;let w=`${e}:${y}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w)||this.isSuggestRepliesAlreadyResolved(h))return null;this.webMcpInflightKeys.add(w),r.push(w);let E=this.markWebMcpToolRunning(h),B=(q=(k=h.agentMetadata)==null?void 0:k.webMcpToolCallId)!=null?q:m;if(m===zr)return{dedupeKey:w,resumeKey:B,output:Di(),toolMessage:h,startedAt:E,completedAt:Date.now()};let T=new AbortController;this.webMcpResolveControllers.add(T),o.push(T);let I=this.client.executeWebMcpToolCall(m,(_=h.toolCall)==null?void 0:_.args,T.signal),M;if(!I)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await I}catch(F){let Z=F instanceof Error&&(F.name==="AbortError"||F.message.includes("aborted")||F.message.includes("abort"));return Z||(O=(R=this.callbacks).onError)==null||O.call(R,F instanceof Error?F:new Error(String(F))),this.markWebMcpToolComplete(h,ea(Z?"Aborted by cancel()":um(F)),E),this.webMcpInflightKeys.delete(w),null}return T.signal.aborted?(this.markWebMcpToolComplete(h,ea("Aborted by cancel()"),E),this.webMcpInflightKeys.delete(w),null):{dedupeKey:w,resumeKey:B,output:M,toolMessage:h,startedAt:E,completedAt:Date.now()}})),i=[];try{if(i=a.filter(y=>y!==null),i.length===0)return;let h={};for(let y of i)h[y.resumeKey]=y.output;let m=await this.client.resumeFlow(e,h,{signal:s.signal});if(!m.ok){let y=await m.json().catch(()=>null);throw new Error((d=y==null?void 0:y.error)!=null?d:`Resume failed: ${m.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)===zr?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(h){if(!(h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"))))(g=(p=this.callbacks).onError)==null||g.call(p,h instanceof Error?h:new Error(String(h)));else for(let y of i)this.markWebMcpToolComplete(y.toolMessage,ea("Aborted by cancel()"),y.startedAt)}finally{for(let h of r)this.webMcpInflightKeys.delete(h);for(let h of o)this.webMcpResolveControllers.delete(h);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var y,w,E,B,T,I,M,P,C,k,q,_;let t=(y=e.agentMetadata)==null?void 0:y.executionId,r=(w=e.toolCall)==null?void 0:w.name,o=(E=e.toolCall)==null?void 0:E.id;if(!t){(T=(B=this.callbacks).onError)==null||T.call(B,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let R=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(R)||this.webMcpResolvedKeys.has(R))return;this.webMcpInflightKeys.add(R);try{await this.resumeWithToolOutput(t,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(R)}catch(O){(M=(I=this.callbacks).onError)==null||M.call(I,O instanceof Error?O:new Error(String(O)))}finally{this.webMcpInflightKeys.delete(R)}return}let s=`${t}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===zr,p=(P=e.toolCall)==null?void 0:P.args,g=c?null:this.client.executeWebMcpToolCall(r,p,d),h="execute",m=a;try{let R;if(c?R=Di():g?R=await g:R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(e,ea("Aborted by cancel()"),a);return}let O=(k=(C=e.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?k:r;h="resume",await this.resumeWithToolOutput(t,O,R,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,R,a,m,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(R){let O=R instanceof Error&&(R.name==="AbortError"||R.message.includes("aborted")||R.message.includes("abort"));(h==="execute"||O||d.aborted)&&this.markWebMcpToolComplete(e,ea(O||d.aborted?"Aborted by cancel()":um(R)),a),O||(_=(q=this.callbacks).onError)==null||_.call(q,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(e,t,r,o){var a,i;let s=await this.client.resumeFlow(e,{[t]: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 e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(t,s),this.selectedArtifactId=t,this.emitArtifactsState(),s}let r={id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,t;(t=(e=this.callbacks).onArtifactsState)==null||t.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var t,r;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(t=e.component)!=null?t:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.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(e,t=null){this.artifacts.clear();for(let r of e)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}trackCursor(e){var o,s;let t=(o=this.agentExecution)==null?void 0:o.executionId;if(!t||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:t,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var e;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((e=this.abortController)==null?void 0:e.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>{var t,r,o;return((t=e.agentMetadata)==null?void 0:t.awaitingLocalTool)===!0&&((r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||e.variant==="approval"&&((o=e.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var e,t;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(t=(e=this.callbacks).onReconnect)==null||t.call(e,{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(()=>(pm(),dm)).then(({createReconnectController:e})=>{let t=e(this.buildReconnectHost());return this.reconnectController=t,t})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:t=>e.setStatus(t),setStreaming:t=>e.setStreaming(t),setReconnecting:t=>{e.reconnecting=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,r,o)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:t=>e.appendMessage(t),nextSequence:()=>e.nextSequence(),emitReconnect:t=>{var r,o;return(o=(r=e.callbacks).onReconnect)==null?void 0:o.call(r,t)},buildErrorContent:t=>Vi(new Error(t),e.config.errorMessage),onError:t=>{var r,o;return(o=(r=e.callbacks).onError)==null?void 0:o.call(r,t)}}}reconnectNow(){var e;if(this.reconnecting){(e=this.reconnectController)==null||e.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let t=this.reopenTrailingAssistant();t||(t=fs(),this.appendMessage({id:t,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=t,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role==="assistant"&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role==="user")break}return null}teardownReconnect(){var e;this.reconnecting=!1,(e=this.reconnectController)==null||e.teardown(),this.clearResumable()}clearResumable(){var t,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&((r=(t=this.config).onExecutionState)==null||r.call(t,null))}notifyExecutionState(e){let t=this.config.onExecutionState;if(t){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),t(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(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.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=zi(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Fa(e)}toggleReadAloud(e){let t=this.messages.find(s=>s.id===e);if(!t||t.role!=="assistant")return;let r=zi(t.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let t=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.ensureSequence(e),r=this.messages.findIndex(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>{var p,g,h,m,y,w,E,B,T,I,M,P,C,k,q;if(s!==r)return o;let a={...o,...t};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((g=o.agentMetadata)==null?void 0:g.suggestRepliesResolved)===!0&&t.agentMetadata&&(a.agentMetadata={...(h=a.agentMetadata)!=null?h:t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&t.approval&&o.approval.id===t.approval.id){let _=o.approval,R=t.approval;a.approval={..._,...R,executionId:R.executionId||_.executionId,toolName:R.toolName||_.toolName,description:R.description||_.description,toolType:(m=R.toolType)!=null?m:_.toolType,reason:(y=R.reason)!=null?y:_.reason,parameters:(w=R.parameters)!=null?w:_.parameters}}let i=(E=t.toolCall)==null?void 0:E.name,d=(B=t.agentMetadata)==null?void 0:B.executionId,c=(T=t.toolCall)==null?void 0:T.id;if(i&&mm(i)&&d&&c&&((I=t.agentMetadata)==null?void 0:I.awaitingLocalTool)===!0){let _=`${d}:${c}`,R=this.webMcpInflightKeys.has(_),O=this.webMcpResolvedKeys.has(_),F=(M=o.toolCall)==null?void 0:M.name,Z=((P=o.agentMetadata)==null?void 0:P.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&F!==void 0&&mm(F)&&((k=o.toolCall)==null?void 0:k.status)==="complete";(R||O||Z)&&(a.agentMetadata={...(q=a.agentMetadata)!=null?q:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((t,r)=>{var d,c;let o=new Date(t.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=t.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var A=require("lucide"),Mh={activity:A.Activity,"arrow-down":A.ArrowDown,"arrow-up":A.ArrowUp,"arrow-up-right":A.ArrowUpRight,bot:A.Bot,"chevron-down":A.ChevronDown,"chevron-up":A.ChevronUp,"chevron-right":A.ChevronRight,"chevron-left":A.ChevronLeft,check:A.Check,clipboard:A.Clipboard,"clipboard-copy":A.ClipboardCopy,copy:A.Copy,file:A.File,"file-code":A.FileCode,"file-spreadsheet":A.FileSpreadsheet,"file-text":A.FileText,"image-plus":A.ImagePlus,loader:A.Loader,"loader-circle":A.LoaderCircle,mic:A.Mic,paperclip:A.Paperclip,"refresh-cw":A.RefreshCw,search:A.Search,send:A.Send,"shield-alert":A.ShieldAlert,"shield-check":A.ShieldCheck,"shield-x":A.ShieldX,square:A.Square,"thumbs-down":A.ThumbsDown,"thumbs-up":A.ThumbsUp,upload:A.Upload,"volume-2":A.Volume2,x:A.X,user:A.User,mail:A.Mail,phone:A.Phone,calendar:A.Calendar,clock:A.Clock,building:A.Building,"map-pin":A.MapPin,lock:A.Lock,key:A.Key,"credit-card":A.CreditCard,"at-sign":A.AtSign,hash:A.Hash,globe:A.Globe,link:A.Link,"circle-check":A.CircleCheck,"circle-x":A.CircleX,"triangle-alert":A.TriangleAlert,info:A.Info,ban:A.Ban,shield:A.Shield,"arrow-left":A.ArrowLeft,"arrow-right":A.ArrowRight,"external-link":A.ExternalLink,ellipsis:A.Ellipsis,"ellipsis-vertical":A.EllipsisVertical,menu:A.Menu,house:A.House,plus:A.Plus,minus:A.Minus,pencil:A.Pencil,trash:A.Trash,"trash-2":A.Trash2,save:A.Save,download:A.Download,share:A.Share,funnel:A.Funnel,settings:A.Settings,"rotate-cw":A.RotateCw,maximize:A.Maximize,minimize:A.Minimize,"shopping-cart":A.ShoppingCart,"shopping-bag":A.ShoppingBag,package:A.Package,truck:A.Truck,tag:A.Tag,gift:A.Gift,receipt:A.Receipt,wallet:A.Wallet,store:A.Store,"dollar-sign":A.DollarSign,percent:A.Percent,play:A.Play,pause:A.Pause,"volume-x":A.VolumeX,camera:A.Camera,image:A.Image,film:A.Film,headphones:A.Headphones,"message-circle":A.MessageCircle,"message-square":A.MessageSquare,bell:A.Bell,heart:A.Heart,star:A.Star,eye:A.Eye,"eye-off":A.EyeOff,bookmark:A.Bookmark,"calendar-days":A.CalendarDays,history:A.History,timer:A.Timer,folder:A.Folder,"folder-open":A.FolderOpen,files:A.Files,sparkles:A.Sparkles,zap:A.Zap,sun:A.Sun,moon:A.Moon,flag:A.Flag,monitor:A.Monitor,smartphone:A.Smartphone},ye=(n,e=24,t="currentColor",r=2)=>{let o=Mh[n];return o?kh(o,e,t,r):(console.warn(`Lucide icon "${n}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function kh(n,e,t,r){if(!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.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 Ua={allowedTypes:jr,maxFileSize:10*1024*1024,maxFiles:4};function Lh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ph(n){return n==="application/pdf"||n.startsWith("text/")||n.includes("word")?"file-text":n.includes("excel")||n.includes("spreadsheet")?"file-spreadsheet":n==="application/json"?"file-code":"file"}var ta=class n{constructor(e={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:Ua.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:Ua.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:Ua.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Ua.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var t,r,o,s,a,i,d;if(e.length){for(let c of e){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let p=em(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let g=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,g);continue}try{let g=await Zu(c),h=Na(c)?URL.createObjectURL(c):null,m={id:Lh(),file:c,previewUrl:h,contentPart:g};this.attachments.push(m),this.renderPreview(m)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let t=this.attachments.findIndex(d=>d.id===e);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(e=this.config).onAttachmentsChange)==null||t.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let t=Na(e.file),r=v("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",t&&e.previewUrl){let a=v("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=v("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Ph(e.file.type),d=ye(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=v("span");c.textContent=tm(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=v("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(e.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,t){return new n({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:t})}};var gm=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function na(n,e){if(!n)return e;if(!e)return n;let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];gm(s)&&gm(o)?t[r]=na(s,o):t[r]=o}return t}var Vr="min(440px, calc(100vw - 24px))",hm="440px",Ih={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:Vr,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)"},Bt={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:Ih,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 fm(n,e){if(!(!n&&!e))return n?e?na(n,e):n:e}function ym(n){var e,t,r,o,s,a,i,d,c,p,g,h,m,y,w,E,B,T,I,M,P;return n?{...Bt,...n,theme:fm(Bt.theme,n.theme),darkTheme:fm(Bt.darkTheme,n.darkTheme),launcher:{...Bt.launcher,...n.launcher,dock:{...(e=Bt.launcher)==null?void 0:e.dock,...(t=n.launcher)==null?void 0:t.dock},clearChat:{...(r=Bt.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...Bt.copy,...n.copy},sendButton:{...Bt.sendButton,...n.sendButton},statusIndicator:{...Bt.statusIndicator,...n.statusIndicator},voiceRecognition:{...Bt.voiceRecognition,...n.voiceRecognition},features:(()=>{var re,oe,de,Ae,$e,K,J,Se,Y,le;let C=(re=Bt.features)==null?void 0:re.artifacts,k=(oe=n.features)==null?void 0:oe.artifacts,q=(de=Bt.features)==null?void 0:de.scrollToBottom,_=(Ae=n.features)==null?void 0:Ae.scrollToBottom,R=($e=Bt.features)==null?void 0:$e.scrollBehavior,O=(K=n.features)==null?void 0:K.scrollBehavior,F=(J=Bt.features)==null?void 0:J.streamAnimation,Z=(Se=n.features)==null?void 0:Se.streamAnimation,ke=(Y=Bt.features)==null?void 0:Y.askUserQuestion,pe=(le=n.features)==null?void 0:le.askUserQuestion,ee=C===void 0&&k===void 0?void 0:{...C,...k,layout:{...C==null?void 0:C.layout,...k==null?void 0:k.layout}},Pe=q===void 0&&_===void 0?void 0:{...q,..._},Ie=R===void 0&&O===void 0?void 0:{...R,...O},ie=F===void 0&&Z===void 0?void 0:{...F,...Z},he=ke===void 0&&pe===void 0?void 0:{...ke,...pe,styles:{...ke==null?void 0:ke.styles,...pe==null?void 0:pe.styles}};return{...Bt.features,...n.features,...Pe!==void 0?{scrollToBottom:Pe}:{},...Ie!==void 0?{scrollBehavior:Ie}:{},...ee!==void 0?{artifacts:ee}:{},...ie!==void 0?{streamAnimation:ie}:{},...he!==void 0?{askUserQuestion:he}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:Bt.suggestionChips,suggestionChipsConfig:{...Bt.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Bt.layout,...n.layout,header:{...(a=Bt.layout)==null?void 0:a.header,...(i=n.layout)==null?void 0:i.header},messages:{...(d=Bt.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(g=(p=Bt.layout)==null?void 0:p.messages)==null?void 0:g.avatar,...(m=(h=n.layout)==null?void 0:h.messages)==null?void 0:m.avatar},timestamp:{...(w=(y=Bt.layout)==null?void 0:y.messages)==null?void 0:w.timestamp,...(B=(E=n.layout)==null?void 0:E.messages)==null?void 0:B.timestamp}},slots:{...(T=Bt.layout)==null?void 0:T.slots,...(I=n.layout)==null?void 0:I.slots}},markdown:{...Bt.markdown,...n.markdown,options:{...(M=Bt.markdown)==null?void 0:M.options,...(P=n.markdown)==null?void 0:P.options}},messageActions:{...Bt.messageActions,...n.messageActions}}:Bt}var Rh={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"}},Wh={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"}},Hh={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:Vr,maxWidth:hm,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 vs(n,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let t=e.split("."),r=n;for(let o of t){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?vs(n,r):r}function bm(n){let e={};function t(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=vs(n,a);d!==void 0&&(e[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&&t(a,i)}}return t(n.palette,"palette"),t(n.semantic,"semantic"),t(n.components,"components"),e}function Bh(n){let e=[],t=[];return n.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),n.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),n.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:t}}function vm(n,e){let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?t[r]=vm(s,o):t[r]=o}return t}function Dh(n,e){return e?vm(n,e):n}function qo(n,e={}){var o,s,a,i,d,c,p,g,h,m,y,w,E;let t={palette:Rh,semantic:Wh,components:Hh},r={palette:{...t.palette,...n==null?void 0:n.palette,colors:{...t.palette.colors,...(o=n==null?void 0:n.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=n==null?void 0:n.palette)==null?void 0:s.spacing},typography:{...t.palette.typography,...(a=n==null?void 0:n.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=n==null?void 0:n.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=n==null?void 0:n.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=n==null?void 0:n.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...n==null?void 0:n.semantic,colors:{...t.semantic.colors,...(p=n==null?void 0:n.semantic)==null?void 0:p.colors,interactive:{...t.semantic.colors.interactive,...(h=(g=n==null?void 0:n.semantic)==null?void 0:g.colors)==null?void 0:h.interactive},feedback:{...t.semantic.colors.feedback,...(y=(m=n==null?void 0:n.semantic)==null?void 0:m.colors)==null?void 0:y.feedback}},spacing:{...t.semantic.spacing,...(w=n==null?void 0:n.semantic)==null?void 0:w.spacing},typography:{...t.semantic.typography,...(E=n==null?void 0:n.semantic)==null?void 0:E.typography}},components:Dh(t.components,n==null?void 0:n.components)};if(e.validate!==!1){let B=Bh(r);if(!B.valid)throw new Error(`Theme validation failed: ${B.errors.map(T=>T.message).join(", ")}`)}if(e.plugins)for(let B of e.plugins)r=B.transform(r);return r}function wm(n){var w,E,B,T,I,M,P,C,k,q,_,R,O,F,Z,ke,pe,ee,Pe,Ie,ie,he,re,oe,de,Ae,$e,K,J,Se,Y,le,Te,Ye,tt,Wt,ht,ot,me,X,lt,Ve,Ee,xe,Ze,jt,be,ue,xn,At,fn,hr,yr,qe,L,ge,Me,Le,He,nt,Xe,yt,fe,D,ve,ce,ft,Ge,Pt,kt,wt,Ht,Xt,Ot,en,br,Wr,rr,or,Kr,Vt,sr,Hr,Bn,Ln,Dn,ar,vr,Gr,Vn,Qr,St,wr,xr,Br,ir,bt,Co,Cr,Ao,Pn,Qo,Xr,Dr,Jr,Yr,So,To,Zr,xt,Nn,Fn,Cn,Tt,Kn,Gn,On,eo;let e=bm(n),t={};for(let[Ce,Nr]of Object.entries(e)){let Qn=Ce.replace(/\./g,"-");t[`--persona-${Qn}`]=Nr.value}t["--persona-primary"]=(w=t["--persona-semantic-colors-primary"])!=null?w:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(E=t["--persona-semantic-colors-secondary"])!=null?E:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(B=t["--persona-semantic-colors-accent"])!=null?B:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(T=t["--persona-semantic-colors-surface"])!=null?T:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(I=t["--persona-semantic-colors-background"])!=null?I:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(M=t["--persona-semantic-colors-container"])!=null?M:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(P=t["--persona-semantic-colors-text"])!=null?P:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(C=t["--persona-semantic-colors-text-muted"])!=null?C:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(k=t["--persona-semantic-colors-text-inverse"])!=null?k:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(q=t["--persona-semantic-colors-border"])!=null?q:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(_=t["--persona-semantic-colors-divider"])!=null?_:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(R=t["--persona-components-voice-recording-indicator"])!=null?R:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(O=t["--persona-components-voice-recording-background"])!=null?O:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(F=t["--persona-components-voice-processing-icon"])!=null?F:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(Z=t["--persona-components-voice-speaking-icon"])!=null?Z:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(ke=t["--persona-components-approval-requested-background"])!=null?ke:t["--persona-surface"],t["--persona-approval-border"]=(pe=t["--persona-components-approval-requested-border"])!=null?pe:t["--persona-border"],t["--persona-approval-text"]=(ee=t["--persona-components-approval-requested-text"])!=null?ee:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(Pe=t["--persona-components-approval-requested-shadow"])!=null?Pe:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",t["--persona-approval-approve-bg"]=(Ie=t["--persona-components-approval-approve-background"])!=null?Ie:t["--persona-button-primary-bg"],t["--persona-approval-deny-bg"]=(ie=t["--persona-components-approval-deny-background"])!=null?ie:t["--persona-container"],t["--persona-attachment-image-bg"]=(he=t["--persona-components-attachment-image-background"])!=null?he:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(re=t["--persona-components-attachment-image-border"])!=null?re:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(oe=t["--persona-semantic-typography-fontFamily"])!=null?oe:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(de=t["--persona-semantic-typography-fontSize"])!=null?de:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(Ae=t["--persona-semantic-typography-fontWeight"])!=null?Ae:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=($e=t["--persona-semantic-typography-lineHeight"])!=null?$e:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(K=t["--persona-palette-radius-sm"])!=null?K:"0.125rem",t["--persona-radius-md"]=(J=t["--persona-palette-radius-md"])!=null?J:"0.375rem",t["--persona-radius-lg"]=(Se=t["--persona-palette-radius-lg"])!=null?Se:"0.5rem",t["--persona-radius-xl"]=(Y=t["--persona-palette-radius-xl"])!=null?Y:"0.75rem",t["--persona-radius-full"]=(le=t["--persona-palette-radius-full"])!=null?le:"9999px",t["--persona-launcher-radius"]=(Ye=(Te=t["--persona-components-launcher-borderRadius"])!=null?Te:t["--persona-palette-radius-full"])!=null?Ye:"9999px",t["--persona-launcher-bg"]=(tt=t["--persona-components-launcher-background"])!=null?tt:t["--persona-primary"],t["--persona-launcher-fg"]=(Wt=t["--persona-components-launcher-foreground"])!=null?Wt:t["--persona-text-inverse"],t["--persona-launcher-border"]=(ht=t["--persona-components-launcher-border"])!=null?ht:t["--persona-border"],t["--persona-button-primary-bg"]=(ot=t["--persona-components-button-primary-background"])!=null?ot:t["--persona-primary"],t["--persona-button-primary-fg"]=(me=t["--persona-components-button-primary-foreground"])!=null?me:t["--persona-text-inverse"],t["--persona-button-radius"]=(lt=(X=t["--persona-components-button-primary-borderRadius"])!=null?X:t["--persona-palette-radius-full"])!=null?lt:"9999px",t["--persona-panel-radius"]=(Ee=(Ve=t["--persona-components-panel-borderRadius"])!=null?Ve:t["--persona-radius-xl"])!=null?Ee:"0.75rem",t["--persona-panel-border"]=(xe=t["--persona-components-panel-border"])!=null?xe:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(jt=(Ze=t["--persona-components-panel-shadow"])!=null?Ze:t["--persona-palette-shadows-xl"])!=null?jt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(be=t["--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)",t["--persona-input-radius"]=(xn=(ue=t["--persona-components-input-borderRadius"])!=null?ue:t["--persona-radius-lg"])!=null?xn:"0.5rem",t["--persona-message-user-radius"]=(fn=(At=t["--persona-components-message-user-borderRadius"])!=null?At:t["--persona-radius-lg"])!=null?fn:"0.5rem",t["--persona-message-assistant-radius"]=(yr=(hr=t["--persona-components-message-assistant-borderRadius"])!=null?hr:t["--persona-radius-lg"])!=null?yr:"0.5rem",t["--persona-header-bg"]=(qe=t["--persona-components-header-background"])!=null?qe:t["--persona-surface"],t["--persona-header-border"]=(L=t["--persona-components-header-border"])!=null?L:t["--persona-divider"],t["--persona-header-icon-bg"]=(ge=t["--persona-components-header-iconBackground"])!=null?ge:t["--persona-primary"],t["--persona-header-icon-fg"]=(Me=t["--persona-components-header-iconForeground"])!=null?Me:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Le=t["--persona-components-header-titleForeground"])!=null?Le:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(He=t["--persona-components-header-subtitleForeground"])!=null?He:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(nt=t["--persona-components-header-actionIconForeground"])!=null?nt:t["--persona-muted"];let r=(Xe=n.components)==null?void 0:Xe.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(yt=n.components)==null?void 0:yt.introCard;t["--persona-intro-card-bg"]=(fe=t["--persona-components-introCard-background"])!=null?fe:t["--persona-surface"],t["--persona-intro-card-radius"]=(D=t["--persona-components-introCard-borderRadius"])!=null?D:"1rem",t["--persona-intro-card-padding"]=(ve=t["--persona-components-introCard-padding"])!=null?ve:"1.5rem",t["--persona-intro-card-shadow"]=(ft=(ce=o==null?void 0:o.shadow)!=null?ce:t["--persona-components-introCard-shadow"])!=null?ft:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(Ge=t["--persona-components-input-background"])!=null?Ge:t["--persona-surface"],t["--persona-input-placeholder"]=(Pt=t["--persona-components-input-placeholder"])!=null?Pt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(kt=t["--persona-components-message-user-background"])!=null?kt:t["--persona-accent"],t["--persona-message-user-text"]=(wt=t["--persona-components-message-user-text"])!=null?wt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Ht=t["--persona-components-message-user-shadow"])!=null?Ht:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Xt=t["--persona-components-message-assistant-background"])!=null?Xt:t["--persona-surface"],t["--persona-message-assistant-text"]=(Ot=t["--persona-components-message-assistant-text"])!=null?Ot:t["--persona-text"],t["--persona-message-assistant-border"]=(en=t["--persona-components-message-assistant-border"])!=null?en:t["--persona-border"],t["--persona-message-assistant-shadow"]=(br=t["--persona-components-message-assistant-shadow"])!=null?br:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(rr=(Wr=t["--persona-components-scrollToBottom-background"])!=null?Wr:t["--persona-button-primary-bg"])!=null?rr:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Kr=(or=t["--persona-components-scrollToBottom-foreground"])!=null?or:t["--persona-button-primary-fg"])!=null?Kr:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Vt=t["--persona-components-scrollToBottom-border"])!=null?Vt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(sr=t["--persona-components-scrollToBottom-size"])!=null?sr:"40px",t["--persona-scroll-to-bottom-radius"]=(Ln=(Bn=(Hr=t["--persona-components-scrollToBottom-borderRadius"])!=null?Hr:t["--persona-button-radius"])!=null?Bn:t["--persona-radius-full"])!=null?Ln:"9999px",t["--persona-scroll-to-bottom-shadow"]=(ar=(Dn=t["--persona-components-scrollToBottom-shadow"])!=null?Dn:t["--persona-palette-shadows-sm"])!=null?ar:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(vr=t["--persona-components-scrollToBottom-padding"])!=null?vr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(Gr=t["--persona-components-scrollToBottom-gap"])!=null?Gr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Qr=(Vn=t["--persona-components-scrollToBottom-fontSize"])!=null?Vn:t["--persona-palette-typography-fontSize-sm"])!=null?Qr:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(St=t["--persona-components-scrollToBottom-iconSize"])!=null?St:"14px",t["--persona-tool-bubble-shadow"]=(wr=t["--persona-components-toolBubble-shadow"])!=null?wr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(xr=t["--persona-components-reasoningBubble-shadow"])!=null?xr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Br=t["--persona-components-composer-shadow"])!=null?Br:"none",t["--persona-md-inline-code-bg"]=(ir=t["--persona-components-markdown-inlineCode-background"])!=null?ir:t["--persona-container"],t["--persona-md-inline-code-color"]=(bt=t["--persona-components-markdown-inlineCode-foreground"])!=null?bt:t["--persona-text"],t["--persona-md-link-color"]=(Cr=(Co=t["--persona-components-markdown-link-foreground"])!=null?Co:t["--persona-accent"])!=null?Cr:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let c=t["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(t["--persona-md-prose-font-family"]=c),t["--persona-md-code-block-bg"]=(Ao=t["--persona-components-markdown-codeBlock-background"])!=null?Ao:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Pn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Pn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Qo=t["--persona-components-markdown-codeBlock-textColor"])!=null?Qo:"inherit",t["--persona-md-table-header-bg"]=(Xr=t["--persona-components-markdown-table-headerBackground"])!=null?Xr:t["--persona-container"],t["--persona-md-table-border-color"]=(Dr=t["--persona-components-markdown-table-borderColor"])!=null?Dr:t["--persona-border"],t["--persona-md-hr-color"]=(Jr=t["--persona-components-markdown-hr-color"])!=null?Jr:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(Yr=t["--persona-components-markdown-blockquote-borderColor"])!=null?Yr:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(So=t["--persona-components-markdown-blockquote-background"])!=null?So:"transparent",t["--persona-md-blockquote-text-color"]=(To=t["--persona-components-markdown-blockquote-textColor"])!=null?To:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Zr=t["--persona-components-collapsibleWidget-container"])!=null?Zr:t["--persona-surface"],t["--cw-surface"]=(xt=t["--persona-components-collapsibleWidget-surface"])!=null?xt:t["--persona-surface"],t["--cw-border"]=(Nn=t["--persona-components-collapsibleWidget-border"])!=null?Nn:t["--persona-border"],t["--persona-message-border"]=(Fn=t["--persona-components-message-border"])!=null?Fn:t["--persona-border"];let p=n.components,g=p==null?void 0:p.iconButton;g&&(g.background&&(t["--persona-icon-btn-bg"]=g.background),g.border&&(t["--persona-icon-btn-border"]=g.border),g.color&&(t["--persona-icon-btn-color"]=g.color),g.padding&&(t["--persona-icon-btn-padding"]=g.padding),g.borderRadius&&(t["--persona-icon-btn-radius"]=g.borderRadius),g.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=g.hoverBackground),g.hoverColor&&(t["--persona-icon-btn-hover-color"]=g.hoverColor),g.activeBackground&&(t["--persona-icon-btn-active-bg"]=g.activeBackground),g.activeBorder&&(t["--persona-icon-btn-active-border"]=g.activeBorder));let h=p==null?void 0:p.labelButton;h&&(h.background&&(t["--persona-label-btn-bg"]=h.background),h.border&&(t["--persona-label-btn-border"]=h.border),h.color&&(t["--persona-label-btn-color"]=h.color),h.padding&&(t["--persona-label-btn-padding"]=h.padding),h.borderRadius&&(t["--persona-label-btn-radius"]=h.borderRadius),h.hoverBackground&&(t["--persona-label-btn-hover-bg"]=h.hoverBackground),h.fontSize&&(t["--persona-label-btn-font-size"]=h.fontSize),h.gap&&(t["--persona-label-btn-gap"]=h.gap));let m=p==null?void 0:p.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let y=p==null?void 0:p.artifact;if(y!=null&&y.toolbar){let Ce=y.toolbar;Ce.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=Ce.iconHoverColor),Ce.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=Ce.iconHoverBackground),Ce.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=Ce.iconPadding),Ce.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=Ce.iconBorderRadius),Ce.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=Ce.iconBorder),Ce.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=Ce.toggleGroupGap),Ce.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=Ce.toggleBorderRadius),Ce.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=Ce.copyBackground),Ce.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=Ce.copyBorder),Ce.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=Ce.copyColor),Ce.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=Ce.copyBorderRadius),Ce.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=Ce.copyPadding),Ce.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=Ce.copyMenuBackground,t["--persona-dropdown-bg"]=(Cn=t["--persona-dropdown-bg"])!=null?Cn:Ce.copyMenuBackground),Ce.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=Ce.copyMenuBorder,t["--persona-dropdown-border"]=(Tt=t["--persona-dropdown-border"])!=null?Tt:Ce.copyMenuBorder),Ce.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=Ce.copyMenuShadow,t["--persona-dropdown-shadow"]=(Kn=t["--persona-dropdown-shadow"])!=null?Kn:Ce.copyMenuShadow),Ce.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=Ce.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Gn=t["--persona-dropdown-radius"])!=null?Gn:Ce.copyMenuBorderRadius),Ce.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Ce.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(On=t["--persona-dropdown-item-hover-bg"])!=null?On:Ce.copyMenuItemHoverBackground),Ce.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=Ce.iconBackground),Ce.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=Ce.toolbarBorder)}if(y!=null&&y.tab){let Ce=y.tab;Ce.background&&(t["--persona-artifact-tab-bg"]=Ce.background),Ce.activeBackground&&(t["--persona-artifact-tab-active-bg"]=Ce.activeBackground),Ce.activeBorder&&(t["--persona-artifact-tab-active-border"]=Ce.activeBorder),Ce.borderRadius&&(t["--persona-artifact-tab-radius"]=Ce.borderRadius),Ce.textColor&&(t["--persona-artifact-tab-color"]=Ce.textColor),Ce.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=Ce.hoverBackground),Ce.listBackground&&(t["--persona-artifact-tab-list-bg"]=Ce.listBackground),Ce.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=Ce.listBorderColor),Ce.listPadding&&(t["--persona-artifact-tab-list-padding"]=Ce.listPadding)}if(y!=null&&y.pane){let Ce=y.pane;if(Ce.toolbarBackground){let Nr=(eo=vs(n,Ce.toolbarBackground))!=null?eo:Ce.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Nr}}return t}var Nh={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"}}},xm=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},Ki=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Fh=n=>{var t;let e=(t=n==null?void 0:n.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":Ki()},Oh=n=>Fh(n),_h=n=>qo(n),$h=n=>{var t;let e=qo(void 0,{validate:!1});return qo({...n,palette:{...e.palette,colors:{...Nh.colors,...(t=n==null?void 0:n.palette)==null?void 0:t.colors}}},{validate:!1})},qa=n=>{let e=Oh(n),t=xm(n==null?void 0:n.theme),r=xm(n==null?void 0:n.darkTheme);return e==="dark"?$h(na(t!=null?t:{},r!=null?r:{})):_h(t)},Uh=n=>wm(n),ws=(n,e)=>{let t=qa(e),r=Uh(t);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},Cm=n=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{n(Ki())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>n(Ki());t.addEventListener?(t.addEventListener("change",r),e.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),e.push(()=>t.removeListener(r)))}return()=>{e.forEach(t=>t())}};var Am=require("idiomorph"),za=(n,e,t={})=>{let{preserveTypingAnimation:r=!0}=t;Am.Idiomorph.morph(n,e.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 Sm=n=>n.replace(/^\n+/,"").replace(/\s+$/,"");var ja={index:-1,draft:""};function Tm(n){let{direction:e,history:t,currentValue:r,atStart:o,state:s}=n,a=s.index!==-1;if(t.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<t.length-1){let i=s.index+1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...ja}}}function Em(n,e){var t,r,o,s,a,i,d,c,p,g,h,m,y,w,E,B,T,I,M,P,C,k,q,_,R,O,F,Z,ke,pe,ee,Pe,Ie,ie,he,re,oe,de;return[n.id,n.role,(r=(t=n.content)==null?void 0:t.length)!=null?r:0,(s=(o=n.content)==null?void 0:o.slice(-32))!=null?s:"",n.streaming?"1":"0",n.voiceProcessing?"1":"0",(a=n.variant)!=null?a:"",(d=(i=n.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=n.llmContent)==null?void 0:c.length)!=null?p:0,(h=(g=n.approval)==null?void 0:g.status)!=null?h:"",(y=(m=n.toolCall)==null?void 0:m.status)!=null?y:"",(E=(w=n.toolCall)==null?void 0:w.name)!=null?E:"",(I=(T=(B=n.toolCall)==null?void 0:B.chunks)==null?void 0:T.length)!=null?I:0,(k=(C=(P=(M=n.toolCall)==null?void 0:M.chunks)==null?void 0:P[n.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?k:"",typeof((q=n.toolCall)==null?void 0:q.args)=="string"?n.toolCall.args.length:(_=n.toolCall)!=null&&_.args?JSON.stringify(n.toolCall.args).length:0,(F=(O=(R=n.reasoning)==null?void 0:R.chunks)==null?void 0:O.length)!=null?F:0,(ee=(pe=(ke=(Z=n.reasoning)==null?void 0:Z.chunks)==null?void 0:ke[n.reasoning.chunks.length-1])==null?void 0:pe.length)!=null?ee:0,(he=(ie=(Ie=(Pe=n.reasoning)==null?void 0:Pe.chunks)==null?void 0:Ie[n.reasoning.chunks.length-1])==null?void 0:ie.slice(-32))!=null?he:"",(oe=(re=n.contentParts)==null?void 0:re.length)!=null?oe:0,(de=n.stopReason)!=null?de:"",e].join("\0")}function Mm(){return new Map}function km(n,e,t){let r=n.get(e);return r&&r.fingerprint===t?r.wrapper:null}function Lm(n,e,t,r){n.set(e,{fingerprint:t,wrapper:r})}function Pm(n,e){for(let t of n.keys())e.has(t)||n.delete(t)}function Va(n=!0){let e=n;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Rr(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function vo(n,e){return Rr(n)-n.scrollTop<=e}function Ka(n){let{following:e,currentScrollTop:t,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=n,p=t-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:t}:!e&&o&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:e&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:e&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function Ga(n){let{following:e,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=n;return e&&t<0?"pause":!e&&o&&t>0&&r?"resume":"none"}function Im(n,e){return!n||n.isCollapsed?!1:e.contains(n.anchorNode)||e.contains(n.focusNode)}function Rm(n){let e=Math.max(0,n.anchorOffsetTop-n.topOffset),t=Math.max(0,e+n.viewportHeight-n.contentHeight);return{targetScrollTop:e,spacerHeight:t}}function Wm(n){let e=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-e)}var nn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},vn=1e5,wo=vn+1;var ra={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},qh=["pre","code","a","script","style"],Qa=n=>{var e,t,r,o,s;return{type:(e=n==null?void 0:n.type)!=null?e:ra.type,placeholder:(t=n==null?void 0:n.placeholder)!=null?t:ra.placeholder,speed:(r=n==null?void 0:n.speed)!=null?r:ra.speed,duration:(o=n==null?void 0:n.duration)!=null?o:ra.duration,buffer:(s=n==null?void 0:n.buffer)!=null?s:ra.buffer}},zh=[{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"}],Bm=new Map;for(let n of zh)Bm.set(n.name,n);var xs=(n,e)=>{var t,r;return n==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,n)?(t=e[n])!=null?t:null:(r=Bm.get(n))!=null?r:null},Xa=(n,e,t,r,o)=>{if(!o)return n;if(t!=null&&t.bufferContent)return t.bufferContent(n,r);if(!n)return n;if(e==="word"){let s=n.search(/\s(?=\S*$)/);return s<0?"":n.slice(0,s)}if(e==="line"){let s=n.lastIndexOf(`
|
|
19
|
+
`);return s<0?"":n.slice(0,s)}return n},jh=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${t}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=e,o},Vh=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${t}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=e,o},Gi=/\s/,Kh=(n,e)=>{let t=n.parentNode;for(;t;){if(t.nodeType===1){let r=t;if(e.has(r.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},Gh=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(Gi.test(s[i])){let c=i;for(;c<s.length&&Gi.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&&!Gi.test(s[p]);)c.appendChild(jh(r,s[p],e,t.value)),t.value+=1,p+=1;a.appendChild(c),i=p}o.replaceChild(a,n)},Qh=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.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(Vh(r,c,e,t.value)),t.value+=1));o.replaceChild(a,n)},oa=(n,e,t,r)=>{var g,h;if(!n||typeof document=="undefined")return n;let o=document.createElement("div");o.innerHTML=n;let s=new Set(((g=r==null?void 0:r.skipTags)!=null?g:qh).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Kh(d,s)||i.push(d),d=a.nextNode();let c={value:(h=r==null?void 0:r.startIndex)!=null?h:0},p=e==="char"?Gh:Qh;for(let m of i)p(m,t,c);return o.innerHTML},Ja=(n=document)=>{let e=n.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},sa=(n=document)=>{let e=n.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let t=n.createElement("div");return t.className="persona-stream-skeleton-line",e.appendChild(t),e},Hm=new WeakMap,Xh=(n,e)=>{var s;if(!n.styles)return;let t=Hm.get(e);if(t||(t=new Set,Hm.set(e,t)),t.has(n.name)){let a=n.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(n.name)}t.add(n.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(s=e.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",n.name),o.textContent=n.styles,e.appendChild(o)},Qi=new WeakMap,Jh=(n,e)=>{if(!n.onAttach)return;let t=Qi.get(e);if(t||(t=new Map,Qi.set(e,t)),t.has(n.name))return;let r=n.onAttach(e);t.set(n.name,r)},Dm=n=>{let e=Qi.get(n);if(e){for(let t of e.values())typeof t=="function"&&t();e.clear()}},Ya=(n,e)=>{Xh(n,e),Jh(n,e)};function Xi(n,e=vn){let t=n.style.position,r=n.style.zIndex,o=n.style.isolation,s=getComputedStyle(n),a=s.position==="static"||s.position==="";return a&&(n.style.position="relative"),n.style.zIndex=String(e),n.style.isolation="isolate",()=>{a&&(n.style.position=t),n.style.zIndex=r,n.style.isolation=o}}var aa=0,xo=null;function Ji(n=document){var t;if(aa++,aa===1){let r=n.body,s=((t=n.defaultView)!=null?t:window).scrollY||n.documentElement.scrollTop;xo={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 e=!1;return()=>{var r;if(!e&&(e=!0,aa=Math.max(0,aa-1),aa===0&&xo)){let o=n.body,s=(r=n.defaultView)!=null?r:window;o.style.overflow=xo.originalOverflow,o.style.position=xo.originalPosition,o.style.top=xo.originalTop,o.style.width=xo.originalWidth,s.scrollTo(0,xo.scrollY),xo=null}}}var ia={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},gn=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="docked"},la=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="composer-bar"},gr=n=>{var t,r,o,s,a,i;let e=(t=n==null?void 0:n.launcher)==null?void 0:t.dock;return{side:(r=e==null?void 0:e.side)!=null?r:ia.side,width:(o=e==null?void 0:e.width)!=null?o:ia.width,animate:(s=e==null?void 0:e.animate)!=null?s:ia.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:ia.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:ia.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 Yh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Za=(n,e={})=>{var E,B,T,I,M,P;let{showClose:t=!0,wrapperClassName:r=Yh,buttonSize:o,iconSize:s="28px"}=e,a=(E=n==null?void 0:n.launcher)!=null?E:{},i=(B=o!=null?o:a.closeButtonSize)!=null?B:"32px",d=v("div",r),c=(T=a.closeButtonTooltipText)!=null?T:"Close chat",p=(I=a.closeButtonShowTooltip)!=null?I:!0,g=(M=a.closeButtonIconName)!=null?M:"x",h=(P=a.closeButtonIconText)!=null?P:"\xD7",m=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),y=Mt("button",{className:zs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:t?void 0:"none",color:a.closeButtonColor||kn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:m?`${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}}),w=ye(g,s,"currentColor",1);if(w?(w.style.display="block",y.appendChild(w)):y.textContent=h,d.appendChild(y),p&&c){let C=null,k=()=>{if(C)return;let _=y.ownerDocument,R=_.body;if(!R)return;C=Ir(_,"div","persona-clear-chat-tooltip"),C.textContent=c;let O=Ir(_,"div");O.className="persona-clear-chat-tooltip-arrow",C.appendChild(O);let F=y.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(wo),C.style.left=`${F.left+F.width/2}px`,C.style.top=`${F.top-8}px`,C.style.transform="translate(-50%, -100%)",R.appendChild(C)},q=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",k),d.addEventListener("mouseleave",q),y.addEventListener("focus",k),y.addEventListener("blur",q),d._cleanupTooltip=()=>{q(),d.removeEventListener("mouseenter",k),d.removeEventListener("mouseleave",q),y.removeEventListener("focus",k),y.removeEventListener("blur",q)}}return{button:y,wrapper:d}},Zh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ei=(n,e={})=>{var C,k,q,_,R,O,F,Z,ke,pe,ee,Pe,Ie;let{wrapperClassName:t=Zh,buttonSize:r,iconSize:o="20px"}=e,a=(k=((C=n==null?void 0:n.launcher)!=null?C:{}).clearChat)!=null?k:{},i=(q=r!=null?r:a.size)!=null?q:"32px",d=(_=a.iconName)!=null?_:"refresh-cw",c=(R=a.iconColor)!=null?R:"",p=(O=a.backgroundColor)!=null?O:"",g=(F=a.borderWidth)!=null?F:"",h=(Z=a.borderColor)!=null?Z:"",m=(ke=a.borderRadius)!=null?ke:"",y=(pe=a.paddingX)!=null?pe:"",w=(ee=a.paddingY)!=null?ee:"",E=(Pe=a.tooltipText)!=null?Pe:"Clear chat",B=(Ie=a.showTooltip)!=null?Ie:!0,T=v("div",t),I=!!(g||h),M=Mt("button",{className:zs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!I&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:i,width:i,color:c||kn.actionIconColor,backgroundColor:p||void 0,border:I?`${g||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:y||void 0,paddingRight:y||void 0,paddingTop:w||void 0,paddingBottom:w||void 0}}),P=ye(d,o,"currentColor",1);if(P&&(P.style.display="block",M.appendChild(P)),T.appendChild(M),B&&E){let ie=null,he=()=>{if(ie)return;let oe=M.ownerDocument,de=oe.body;if(!de)return;ie=Ir(oe,"div","persona-clear-chat-tooltip"),ie.textContent=E;let Ae=Ir(oe,"div");Ae.className="persona-clear-chat-tooltip-arrow",ie.appendChild(Ae);let $e=M.getBoundingClientRect();ie.style.position="fixed",ie.style.zIndex=String(wo),ie.style.left=`${$e.left+$e.width/2}px`,ie.style.top=`${$e.top-8}px`,ie.style.transform="translate(-50%, -100%)",de.appendChild(ie)},re=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};T.addEventListener("mouseenter",he),T.addEventListener("mouseleave",re),M.addEventListener("focus",he),M.addEventListener("blur",re),T._cleanupTooltip=()=>{re(),T.removeEventListener("mouseenter",he),T.removeEventListener("mouseleave",re),M.removeEventListener("focus",he),M.removeEventListener("blur",re)}}return{button:M,wrapper:T}};var kn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},zo=n=>{var P,C,k,q,_,R,O,F,Z,ke,pe,ee,Pe,Ie,ie,he;let{config:e,showClose:t=!0}=n,r=Mt("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=e==null?void 0:e.launcher)!=null?P:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(k=o.closeButtonPlacement)!=null?k:"inline",i=(q=o.headerIconHidden)!=null?q:!1,d=o.headerIconName,c=Mt("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,oe=ye(d,re*.6,"currentColor",1);oe?c.replaceChildren(oe):c.textContent=(R=(_=e==null?void 0:e.launcher)==null?void 0:_.agentIconText)!=null?R:"\u{1F4AC}"}else if((O=e==null?void 0:e.launcher)!=null&&O.iconUrl){let re=v("img");re.src=e.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=e==null?void 0:e.launcher)==null?void 0:F.agentIconText)!=null?Z:"\u{1F4AC}";let p=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=Mt("span",{className:"persona-text-base persona-font-semibold",text:(pe=(ke=e==null?void 0:e.launcher)==null?void 0:ke.title)!=null?pe:"Chat Assistant",style:{color:kn.titleColor}}),h=Mt("span",{className:"persona-text-xs",text:(Pe=(ee=e==null?void 0:e.launcher)==null?void 0:ee.subtitle)!=null?Pe:"Here to help you get answers fast",style:{color:kn.subtitleColor}});p.append(g,h),i?r.append(p):r.append(c,p);let m=(Ie=o.clearChat)!=null?Ie:{},y=(ie=m.enabled)!=null?ie:!0,w=(he=m.placement)!=null?he:"inline",E=null,B=null;if(y){let oe=ei(e,{wrapperClassName:w==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=oe.button,B=oe.wrapper,w==="top-right"&&(B.style.right="48px"),w==="inline"&&r.appendChild(B)}let T=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&w==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:I,wrapper:M}=Za(e,{showClose:t,wrapperClassName:T});return a!=="top-right"&&r.appendChild(M),{header:r,iconHolder:c,headerTitle:g,headerSubtitle:h,closeButton:I,closeButtonWrapper:M,clearChatButton:E,clearChatButtonWrapper:B}},ca=(n,e,t)=>{var a,i,d,c;let r=(a=t==null?void 0:t.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(e.header),o==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};function Cs(n){let{items:e,onSelect:t,anchor:r,position:o="bottom-left",portal:s}=n,a=v("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(wo)):(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 m of e){if(m.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let y=document.createElement("button");if(y.type="button",y.setAttribute("role","menuitem"),y.setAttribute("data-dropdown-item-id",m.id),m.destructive&&y.setAttribute("data-destructive",""),m.icon){let E=ye(m.icon,16,"currentColor",1.5);E&&y.appendChild(E)}let w=document.createElement("span");w.textContent=m.label,y.appendChild(w),y.addEventListener("click",E=>{E.stopPropagation(),p(),t(m.id)}),a.appendChild(y)}let i=null;function d(){if(!s)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=y=>{!a.contains(y.target)&&!r.contains(y.target)&&p()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function g(){a.classList.contains("persona-hidden")?c():p()}function h(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:p,toggle:g,destroy:h}}function wn(n){let{icon:e,label:t,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=n,d=v("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=ye(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,g]of Object.entries(i))d.setAttribute(p,g);return d}function Yi(n){let{icon:e,label:t,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=n,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let p=v("button",c);if(p.type="button",p.setAttribute("aria-label",t),e){let h=ye(e,s!=null?s:14,"currentColor",2);h&&p.appendChild(h)}let g=v("span");if(g.textContent=t,p.appendChild(g),i&&p.addEventListener("click",i),d)for(let[h,m]of Object.entries(d))p.setAttribute(h,m);return p}function Nm(n){var m,y;let{label:e,icon:t="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=n,c=v("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",e);let p=v("span","persona-combo-btn-label");p.textContent=e,c.appendChild(p);let g=ye(t,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",c.appendChild(g)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"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 w,E;c.style.backgroundColor=(w=d.background)!=null?w:"",c.style.borderColor=(E=d.border)!=null?E:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let h=Cs({items:r,onSelect:w=>{c.setAttribute("aria-expanded","false"),o(w)},anchor:c,position:s,portal:a});return a||c.appendChild(h.element),c.addEventListener("click",w=>{w.stopPropagation();let E=!h.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",E?"false":"true"),h.toggle()}),c.addEventListener("keydown",w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),c.click())}),{element:c,setLabel:w=>{p.textContent=w,c.setAttribute("aria-label",w)},open:()=>{c.setAttribute("aria-expanded","true"),h.show()},close:()=>{c.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let w=!h.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",w?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),c.remove()}}}var ey=n=>{var r;let e=zo({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),t=(r=n.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>t()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),t())}))}return e};function ty(n,e,t){var r,o,s;if(e!=null&&e.length)for(let a of e){let i=v("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=v("div","persona-relative");d.appendChild(i);let c=Cs({items:a.menuItems,onSelect:p=>t==null?void 0:t(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),n.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),n.appendChild(i)}}var ny=n=>{var T,I,M,P,C,k,q,_,R;let{config:e,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=n,a=(T=e==null?void 0:e.launcher)!=null?T:{},i=v("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=Nm({label:(I=a.title)!=null?I:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=kn.titleColor,p=(M=c.querySelector(".persona-combo-btn-label"))!=null?M:c;else{if(c=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=v("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=kn.titleColor,p.textContent=(P=a.title)!=null?P:"Chat Assistant",c.appendChild(p),ty(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 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=(k=O.borderRadius)!=null?k:"10px",c.style.padding=(q=O.padding)!=null?q:"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 g=(_=a.closeButtonSize)!=null?_:"32px",h=v("div",""),m=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=g,m.style.width=g,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||kn.actionIconColor;let y=(R=a.closeButtonIconName)!=null?R:"x",w=ye(y,"28px","currentColor",1);w?m.appendChild(w):m.textContent="\xD7",r&&m.addEventListener("click",r),h.appendChild(m),i.appendChild(h);let E=v("div");E.style.display="none";let B=v("span");return B.style.display="none",{header:i,iconHolder:E,headerTitle:p,headerSubtitle:B,closeButton:m,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}},Fm={default:ey,minimal:ny},ry=n=>{var e;return(e=Fm[n])!=null?e:Fm.default},ti=(n,e,t)=>{var a,i,d;if(e!=null&&e.render){let c=e.render({config:n,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),p=v("div");p.style.display="none";let g=v("span"),h=v("span"),m=v("button");m.style.display="none";let y=v("div");return y.style.display="none",{header:c,iconHolder:p,headerTitle:g,headerSubtitle:h,closeButton:m,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=ry(r)({config:n,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var ni=n=>{var a,i;let e=v("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(a=n==null?void 0:n.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;e.style.maxHeight=`${t*r}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},ri=n=>{var P,C,k,q,_,R,O,F,Z,ke,pe,ee;let e=(P=n==null?void 0:n.sendButton)!=null?P:{},t=(C=e.useIcon)!=null?C:!1,r=(k=e.iconText)!=null?k:"\u2191",o=e.iconName,s=(q=e.stopIconName)!=null?q:"square",a=(_=e.tooltipText)!=null?_:"Send message",i=(R=e.stopTooltipText)!=null?R:"Stop generating",d=(F=(O=n==null?void 0:n.copy)==null?void 0:O.sendButtonLabel)!=null?F:"Send",c=(ke=(Z=n==null?void 0:n.copy)==null?void 0:Z.stopButtonLabel)!=null?ke:"Stop",p=(pe=e.showTooltip)!=null?pe:!1,g=(ee=e.size)!=null?ee:"40px",h=e.backgroundColor,m=e.textColor,y=v("div","persona-send-button-wrapper"),w=Mt("button",{className:zs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",t?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",t&&!h&&"persona-bg-persona-primary",!t&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:t?g:void 0,height:t?g:void 0,minWidth:t?g:void 0,minHeight:t?g:void 0,fontSize:t?"18px":void 0,lineHeight:t?"1":void 0,color:t?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:t&&h||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),E=null,B=null;if(t){let Pe=parseFloat(g)||24,Ie=(m==null?void 0:m.trim())||"currentColor";o?(E=ye(o,Pe,Ie,2),E?w.appendChild(E):w.textContent=r):w.textContent=r,B=ye(s,Pe,Ie,2)}else w.textContent=d;let T=null;p&&a&&(T=v("div","persona-send-button-tooltip"),T.textContent=a,y.appendChild(T)),w.setAttribute("aria-label",a),y.appendChild(w);let I="send";return{button:w,wrapper:y,setMode:Pe=>{if(Pe===I)return;I=Pe;let Ie=Pe==="stop"?i:a;if(w.setAttribute("aria-label",Ie),T&&(T.textContent=Ie),t){if(E&&B){let ie=Pe==="stop"?B:E;w.replaceChildren(ie)}}else w.textContent=Pe==="stop"?c:d}}},oi=n=>{var T,I,M,P,C,k,q,_,R,O,F,Z;let e=(T=n==null?void 0:n.voiceRecognition)!=null?T:{};if(!(e.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((I=e.provider)==null?void 0:I.type)==="runtype";if(!(r||o))return null;let a=(P=(M=n==null?void 0:n.sendButton)==null?void 0:M.size)!=null?P:"40px",i=(C=e.iconName)!=null?C:"mic",d=(k=e.iconSize)!=null?k:a,c=parseFloat(d)||24,p=(_=e.backgroundColor)!=null?_:(q=n==null?void 0:n.sendButton)==null?void 0:q.backgroundColor,g=(O=e.iconColor)!=null?O:(R=n==null?void 0:n.sendButton)==null?void 0:R.textColor,h=v("div","persona-send-button-wrapper"),m=Mt("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:g||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),w=ye(i,c,g||"currentColor",1.5);w?m.appendChild(w):m.textContent="\u{1F3A4}",h.appendChild(m);let E=(F=e.tooltipText)!=null?F:"Start voice recognition";if(((Z=e.showTooltip)!=null?Z:!1)&&E){let ke=v("div","persona-send-button-tooltip");ke.textContent=E,h.appendChild(ke)}return{button:m,wrapper:h}},si=n=>{var y,w,E,B,T,I,M,P;let e=(y=n==null?void 0:n.attachments)!=null?y:{};if(e.enabled!==!0)return null;let t=(E=(w=n==null?void 0:n.sendButton)==null?void 0:w.size)!=null?E:"40px",r=v("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=v("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((B=e.allowedTypes)!=null?B:jr).join(","),o.multiple=((T=e.maxFiles)!=null?T:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(I=e.buttonIconName)!=null?I:"paperclip",a=t,i=parseFloat(a)||40,d=Math.round(i*.6),c=v("div","persona-send-button-wrapper"),p=Mt("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":(M=e.buttonTooltipText)!=null?M:"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 g=ye(s,d,"currentColor",1.5);g?p.appendChild(g):p.textContent="\u{1F4CE}",p.addEventListener("click",C=>{C.preventDefault(),o.click()}),c.appendChild(p);let h=(P=e.buttonTooltipText)!=null?P:"Attach file",m=v("div","persona-send-button-tooltip");return m.textContent=h,c.appendChild(m),{button:p,wrapper:c,input:o,previewsContainer:r}},ai=n=>{var a,i,d;let e=(a=n==null?void 0:n.statusIndicator)!=null?a:{},t=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",r=v("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=e.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let c=v("a");c.href=e.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},ii=()=>Mt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var li=n=>{var y,w,E,B,T,I;let{config:e}=n,t=Mt("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=ii(),o=Mt("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}=ni(e);a();let i=ri(e),d=oi(e),c=si(e),p=ai(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let g=Mt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=v("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=v("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&h.append(c.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),g.append(h,m),o.append(g),o.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(c==null?void 0:c.button)&&M.target!==(c==null?void 0:c.wrapper)&&s.focus()}),t.append(r,o,p),{footer:t,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(w=d==null?void 0:d.wrapper)!=null?w:null,statusText:p,attachmentButton:(E=c==null?void 0:c.button)!=null?E:null,attachmentButtonWrapper:(B=c==null?void 0:c.wrapper)!=null?B:null,attachmentInput:(T=c==null?void 0:c.input)!=null?T:null,attachmentPreviewsContainer:(I=c==null?void 0:c.previewsContainer)!=null?I:null,actionsRow:g,leftActions:h,rightActions:m,setSendButtonMode:i.setMode}};var Om=()=>{let n=Mt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=v("span","persona-pill-peek__icon"),t=ye("message-square",16,"currentColor",1.5);t&&e.appendChild(t);let r=v("span","persona-pill-peek__text"),o=v("span","persona-pill-peek__caret"),s=ye("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),n.append(e,r,o),{root:n,textNode:r}},_m=n=>{var y,w,E,B,T,I;let{config:e}=n,t=Mt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=ii();r.style.display="none";let o=ai(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=ni(e);s.style.maxHeight="100px",a();let i=ri(e),d=oi(e),c=si(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let p=Mt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=v("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&g.append(c.wrapper);let h=v("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&h.append(d.wrapper),h.append(i.wrapper),p.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(c==null?void 0:c.button)&&M.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&p.append(c.input),p.append(g,s,h),c&&t.append(c.previewsContainer),t.append(p,r,o);let m=p;return{footer:t,suggestions:r,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(w=d==null?void 0:d.wrapper)!=null?w:null,statusText:o,attachmentButton:(E=c==null?void 0:c.button)!=null?E:null,attachmentButtonWrapper:(B=c==null?void 0:c.wrapper)!=null?B:null,attachmentInput:(T=c==null?void 0:c.input)!=null?T:null,attachmentPreviewsContainer:(I=c==null?void 0:c.previewsContainer)!=null?I:null,actionsRow:m,leftActions:g,rightActions:h,setSendButtonMode:i.setMode}};var $m=n=>{var p,g,h,m,y,w,E,B,T,I,M,P,C,k,q,_,R;let e=(g=(p=n==null?void 0:n.launcher)==null?void 0:p.enabled)!=null?g:!0,t=gn(n);if(la(n)){let O=(m=(h=n==null?void 0:n.launcher)==null?void 0:h.composerBar)!=null?m:{},F=v("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((E=(w=n==null?void 0:n.launcher)==null?void 0:w.zIndex)!=null?E:vn);let Z=v("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 ke=v("div","persona-widget-pill-root");return ke.setAttribute("data-persona-composer-bar",""),ke.dataset.state="collapsed",ke.dataset.expandedSize=(B=O.expandedSize)!=null?B:"anchored",ke.style.zIndex=String((I=(T=n==null?void 0:n.launcher)==null?void 0:T.zIndex)!=null?I:vn),{wrapper:F,panel:Z,pillRoot:ke}}if(t){let O=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),F=v("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(!e){let O=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),F=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(P=(M=n==null?void 0:n.launcher)==null?void 0:M.width)!=null?P:"100%";return O.style.width=Z,F.style.width="100%",O.appendChild(F),{wrapper:O,panel:F}}let o=(C=n==null?void 0:n.launcher)!=null?C:{},s=o.position&&fr[o.position]?fr[o.position]:fr["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((q=(k=n==null?void 0:n.launcher)==null?void 0:k.zIndex)!=null?q:vn);let i=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=(_=n==null?void 0:n.launcher)==null?void 0:_.width)!=null?R:n==null?void 0:n.launcherWidth,c=d!=null?d:Vr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},oy=(n,e)=>{var M,P,C,k,q,_,R,O,F;let t=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=Za(n,{showClose:e,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=(P=(M=n==null?void 0:n.launcher)==null?void 0:M.clearChat)==null?void 0:P.enabled)!=null?C:!0,a=null,i=null;if(s){let Z=ei(n,{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=Mt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Mt("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=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(q=(k=n==null?void 0:n.copy)==null?void 0:k.welcomeTitle)!=null?q:"Hello \u{1F44B}"}),g=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=(_=n==null?void 0:n.copy)==null?void 0:_.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),h=Mt("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,g),m=v("div","persona-flex persona-flex-col persona-gap-3"),y=(O=n==null?void 0:n.layout)==null?void 0:O.contentMaxWidth;y&&(m.style.maxWidth=y,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((F=n==null?void 0:n.copy)==null?void 0:F.showWelcomeCard)!==!1||(h.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(h,m);let E=Mt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),B=_m({config:n}),{root:T,textNode:I}=Om();return t.append(d,o,c,E),i&&t.appendChild(i),{container:t,body:c,messagesWrapper:m,composerOverlay:E,suggestions:B.suggestions,textarea:B.textarea,sendButton:B.sendButton,sendButtonWrapper:B.sendButtonWrapper,micButton:B.micButton,micButtonWrapper:B.micButtonWrapper,composerForm:B.composerForm,statusText:B.statusText,introTitle:p,introSubtitle:g,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:d,footer:B.footer,attachmentButton:B.attachmentButton,attachmentButtonWrapper:B.attachmentButtonWrapper,attachmentInput:B.attachmentInput,attachmentPreviewsContainer:B.attachmentPreviewsContainer,actionsRow:B.actionsRow,leftActions:B.leftActions,rightActions:B.rightActions,setSendButtonMode:B.setSendButtonMode,peekBanner:T,peekTextNode:I}},Um=(n,e=!0)=>{var E,B,T,I,M,P,C,k,q;if(la(n))return oy(n,e);let t=Mt("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=(E=n==null?void 0:n.layout)==null?void 0:E.header,o=((B=n==null?void 0:n.layout)==null?void 0:B.showHeader)!==!1,s=r?ti(n,r,{showClose:e}):zo({config:n,showClose:e}),a=Mt("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=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(I=(T=n==null?void 0:n.copy)==null?void 0:T.welcomeTitle)!=null?I:"Hello \u{1F44B}"}),d=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(P=(M=n==null?void 0:n.copy)==null?void 0:M.welcomeSubtitle)!=null?P:"Ask anything about your account or products."}),c=Mt("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:gn(n)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),p=v("div","persona-flex persona-flex-col persona-gap-3"),g=(C=n==null?void 0:n.layout)==null?void 0:C.contentMaxWidth;g&&(p.style.maxWidth=g,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((k=n==null?void 0:n.copy)==null?void 0:k.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,p);let m=li({config:n}),y=((q=n==null?void 0:n.layout)==null?void 0:q.showFooter)!==!1;o?ca(t,s,n):(s.header.style.display="none",ca(t,s,n)),t.append(a);let w=Mt("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||(m.footer.style.display="none"),t.append(m.footer),t.append(w),{container:t,body:a,messagesWrapper:p,composerOverlay:w,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.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:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var Zi=(n,e)=>{let t=v("button");t.type="button",t.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 js=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
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",e);let r=s=>{var L,M,I,A,P,O,_,H,U,F,Z,Te,pe;let a=(L=s.launcher)!=null?L:{},i=fn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ee=(M=a.title)!=null?M:"Chat Assistant";d.textContent=ee,d.setAttribute("title",ee)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let ee=(I=a.subtitle)!=null?I:"Here to help you get answers fast";c.textContent=ee,c.setAttribute("title",ee)}let u=n.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let m=n.querySelector("[data-role='launcher-icon']");if(m)if(a.agentIconHidden)m.style.display="none";else{let ee=(A=a.agentIconSize)!=null?A:"40px";if(m.style.height=ee,m.style.width=ee,a.agentIconBackgroundColor?(m.style.backgroundColor=a.agentIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),m.innerHTML="",a.agentIconName){let xe=parseFloat(ee)||24,Re=be(a.agentIconName,xe*.6,"var(--persona-text-inverse, #ffffff)",2);Re?(m.appendChild(Re),m.style.display=""):(m.textContent=(P=a.agentIconText)!=null?P:"\u{1F4AC}",m.style.display="")}else a.iconUrl?m.style.display="none":(m.textContent=(O=a.agentIconText)!=null?O:"\u{1F4AC}",m.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let ee=(_=a.agentIconSize)!=null?_:"40px";g.style.height=ee,g.style.width=ee,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let ee=(H=a.callToActionIconSize)!=null?H:"32px";f.style.height=ee,f.style.width=ee,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let xe=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,xe=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let Re=parseFloat(ee)||24,le=Math.max(Re-xe,8),me=be(a.callToActionIconName,le,"currentColor",2);me?f.appendChild(me):f.textContent=(U=a.callToActionIconText)!=null?U:"\u2197"}else f.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}let w=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",k="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?k:`${v} ${w}`,i||(n.style.zIndex=String((Z=a.zIndex)!=null?Z:xn));let R="1px solid var(--persona-border, #e5e7eb)",E="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(Te=a.border)!=null?Te:R,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:E,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=(pe=a.collapsedMaxWidth)!=null?pe:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",e),n.remove()};return t&&r(t),{element:n,update:r,destroy:o}};var ym=({config:t,showClose:e})=>{let{wrapper:n,panel:r,pillRoot:o}=fm(t),s=hm(t,e),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:g=>(d.element.replaceWith(g.header),d.element=g.header,d.iconHolder=g.iconHolder,d.headerTitle=g.headerTitle,d.headerSubtitle=g.headerSubtitle,d.closeButton=g.closeButton,d.closeButtonWrapper=g.closeButtonWrapper,d.clearChatButton=g.clearChatButton,d.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{c.footer.replaceWith(g),c.footer=g}}},Vi=({config:t,plugins:e,onToggle:n})=>{let r=e.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:t,defaultRenderer:()=>ji(t,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=ji(t,n);return{instance:o,element:o.element}};var Mh=t=>{switch(t){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},kh=(t,e)=>{if(!t)return null;let n=Mh(t);if(n===null)return null;let r=e==null?void 0:e[t],o=r!==void 0?r:n;return o||null},Lh=(t,e)=>{let n=b("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",t),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=e,n},Ph=t=>{let e=t.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:image/")||!t.includes(":"))},Ki=t=>{let e=t.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(t)||e.startsWith("data:")||!t.includes(":"))},Gi=320,vm=320,Ih=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),Wh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),Rh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),Hh=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),Bh=(t,e,n)=>{if(t.length===0)return null;try{let r=b("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),e&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};return t.forEach((i,d)=>{var m;let c=b("img");c.alt=((m=i.alt)==null?void 0:m.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=`${Gi}px`,c.style.maxHeight=`${vm}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 u=!1;o+=1,c.addEventListener("error",()=>{u||(u=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{u=!0}),Ph(i.image)?(c.src=i.image,r.appendChild(c)):(u=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},Dh=t=>{if(t.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let n=0;return t.forEach(r=>{if(!Ki(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=`${Gi}px`,e.appendChild(o),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Nh=t=>{if(t.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let n=0;return t.forEach(r=>{if(!Ki(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=`${Gi}px`,o.style.maxHeight=`${vm}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),n+=1}),n===0?(e.remove(),null):e}catch{return null}},Fh=t=>{if(t.length===0)return null;try{let e=b("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let n=0;return t.forEach(r=>{if(!Ki(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",e.appendChild(o),n+=1}),n===0?(e.remove(),null):e}catch{return null}},na=()=>{let t=document.createElement("div");t.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let 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",t.appendChild(e),t.appendChild(n),t.appendChild(r),t.appendChild(o),t},Oh=(t,e,n)=>{let r={config:n!=null?n:{},streaming:!0,location:t,defaultRenderer:na};if(e){let o=e(r);if(o!==null)return o}return na()},_h=(t,e)=>{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=e==="user"?t.userAvatar:t.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=b("img");o.src=r,o.alt=e==="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(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=e==="user"?"U":"A",n.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},bm=(t,e,n="div")=>{let r=b(n,"persona-text-xs persona-text-persona-muted"),o=new Date(t.createdAt);return e.format?r.textContent=e.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},$h=(t,e="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),t==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},Uh=(t,e,n)=>{var w,v,k,R,E,L,M;let r=(w=e.showCopy)!=null?w:!0,o=(v=e.showUpvote)!=null?v:!0,s=(k=e.showDownvote)!=null?k:!0,a=(R=e.showReadAloud)!=null?R:!1;if(!r&&!o&&!s&&!a){let I=b("div");return I.style.display="none",I.id=`actions-${t.id}`,I.setAttribute("data-actions-for",t.id),I}let i=(E=e.visibility)!=null?E:"hover",d=(L=e.align)!=null?L:"right",c=(M=e.layout)!=null?M:"pill-inside",u={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],m={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],g=b("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${u} ${m} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${t.id}`,g.setAttribute("data-actions-for",t.id);let f=(I,A,P)=>{let O=Cn({icon:I,label:A,size:14,className:"persona-message-action-btn"});return O.setAttribute("data-action",P),O};return r&&g.appendChild(f("copy","Copy message","copy")),a&&g.appendChild(f("volume-2","Read aloud","read-aloud")),o&&g.appendChild(f("thumbs-up","Upvote","upvote")),s&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},Qi=(t,e,n,r,o,s)=>{var oe,se,de,Ee,He,K,J,Le,G,ue,De,Xe,et,vt,wt,Je,fe;let a=n!=null?n:{},i=(oe=a.layout)!=null?oe:"bubble",d=a.avatar,c=a.timestamp,u=(se=d==null?void 0:d.show)!=null?se:!1,m=(de=c==null?void 0:c.show)!=null?de:!1,g=(Ee=d==null?void 0:d.position)!=null?Ee:"left",f=(He=c==null?void 0:c.position)!=null?He:"below",w=$h(t.role,i),v=b("div",w.join(" "));v.id=`bubble-${t.id}`,v.setAttribute("data-message-id",t.id),v.setAttribute("data-persona-theme-zone",t.role==="user"?"user-message":"assistant-message"),t.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):t.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 k=Ih(t),R=(J=(K=t.content)==null?void 0:K.trim())!=null?J:"",L=k.length>0&&R===Pa,M=za((G=(Le=s==null?void 0:s.widgetConfig)==null?void 0:Le.features)==null?void 0:G.streamAnimation),I=(Xe=(De=(ue=s==null?void 0:s.widgetConfig)==null?void 0:ue.features)==null?void 0:De.streamAnimation)==null?void 0:Xe.plugins,A=t.role==="assistant"&&M.type!=="none"?Qs(M.type,I):null,P=t.role==="assistant"&&((et=A==null?void 0:A.isAnimating)==null?void 0:et.call(A,t))===!0,O=t.role==="assistant"&&A!==null&&(!!t.streaming||P);O&&(A!=null&&A.bubbleClass)&&v.classList.add(A.bubbleClass);let _=document.createElement("div");_.classList.add("persona-message-content"),t.streaming&&_.classList.add("persona-content-streaming"),O&&A&&(A.containerClass&&_.classList.add(A.containerClass),_.style.setProperty("--persona-stream-step",`${M.speed}ms`),_.style.setProperty("--persona-stream-duration",`${M.duration}ms`));let H=O?qa((vt=t.content)!=null?vt:"",M.buffer,A,t,!!t.streaming):(wt=t.content)!=null?wt:"",U=e({text:H,message:t,streaming:!!t.streaming,raw:t.rawContent}),F=U;O&&(A==null?void 0:A.wrap)==="char"?F=Xs(U,"char",t.id,{skipTags:A.skipTags}):O&&(A==null?void 0:A.wrap)==="word"&&(F=Xs(U,"word",t.id,{skipTags:A.skipTags}));let Z=null;if(L?(Z=document.createElement("div"),Z.innerHTML=F,Z.style.display="none",_.appendChild(Z)):_.innerHTML=F,O&&(A!=null&&A.useCaret)&&!L&&R){let Q=ja(),dt=_.querySelectorAll(".persona-stream-char, .persona-stream-word"),qe=dt[dt.length-1];if(qe!=null&&qe.parentNode)qe.parentNode.insertBefore(Q,qe.nextSibling);else{let Ce=_.lastElementChild;Ce?Ce.appendChild(Q):_.appendChild(Q)}}if(m&&f==="inline"&&t.createdAt){let Q=bm(t,c,"span");Q.classList.add("persona-timestamp-inline");let dt=_.lastElementChild;dt?dt.appendChild(Q):_.appendChild(Q)}if(k.length>0){let Q=Bh(k,!L&&!!R,()=>{L&&Z&&(Z.style.display="")});Q?v.appendChild(Q):L&&Z&&(Z.style.display="")}let Te=Wh(t);if(Te.length>0){let Q=Dh(Te);Q&&v.appendChild(Q)}let pe=Rh(t);if(pe.length>0){let Q=Nh(pe);Q&&v.appendChild(Q)}let ee=Hh(t);if(ee.length>0){let Q=Fh(ee);Q&&v.appendChild(Q)}if(v.appendChild(_),m&&f==="below"&&t.createdAt){let Q=bm(t,c);Q.classList.add("persona-mt-1"),v.appendChild(Q)}let xe=t.role==="assistant"?kh(t.stopReason,(fe=(Je=s==null?void 0:s.widgetConfig)==null?void 0:Je.copy)==null?void 0:fe.stopReasonNotice):null;if(t.streaming&&t.role==="assistant"){let Q=!!(H&&H.trim()),dt=M.placeholder==="skeleton",qe=dt&&M.buffer==="line"&&Q;if(Q)qe&&v.appendChild(Js());else if(dt)v.appendChild(Js());else{let Ce=Oh("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Ce&&v.appendChild(Ce)}}if(xe&&t.stopReason&&!t.streaming&&(R||(_.style.display="none"),v.appendChild(Lh(t.stopReason,xe))),t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let Q=Uh(t,r,o);v.appendChild(Q)}if(!u||t.role==="system")return v;let le=b("div",`persona-flex persona-gap-2 ${t.role==="user"?"persona-flex-row-reverse":""}`),me=_h(d,t.role);return g==="right"||g==="left"&&t.role==="user"?le.append(v,me):le.append(me,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),le};var gs=new Set,zh=(t,e)=>e==null?!1:typeof e=="string"?(t.textContent=e,!0):(t.appendChild(e),!0),qh=(t,e)=>{var r,o;let n=(o=(r=t.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
|
|
28
|
-
`):""},
|
|
29
|
-
`);let o=
|
|
30
|
-
`):""},Ji=(t,e)=>{var n,r,o;t.style.backgroundColor=(n=e.codeBlockBackgroundColor)!=null?n:"var(--persona-container, #f3f4f6)",t.style.borderColor=(r=e.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",t.style.color=(o=e.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},Kh=(t,e)=>{var u,m,g,f,w;let n=t.toolCall,r=(u=e==null?void 0:e.features)==null?void 0:u.toolCallDisplay,o=(m=r==null?void 0:r.collapsedMode)!=null?m:"tool-call",s=Vh(t,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?wu(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(f=e==null?void 0:e.toolCall)!=null?f:{},c=a;return o==="tool-name"?c=((w=n.name)==null?void 0:w.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=Ii(n,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Ii(n,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},xm=(t,e,n)=>{var u;let r=fs.has(t),o=(u=n==null?void 0:n.toolCall)!=null?u:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),i=e.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 m=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",g=be(r?"chevron-up":"chevron-down",16,m,2);g?c.appendChild(g):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Yi=(t,e)=>{var F,Z,Te,pe,ee,xe,Re,le,me;let n=t.toolCall,r=(F=e==null?void 0:e.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-${t.id}`,o.setAttribute("data-message-id",t.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=(Te=(Z=e==null?void 0:e.features)==null?void 0:Z.toolCallDisplay)!=null?Te:{},a=s.expandable!==!1,i=a&&fs.has(t.id),{summary:d,previewText:c,isActive:u}=Kh(t,e),m=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");m.type="button",a&&(m.setAttribute("aria-expanded",i?"true":"false"),m.setAttribute("data-expand-header","true")),m.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(m.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(m.style.paddingLeft=r.headerPaddingX,m.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(m.style.paddingTop=r.headerPaddingY,m.style.paddingBottom=r.headerPaddingY);let g=b("div","persona-flex persona-flex-col persona-text-left"),f=b("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(f.style.color=r.headerTextColor);let w=String((pe=n.startedAt)!=null?pe:Date.now()),v=()=>{let oe=b("span","");return oe.setAttribute("data-tool-elapsed",w),oe.textContent=Fs(n),oe},k=(xe=r.renderCollapsedSummary)==null?void 0:xe.call(r,{message:t,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:(ee=s.collapsedMode)!=null?ee:"tool-call",isActive:u,config:e!=null?e:{},elapsed:Fs(n),createElapsedElement:v});typeof k=="string"&&k.trim()?(f.textContent=k,g.appendChild(f)):k instanceof HTMLElement?g.appendChild(k):(f.textContent=d,g.appendChild(f));let R=(Re=s.loadingAnimation)!=null?Re:"none",E=r.activeTextTemplate,L=r.completeTextTemplate,M=u?E:L,I=k instanceof HTMLElement,A=(oe,se,de)=>{let Ee=de;for(let He of se){let K=b("span","persona-tool-char");K.style.setProperty("--char-index",String(Ee)),K.textContent=He===" "?"\xA0":He,oe.appendChild(K),Ee++}return Ee},P=(oe,se)=>{var K;f.textContent="";let de=((K=n.name)==null?void 0:K.trim())||"tool",Ee=Ma(oe,de),He=0;for(let J of Ee){let Le=J.styles.length>0?(()=>{let G=b("span",J.styles.map(ue=>`persona-tool-text-${ue}`).join(" "));return f.appendChild(G),G})():f;if(J.isDuration&&u)Le.appendChild(v());else{let G=J.isDuration?Fs(n):J.text;se?He=A(Le,G,He):Le.appendChild(document.createTextNode(G))}}};if(!I)if(u&&R!=="none"){let oe=(le=r.loadingAnimationDuration)!=null?le:2e3;if(f.setAttribute("data-preserve-animation","true"),R==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),M&&P(M,!1);else if(f.classList.add(`persona-tool-loading-${R}`),f.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),R==="shimmer-color"&&(r.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),M)P(M,!0);else{let se=f.textContent||d;f.textContent="",A(f,se,0)}}else M&&P(M,!1);let O=null;if(a){O=b("div","persona-flex persona-items-center");let oe=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=be(i?"chevron-up":"chevron-down",16,oe,2);se?O.appendChild(se):O.textContent=i?"Hide":"Show";let de=b("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");de.append(O),m.append(g,de)}else m.append(g);let _=b("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&&u&&s.activePreview&&c){let oe=(me=r.renderCollapsedPreview)==null?void 0:me.call(r,{message:t,toolCall:n,defaultPreview:c,isActive:u,config:e!=null?e:{}});jh(_,oe)||(_.textContent=c),_.style.display=""}if(!i&&u&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(m,_),o;let H=b("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(H.style.display=i?"":"none",r.contentBackgroundColor&&(H.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(H.style.color=r.contentTextColor),r.contentPaddingX&&(H.style.paddingLeft=r.contentPaddingX,H.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(H.style.paddingTop=r.contentPaddingY,H.style.paddingBottom=r.contentPaddingY),n.name){let oe=b("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?oe.style.color=r.contentTextColor:r.headerTextColor&&(oe.style.color=r.headerTextColor),oe.textContent=n.name,H.appendChild(oe)}if(n.args!==void 0){let oe=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 de=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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",Ji(de,r),de.textContent=uo(n.args),oe.append(se,de),H.appendChild(oe)}if(n.chunks&&n.chunks.length){let oe=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 de=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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",Ji(de,r),de.textContent=n.chunks.join(""),oe.append(se,de),H.appendChild(oe)}if(n.status==="complete"&&n.result!==void 0){let oe=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 de=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");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",Ji(de,r),de.textContent=uo(n.result),oe.append(se,de),H.appendChild(oe)}if(n.status==="complete"&&typeof n.duration=="number"){let oe=b("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(oe.style.color=r.contentTextColor),oe.textContent=`Duration: ${n.duration}ms`,H.appendChild(oe)}return(()=>{if(m.setAttribute("aria-expanded",i?"true":"false"),O){O.innerHTML="";let oe=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=be(i?"chevron-up":"chevron-down",16,oe,2);se?O.appendChild(se):O.textContent=i?"Hide":"Show"}H.style.display=i?"":"none",_.style.display=i?"none":_.textContent||_.childNodes.length?"":"none"})(),o.append(m,_,H),o};var No=new Map,ni=t=>{let n=(t.startsWith(Ur)?t.slice(Ur.length):t).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return t;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Cm=t=>(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,Am=(t,e)=>{var r,o,s;let n=(o=(r=Cm(e))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=No.get(t))!=null?s:n==="expanded"},Sm=(t,e,n)=>{var a,i;let r=Cm(n);t.setAttribute("aria-expanded",e?"true":"false");let o=t.querySelector("[data-approval-details-label]");o&&(o.textContent=e?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=t.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=be(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},Tm=(t,e,n)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!r||!o)return;let s=Am(t,n);Sm(r,s,n),o.style.display=s?"":"none"};var ri=(t,e)=>{var P,O,_,H,U,F,Z,Te,pe,ee,xe,Re,le,me,oe;let n=t.approval,r=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.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-${t.id}`,s.setAttribute("data-message-id",t.id),s.style.backgroundColor=(P=r==null?void 0:r.backgroundColor)!=null?P:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(O=r==null?void 0:r.borderColor)!=null?O:"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)":(_=r==null?void 0:r.titleColor)!=null?_:"currentColor",u=be(d,20,c,2);u&&i.appendChild(u);let m=b("div","persona-flex-1 persona-min-w-0"),g=b("div","persona-flex persona-items-center persona-gap-2"),f=b("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(f.style.color=r.titleColor),f.textContent=(H=r==null?void 0:r.title)!=null?H:"Approval Required",g.appendChild(f),!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"),g.appendChild(se)}m.appendChild(g);let v=n.toolType==="webmcp"||n.toolName.startsWith(Ur)?Rs(n.toolName):void 0,k=(U=r==null?void 0:r.formatDescription)==null?void 0:U.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),R=!n.toolName,E=k||(R?n.description:`The assistant wants to use \u201C${v!=null?v:ni(n.toolName)}\u201D.`),L=b("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(L.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(L.style.color=r.descriptionColor),L.textContent=E,m.appendChild(L),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 de=b("span","persona-font-medium");de.textContent=`${(F=r==null?void 0:r.reasonLabel)!=null?F:"Agent's stated reason:"} `,se.appendChild(de),se.appendChild(document.createTextNode(n.reason)),m.appendChild(se)}let M=(Z=r==null?void 0:r.detailsDisplay)!=null?Z:"collapsed",I=!!n.description&&!R,A=I||!!n.parameters;if(M!=="hidden"&&A){let se=Am(t.id,e),de=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");de.type="button",de.setAttribute("data-expand-header","true"),de.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(de.style.color=r.descriptionColor);let Ee=b("span");Ee.setAttribute("data-approval-details-label","true");let He=b("span","persona-inline-flex persona-items-center");He.setAttribute("data-approval-details-chevron","true"),de.append(Ee,He),Sm(de,se,e),m.appendChild(de);let K=b("div");if(K.setAttribute("data-approval-details","true"),K.style.display=se?"":"none",I){let J=b("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(J.style.color=r.descriptionColor),J.textContent=n.description,K.appendChild(J)}if(n.parameters){let J=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&&(J.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(J.style.color=r.parameterTextColor),J.style.fontSize="0.75rem",J.style.lineHeight="1rem",J.textContent=uo(n.parameters),K.appendChild(J)}m.appendChild(K)}if(o){let se=b("div","persona-flex persona-gap-2 persona-mt-2");se.setAttribute("data-approval-buttons","true");let de=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");de.type="button",de.style.backgroundColor=(Te=r==null?void 0:r.approveButtonColor)!=null?Te:"var(--persona-approval-approve-bg, #22c55e)",de.style.color=(pe=r==null?void 0:r.approveButtonTextColor)!=null?pe:"#ffffff",de.setAttribute("data-approval-action","approve");let Ee=be("shield-check",14,(ee=r==null?void 0:r.approveButtonTextColor)!=null?ee:"#ffffff",2);Ee&&(Ee.style.marginRight="4px",de.appendChild(Ee));let He=document.createTextNode((xe=r==null?void 0:r.approveLabel)!=null?xe:"Approve");de.appendChild(He);let K=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");K.type="button",K.style.backgroundColor=(Re=r==null?void 0:r.denyButtonColor)!=null?Re:"transparent",K.style.color=(le=r==null?void 0:r.denyButtonTextColor)!=null?le:"var(--persona-feedback-error, #dc2626)",K.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,K.setAttribute("data-approval-action","deny");let J=be("shield-x",14,(me=r==null?void 0:r.denyButtonTextColor)!=null?me:"var(--persona-feedback-error, #dc2626)",2);J&&(J.style.marginRight="4px",K.appendChild(J));let Le=document.createTextNode((oe=r==null?void 0:r.denyLabel)!=null?oe:"Deny");K.appendChild(Le),se.append(de,K),m.appendChild(se)}return a.append(i,m),s.appendChild(a),s};function Gh(t){var n,r;let e=(n=t.getRootNode)==null?void 0:n.call(t);return e instanceof ShadowRoot?e:((r=t.ownerDocument)!=null?r:document).body}function Em(t){var v;let{anchor:e,content:n,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=t,c=(v=t.container)!=null?v:Gh(e),u=!1,m=null,g=()=>{if(!u)return;let k=e.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${k.width}px`);let R=r==="top-start"||r==="top-end"?k.top-o-n.getBoundingClientRect().height:k.bottom+o,E=r==="bottom-end"||r==="top-end"?k.right-n.getBoundingClientRect().width:k.left;n.style.top=`${R}px`,n.style.left=`${E}px`},f=()=>{u&&(u=!1,m&&(m(),m=null),n.remove())},w=()=>{var I,A,P;if(u)return;u=!0,a!=null&&(n.style.zIndex=String(a)),c.appendChild(n),g();let k=(A=((I=e.ownerDocument)!=null?I:document).defaultView)!=null?A:window,R=(P=e.ownerDocument)!=null?P:document,E=()=>{if(!e.isConnected){f(),d==null||d("anchor-removed");return}g()},L=O=>{let _=typeof O.composedPath=="function"?O.composedPath():[];_.includes(n)||_.includes(e)||(f(),d==null||d("outside"))},M=k.setTimeout(()=>{R.addEventListener("pointerdown",L,!0)},0);k.addEventListener("scroll",E,!0),k.addEventListener("resize",E),m=()=>{k.clearTimeout(M),R.removeEventListener("pointerdown",L,!0),k.removeEventListener("scroll",E,!0),k.removeEventListener("resize",E)},i==null||i()};return{get isOpen(){return u},open:w,close:f,toggle:()=>u?f():w(),reposition:g,destroy:f}}function Mm(t){return(typeof t.composedPath=="function"?t.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Qh=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),km=(t,e)=>{let n=t.keyHandlers.get(e);n&&(document.removeEventListener("keydown",n),t.keyHandlers.delete(e));let r=t.popovers.get(e);r&&(r.destroy(),t.popovers.delete(e))},Fo=(t,e)=>{km(t,e);let n=t.pendingOrder.indexOf(e);n!==-1&&t.pendingOrder.splice(n,1),t.latestPendingApprovalId===e&&(t.latestPendingApprovalId=t.pendingOrder.length?t.pendingOrder[t.pendingOrder.length-1]:null)},Xh=t=>(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,Jh=(t,e)=>{var r,o;let n=(r=e==null?void 0:e.detailsDisplay)!=null?r:"collapsed";return(o=No.get(t))!=null?o:n==="expanded"},Zi=t=>{let e=b("span","persona-approval-kbd");return e.textContent=t,e},Yh=(t,e)=>{var c,u;let n=b("span","persona-approval-title");e!=null&&e.titleColor&&(n.style.color=e.titleColor);let o=t.toolType==="webmcp"||t.toolName.startsWith(Ur)?Rs(t.toolName):void 0,s=(u=e==null?void 0:e.formatDescription)==null?void 0:u.call(e,{toolName:t.toolName,toolType:t.toolType,description:(c=t.description)!=null?c:"",parameters:t.parameters,...o?{displayTitle:o}:{},...t.reason?{reason:t.reason}:{}});if(s)return n.textContent=s,n;let a=o!=null?o:ni(t.toolName),i=t.toolType&&t.toolType!=="webmcp"?t.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),i){n.append(" from ");let m=document.createElement("strong");m.textContent=i,n.appendChild(m)}return n},Zh=t=>{let e=b("div","persona-approval-resolved"),n=be("ban",15,"currentColor",2);n&&e.appendChild(n);let r=b("span","persona-approval-resolved-name");return r.textContent=t.toolName?ni(t.toolName):"Tool",e.append(r,document.createTextNode(t.status==="timeout"?" timed out":" denied")),e},ey=(t,e,n,r,o,s,a)=>{var O,_,H,U,F,Z,Te;let i=b("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${e.id}`,i.setAttribute("data-message-id",e.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=(O=r==null?void 0:r.detailsDisplay)!=null?O:"collapsed",c=!!n.description&&d!=="hidden",u=n.parameters!=null&&d!=="hidden",m=c||u,g=m&&Jh(e.id,r),f=(_=r==null?void 0:r.showDetailsLabel)!=null?_:"Show details",w=(H=r==null?void 0:r.hideDetailsLabel)!=null?H:"Hide details",v=b("button","persona-approval-head");v.type="button",m?(v.setAttribute("data-action","toggle-params"),v.setAttribute("aria-expanded",g?"true":"false"),v.setAttribute("aria-label",g?w:f)):v.setAttribute("data-static","true");let k=b("span","persona-approval-logo"),R=be("shield-check",16,"currentColor",2);R&&k.appendChild(R),v.appendChild(k);let E=Yh(n,r);if(m){let pe=b("span","persona-approval-toggle");pe.setAttribute("aria-hidden","true");let ee=be("chevron-down",14,"currentColor",2);ee&&pe.appendChild(ee),E.append(" "),E.appendChild(pe)}v.appendChild(E),i.appendChild(v);let L=b("div","persona-approval-body");if(m){let pe=b("div","persona-approval-details");if(pe.setAttribute("data-role","params"),pe.hidden=!g,c){let ee=b("p","persona-approval-desc");r!=null&&r.descriptionColor&&(ee.style.color=r.descriptionColor),ee.textContent=n.description,pe.appendChild(ee)}if(u){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=uo(n.parameters),pe.appendChild(ee)}L.appendChild(pe)}if(n.reason){let pe=b("p","persona-approval-reason");r!=null&&r.reasonColor?pe.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(pe.style.color=r.descriptionColor);let ee=b("span","persona-approval-reason-label");ee.textContent=`${(U=r==null?void 0:r.reasonLabel)!=null?U:"Agent's stated reason:"} `,pe.append(ee,document.createTextNode(n.reason)),L.appendChild(pe)}let M=b("div","persona-approval-actions"),I=null,A=pe=>{r!=null&&r.approveButtonColor&&(pe.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(pe.style.color=r.approveButtonTextColor)},P=b("button","persona-approval-deny");if(P.type="button",P.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(P.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(P.style.color=r.denyButtonTextColor),P.append((F=r==null?void 0:r.denyLabel)!=null?F:"Deny"),a){let pe=b("div","persona-approval-split"),ee=b("button","persona-approval-primary");ee.type="button",ee.setAttribute("data-action","always"),A(ee),ee.append((Z=r==null?void 0:r.approveLabel)!=null?Z:"Always allow",Zi("\u23CE"));let xe=b("button","persona-approval-caret");xe.type="button",xe.setAttribute("data-action","toggle-menu"),xe.setAttribute("aria-label","More options"),A(xe);let Re=be("chevron-down",15,"currentColor",2);Re&&xe.appendChild(Re),pe.append(ee,xe),M.append(pe,P),P.append(Zi("Esc"));let le=b("div","persona-approval-menu"),me=b("button","persona-approval-menu-item");me.type="button",me.append("Allow once",Zi("\u2318\u23CE")),le.appendChild(me),I=Em({anchor:pe,content:le,placement:"bottom-start",matchAnchorWidth:!0}),t.popovers.set(e.id,I),me.addEventListener("click",()=>{Fo(t,e.id),o()})}else{let pe=b("button","persona-approval-primary persona-approval-primary--solo");pe.type="button",pe.setAttribute("data-action","allow"),A(pe),pe.append((Te=r==null?void 0:r.approveLabel)!=null?Te:"Allow"),M.append(pe,P)}return L.appendChild(M),i.appendChild(L),i.addEventListener("click",pe=>{let ee=pe.target instanceof Element?pe.target.closest("[data-action]"):null;if(!ee)return;let xe=ee.getAttribute("data-action");if(xe==="toggle-params"){let Re=i.querySelector('[data-role="params"]');if(Re){let le=Re.hidden;Re.hidden=!le,v.setAttribute("aria-expanded",le?"true":"false"),v.setAttribute("aria-label",le?w:f),No.set(e.id,le)}return}if(xe==="toggle-menu"){I==null||I.toggle();return}if(xe==="always"){Fo(t,e.id),o({remember:!0});return}if(xe==="allow"){Fo(t,e.id),o();return}if(xe==="deny"){Fo(t,e.id),s();return}}),i},Lm=()=>{let t=Qh();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=Xh(a);if(i.status!=="pending"){if(Fo(t,r.id),i.status==="approved"){let m=document.createElement("div");return m.style.display="none",m}return Zh(i)}km(t,r.id);let c=(d==null?void 0:d.enableAlwaysAllow)===!0,u=ey(t,r,i,d,o,s,c);if(c){t.pendingOrder.includes(r.id)||t.pendingOrder.push(r.id),t.latestPendingApprovalId=t.pendingOrder[t.pendingOrder.length-1];let m=g=>{Mm(g)||r.id===t.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),Fo(t,r.id),g.key==="Escape"?s():g.metaKey||g.ctrlKey?o():o({remember:!0})))};t.keyHandlers.set(r.id,m),document.addEventListener("keydown",m)}return u}},teardown:()=>{for(let r of[...t.keyHandlers.keys(),...t.popovers.keys()])Fo(t,r);t.latestPendingApprovalId=null}}};var Pm=t=>{let e=[],n=null;return{buttons:e,render:(o,s,a,i,d,c)=>{t.innerHTML="",e.length=0;let u=(c==null?void 0:c.agentPushed)===!0;if(u||(n=null),!o||!o.length||!u&&(i!=null?i:s?s.getMessages():[]).some(k=>k.role==="user"))return;let m=document.createDocumentFragment(),g=s?s.isStreaming():!1,f=w=>{switch(w){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(w=>{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=w,v.disabled=g,d!=null&&d.fontFamily&&(v.style.fontFamily=f(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="",u&&t.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:w},bubbles:!0,composed:!0})),s.sendMessage(w))}),m.appendChild(v),e.push(v)}),t.appendChild(m),u){let w=JSON.stringify(o);w!==n&&(n=w,t.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var ra=class{constructor(e=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=n}push(e){var n;this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),(n=this.store)==null||n.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let n=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let 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=e.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let n=this.getAll();return e>=n.length?n:n.slice(n.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var e;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.clear()}destroy(){var e;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var oa=class{constructor(e="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=n}open(){return new Promise((e,n)=>{try{let 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,e()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}getAll(){return new Promise((e,n)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((e,n)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}clear(){return new Promise((e,n)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{e()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}};var ty=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),ny=new Set(["step_start","execution_start"]),ry=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),oy=new Set(["step_complete","agent_turn_complete"]),sy=new Set(["flow_complete","agent_complete"]),Im=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Rm=t=>typeof t=="object"&&t!==null&&!Array.isArray(t),Gn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0,Oo=(t,e)=>{let n=t[e];return Rm(n)?n:void 0};function el(t){return t>0?Math.max(1,Math.ceil(t/4)):0}function oi(t,e){if(!(t<=0||e===void 0||e<250))return t/(e/1e3)}function ay(t,e){return typeof e.type=="string"?e.type:t}function iy(t){return typeof t.text=="string"?t.text:typeof t.delta=="string"?t.delta:typeof t.content=="string"?t.content:typeof t.chunk=="string"?t.chunk:""}function ly(t,e){return t==="step_delta"||t==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":t!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function Wm(t){var r,o,s,a,i;let e=Oo(t,"result"),n=[Oo(t,"tokens"),Oo(t,"totalTokens"),e?Oo(e,"tokens"):void 0,Oo(t,"usage"),e?Oo(e,"usage"):void 0];for(let d of n){if(!d)continue;let c=(o=(r=Gn(d.output))!=null?r:Gn(d.outputTokens))!=null?o:Gn(d.completionTokens);if(c!==void 0)return c}return(i=(s=Gn(t.outputTokens))!=null?s:Gn(t.completionTokens))!=null?i:e?(a=Gn(e.outputTokens))!=null?a:Gn(e.completionTokens):void 0}function cy(t){var n,r,o,s,a;let e=Oo(t,"result");return(a=(o=(r=(n=Gn(t.executionTime))!=null?n:Gn(t.executionTimeMs))!=null?r:Gn(t.execution_time))!=null?o:Gn(t.duration))!=null?a:e?(s=Gn(e.executionTime))!=null?s:Gn(e.executionTimeMs):void 0}function dy(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var sa=class{constructor(e=dy){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:oi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,n){var s;if(!Rm(n)){Im.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=ay(e,n),o=this.now();if(ty.has(r)){this.startRun(o);return}if(ny.has(r)){this.run||this.startRun(o);return}if(ry.has(r)){if(!ly(r,n))return;let a=iy(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+el(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:oi(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(oy.has(r)){if(!this.run)return;let a=this.run,i=Wm(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+el(a.visibleCharCount),u=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:oi(c,u),outputTokens:c,durationMs:u,source:d?"usage":"estimate"};return}if(sy.has(r)){if(!this.run)return;let a=this.run,i=Wm(n),d=i!=null?i:a.exactOutputTokens+el(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",u=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:oi(d,u),outputTokens:d,durationMs:u,source:c},this.run=null;return}if(Im.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,n,r){let o=e.firstDeltaAt!==void 0?r-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=cy(n);return s!=null?s:r-e.startedAt}};function hs(t,e){e&&e.split(/\s+/).forEach(n=>n&&t.classList.add(n))}var py={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},uy={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},my=["flowName","stepName","reasoningText","text","name","tool","toolName"],gy=100;function fy(t,e){let n={...py,...e};if(n[t])return n[t];for(let r of Object.keys(n))if(r.endsWith("_")&&t.startsWith(r))return n[r];return uy}function hy(t,e){return`+${((t-e)/1e3).toFixed(3)}s`}function yy(t){let e=new Date(t),n=String(e.getHours()).padStart(2,"0"),r=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${o}.${s}`}function by(t,e){try{let n=JSON.parse(t);if(typeof n!="object"||n===null)return null;for(let r of e){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 vy(t){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(t):new Promise(n=>{let r=document.createElement("textarea");r.value=t,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function wy(t){let e;try{e=JSON.parse(t.payload)}catch{e=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:e},null,2)}function xy(t){return t.tokensPerSecond===void 0||!Number.isFinite(t.tokensPerSecond)?"-- tok/s":`${t.tokensPerSecond.toFixed(1)} tok/s`}function Cy(t){let e=[];return t.outputTokens!==void 0&&e.push(`${t.outputTokens.toLocaleString()} tok`),t.durationMs!==void 0&&e.push(`${(t.durationMs/1e3).toFixed(2)}s`),t.source&&e.push(t.source),e.join(" \xB7 ")}function Ay(t,e,n){let r,o;try{o=JSON.parse(t.payload),r=JSON.stringify(o,null,2)}catch{o=t.payload,r=t.payload}let s=e.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:t,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 tl(t,e,n,r,o,s,a,i){var g;let d=o.has(t.id),c=b("div","persona-border-b persona-border-persona-divider persona-text-xs");hs(c,(g=r.classNames)==null?void 0:g.eventRow);let u=a.find(f=>f.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let f=u.renderEventStreamRow({event:t,index:e,config:i,defaultRenderer:()=>m(),isExpanded:d,onToggleExpand:()=>s(t.id)});if(f)return c.appendChild(f),c}return c.appendChild(m()),c;function m(){var F,Z;let f=b("div",""),w=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");w.setAttribute("data-event-id",t.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"),k=be(d?"chevron-down":"chevron-right","14px","currentColor",2);k&&v.appendChild(k);let R=b("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),E=(F=r.timestampFormat)!=null?F:"relative";R.textContent=E==="relative"?hy(t.timestamp,n):yy(t.timestamp);let L=null;r.showSequenceNumbers!==!1&&(L=b("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),L.textContent=String(e+1));let M=fy(t.type,r.badgeColors),I=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");I.style.backgroundColor=M.bg,I.style.color=M.text,I.style.borderColor=M.text+"50",I.textContent=t.type;let A=(Z=r.descriptionFields)!=null?Z:my,P=by(t.payload,A),O=null;P&&(O=b("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),O.textContent=P);let _=b("div","persona-flex-1 persona-min-w-0"),H=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"),U=be("clipboard","12px","currentColor",1.5);return U&&H.appendChild(U),H.addEventListener("click",async Te=>{Te.stopPropagation(),await vy(wy(t)),H.innerHTML="";let pe=be("check","12px","currentColor",1.5);pe&&H.appendChild(pe),setTimeout(()=>{H.innerHTML="";let ee=be("clipboard","12px","currentColor",1.5);ee&&H.appendChild(ee)},1500)}),w.appendChild(v),w.appendChild(R),L&&w.appendChild(L),w.appendChild(I),O&&w.appendChild(O),w.appendChild(_),w.appendChild(H),f.appendChild(w),d&&f.appendChild(Ay(t,a,i)),f}}function Hm(t){var w,v,k,R,E;let{buffer:e,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=t,i=(w=o==null?void 0:o.features)==null?void 0:w.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",u=(k=i==null?void 0:i.label)!=null?k:"",m=(E=(R=o==null?void 0:o.features)==null?void 0:R.eventStream)!=null?E:{},g=s.find(L=>L.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&o){let L=g.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>f().element,onClose:r});if(L)return{element:L,update:()=>{},destroy:()=>{}}}return f();function f(){let L=m.classNames,M=b("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");hs(M,L==null?void 0:L.panel);let I=[],A="",P="",O=null,_=[],H={},U=0,F=_a(),Z=0,Te=0,pe=!1,ee=null,xe=!1,Re=0,le=new Set,me=new Map,oe="",se="",de=null,Ee,He,K,J,Le=null,G=null,ue=null;function De(){let ce=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(hs(B,L==null?void 0:L.headerBar),a){G=b("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),G.style.cursor="help",Le=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"),Le.textContent="-- tok/s",ue=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"),ue.style.display="none",ue.style.pointerEvents="none";let $t=G,Bn=ue,zt=()=>{if(!Bn.textContent)return;let Qn=$t.getBoundingClientRect(),yn=ce.getBoundingClientRect();Bn.style.left=`${Qn.left-yn.left}px`,Bn.style.top=`${Qn.bottom-yn.top+4}px`,Bn.style.display="block"},Dn=()=>{Bn.style.display="none"};G.addEventListener("mouseenter",zt),G.addEventListener("mouseleave",Dn),G.appendChild(Le)}let he=b("div","persona-flex-1");Ee=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 _e=b("option","");_e.value="",_e.textContent="All events (0)",Ee.appendChild(_e),He=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"),He.type="button",He.title="Copy All";let Ye=be("clipboard-copy","12px","currentColor",1.5);Ye&&He.appendChild(Ye);let Nt=b("span","persona-event-copy-all persona-text-xs");Nt.textContent="Copy All",He.appendChild(Nt),G&&B.appendChild(G),B.appendChild(he),B.appendChild(Ee),B.appendChild(He);let Mt=b("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");hs(Mt,L==null?void 0:L.searchBar);let ht=be("search","14px","var(--persona-muted, #9ca3af)",1.5),It=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");ht&&It.appendChild(ht),K=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"),hs(K,L==null?void 0:L.searchInput),K.type="text",K.placeholder="Search event payloads...",J=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"),J.type="button",J.style.display="none";let Jt=be("x","12px","currentColor",2);return Jt&&J.appendChild(Jt),Mt.appendChild(It),Mt.appendChild(K),Mt.appendChild(J),ce.appendChild(B),ce.appendChild(Mt),ue&&ce.appendChild(ue),ce}let Xe,et=s.find(ce=>ce.renderEventStreamToolbar);if(et!=null&&et.renderEventStreamToolbar&&o){let ce=et.renderEventStreamToolbar({config:o,defaultRenderer:()=>De(),eventCount:e.getSize(),filteredCount:0,onFilterChange:B=>{A=B,te(),xt()},onSearchChange:B=>{P=B,te(),xt()}});Xe=ce!=null?ce:De()}else Xe=De();let vt=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");vt.style.display="none";function wt(){if(!a||!Le||!G)return;let ce=a(),B=xy(ce);Le.textContent=B;let he=Cy(ce);ue&&(ue.textContent=he,he||(ue.style.display="none")),G.setAttribute("aria-label",he?`Throughput: ${B}, ${he}`:`Throughput: ${B}`)}let Je=b("div","persona-flex-1 persona-min-h-0 persona-relative"),fe=b("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");fe.style.height="100%";let Q=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");hs(Q,L==null?void 0:L.scrollIndicator),Q.style.display="none",Q.setAttribute("data-persona-scroll-to-bottom-has-label",u?"true":"false");let dt=be(c,"14px","currentColor",2);dt&&Q.appendChild(dt);let qe=b("span","");qe.textContent=u,Q.appendChild(qe);let Ce=b("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ce.style.display="none",Je.appendChild(fe),Je.appendChild(Ce),Je.appendChild(Q),M.setAttribute("tabindex","0"),M.appendChild(Xe),M.appendChild(vt),M.appendChild(Je);function Me(){let ce=e.getAll(),B={};for(let Mt of ce)B[Mt.type]=(B[Mt.type]||0)+1;let he=Object.keys(B).sort(),_e=he.length!==_.length||!he.every((Mt,ht)=>Mt===_[ht]),Ct=!_e&&he.some(Mt=>B[Mt]!==H[Mt]),Ye=ce.length!==Object.values(H).reduce((Mt,ht)=>Mt+ht,0);if(!_e&&!Ct&&!Ye||(_=he,H=B,!Ee))return;let Nt=Ee.value;if(Ee.options[0].textContent=`All events (${ce.length})`,_e){for(;Ee.options.length>1;)Ee.remove(1);for(let Mt of he){let ht=b("option","");ht.value=Mt,ht.textContent=`${Mt} (${B[Mt]||0})`,Ee.appendChild(ht)}Nt&&he.includes(Nt)?Ee.value=Nt:Nt&&(Ee.value="",A="")}else for(let Mt=1;Mt<Ee.options.length;Mt++){let ht=Ee.options[Mt];ht.textContent=`${ht.value} (${B[ht.value]||0})`}}function nt(){let ce=e.getAll();if(A&&(ce=ce.filter(B=>B.type===A)),P){let B=P.toLowerCase();ce=ce.filter(he=>he.type.toLowerCase().includes(B)||he.payload.toLowerCase().includes(B))}return ce}function Wt(){return A!==""||P!==""}function te(){U=0,Z=0,F.resume(),Q.style.display="none"}function Ue(ce){le.has(ce)?le.delete(ce):le.add(ce),de=ce;let B=fe.scrollTop,he=F.isFollowing();xe=!0,F.pause(),xt(),fe.scrollTop=B,he&&F.resume(),xe=!1}function An(){return Bo(fe,50)}function xt(){Te=Date.now(),pe=!1,wt(),Me();let ce=e.getEvictedCount();ce>0?(vt.textContent=`${ce.toLocaleString()} older events truncated`,vt.style.display=""):vt.style.display="none",I=nt();let B=I.length,he=e.getSize()>0;B===0&&he&&Wt()?(Ce.textContent=P?`No events matching '${P}'`:"No events matching filter",Ce.style.display="",fe.style.display="none"):(Ce.style.display="none",fe.style.display=""),He&&(He.title=Wt()?`Copy Filtered (${B})`:"Copy All"),d&&!F.isFollowing()&&B>U&&(Z+=B-U,qe.textContent=u?`${u}${Z>0?` (${Z})`:""}`:"",Q.style.display=""),U=B;let _e=e.getAll(),Ct=_e.length>0?_e[0].timestamp:0,Ye=new Set(I.map(ht=>ht.id));for(let ht of le)Ye.has(ht)||le.delete(ht);let Nt=A!==oe||P!==se,Mt=me.size===0&&I.length>0;if(Nt||Mt||I.length===0){fe.innerHTML="",me.clear();let ht=document.createDocumentFragment();for(let It=0;It<I.length;It++){let Jt=tl(I[It],It,Ct,m,le,Ue,s,o);me.set(I[It].id,Jt),ht.appendChild(Jt)}fe.appendChild(ht),oe=A,se=P,de=null}else{if(de!==null){let It=me.get(de);if(It&&It.parentNode===fe){let Jt=I.findIndex($t=>$t.id===de);if(Jt>=0){let $t=tl(I[Jt],Jt,Ct,m,le,Ue,s,o);fe.insertBefore($t,It),It.remove(),me.set(de,$t)}}de=null}let ht=new Set(I.map(It=>It.id));for(let[It,Jt]of me)ht.has(It)||(Jt.remove(),me.delete(It));for(let It=0;It<I.length;It++){let Jt=I[It];if(!me.has(Jt.id)){let $t=tl(Jt,It,Ct,m,le,Ue,s,o);me.set(Jt.id,$t),fe.appendChild($t)}}}F.isFollowing()&&(fe.scrollTop=fe.scrollHeight)}function hn(){if(Date.now()-Te>=gy){ee!==null&&(cancelAnimationFrame(ee),ee=null),xt();return}pe||(pe=!0,ee=requestAnimationFrame(()=>{ee=null,xt()}))}let hr=(ce,B)=>{if(!He)return;He.innerHTML="";let he=be(ce,"12px","currentColor",1.5);he&&He.appendChild(he);let _e=b("span","persona-text-xs");_e.textContent="Copy All",He.appendChild(_e),setTimeout(()=>{He.innerHTML="";let Ct=be("clipboard-copy","12px","currentColor",1.5);Ct&&He.appendChild(Ct);let Ye=b("span","persona-text-xs");Ye.textContent="Copy All",He.appendChild(Ye),He.disabled=!1},B)},yr=async()=>{if(He){He.disabled=!0;try{let ce;Wt()?ce=I:n?(ce=await n(),ce.length===0&&(ce=e.getAll())):ce=e.getAll();let B=ce.map(he=>{try{return JSON.parse(he.payload)}catch{return he.payload}});await navigator.clipboard.writeText(JSON.stringify(B,null,2)),hr("check",1500)}catch{hr("x",1500)}}},S=()=>{Ee&&(A=Ee.value,te(),xt())},ne=()=>{!K||!J||(J.style.display=K.value?"":"none",O&&clearTimeout(O),O=setTimeout(()=>{P=K.value,te(),xt()},150))},Se=()=>{!K||!J||(K.value="",P="",J.style.display="none",O&&clearTimeout(O),te(),xt())},Ne=()=>{if(xe)return;let ce=fe.scrollTop,{action:B,nextLastScrollTop:he}=$a({following:F.isFollowing(),currentScrollTop:ce,lastScrollTop:Re,nearBottom:An(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Re=he,B==="resume"?(F.resume(),Z=0,Q.style.display="none"):B==="pause"&&(F.pause(),d&&(qe.textContent=u,Q.style.display=""))},Pe=ce=>{let B=Ua({following:F.isFollowing(),deltaY:ce.deltaY,nearBottom:An(),resumeWhenNearBottom:!0});B==="pause"?(F.pause(),d&&(qe.textContent=u,Q.style.display="")):B==="resume"&&(F.resume(),Z=0,Q.style.display="none")},Fe=()=>{d&&(fe.scrollTop=fe.scrollHeight,F.resume(),Z=0,Q.style.display="none")},Ke=ce=>{let B=ce.target;if(!B||B.closest("button"))return;let he=B.closest("[data-event-id]");if(!he)return;let _e=he.getAttribute("data-event-id");_e&&Ue(_e)},it=ce=>{if((ce.metaKey||ce.ctrlKey)&&ce.key==="f"){ce.preventDefault(),K==null||K.focus(),K==null||K.select();return}ce.key==="Escape"&&(K&&document.activeElement===K?(Se(),K.blur(),M.focus()):r&&r())};He&&He.addEventListener("click",yr),Ee&&Ee.addEventListener("change",S),K&&K.addEventListener("input",ne),J&&J.addEventListener("click",Se),fe.addEventListener("scroll",Ne),fe.addEventListener("wheel",Pe,{passive:!0}),fe.addEventListener("click",Ke),Q.addEventListener("click",Fe),M.addEventListener("keydown",it);function Rt(){O&&clearTimeout(O),ee!==null&&(cancelAnimationFrame(ee),ee=null),pe=!1,me.clear(),He&&He.removeEventListener("click",yr),Ee&&Ee.removeEventListener("change",S),K&&K.removeEventListener("input",ne),J&&J.removeEventListener("click",Se),fe.removeEventListener("scroll",Ne),fe.removeEventListener("wheel",Pe),fe.removeEventListener("click",Ke),Q.removeEventListener("click",Fe),M.removeEventListener("keydown",it)}return{element:M,update:hn,destroy:Rt}}}function Bm(t,e){let n=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",r=typeof t.artifactId=="string"?t.artifactId:"",o=t.status==="streaming"?"streaming":"complete",a=(typeof t.artifactType=="string"?t.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 u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=n;let m=document.createElement("div");if(m.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",m.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",m.appendChild(g);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,m.appendChild(f)}else m.textContent=a;if(c.append(u,m),i.append(d,c),o==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var Dm=(t,e)=>{var r,o,s;let n=(s=(o=(r=e==null?void 0:e.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof t.title=="string"&&t.title?t.title:"Untitled artifact",i=typeof t.artifactId=="string"?t.artifactId:"",d=t.status==="streaming"?"streaming":"complete",c=typeof t.artifactType=="string"?t.artifactType:"markdown",u=n({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:e.config,defaultRenderer:()=>Bm(t,e)});if(u)return u}return Bm(t,e)};var nl=class{constructor(){this.components=new Map}register(e,n){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,n)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([n,r])=>{this.register(n,r)})}},_o=new nl;_o.register("PersonaArtifactCard",Dm);function Sy(t){var o;let e=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=t.component?`Component: ${t.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=t.props)!=null?o:{},null,2),e.appendChild(n),e.appendChild(r),e}function Nm(t,e){var He,K,J,Le;let n=(K=(He=t.features)==null?void 0:He.artifacts)==null?void 0:K.layout,o=((J=n==null?void 0:n.toolbarPreset)!=null?J:"default")==="document",s=(Le=n==null?void 0:n.panePadding)==null?void 0:Le.trim(),a=t.markdown?ba(t.markdown):null,i=va(t.sanitize),d=G=>{let ue=a?a(G):io(G);return i?i(ue):ue},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,u=()=>{c==null||c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"),U==null||U.hide()};c&&c.addEventListener("click",()=>{var G;u(),(G=e.onDismiss)==null||G.call(e)});let m=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");m.setAttribute("data-persona-theme-zone","artifact-pane"),o&&m.classList.add("persona-artifact-pane-document");let g=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");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&g.classList.add("persona-artifact-toolbar-document");let f=b("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let w=b("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");w.type="button",w.textContent="Close",w.setAttribute("aria-label","Close artifacts panel"),w.addEventListener("click",()=>{var G;u(),(G=e.onDismiss)==null||G.call(e)});let v="rendered",k=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),R=o?Cn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Cn({icon:"eye",label:"Rendered view"}),E=o?Cn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Cn({icon:"code-2",label:"Source"}),L=b("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),M=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,I=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,A=n==null?void 0:n.documentToolbarCopyMenuItems,P=!!(I&&A&&A.length>0),O=null,_,H=null,U=null;if(o&&(M||I)&&!P){if(_=M?qi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I){let G=be("chevron-down",14,"currentColor",2);G&&_.appendChild(G)}}else o&&P?(O=b("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),_=M?qi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),H=Cn({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"}}),O.append(_,H)):o?_=Cn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):_=Cn({icon:"copy",label:"Copy"});let F=o?Cn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Cn({icon:"refresh-cw",label:"Refresh"}),Z=o?Cn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Cn({icon:"x",label:"Close"}),Te=()=>{var et,vt,wt;let G=(et=me.find(Je=>Je.id===oe))!=null?et:me[me.length-1],ue=(vt=G==null?void 0:G.id)!=null?vt:null,De=(G==null?void 0:G.artifactType)==="markdown"&&(wt=G.markdown)!=null?wt:"",Xe=G?JSON.stringify({component:G.component,props:G.props},null,2):"";return{markdown:De,jsonPayload:Xe,id:ue}},pe=async()=>{var et;let{markdown:G,jsonPayload:ue}=Te(),De=(et=me.find(vt=>vt.id===oe))!=null?et:me[me.length-1],Xe=(De==null?void 0:De.artifactType)==="markdown"?G:De?ue:"";try{await navigator.clipboard.writeText(Xe)}catch{}};if(_.addEventListener("click",async()=>{let G=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(G&&P){let{markdown:ue,jsonPayload:De,id:Xe}=Te();try{await G({actionId:"primary",artifactId:Xe,markdown:ue,jsonPayload:De})}catch{}return}await pe()}),H&&(A!=null&&A.length)){let G=()=>{var De;return(De=m.closest("[data-persona-root]"))!=null?De:document.body},ue=()=>{U=ms({items:A.map(De=>({id:De.id,label:De.label})),onSelect:async De=>{let{markdown:Xe,jsonPayload:et,id:vt}=Te(),wt=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{wt?await wt({actionId:De,artifactId:vt,markdown:Xe,jsonPayload:et}):De==="markdown"||De==="md"?await navigator.clipboard.writeText(Xe):De==="json"||De==="source"?await navigator.clipboard.writeText(et):await navigator.clipboard.writeText(Xe||et)}catch{}},anchor:O!=null?O:H,position:"bottom-right",portal:G()})};m.isConnected?ue():requestAnimationFrame(ue),H.addEventListener("click",De=>{De.stopPropagation(),U==null||U.toggle()})}F.addEventListener("click",async()=>{var G;try{await((G=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:G.call(n))}catch{}de()}),Z.addEventListener("click",()=>{var G;u(),(G=e.onDismiss)==null||G.call(e)});let ee=()=>{o&&(R.setAttribute("aria-pressed",v==="rendered"?"true":"false"),E.setAttribute("aria-pressed",v==="source"?"true":"false"))};R.addEventListener("click",()=>{v="rendered",ee(),de()}),E.addEventListener("click",()=>{v="source",ee(),de()});let xe=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?(g.replaceChildren(),k.append(R,E),O?L.append(O,F,Z):L.append(_,F,Z),g.append(k,xe,L),ee()):(g.appendChild(f),g.appendChild(w)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let Re=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"),le=b("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Re.style.paddingLeft=s,Re.style.paddingRight=s,le.style.padding=s),m.appendChild(g),m.appendChild(Re),m.appendChild(le);let me=[],oe=null,se=!1,de=()=>{var Xe,et,vt,wt;let G=o&&me.length<=1;Re.classList.toggle("persona-hidden",G),Re.replaceChildren();for(let Je of me){let fe=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");fe.type="button",fe.textContent=Je.title||Je.id.slice(0,8),Je.id===oe&&fe.classList.add("persona-bg-persona-container","persona-border-persona-border"),fe.addEventListener("click",()=>e.onSelect(Je.id)),Re.appendChild(fe)}le.replaceChildren();let ue=oe&&me.find(Je=>Je.id===oe)||me[me.length-1];if(!ue)return;if(o){let Je=ue.artifactType==="markdown"?"MD":(Xe=ue.component)!=null?Xe:"Component",Q=(ue.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";xe.textContent=`${Q} \xB7 ${Je}`}else f.textContent="Artifacts";if(ue.artifactType==="markdown"){if(o&&v==="source"){let fe=b("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");fe.textContent=(et=ue.markdown)!=null?et:"",le.appendChild(fe);return}let Je=b("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Je.innerHTML=d((vt=ue.markdown)!=null?vt:""),le.appendChild(Je);return}let De=ue.component?_o.get(ue.component):void 0;if(De){let fe={message:{id:ue.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:t,updateProps:()=>{}};try{let Q=De((wt=ue.props)!=null?wt:{},fe);if(Q){le.appendChild(Q);return}}catch{}}le.appendChild(Sy(ue))},Ee=()=>{var ue;let G=me.length>0;if(m.classList.toggle("persona-hidden",!G),c){let De=typeof m.closest=="function"?m.closest("[data-persona-root]"):null,et=((ue=De==null?void 0:De.classList.contains("persona-artifact-narrow-host"))!=null?ue:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;G&&et&&se?(c.classList.remove("persona-hidden"),m.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open"))}};return{element:m,backdrop:c,update(G){var ue,De,Xe;me=G.artifacts,oe=(Xe=(De=G.selectedId)!=null?De:(ue=G.artifacts[G.artifacts.length-1])==null?void 0:ue.id)!=null?Xe:null,me.length>0&&(se=!0),de(),Ee()},setMobileOpen(G){se=G,!G&&c?(c.classList.add("persona-hidden"),m.classList.remove("persona-artifact-drawer-open")):Ee()}}}function ar(t){var e,n;return((n=(e=t==null?void 0:t.features)==null?void 0:e.artifacts)==null?void 0:n.enabled)===!0}function Fm(t,e){var s,a,i,d;if(t.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),t.style.removeProperty("--persona-artifact-pane-border"),t.style.removeProperty("--persona-artifact-pane-border-left"),!ar(e))return;let n=(a=(s=e.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?(t.classList.add("persona-artifact-border-full"),t.style.setProperty("--persona-artifact-pane-border",r)):o&&(t.classList.add("persona-artifact-border-left"),t.style.setProperty("--persona-artifact-pane-border-left",o))}function Ty(t){t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),t.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),t.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function si(t,e){var d,c,u,m,g,f,w,v,k,R;if(!ar(e)){t.style.removeProperty("--persona-artifact-split-gap"),t.style.removeProperty("--persona-artifact-pane-width"),t.style.removeProperty("--persona-artifact-pane-max-width"),t.style.removeProperty("--persona-artifact-pane-min-width"),t.style.removeProperty("--persona-artifact-pane-bg"),t.style.removeProperty("--persona-artifact-pane-padding"),Ty(t),Fm(t,e);return}let n=(c=(d=e.features)==null?void 0:d.artifacts)==null?void 0:c.layout;t.style.setProperty("--persona-artifact-split-gap",(u=n==null?void 0:n.splitGap)!=null?u:"0.5rem"),t.style.setProperty("--persona-artifact-pane-width",(m=n==null?void 0:n.paneWidth)!=null?m:"40%"),t.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?t.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):t.style.removeProperty("--persona-artifact-pane-min-width");let r=(f=n==null?void 0:n.paneBackground)==null?void 0:f.trim();r?t.style.setProperty("--persona-artifact-pane-bg",r):t.style.removeProperty("--persona-artifact-pane-bg");let o=(w=n==null?void 0:n.panePadding)==null?void 0:w.trim();o?t.style.setProperty("--persona-artifact-pane-padding",o):t.style.removeProperty("--persona-artifact-pane-padding");let s=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();s?t.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):t.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(k=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:k.trim();a?t.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):t.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(R=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:R.trim();i?t.style.setProperty("--persona-artifact-doc-toggle-active-border",i):t.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Fm(t,e)}var Om=["panel","seamless"];function ai(t,e){var i,d,c,u,m,g;for(let f of Om)t.classList.remove(`persona-artifact-appearance-${f}`);if(t.classList.remove("persona-artifact-unified-split"),t.style.removeProperty("--persona-artifact-pane-radius"),t.style.removeProperty("--persona-artifact-pane-shadow"),t.style.removeProperty("--persona-artifact-unified-outer-radius"),!ar(e))return;let n=(d=(i=e.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=n==null?void 0:n.paneAppearance)!=null?c:"panel",o=Om.includes(r)?r:"panel";t.classList.add(`persona-artifact-appearance-${o}`);let s=(u=n==null?void 0:n.paneBorderRadius)==null?void 0:u.trim();s&&t.style.setProperty("--persona-artifact-pane-radius",s);let a=(m=n==null?void 0:n.paneShadow)==null?void 0:m.trim();if(a&&t.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){t.classList.add("persona-artifact-unified-split");let f=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;f&&t.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function _m(t,e){var n,r,o;return!e||!ar(t)?!1:((o=(r=(n=t.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Ey(t,e){if(!(t!=null&&t.trim()))return e;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return n?Math.max(0,Number(n[1])):e}function My(t){if(!(t!=null&&t.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(t.trim());return e?Math.max(0,Number(e[1])):null}function ky(t,e,n){return n<e?e:Math.min(n,Math.max(e,t))}function Ly(t,e,n,r){let o=t-r-2*e-n;return Math.max(0,o)}function $m(t,e){var a;let r=(a=(e.getComputedStyle(t).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 Um(t,e,n,r,o,s){let a=Ey(o,200),i=Ly(e,n,r,200);i=Math.max(a,i);let d=My(s);return d!==null&&(i=Math.min(i,d)),ky(t,a,i)}var zm={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"}},rl=(t,e,n,r)=>{let o=t.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var w,v,k;if(s.dataset.enhanced==="true")return;let a=(w=s.dataset.tvForm)!=null?w:"init";s.dataset.enhanced="true";let i=(v=zm[a])!=null?v:zm.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 R=b("p","persona-text-sm persona-text-persona-muted");R.textContent=i.description,d.appendChild(R)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(R=>{var A,P;let E=b("label","persona-form-field persona-flex persona-flex-col persona-gap-1");E.htmlFor=`${e.id}-${a}-${R.name}`;let L=b("span","persona-text-xs persona-font-medium persona-text-persona-muted");L.textContent=R.label,E.appendChild(L);let M=(A=R.type)!=null?A:"text",I;M==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=M),I.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",I.id=`${e.id}-${a}-${R.name}`,I.name=R.name,I.placeholder=(P=R.placeholder)!=null?P:"",R.required&&(I.required=!0),E.appendChild(I),u.appendChild(E)});let m=b("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=b("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=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");f.type="submit",f.textContent=(k=i.submitLabel)!=null?k:"Submit",m.appendChild(g),m.appendChild(f),u.appendChild(m),s.replaceChildren(d,u),u.addEventListener("submit",async R=>{var I,A;R.preventDefault();let E=(I=n.formEndpoint)!=null?I:"/form",L=new FormData(u),M={};L.forEach((P,O)=>{M[O]=P}),M.type=a,f.disabled=!0,g.textContent="Submitting\u2026";try{let P=await fetch(E,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!P.ok)throw new Error(`Form submission failed (${P.status})`);let O=await P.json();g.textContent=(A=O.message)!=null?A:"Thanks! We'll be in touch soon.",O.success&&O.nextPrompt&&await r.sendMessage(String(O.nextPrompt))}catch(P){g.textContent=P instanceof Error?P.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var ol=class{constructor(){this.plugins=new Map}register(e){var n;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(n=e.onRegister)==null||n.call(e)}unregister(e){var r;let n=this.plugins.get(e);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,n)=>{var r,o;return((r=n.priority)!=null?r:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let n=this.getAll();if(!e||e.length===0)return n;let r=new Set(e.map(s=>s.id));return[...n.filter(s=>!r.has(s.id)),...e].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var n;return(n=e.onUnregister)==null?void 0:n.call(e)}),this.plugins.clear()}},sl=new ol;var qm=()=>{let t=new Map,e=(o,s)=>(t.has(o)||t.set(o,new Set),t.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=t.get(o))==null||a.delete(s)};return{on:e,off:n,emit:(o,s)=>{var a;(a=t.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Py=t=>{let e=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:t},Iy=t=>{let e=t.trim(),n=e.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<e.length;o+=1){let s=e[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return e.slice(n,o+1)}return null},il=({text:t})=>{if(!t||!t.includes("{"))return null;try{let e=Py(t),n=Iy(e);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}},al=t=>typeof t=="string"?t:t==null?"":String(t),aa={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:al(t.payload.text)},messageAndClick:(t,e)=>{var o;if(t.type!=="message_and_click")return;let n=t.payload,r=al(n.element);if(r&&((o=e.document)!=null&&o.querySelector)){let s=e.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:al(n.text)}}},jm=t=>Array.isArray(t)?t.map(e=>String(e)):[],ll=t=>{let e=new Set(jm(t.getSessionMetadata().processedActionMessageIds)),n=()=>{e=new Set(jm(t.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(e);t.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?t.parsers.reduce((c,u)=>c||(u==null?void 0:u({text:a,message:s.message}))||null,null):null;if(!i)return null;e.add(s.message.id),r();let d={action:i,message:s.message};t.emit("action:detected",d);for(let c of t.handlers)if(c)try{let u=()=>{t.emit("action:resubmit",d)},m=c(i,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:u});if(!m)continue;if(m.handled){let g=m.persistMessage!==!1;return{text:m.displayText!==void 0?m.displayText:"",persist:g,resubmit:m.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:n}};var Wy=t=>{if(!t)return null;try{return JSON.parse(t)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},Ry=t=>t.map(e=>({...e,streaming:!1})),Hy=t=>t.map(e=>({...e,status:"complete"})),Vm=(t="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=e();return n?Wy(n.getItem(t)):null},save:n=>{let r=e();if(r)try{let o={...n,messages:n.messages?Ry(n.messages):void 0,artifacts:n.artifacts?Hy(n.artifacts):void 0};r.setItem(t,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let n=e();if(n)try{n.removeItem(t)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var cl=require("partial-json");function Km(t,e){let{config:n,message:r,onPropsUpdate:o}=e,s=_o.get(t.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${t.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{o&&o(i)}};try{return s(t.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,i),null}}function Gm(t){if(typeof t.rawContent=="string"&&t.rawContent.length>0)return t.rawContent;if(typeof t.content=="string"){let e=t.content.trim();if(e.startsWith("{")||e.startsWith("["))return t.content}return null}function Qm(t){let e=Gm(t);if(!e)return!1;try{let n=JSON.parse(e);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Xm(t){let e=Gm(t);if(!e)return null;try{let n=JSON.parse(e);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e}}}catch{}return null}var By=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Jm(t){let{onSubmit:e,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=By}=t,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let m=null,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=r,f.appendChild(w);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=o,f.appendChild(v),g.appendChild(f);let k=document.createElement("div");k.className="persona-feedback-rating persona-feedback-rating-csat",k.setAttribute("role","radiogroup"),k.setAttribute("aria-label","Satisfaction rating from 1 to 5");let R=[];for(let A=1;A<=5;A++){let P=document.createElement("button");P.type="button",P.className="persona-feedback-rating-btn persona-feedback-star-btn",P.setAttribute("role","radio"),P.setAttribute("aria-checked","false"),P.setAttribute("aria-label",`${A} star${A>1?"s":""}: ${c[A-1]}`),P.title=c[A-1],P.dataset.rating=String(A),P.innerHTML=`
|
|
27
|
+
`,t.addEventListener("click",e);let r=s=>{var I,M,P,C,k,q,_,R,O,F,Z,ke,pe;let a=(I=s.launcher)!=null?I:{},i=gn(s),d=t.querySelector("[data-role='launcher-title']");if(d){let ee=(M=a.title)!=null?M:"Chat Assistant";d.textContent=ee,d.setAttribute("title",ee)}let c=t.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=t.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let g=t.querySelector("[data-role='launcher-icon']");if(g)if(a.agentIconHidden)g.style.display="none";else{let ee=(C=a.agentIconSize)!=null?C:"40px";if(g.style.height=ee,g.style.width=ee,a.agentIconBackgroundColor?(g.style.backgroundColor=a.agentIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),g.innerHTML="",a.agentIconName){let Pe=parseFloat(ee)||24,Ie=ye(a.agentIconName,Pe*.6,"var(--persona-text-inverse, #ffffff)",2);Ie?(g.appendChild(Ie),g.style.display=""):(g.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",g.style.display="")}else a.iconUrl?g.style.display="none":(g.textContent=(q=a.agentIconText)!=null?q:"\u{1F4AC}",g.style.display="")}let h=t.querySelector("[data-role='launcher-image']");if(h){let ee=(_=a.agentIconSize)!=null?_:"40px";h.style.height=ee,h.style.width=ee,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(h.src=a.iconUrl,h.style.display="block"):h.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ee=(R=a.callToActionIconSize)!=null?R:"32px";m.style.height=ee,m.style.width=ee,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Pe=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Pe=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let Ie=parseFloat(ee)||24,ie=Math.max(Ie-Pe,8),he=ye(a.callToActionIconName,ie,"currentColor",2);he?m.appendChild(he):m.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else m.textContent=(F=a.callToActionIconText)!=null?F:"\u2197"}let y=a.position&&fr[a.position]?fr[a.position]:fr["bottom-right"],w="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",E="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";t.className=i?E:`${w} ${y}`,i||(t.style.zIndex=String((Z=a.zIndex)!=null?Z:vn));let B="1px solid var(--persona-border, #e5e7eb)",T="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(ke=a.border)!=null?ke:B,t.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:T,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(pe=a.collapsedMaxWidth)!=null?pe:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},o=()=>{t.removeEventListener("click",e),t.remove()};return n&&r(n),{element:t,update:r,destroy:o}};var qm=({config:n,showClose:e})=>{let{wrapper:t,panel:r,pillRoot:o}=$m(n),s=Um(n,e),a={wrapper:t,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:h=>(d.element.replaceWith(h.header),d.element=h.header,d.iconHolder=h.iconHolder,d.headerTitle=h.headerTitle,d.headerSubtitle=h.headerSubtitle,d.closeButton=h.closeButton,d.closeButtonWrapper=h.closeButtonWrapper,d.clearChatButton=h.clearChatButton,d.clearChatButtonWrapper=h.clearChatButtonWrapper,h),replaceComposer:h=>{c.footer.replaceWith(h),c.footer=h}}},el=({config:n,plugins:e,onToggle:t})=>{let r=e.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:n,defaultRenderer:()=>Zi(n,t).element,onToggle:t});if(s)return{instance:null,element:s}}let o=Zi(n,t);return{instance:o,element:o.element}};var sy=n=>{switch(n){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}},ay=(n,e)=>{if(!n)return null;let t=sy(n);if(t===null)return null;let r=e==null?void 0:e[n],o=r!==void 0?r:t;return o||null},iy=(n,e)=>{let t=v("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",n),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=e,t},ly=n=>{let e=n.toLowerCase();return e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||e.startsWith("data:image/")||!n.includes(":"))},tl=n=>{let e=n.toLowerCase();return e.startsWith("javascript:")||e.startsWith("data:text/html")||e.startsWith("data:text/javascript")||e.startsWith("data:text/xml")||e.startsWith("data:application/xhtml")||e.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(n)||e.startsWith("data:")||!n.includes(":"))},nl=320,jm=320,cy=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="image"&&typeof e.image=="string"&&e.image.trim().length>0),dy=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="audio"&&typeof e.audio=="string"&&e.audio.trim().length>0),py=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="video"&&typeof e.video=="string"&&e.video.trim().length>0),uy=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(e=>e.type==="file"&&typeof e.data=="string"&&e.data.trim().length>0),my=(n,e,t)=>{if(n.length===0)return null;try{let r=v("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),e&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),t==null||t())};return n.forEach((i,d)=>{var g;let c=v("img");c.alt=((g=i.alt)==null?void 0:g.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=`${nl}px`,c.style.maxHeight=`${jm}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}),ly(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 t==null||t(),null}},gy=n=>{if(n.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","audio");let t=0;return n.forEach(r=>{if(!tl(r.audio))return;let o=v("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${nl}px`,e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},fy=n=>{if(n.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","video");let t=0;return n.forEach(r=>{if(!tl(r.video))return;let o=v("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${nl}px`,o.style.maxHeight=`${jm}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},hy=n=>{if(n.length===0)return null;try{let e=v("div","persona-flex persona-flex-col persona-gap-2");e.setAttribute("data-message-attachments","files");let t=0;return n.forEach(r=>{if(!tl(r.data))return;let o=v("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",e.appendChild(o),t+=1}),t===0?(e.remove(),null):e}catch{return null}},da=()=>{let n=document.createElement("div");n.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let e=document.createElement("div");e.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",e.style.backgroundColor="currentColor",e.style.opacity="0.4",e.style.animationDelay="0ms";let 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="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",n.appendChild(e),n.appendChild(t),n.appendChild(r),n.appendChild(o),n},yy=(n,e,t)=>{let r={config:t!=null?t:{},streaming:!0,location:n,defaultRenderer:da};if(e){let o=e(r);if(o!==null)return o}return da()},by=(n,e)=>{let t=v("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=e==="user"?n.userAvatar:n.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=v("img");o.src=r,o.alt=e==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(o)}else t.textContent=r,t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=e==="user"?"U":"A",t.classList.add(e==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},zm=(n,e,t="div")=>{let r=v(t,"persona-text-xs persona-text-persona-muted"),o=new Date(n.createdAt);return e.format?r.textContent=e.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},vy=(n,e="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(e){case"flat":n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),n==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.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 t},wy=(n,e,t)=>{var y,w,E,B,T,I,M;let r=(y=e.showCopy)!=null?y:!0,o=(w=e.showUpvote)!=null?w:!0,s=(E=e.showDownvote)!=null?E:!0,a=(B=e.showReadAloud)!=null?B:!1;if(!r&&!o&&!s&&!a){let P=v("div");return P.style.display="none",P.id=`actions-${n.id}`,P.setAttribute("data-actions-for",n.id),P}let i=(T=e.visibility)!=null?T:"hover",d=(I=e.align)!=null?I:"right",c=(M=e.layout)!=null?M:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],h=v("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${g} ${i==="hover"?"persona-message-actions-hover":""}`);h.id=`actions-${n.id}`,h.setAttribute("data-actions-for",n.id);let m=(P,C,k)=>{let q=wn({icon:P,label:C,size:14,className:"persona-message-action-btn"});return q.setAttribute("data-action",k),q};return r&&h.appendChild(m("copy","Copy message","copy")),a&&h.appendChild(m("volume-2","Read aloud","read-aloud")),o&&h.appendChild(m("thumbs-up","Upvote","upvote")),s&&h.appendChild(m("thumbs-down","Downvote","downvote")),h},rl=(n,e,t,r,o,s)=>{var re,oe,de,Ae,$e,K,J,Se,Y,le,Te,Ye,tt,Wt,ht,ot,me;let a=t!=null?t:{},i=(re=a.layout)!=null?re:"bubble",d=a.avatar,c=a.timestamp,p=(oe=d==null?void 0:d.show)!=null?oe:!1,g=(de=c==null?void 0:c.show)!=null?de:!1,h=(Ae=d==null?void 0:d.position)!=null?Ae:"left",m=($e=c==null?void 0:c.position)!=null?$e:"below",y=vy(n.role,i),w=v("div",y.join(" "));w.id=`bubble-${n.id}`,w.setAttribute("data-message-id",n.id),w.setAttribute("data-persona-theme-zone",n.role==="user"?"user-message":"assistant-message"),n.role==="user"?(w.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",w.style.color="var(--persona-message-user-text, white)"):n.role==="assistant"&&(w.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",w.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=cy(n),B=(J=(K=n.content)==null?void 0:K.trim())!=null?J:"",I=E.length>0&&B===Da,M=Qa((Y=(Se=s==null?void 0:s.widgetConfig)==null?void 0:Se.features)==null?void 0:Y.streamAnimation),P=(Ye=(Te=(le=s==null?void 0:s.widgetConfig)==null?void 0:le.features)==null?void 0:Te.streamAnimation)==null?void 0:Ye.plugins,C=n.role==="assistant"&&M.type!=="none"?xs(M.type,P):null,k=n.role==="assistant"&&((tt=C==null?void 0:C.isAnimating)==null?void 0:tt.call(C,n))===!0,q=n.role==="assistant"&&C!==null&&(!!n.streaming||k);q&&(C!=null&&C.bubbleClass)&&w.classList.add(C.bubbleClass);let _=document.createElement("div");_.classList.add("persona-message-content"),n.streaming&&_.classList.add("persona-content-streaming"),q&&C&&(C.containerClass&&_.classList.add(C.containerClass),_.style.setProperty("--persona-stream-step",`${M.speed}ms`),_.style.setProperty("--persona-stream-duration",`${M.duration}ms`));let R=q?Xa((Wt=n.content)!=null?Wt:"",M.buffer,C,n,!!n.streaming):(ht=n.content)!=null?ht:"",O=e({text:R,message:n,streaming:!!n.streaming,raw:n.rawContent}),F=O;q&&(C==null?void 0:C.wrap)==="char"?F=oa(O,"char",n.id,{skipTags:C.skipTags}):q&&(C==null?void 0:C.wrap)==="word"&&(F=oa(O,"word",n.id,{skipTags:C.skipTags}));let Z=null;if(I?(Z=document.createElement("div"),Z.innerHTML=F,Z.style.display="none",_.appendChild(Z)):_.innerHTML=F,q&&(C!=null&&C.useCaret)&&!I&&B){let X=Ja(),lt=_.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ve=lt[lt.length-1];if(Ve!=null&&Ve.parentNode)Ve.parentNode.insertBefore(X,Ve.nextSibling);else{let Ee=_.lastElementChild;Ee?Ee.appendChild(X):_.appendChild(X)}}if(g&&m==="inline"&&n.createdAt){let X=zm(n,c,"span");X.classList.add("persona-timestamp-inline");let lt=_.lastElementChild;lt?lt.appendChild(X):_.appendChild(X)}if(E.length>0){let X=my(E,!I&&!!B,()=>{I&&Z&&(Z.style.display="")});X?w.appendChild(X):I&&Z&&(Z.style.display="")}let ke=dy(n);if(ke.length>0){let X=gy(ke);X&&w.appendChild(X)}let pe=py(n);if(pe.length>0){let X=fy(pe);X&&w.appendChild(X)}let ee=uy(n);if(ee.length>0){let X=hy(ee);X&&w.appendChild(X)}if(w.appendChild(_),g&&m==="below"&&n.createdAt){let X=zm(n,c);X.classList.add("persona-mt-1"),w.appendChild(X)}let Pe=n.role==="assistant"?ay(n.stopReason,(me=(ot=s==null?void 0:s.widgetConfig)==null?void 0:ot.copy)==null?void 0:me.stopReasonNotice):null;if(n.streaming&&n.role==="assistant"){let X=!!(R&&R.trim()),lt=M.placeholder==="skeleton",Ve=lt&&M.buffer==="line"&&X;if(X)Ve&&w.appendChild(sa());else if(lt)w.appendChild(sa());else{let Ee=yy("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Ee&&w.appendChild(Ee)}}if(Pe&&n.stopReason&&!n.streaming&&(B||(_.style.display="none"),w.appendChild(iy(n.stopReason,Pe))),n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let X=wy(n,r,o);w.appendChild(X)}if(!p||n.role==="system")return w;let ie=v("div",`persona-flex persona-gap-2 ${n.role==="user"?"persona-flex-row-reverse":""}`),he=by(d,n.role);return h==="right"||h==="left"&&n.role==="user"?ie.append(w,he):ie.append(he,w),w.classList.remove("persona-max-w-[85%]"),w.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ie};var As=new Set,xy=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),Cy=(n,e)=>{var r,o;let t=(o=(r=n.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return t?t.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,e).join(`
|
|
28
|
+
`):""},Vm=(n,e)=>{let t=As.has(n),r=e.querySelector('button[data-expand-header="true"]'),o=e.querySelector(".persona-border-t"),s=e.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",t?"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(t?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=t?"Hide":"Show"}o.style.display=t?"":"none",s&&(s.style.display=t?"none":s.textContent||s.childNodes.length?"":"none")},ol=(n,e)=>{var pe,ee,Pe,Ie,ie,he,re,oe,de,Ae,$e;let t=n.reasoning,r=v("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-${n.id}`,r.setAttribute("data-message-id",n.id),!t)return r;let o=(ee=(pe=e==null?void 0:e.features)==null?void 0:pe.reasoningDisplay)!=null?ee:{},s=o.expandable!==!1,a=s&&As.has(n.id),i=t.status!=="complete",d=Cy(n,(Pe=o.previewMaxLines)!=null?Pe:3),c=v("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");c.type="button",s&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let p=v("div","persona-flex persona-flex-col persona-text-left"),g=v("span","persona-text-xs persona-text-persona-primary"),h="Thinking...",m=(Ie=e==null?void 0:e.reasoning)!=null?Ie:{},y=String((ie=t.startedAt)!=null?ie:Date.now()),w=()=>{let K=v("span","");return K.setAttribute("data-tool-elapsed",y),K.textContent=Ra(t),K},E=(he=m.renderCollapsedSummary)==null?void 0:he.call(m,{message:n,reasoning:t,defaultSummary:h,previewText:d,isActive:i,config:e!=null?e:{},elapsed:Ra(t),createElapsedElement:w});typeof E=="string"&&E.trim()?(g.textContent=E,p.appendChild(g)):E instanceof HTMLElement?p.appendChild(E):(g.textContent=h,p.appendChild(g));let B=v("span","persona-text-xs persona-text-persona-primary");B.textContent=zu(t),p.appendChild(B);let T=(re=o.loadingAnimation)!=null?re:"none",I=m.activeTextTemplate,M=m.completeTextTemplate,P=i?I:M,C=E instanceof HTMLElement,k=(K,J,Se)=>{let Y=Se;for(let le of J){let Te=v("span","persona-tool-char");Te.style.setProperty("--char-index",String(Y)),Te.textContent=le===" "?"\xA0":le,K.appendChild(Te),Y++}return Y},q=(K,J)=>{g.textContent="";let Se=Wa(K,""),Y=0;for(let le of Se){let Te=le.styles.length>0?(()=>{let Ye=v("span",le.styles.map(tt=>`persona-tool-text-${tt}`).join(" "));return g.appendChild(Ye),Ye})():g;if(le.isDuration&&i)Te.appendChild(w());else{let Ye=le.isDuration?Ra(t):le.text;J?Y=k(Te,Ye,Y):Te.appendChild(document.createTextNode(Ye))}}};if(!C&&P)if(B.style.display="none",g.style.display="",i&&T!=="none"){let K=(oe=m.loadingAnimationDuration)!=null?oe:2e3;g.setAttribute("data-preserve-animation","true"),T==="pulse"?(g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),q(P,!1)):(g.classList.add(`persona-tool-loading-${T}`),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),T==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),q(P,!0))}else q(P,!1);else if(!C&&i&&T!=="none"){g.style.display="";let K=(de=m.loadingAnimationDuration)!=null?de:2e3;if(g.setAttribute("data-preserve-animation","true"),T==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`);else{g.classList.add(`persona-tool-loading-${T}`),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),T==="shimmer-color"&&(m.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let J=g.textContent||h;g.textContent="",k(g,J,0)}t.status==="complete"&&(g.style.display="none")}else C||(t.status==="complete"?g.style.display="none":g.style.display="");let _=null;if(s){_=v("div","persona-flex persona-items-center");let J=ye(a?"chevron-up":"chevron-down",16,"currentColor",2);J?_.appendChild(J):_.textContent=a?"Hide":"Show";let Se=v("div","persona-flex persona-items-center persona-ml-auto");Se.append(_),c.append(p,Se)}else c.append(p);let R=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(R.setAttribute("data-persona-collapsed-preview","reasoning"),R.style.display="none",R.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let K=($e=(Ae=e==null?void 0:e.reasoning)==null?void 0:Ae.renderCollapsedPreview)==null?void 0:$e.call(Ae,{message:n,reasoning:t,defaultPreview:d,isActive:i,config:e!=null?e:{}});xy(R,K)||(R.textContent=d),R.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,R),r;let O=v("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=t.chunks.join(""),Z=v("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Z.textContent=F||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(Z),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),_){_.innerHTML="";let J=ye(a?"chevron-up":"chevron-down",16,"currentColor",2);J?_.appendChild(J):_.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",R.style.display=a?"none":R.textContent||R.childNodes.length?"":"none"})(),r.append(c,R,O),r};var Ss=new Set,Ay=(n,e)=>e==null?!1:typeof e=="string"?(n.textContent=e,!0):(n.appendChild(e),!0),Sy=(n,e)=>{var s;let t=n.toolCall;if(!t)return"";let r=((s=t.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-e).join(`
|
|
29
|
+
`);let o=bo(t.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,e).join(`
|
|
30
|
+
`):""},sl=(n,e)=>{var t,r,o;n.style.backgroundColor=(t=e.codeBlockBackgroundColor)!=null?t:"var(--persona-container, #f3f4f6)",n.style.borderColor=(r=e.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",n.style.color=(o=e.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},Ty=(n,e)=>{var p,g,h,m,y;let t=n.toolCall,r=(p=e==null?void 0:e.features)==null?void 0:p.toolCallDisplay,o=(g=r==null?void 0:r.collapsedMode)!=null?g:"tool-call",s=Sy(n,(h=r==null?void 0:r.previewMaxLines)!=null?h:3),a=t?ju(t):"";if(!t)return{summary:a,previewText:s,isActive:!1};let i=t.status!=="complete",d=(m=e==null?void 0:e.toolCall)!=null?m:{},c=a;return o==="tool-name"?c=((y=t.name)==null?void 0:y.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=Oi(t,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=Oi(t,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},Km=(n,e,t)=>{var p;let r=Ss.has(n),o=(p=t==null?void 0:t.toolCall)!=null?p:{},s=e.querySelector('button[data-expand-header="true"]'),a=e.querySelector(".persona-border-t"),i=e.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 g=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",h=ye(r?"chevron-up":"chevron-down",16,g,2);h?c.appendChild(h):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},al=(n,e)=>{var F,Z,ke,pe,ee,Pe,Ie,ie,he;let t=n.toolCall,r=(F=e==null?void 0:e.toolCall)!=null?F:{},o=v("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-${n.id}`,o.setAttribute("data-message-id",n.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))",!t)return o;let s=(ke=(Z=e==null?void 0:e.features)==null?void 0:Z.toolCallDisplay)!=null?ke:{},a=s.expandable!==!1,i=a&&Ss.has(n.id),{summary:d,previewText:c,isActive:p}=Ty(n,e),g=v("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");g.type="button",a&&(g.setAttribute("aria-expanded",i?"true":"false"),g.setAttribute("data-expand-header","true")),g.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(g.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(g.style.paddingLeft=r.headerPaddingX,g.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(g.style.paddingTop=r.headerPaddingY,g.style.paddingBottom=r.headerPaddingY);let h=v("div","persona-flex persona-flex-col persona-text-left"),m=v("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(m.style.color=r.headerTextColor);let y=String((pe=t.startedAt)!=null?pe:Date.now()),w=()=>{let re=v("span","");return re.setAttribute("data-tool-elapsed",y),re.textContent=Gs(t),re},E=(Pe=r.renderCollapsedSummary)==null?void 0:Pe.call(r,{message:n,toolCall:t,defaultSummary:d,previewText:c,collapsedMode:(ee=s.collapsedMode)!=null?ee:"tool-call",isActive:p,config:e!=null?e:{},elapsed:Gs(t),createElapsedElement:w});typeof E=="string"&&E.trim()?(m.textContent=E,h.appendChild(m)):E instanceof HTMLElement?h.appendChild(E):(m.textContent=d,h.appendChild(m));let B=(Ie=s.loadingAnimation)!=null?Ie:"none",T=r.activeTextTemplate,I=r.completeTextTemplate,M=p?T:I,P=E instanceof HTMLElement,C=(re,oe,de)=>{let Ae=de;for(let $e of oe){let K=v("span","persona-tool-char");K.style.setProperty("--char-index",String(Ae)),K.textContent=$e===" "?"\xA0":$e,re.appendChild(K),Ae++}return Ae},k=(re,oe)=>{var K;m.textContent="";let de=((K=t.name)==null?void 0:K.trim())||"tool",Ae=Wa(re,de),$e=0;for(let J of Ae){let Se=J.styles.length>0?(()=>{let Y=v("span",J.styles.map(le=>`persona-tool-text-${le}`).join(" "));return m.appendChild(Y),Y})():m;if(J.isDuration&&p)Se.appendChild(w());else{let Y=J.isDuration?Gs(t):J.text;oe?$e=C(Se,Y,$e):Se.appendChild(document.createTextNode(Y))}}};if(!P)if(p&&B!=="none"){let re=(ie=r.loadingAnimationDuration)!=null?ie:2e3;if(m.setAttribute("data-preserve-animation","true"),B==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${re}ms`),M&&k(M,!1);else if(m.classList.add(`persona-tool-loading-${B}`),m.style.setProperty("--persona-tool-anim-duration",`${re}ms`),B==="shimmer-color"&&(r.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),M)k(M,!0);else{let oe=m.textContent||d;m.textContent="",C(m,oe,0)}}else M&&k(M,!1);let q=null;if(a){q=v("div","persona-flex persona-items-center");let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",oe=ye(i?"chevron-up":"chevron-down",16,re,2);oe?q.appendChild(oe):q.textContent=i?"Hide":"Show";let de=v("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");de.append(q),g.append(h,de)}else g.append(h);let _=v("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(_.setAttribute("data-persona-collapsed-preview","tool"),_.style.display="none",_.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&c){let re=(he=r.renderCollapsedPreview)==null?void 0:he.call(r,{message:n,toolCall:t,defaultPreview:c,isActive:p,config:e!=null?e:{}});Ay(_,re)||(_.textContent=c),_.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(g,_),o;let R=v("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),t.name){let re=v("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=t.name,R.appendChild(re)}if(t.args!==void 0){let re=v("div","persona-space-y-1"),oe=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(oe.style.color=r.labelTextColor),oe.textContent="Arguments";let de=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",sl(de,r),de.textContent=bo(t.args),re.append(oe,de),R.appendChild(re)}if(t.chunks&&t.chunks.length){let re=v("div","persona-space-y-1"),oe=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(oe.style.color=r.labelTextColor),oe.textContent="Activity";let de=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",sl(de,r),de.textContent=t.chunks.join(""),re.append(oe,de),R.appendChild(re)}if(t.status==="complete"&&t.result!==void 0){let re=v("div","persona-space-y-1"),oe=v("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(oe.style.color=r.labelTextColor),oe.textContent="Result";let de=v("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");de.style.fontSize="0.75rem",de.style.lineHeight="1rem",sl(de,r),de.textContent=bo(t.result),re.append(oe,de),R.appendChild(re)}if(t.status==="complete"&&typeof t.duration=="number"){let re=v("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(re.style.color=r.contentTextColor),re.textContent=`Duration: ${t.duration}ms`,R.appendChild(re)}return(()=>{if(g.setAttribute("aria-expanded",i?"true":"false"),q){q.innerHTML="";let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",oe=ye(i?"chevron-up":"chevron-down",16,re,2);oe?q.appendChild(oe):q.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",_.style.display=i?"none":_.textContent||_.childNodes.length?"":"none"})(),o.append(g,_,R),o};var jo=new Map,ci=n=>{let t=(n.startsWith(qr)?n.slice(qr.length):n).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(t.length===0)return n;let r=t.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Gm=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,Qm=(n,e)=>{var r,o,s;let t=(o=(r=Gm(e))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=jo.get(n))!=null?s:t==="expanded"},Xm=(n,e,t)=>{var a,i;let r=Gm(t);n.setAttribute("aria-expanded",e?"true":"false");let o=n.querySelector("[data-approval-details-label]");o&&(o.textContent=e?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=n.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=ye(e?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},Jm=(n,e,t)=>{let r=e.querySelector('button[data-bubble-type="approval"]'),o=e.querySelector("[data-approval-details]");if(!r||!o)return;let s=Qm(n,t);Xm(r,s,t),o.style.display=s?"":"none"};var di=(n,e)=>{var k,q,_,R,O,F,Z,ke,pe,ee,Pe,Ie,ie,he,re;let t=n.approval,r=(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,o=(t==null?void 0:t.status)==="pending",s=v("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-${n.id}`,s.setAttribute("data-message-id",n.id),s.style.backgroundColor=(k=r==null?void 0:r.backgroundColor)!=null?k:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(q=r==null?void 0:r.borderColor)!=null?q:"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))",!t)return s;let a=v("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=v("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.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 g=v("div","persona-flex-1 persona-min-w-0"),h=v("div","persona-flex persona-items-center persona-gap-2"),m=v("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(R=r==null?void 0:r.title)!=null?R:"Approval Required",h.appendChild(m),!o){let oe=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");oe.setAttribute("data-approval-status",t.status),t.status==="approved"?(oe.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",oe.style.color="var(--persona-palette-colors-success-700, #15803d)",oe.textContent="Approved"):t.status==="denied"?(oe.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",oe.style.color="var(--persona-palette-colors-error-700, #b91c1c)",oe.textContent="Denied"):t.status==="timeout"&&(oe.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",oe.style.color="var(--persona-palette-colors-warning-700, #b45309)",oe.textContent="Timeout"),h.appendChild(oe)}g.appendChild(h);let w=t.toolType==="webmcp"||t.toolName.startsWith(qr)?qs(t.toolName):void 0,E=(O=r==null?void 0:r.formatDescription)==null?void 0:O.call(r,{toolName:t.toolName,toolType:t.toolType,description:t.description,parameters:t.parameters,...w?{displayTitle:w}:{},...t.reason?{reason:t.reason}:{}}),B=!t.toolName,T=E||(B?t.description:`The assistant wants to use \u201C${w!=null?w:ci(t.toolName)}\u201D.`),I=v("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(I.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(I.style.color=r.descriptionColor),I.textContent=T,g.appendChild(I),t.reason){let oe=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");oe.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?oe.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(oe.style.color=r.descriptionColor);let de=v("span","persona-font-medium");de.textContent=`${(F=r==null?void 0:r.reasonLabel)!=null?F:"Agent's stated reason:"} `,oe.appendChild(de),oe.appendChild(document.createTextNode(t.reason)),g.appendChild(oe)}let M=(Z=r==null?void 0:r.detailsDisplay)!=null?Z:"collapsed",P=!!t.description&&!B,C=P||!!t.parameters;if(M!=="hidden"&&C){let oe=Qm(n.id,e),de=v("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");de.type="button",de.setAttribute("data-expand-header","true"),de.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(de.style.color=r.descriptionColor);let Ae=v("span");Ae.setAttribute("data-approval-details-label","true");let $e=v("span","persona-inline-flex persona-items-center");$e.setAttribute("data-approval-details-chevron","true"),de.append(Ae,$e),Xm(de,oe,e),g.appendChild(de);let K=v("div");if(K.setAttribute("data-approval-details","true"),K.style.display=oe?"":"none",P){let J=v("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(J.style.color=r.descriptionColor),J.textContent=t.description,K.appendChild(J)}if(t.parameters){let J=v("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(J.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(J.style.color=r.parameterTextColor),J.style.fontSize="0.75rem",J.style.lineHeight="1rem",J.textContent=bo(t.parameters),K.appendChild(J)}g.appendChild(K)}if(o){let oe=v("div","persona-flex persona-gap-2 persona-mt-2");oe.setAttribute("data-approval-buttons","true");let de=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");de.type="button",de.style.backgroundColor=(ke=r==null?void 0:r.approveButtonColor)!=null?ke:"var(--persona-approval-approve-bg, #22c55e)",de.style.color=(pe=r==null?void 0:r.approveButtonTextColor)!=null?pe:"#ffffff",de.setAttribute("data-approval-action","approve");let Ae=ye("shield-check",14,(ee=r==null?void 0:r.approveButtonTextColor)!=null?ee:"#ffffff",2);Ae&&(Ae.style.marginRight="4px",de.appendChild(Ae));let $e=document.createTextNode((Pe=r==null?void 0:r.approveLabel)!=null?Pe:"Approve");de.appendChild($e);let K=v("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");K.type="button",K.style.backgroundColor=(Ie=r==null?void 0:r.denyButtonColor)!=null?Ie:"transparent",K.style.color=(ie=r==null?void 0:r.denyButtonTextColor)!=null?ie:"var(--persona-feedback-error, #dc2626)",K.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,K.setAttribute("data-approval-action","deny");let J=ye("shield-x",14,(he=r==null?void 0:r.denyButtonTextColor)!=null?he:"var(--persona-feedback-error, #dc2626)",2);J&&(J.style.marginRight="4px",K.appendChild(J));let Se=document.createTextNode((re=r==null?void 0:r.denyLabel)!=null?re:"Deny");K.appendChild(Se),oe.append(de,K),g.appendChild(oe)}return a.append(i,g),s.appendChild(a),s};function Ey(n){var t,r;let e=(t=n.getRootNode)==null?void 0:t.call(n);return e instanceof ShadowRoot?e:((r=n.ownerDocument)!=null?r:document).body}function Ym(n){var w;let{anchor:e,content:t,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=n,c=(w=n.container)!=null?w:Ey(e),p=!1,g=null,h=()=>{if(!p)return;let E=e.getBoundingClientRect();t.style.position="fixed",s&&(t.style.minWidth=`${E.width}px`);let B=r==="top-start"||r==="top-end"?E.top-o-t.getBoundingClientRect().height:E.bottom+o,T=r==="bottom-end"||r==="top-end"?E.right-t.getBoundingClientRect().width:E.left;t.style.top=`${B}px`,t.style.left=`${T}px`},m=()=>{p&&(p=!1,g&&(g(),g=null),t.remove())},y=()=>{var P,C,k;if(p)return;p=!0,a!=null&&(t.style.zIndex=String(a)),c.appendChild(t),h();let E=(C=((P=e.ownerDocument)!=null?P:document).defaultView)!=null?C:window,B=(k=e.ownerDocument)!=null?k:document,T=()=>{if(!e.isConnected){m(),d==null||d("anchor-removed");return}h()},I=q=>{let _=typeof q.composedPath=="function"?q.composedPath():[];_.includes(t)||_.includes(e)||(m(),d==null||d("outside"))},M=E.setTimeout(()=>{B.addEventListener("pointerdown",I,!0)},0);E.addEventListener("scroll",T,!0),E.addEventListener("resize",T),g=()=>{E.clearTimeout(M),B.removeEventListener("pointerdown",I,!0),E.removeEventListener("scroll",T,!0),E.removeEventListener("resize",T)},i==null||i()};return{get isOpen(){return p},open:y,close:m,toggle:()=>p?m():y(),reposition:h,destroy:m}}function Zm(n){return(typeof n.composedPath=="function"?n.composedPath():[]).some(t=>t instanceof HTMLElement&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable))}var My=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),eg=(n,e)=>{let t=n.keyHandlers.get(e);t&&(document.removeEventListener("keydown",t),n.keyHandlers.delete(e));let r=n.popovers.get(e);r&&(r.destroy(),n.popovers.delete(e))},Vo=(n,e)=>{eg(n,e);let t=n.pendingOrder.indexOf(e);t!==-1&&n.pendingOrder.splice(t,1),n.latestPendingApprovalId===e&&(n.latestPendingApprovalId=n.pendingOrder.length?n.pendingOrder[n.pendingOrder.length-1]:null)},ky=n=>(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,Ly=(n,e)=>{var r,o;let t=(r=e==null?void 0:e.detailsDisplay)!=null?r:"collapsed";return(o=jo.get(n))!=null?o:t==="expanded"},il=n=>{let e=v("span","persona-approval-kbd");return e.textContent=n,e},Py=(n,e)=>{var c,p;let t=v("span","persona-approval-title");e!=null&&e.titleColor&&(t.style.color=e.titleColor);let o=n.toolType==="webmcp"||n.toolName.startsWith(qr)?qs(n.toolName):void 0,s=(p=e==null?void 0:e.formatDescription)==null?void 0:p.call(e,{toolName:n.toolName,toolType:n.toolType,description:(c=n.description)!=null?c:"",parameters:n.parameters,...o?{displayTitle:o}:{},...n.reason?{reason:n.reason}:{}});if(s)return t.textContent=s,t;let a=o!=null?o:ci(n.toolName),i=n.toolType&&n.toolType!=="webmcp"?n.toolType:null;t.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,t.appendChild(d),i){t.append(" from ");let g=document.createElement("strong");g.textContent=i,t.appendChild(g)}return t},Iy=n=>{let e=v("div","persona-approval-resolved"),t=ye("ban",15,"currentColor",2);t&&e.appendChild(t);let r=v("span","persona-approval-resolved-name");return r.textContent=n.toolName?ci(n.toolName):"Tool",e.append(r,document.createTextNode(n.status==="timeout"?" timed out":" denied")),e},Ry=(n,e,t,r,o,s,a)=>{var q,_,R,O,F,Z,ke;let i=v("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${e.id}`,i.setAttribute("data-message-id",e.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=(q=r==null?void 0:r.detailsDisplay)!=null?q:"collapsed",c=!!t.description&&d!=="hidden",p=t.parameters!=null&&d!=="hidden",g=c||p,h=g&&Ly(e.id,r),m=(_=r==null?void 0:r.showDetailsLabel)!=null?_:"Show details",y=(R=r==null?void 0:r.hideDetailsLabel)!=null?R:"Hide details",w=v("button","persona-approval-head");w.type="button",g?(w.setAttribute("data-action","toggle-params"),w.setAttribute("aria-expanded",h?"true":"false"),w.setAttribute("aria-label",h?y:m)):w.setAttribute("data-static","true");let E=v("span","persona-approval-logo"),B=ye("shield-check",16,"currentColor",2);B&&E.appendChild(B),w.appendChild(E);let T=Py(t,r);if(g){let pe=v("span","persona-approval-toggle");pe.setAttribute("aria-hidden","true");let ee=ye("chevron-down",14,"currentColor",2);ee&&pe.appendChild(ee),T.append(" "),T.appendChild(pe)}w.appendChild(T),i.appendChild(w);let I=v("div","persona-approval-body");if(g){let pe=v("div","persona-approval-details");if(pe.setAttribute("data-role","params"),pe.hidden=!h,c){let ee=v("p","persona-approval-desc");r!=null&&r.descriptionColor&&(ee.style.color=r.descriptionColor),ee.textContent=t.description,pe.appendChild(ee)}if(p){let ee=v("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(ee.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ee.style.color=r.parameterTextColor),ee.textContent=bo(t.parameters),pe.appendChild(ee)}I.appendChild(pe)}if(t.reason){let pe=v("p","persona-approval-reason");r!=null&&r.reasonColor?pe.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(pe.style.color=r.descriptionColor);let ee=v("span","persona-approval-reason-label");ee.textContent=`${(O=r==null?void 0:r.reasonLabel)!=null?O:"Agent's stated reason:"} `,pe.append(ee,document.createTextNode(t.reason)),I.appendChild(pe)}let M=v("div","persona-approval-actions"),P=null,C=pe=>{r!=null&&r.approveButtonColor&&(pe.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(pe.style.color=r.approveButtonTextColor)},k=v("button","persona-approval-deny");if(k.type="button",k.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(k.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(k.style.color=r.denyButtonTextColor),k.append((F=r==null?void 0:r.denyLabel)!=null?F:"Deny"),a){let pe=v("div","persona-approval-split"),ee=v("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",il("\u23CE"));let Pe=v("button","persona-approval-caret");Pe.type="button",Pe.setAttribute("data-action","toggle-menu"),Pe.setAttribute("aria-label","More options"),C(Pe);let Ie=ye("chevron-down",15,"currentColor",2);Ie&&Pe.appendChild(Ie),pe.append(ee,Pe),M.append(pe,k),k.append(il("Esc"));let ie=v("div","persona-approval-menu"),he=v("button","persona-approval-menu-item");he.type="button",he.append("Allow once",il("\u2318\u23CE")),ie.appendChild(he),P=Ym({anchor:pe,content:ie,placement:"bottom-start",matchAnchorWidth:!0}),n.popovers.set(e.id,P),he.addEventListener("click",()=>{Vo(n,e.id),o()})}else{let pe=v("button","persona-approval-primary persona-approval-primary--solo");pe.type="button",pe.setAttribute("data-action","allow"),C(pe),pe.append((ke=r==null?void 0:r.approveLabel)!=null?ke:"Allow"),M.append(pe,k)}return I.appendChild(M),i.appendChild(I),i.addEventListener("click",pe=>{let ee=pe.target instanceof Element?pe.target.closest("[data-action]"):null;if(!ee)return;let Pe=ee.getAttribute("data-action");if(Pe==="toggle-params"){let Ie=i.querySelector('[data-role="params"]');if(Ie){let ie=Ie.hidden;Ie.hidden=!ie,w.setAttribute("aria-expanded",ie?"true":"false"),w.setAttribute("aria-label",ie?y:m),jo.set(e.id,ie)}return}if(Pe==="toggle-menu"){P==null||P.toggle();return}if(Pe==="always"){Vo(n,e.id),o({remember:!0});return}if(Pe==="allow"){Vo(n,e.id),o();return}if(Pe==="deny"){Vo(n,e.id),s();return}}),i},tg=()=>{let n=My();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=ky(a);if(i.status!=="pending"){if(Vo(n,r.id),i.status==="approved"){let g=document.createElement("div");return g.style.display="none",g}return Iy(i)}eg(n,r.id);let c=(d==null?void 0:d.enableAlwaysAllow)===!0,p=Ry(n,r,i,d,o,s,c);if(c){n.pendingOrder.includes(r.id)||n.pendingOrder.push(r.id),n.latestPendingApprovalId=n.pendingOrder[n.pendingOrder.length-1];let g=h=>{Zm(h)||r.id===n.latestPendingApprovalId&&(h.key!=="Escape"&&h.key!=="Enter"||(h.preventDefault(),h.stopImmediatePropagation(),Vo(n,r.id),h.key==="Escape"?s():h.metaKey||h.ctrlKey?o():o({remember:!0})))};n.keyHandlers.set(r.id,g),document.addEventListener("keydown",g)}return p}},teardown:()=>{for(let r of[...n.keyHandlers.keys(),...n.popovers.keys()])Vo(n,r);n.latestPendingApprovalId=null}}};var ng=n=>{let e=[],t=null;return{buttons:e,render:(o,s,a,i,d,c)=>{n.innerHTML="",e.length=0;let p=(c==null?void 0:c.agentPushed)===!0;if(p||(t=null),!o||!o.length||!p&&(i!=null?i:s?s.getMessages():[]).some(E=>E.role==="user"))return;let g=document.createDocumentFragment(),h=s?s.isStreaming():!1,m=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 w=v("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");w.type="button",w.textContent=y,w.disabled=h,d!=null&&d.fontFamily&&(w.style.fontFamily=m(d.fontFamily)),d!=null&&d.fontWeight&&(w.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(w.style.paddingLeft=d.paddingX,w.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(w.style.paddingTop=d.paddingY,w.style.paddingBottom=d.paddingY),w.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",p&&n.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:y},bubbles:!0,composed:!0})),s.sendMessage(y))}),g.appendChild(w),e.push(w)}),n.appendChild(g),p){let y=JSON.stringify(o);y!==t&&(t=y,n.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var pa=class{constructor(e=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=e,this.buffer=new Array(e),this.store=t}push(e){var t;this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(e.type),(t=this.store)==null||t.put(e)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let e=await this.store.getAll();if(e.length===0)return 0;let t=e.length>this.maxSize?e.slice(e.length-this.maxSize):e;for(let r of t)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=e.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(e){let t=this.getAll();return e>=t.length?t:t.slice(t.length-e)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var e;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.clear()}destroy(){var e;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(e=this.store)==null||e.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ua=class{constructor(e="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=e,this.storeName=t}open(){return new Promise((e,t)=>{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,e()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(e){!this.db||this.isDestroyed||(this.pendingWrites.push(e),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(e){if(!(!this.db||this.isDestroyed||e.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}getAll(){return new Promise((e,t)=>{if(!this.db){e([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{e(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((e,t)=>{if(!this.db){e(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{e(s.result)},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}clear(){return new Promise((e,t)=>{if(!this.db){e();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{e()},s.onerror=()=>{t(s.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((e,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{e()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let e=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of e)r.put(o)}catch{}}};var Wy=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Hy=new Set(["step_start","execution_start"]),By=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Dy=new Set(["step_complete","agent_turn_complete"]),Ny=new Set(["flow_complete","agent_complete"]),rg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),sg=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),jn=n=>typeof n=="number"&&Number.isFinite(n)?n:void 0,Ko=(n,e)=>{let t=n[e];return sg(t)?t:void 0};function ll(n){return n>0?Math.max(1,Math.ceil(n/4)):0}function pi(n,e){if(!(n<=0||e===void 0||e<250))return n/(e/1e3)}function Fy(n,e){return typeof e.type=="string"?e.type:n}function Oy(n){return typeof n.text=="string"?n.text:typeof n.delta=="string"?n.delta:typeof n.content=="string"?n.content:typeof n.chunk=="string"?n.chunk:""}function _y(n,e){return n==="step_delta"||n==="step_chunk"?e.stepType!=="tool"&&e.executionType!=="context":n!=="agent_turn_delta"?!0:(typeof e.contentType=="string"?e.contentType:typeof e.content_type=="string"?e.content_type:void 0)==="text"}function og(n){var r,o,s,a,i;let e=Ko(n,"result"),t=[Ko(n,"tokens"),Ko(n,"totalTokens"),e?Ko(e,"tokens"):void 0,Ko(n,"usage"),e?Ko(e,"usage"):void 0];for(let d of t){if(!d)continue;let c=(o=(r=jn(d.output))!=null?r:jn(d.outputTokens))!=null?o:jn(d.completionTokens);if(c!==void 0)return c}return(i=(s=jn(n.outputTokens))!=null?s:jn(n.completionTokens))!=null?i:e?(a=jn(e.outputTokens))!=null?a:jn(e.completionTokens):void 0}function $y(n){var t,r,o,s,a;let e=Ko(n,"result");return(a=(o=(r=(t=jn(n.executionTime))!=null?t:jn(n.executionTimeMs))!=null?r:jn(n.execution_time))!=null?o:jn(n.duration))!=null?a:e?(s=jn(e.executionTime))!=null?s:jn(e.executionTimeMs):void 0}function Uy(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ma=class{constructor(e=Uy){this.metric={status:"idle"};this.run=null;this.now=e}getMetric(){let e=this.run;if(e&&this.metric.status==="running"&&e.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let t=this.now()-e.firstDeltaAt;return{...this.metric,durationMs:t,tokensPerSecond:pi(this.metric.outputTokens,t)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(e){this.run={startedAt:e,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(e,t){var s;if(!sg(t)){rg.has(e)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Fy(e,t),o=this.now();if(Wy.has(r)){this.startRun(o);return}if(Hy.has(r)){this.run||this.startRun(o);return}if(By.has(r)){if(!_y(r,t))return;let a=Oy(t);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+ll(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:pi(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Dy.has(r)){if(!this.run)return;let a=this.run,i=og(t);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+ll(a.visibleCharCount),p=this.resolveDuration(a,t,o);this.metric={status:"running",tokensPerSecond:pi(c,p),outputTokens:c,durationMs:p,source:d?"usage":"estimate"};return}if(Ny.has(r)){if(!this.run)return;let a=this.run,i=og(t),d=i!=null?i:a.exactOutputTokens+ll(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,t,o);this.metric={status:"complete",tokensPerSecond:pi(d,p),outputTokens:d,durationMs:p,source:c},this.run=null;return}if(rg.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(e,t,r){let o=e.firstDeltaAt!==void 0?r-e.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=$y(t);return s!=null?s:r-e.startedAt}};function Ts(n,e){e&&e.split(/\s+/).forEach(t=>t&&n.classList.add(t))}var qy={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},zy={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},jy=["flowName","stepName","reasoningText","text","name","tool","toolName"],Vy=100;function Ky(n,e){let t={...qy,...e};if(t[n])return t[n];for(let r of Object.keys(t))if(r.endsWith("_")&&n.startsWith(r))return t[r];return zy}function Gy(n,e){return`+${((n-e)/1e3).toFixed(3)}s`}function Qy(n){let e=new Date(n),t=String(e.getHours()).padStart(2,"0"),r=String(e.getMinutes()).padStart(2,"0"),o=String(e.getSeconds()).padStart(2,"0"),s=String(e.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${o}.${s}`}function Xy(n,e){try{let t=JSON.parse(n);if(typeof t!="object"||t===null)return null;for(let r of e){let o=r.split("."),s=t;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 Jy(n){var e;return(e=navigator.clipboard)!=null&&e.writeText?navigator.clipboard.writeText(n):new Promise(t=>{let r=document.createElement("textarea");r.value=n,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function Yy(n){let e;try{e=JSON.parse(n.payload)}catch{e=n.payload}return JSON.stringify({type:n.type,timestamp:new Date(n.timestamp).toISOString(),payload:e},null,2)}function Zy(n){return n.tokensPerSecond===void 0||!Number.isFinite(n.tokensPerSecond)?"-- tok/s":`${n.tokensPerSecond.toFixed(1)} tok/s`}function eb(n){let e=[];return n.outputTokens!==void 0&&e.push(`${n.outputTokens.toLocaleString()} tok`),n.durationMs!==void 0&&e.push(`${(n.durationMs/1e3).toFixed(2)}s`),n.source&&e.push(n.source),e.join(" \xB7 ")}function tb(n,e,t){let r,o;try{o=JSON.parse(n.payload),r=JSON.stringify(o,null,2)}catch{o=n.payload,r=n.payload}let s=e.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&t){let i=s.renderEventStreamPayload({event:n,config:t,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=v("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=v("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function cl(n,e,t,r,o,s,a,i){var h;let d=o.has(n.id),c=v("div","persona-border-b persona-border-persona-divider persona-text-xs");Ts(c,(h=r.classNames)==null?void 0:h.eventRow);let p=a.find(m=>m.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let m=p.renderEventStreamRow({event:n,index:e,config:i,defaultRenderer:()=>g(),isExpanded:d,onToggleExpand:()=>s(n.id)});if(m)return c.appendChild(m),c}return c.appendChild(g()),c;function g(){var F,Z;let m=v("div",""),y=v("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");y.setAttribute("data-event-id",n.id);let w=v("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=ye(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&w.appendChild(E);let B=v("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),T=(F=r.timestampFormat)!=null?F:"relative";B.textContent=T==="relative"?Gy(n.timestamp,t):Qy(n.timestamp);let I=null;r.showSequenceNumbers!==!1&&(I=v("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),I.textContent=String(e+1));let M=Ky(n.type,r.badgeColors),P=v("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");P.style.backgroundColor=M.bg,P.style.color=M.text,P.style.borderColor=M.text+"50",P.textContent=n.type;let C=(Z=r.descriptionFields)!=null?Z:jy,k=Xy(n.payload,C),q=null;k&&(q=v("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),q.textContent=k);let _=v("div","persona-flex-1 persona-min-w-0"),R=v("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),O=ye("clipboard","12px","currentColor",1.5);return O&&R.appendChild(O),R.addEventListener("click",async ke=>{ke.stopPropagation(),await Jy(Yy(n)),R.innerHTML="";let pe=ye("check","12px","currentColor",1.5);pe&&R.appendChild(pe),setTimeout(()=>{R.innerHTML="";let ee=ye("clipboard","12px","currentColor",1.5);ee&&R.appendChild(ee)},1500)}),y.appendChild(w),y.appendChild(B),I&&y.appendChild(I),y.appendChild(P),q&&y.appendChild(q),y.appendChild(_),y.appendChild(R),m.appendChild(y),d&&m.appendChild(tb(n,a,i)),m}}function ag(n){var y,w,E,B,T;let{buffer:e,getFullHistory:t,onClose:r,config:o,plugins:s=[],getThroughput:a}=n,i=(y=o==null?void 0:o.features)==null?void 0:y.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(w=i==null?void 0:i.iconName)!=null?w:"arrow-down",p=(E=i==null?void 0:i.label)!=null?E:"",g=(T=(B=o==null?void 0:o.features)==null?void 0:B.eventStream)!=null?T:{},h=s.find(I=>I.renderEventStreamView);if(h!=null&&h.renderEventStreamView&&o){let I=h.renderEventStreamView({config:o,events:e.getAll(),defaultRenderer:()=>m().element,onClose:r});if(I)return{element:I,update:()=>{},destroy:()=>{}}}return m();function m(){let I=g.classNames,M=v("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ts(M,I==null?void 0:I.panel);let P=[],C="",k="",q=null,_=[],R={},O=0,F=Va(),Z=0,ke=0,pe=!1,ee=null,Pe=!1,Ie=0,ie=new Set,he=new Map,re="",oe="",de=null,Ae,$e,K,J,Se=null,Y=null,le=null;function Te(){let fe=v("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),D=v("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Ts(D,I==null?void 0:I.headerBar),a){Y=v("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),Y.style.cursor="help",Se=v("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Se.textContent="-- tok/s",le=v("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),le.style.display="none",le.style.pointerEvents="none";let Ot=Y,en=le,br=()=>{if(!en.textContent)return;let rr=Ot.getBoundingClientRect(),or=fe.getBoundingClientRect();en.style.left=`${rr.left-or.left}px`,en.style.top=`${rr.bottom-or.top+4}px`,en.style.display="block"},Wr=()=>{en.style.display="none"};Y.addEventListener("mouseenter",br),Y.addEventListener("mouseleave",Wr),Y.appendChild(Se)}let ve=v("div","persona-flex-1");Ae=v("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let ce=v("option","");ce.value="",ce.textContent="All events (0)",Ae.appendChild(ce),$e=v("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),$e.type="button",$e.title="Copy All";let Ge=ye("clipboard-copy","12px","currentColor",1.5);Ge&&$e.appendChild(Ge);let Pt=v("span","persona-event-copy-all persona-text-xs");Pt.textContent="Copy All",$e.appendChild(Pt),Y&&D.appendChild(Y),D.appendChild(ve),D.appendChild(Ae),D.appendChild($e);let kt=v("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ts(kt,I==null?void 0:I.searchBar);let wt=ye("search","14px","var(--persona-muted, #9ca3af)",1.5),Ht=v("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");wt&&Ht.appendChild(wt),K=v("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Ts(K,I==null?void 0:I.searchInput),K.type="text",K.placeholder="Search event payloads...",J=v("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),J.type="button",J.style.display="none";let Xt=ye("x","12px","currentColor",2);return Xt&&J.appendChild(Xt),kt.appendChild(Ht),kt.appendChild(K),kt.appendChild(J),fe.appendChild(D),fe.appendChild(kt),le&&fe.appendChild(le),fe}let Ye,tt=s.find(fe=>fe.renderEventStreamToolbar);if(tt!=null&&tt.renderEventStreamToolbar&&o){let fe=tt.renderEventStreamToolbar({config:o,defaultRenderer:()=>Te(),eventCount:e.getSize(),filteredCount:0,onFilterChange:D=>{C=D,be(),At()},onSearchChange:D=>{k=D,be(),At()}});Ye=fe!=null?fe:Te()}else Ye=Te();let Wt=v("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");Wt.style.display="none";function ht(){if(!a||!Se||!Y)return;let fe=a(),D=Zy(fe);Se.textContent=D;let ve=eb(fe);le&&(le.textContent=ve,ve||(le.style.display="none")),Y.setAttribute("aria-label",ve?`Throughput: ${D}, ${ve}`:`Throughput: ${D}`)}let ot=v("div","persona-flex-1 persona-min-h-0 persona-relative"),me=v("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");me.style.height="100%";let X=v("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Ts(X,I==null?void 0:I.scrollIndicator),X.style.display="none",X.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let lt=ye(c,"14px","currentColor",2);lt&&X.appendChild(lt);let Ve=v("span","");Ve.textContent=p,X.appendChild(Ve);let Ee=v("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ee.style.display="none",ot.appendChild(me),ot.appendChild(Ee),ot.appendChild(X),M.setAttribute("tabindex","0"),M.appendChild(Ye),M.appendChild(Wt),M.appendChild(ot);function xe(){let fe=e.getAll(),D={};for(let kt of fe)D[kt.type]=(D[kt.type]||0)+1;let ve=Object.keys(D).sort(),ce=ve.length!==_.length||!ve.every((kt,wt)=>kt===_[wt]),ft=!ce&&ve.some(kt=>D[kt]!==R[kt]),Ge=fe.length!==Object.values(R).reduce((kt,wt)=>kt+wt,0);if(!ce&&!ft&&!Ge||(_=ve,R=D,!Ae))return;let Pt=Ae.value;if(Ae.options[0].textContent=`All events (${fe.length})`,ce){for(;Ae.options.length>1;)Ae.remove(1);for(let kt of ve){let wt=v("option","");wt.value=kt,wt.textContent=`${kt} (${D[kt]||0})`,Ae.appendChild(wt)}Pt&&ve.includes(Pt)?Ae.value=Pt:Pt&&(Ae.value="",C="")}else for(let kt=1;kt<Ae.options.length;kt++){let wt=Ae.options[kt];wt.textContent=`${wt.value} (${D[wt.value]||0})`}}function Ze(){let fe=e.getAll();if(C&&(fe=fe.filter(D=>D.type===C)),k){let D=k.toLowerCase();fe=fe.filter(ve=>ve.type.toLowerCase().includes(D)||ve.payload.toLowerCase().includes(D))}return fe}function jt(){return C!==""||k!==""}function be(){O=0,Z=0,F.resume(),X.style.display="none"}function ue(fe){ie.has(fe)?ie.delete(fe):ie.add(fe),de=fe;let D=me.scrollTop,ve=F.isFollowing();Pe=!0,F.pause(),At(),me.scrollTop=D,ve&&F.resume(),Pe=!1}function xn(){return vo(me,50)}function At(){ke=Date.now(),pe=!1,ht(),xe();let fe=e.getEvictedCount();fe>0?(Wt.textContent=`${fe.toLocaleString()} older events truncated`,Wt.style.display=""):Wt.style.display="none",P=Ze();let D=P.length,ve=e.getSize()>0;D===0&&ve&&jt()?(Ee.textContent=k?`No events matching '${k}'`:"No events matching filter",Ee.style.display="",me.style.display="none"):(Ee.style.display="none",me.style.display=""),$e&&($e.title=jt()?`Copy Filtered (${D})`:"Copy All"),d&&!F.isFollowing()&&D>O&&(Z+=D-O,Ve.textContent=p?`${p}${Z>0?` (${Z})`:""}`:"",X.style.display=""),O=D;let ce=e.getAll(),ft=ce.length>0?ce[0].timestamp:0,Ge=new Set(P.map(wt=>wt.id));for(let wt of ie)Ge.has(wt)||ie.delete(wt);let Pt=C!==re||k!==oe,kt=he.size===0&&P.length>0;if(Pt||kt||P.length===0){me.innerHTML="",he.clear();let wt=document.createDocumentFragment();for(let Ht=0;Ht<P.length;Ht++){let Xt=cl(P[Ht],Ht,ft,g,ie,ue,s,o);he.set(P[Ht].id,Xt),wt.appendChild(Xt)}me.appendChild(wt),re=C,oe=k,de=null}else{if(de!==null){let Ht=he.get(de);if(Ht&&Ht.parentNode===me){let Xt=P.findIndex(Ot=>Ot.id===de);if(Xt>=0){let Ot=cl(P[Xt],Xt,ft,g,ie,ue,s,o);me.insertBefore(Ot,Ht),Ht.remove(),he.set(de,Ot)}}de=null}let wt=new Set(P.map(Ht=>Ht.id));for(let[Ht,Xt]of he)wt.has(Ht)||(Xt.remove(),he.delete(Ht));for(let Ht=0;Ht<P.length;Ht++){let Xt=P[Ht];if(!he.has(Xt.id)){let Ot=cl(Xt,Ht,ft,g,ie,ue,s,o);he.set(Xt.id,Ot),me.appendChild(Ot)}}}F.isFollowing()&&(me.scrollTop=me.scrollHeight)}function fn(){if(Date.now()-ke>=Vy){ee!==null&&(cancelAnimationFrame(ee),ee=null),At();return}pe||(pe=!0,ee=requestAnimationFrame(()=>{ee=null,At()}))}let hr=(fe,D)=>{if(!$e)return;$e.innerHTML="";let ve=ye(fe,"12px","currentColor",1.5);ve&&$e.appendChild(ve);let ce=v("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 Ge=v("span","persona-text-xs");Ge.textContent="Copy All",$e.appendChild(Ge),$e.disabled=!1},D)},yr=async()=>{if($e){$e.disabled=!0;try{let fe;jt()?fe=P:t?(fe=await t(),fe.length===0&&(fe=e.getAll())):fe=e.getAll();let D=fe.map(ve=>{try{return JSON.parse(ve.payload)}catch{return ve.payload}});await navigator.clipboard.writeText(JSON.stringify(D,null,2)),hr("check",1500)}catch{hr("x",1500)}}},qe=()=>{Ae&&(C=Ae.value,be(),At())},L=()=>{!K||!J||(J.style.display=K.value?"":"none",q&&clearTimeout(q),q=setTimeout(()=>{k=K.value,be(),At()},150))},ge=()=>{!K||!J||(K.value="",k="",J.style.display="none",q&&clearTimeout(q),be(),At())},Me=()=>{if(Pe)return;let fe=me.scrollTop,{action:D,nextLastScrollTop:ve}=Ka({following:F.isFollowing(),currentScrollTop:fe,lastScrollTop:Ie,nearBottom:xn(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Ie=ve,D==="resume"?(F.resume(),Z=0,X.style.display="none"):D==="pause"&&(F.pause(),d&&(Ve.textContent=p,X.style.display=""))},Le=fe=>{let D=Ga({following:F.isFollowing(),deltaY:fe.deltaY,nearBottom:xn(),resumeWhenNearBottom:!0});D==="pause"?(F.pause(),d&&(Ve.textContent=p,X.style.display="")):D==="resume"&&(F.resume(),Z=0,X.style.display="none")},He=()=>{d&&(me.scrollTop=me.scrollHeight,F.resume(),Z=0,X.style.display="none")},nt=fe=>{let D=fe.target;if(!D||D.closest("button"))return;let ve=D.closest("[data-event-id]");if(!ve)return;let ce=ve.getAttribute("data-event-id");ce&&ue(ce)},Xe=fe=>{if((fe.metaKey||fe.ctrlKey)&&fe.key==="f"){fe.preventDefault(),K==null||K.focus(),K==null||K.select();return}fe.key==="Escape"&&(K&&document.activeElement===K?(ge(),K.blur(),M.focus()):r&&r())};$e&&$e.addEventListener("click",yr),Ae&&Ae.addEventListener("change",qe),K&&K.addEventListener("input",L),J&&J.addEventListener("click",ge),me.addEventListener("scroll",Me),me.addEventListener("wheel",Le,{passive:!0}),me.addEventListener("click",nt),X.addEventListener("click",He),M.addEventListener("keydown",Xe);function yt(){q&&clearTimeout(q),ee!==null&&(cancelAnimationFrame(ee),ee=null),pe=!1,he.clear(),$e&&$e.removeEventListener("click",yr),Ae&&Ae.removeEventListener("change",qe),K&&K.removeEventListener("input",L),J&&J.removeEventListener("click",ge),me.removeEventListener("scroll",Me),me.removeEventListener("wheel",Le),me.removeEventListener("click",nt),X.removeEventListener("click",He),M.removeEventListener("keydown",Xe)}return{element:M,update:fn,destroy:yt}}}function ig(n,e){let t=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",r=typeof n.artifactId=="string"?n.artifactId:"",o=n.status==="streaming"?"streaming":"complete",a=(typeof n.artifactType=="string"?n.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 ${t} 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=t;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let h=document.createElement("span");h.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",h.style.backgroundColor="var(--persona-primary, #171717)",h.style.animation="persona-pulse 1.5s ease-in-out infinite",g.appendChild(h);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,g.appendChild(m)}else g.textContent=a;if(c.append(p,g),i.append(d,c),o==="complete"){let h=document.createElement("button");h.type="button",h.textContent="Download",h.title=`Download ${t}`,h.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",h.style.border="1px solid var(--persona-border, #e5e7eb)",h.style.color="var(--persona-text, #1f2937)",h.style.backgroundColor="transparent",h.style.cursor="pointer",h.setAttribute("data-download-artifact",r),i.append(h)}return i}var lg=(n,e)=>{var r,o,s;let t=(s=(o=(r=e==null?void 0:e.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(t){let a=typeof n.title=="string"&&n.title?n.title:"Untitled artifact",i=typeof n.artifactId=="string"?n.artifactId:"",d=n.status==="streaming"?"streaming":"complete",c=typeof n.artifactType=="string"?n.artifactType:"markdown",p=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:e.config,defaultRenderer:()=>ig(n,e)});if(p)return p}return ig(n,e)};var dl=class{constructor(){this.components=new Map}register(e,t){this.components.has(e)&&console.warn(`[ComponentRegistry] Component "${e}" is already registered. Overwriting.`),this.components.set(e,t)}unregister(e){this.components.delete(e)}get(e){return this.components.get(e)}has(e){return this.components.has(e)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(e){Object.entries(e).forEach(([t,r])=>{this.register(t,r)})}},Go=new dl;Go.register("PersonaArtifactCard",lg);function nb(n){var o;let e=v("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=v("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=n.component?`Component: ${n.component}`:"Component";let r=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=n.props)!=null?o:{},null,2),e.appendChild(t),e.appendChild(r),e}function cg(n,e){var $e,K,J,Se;let t=(K=($e=n.features)==null?void 0:$e.artifacts)==null?void 0:K.layout,o=((J=t==null?void 0:t.toolbarPreset)!=null?J:"default")==="document",s=(Se=t==null?void 0:t.panePadding)==null?void 0:Se.trim(),a=n.markdown?Sa(n.markdown):null,i=Ta(n.sanitize),d=Y=>{let le=a?a(Y):go(Y);return i?i(le):le},c=typeof document!="undefined"?v("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"),g.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};c&&c.addEventListener("click",()=>{var Y;p(),(Y=e.onDismiss)==null||Y.call(e)});let g=v("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");g.setAttribute("data-persona-theme-zone","artifact-pane"),o&&g.classList.add("persona-artifact-pane-document");let h=v("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");h.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&h.classList.add("persona-artifact-toolbar-document");let m=v("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let y=v("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 Y;p(),(Y=e.onDismiss)==null||Y.call(e)});let w="rendered",E=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),B=o?wn({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):wn({icon:"eye",label:"Rendered view"}),T=o?wn({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):wn({icon:"code-2",label:"Source"}),I=v("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),M=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,P=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,C=t==null?void 0:t.documentToolbarCopyMenuItems,k=!!(P&&C&&C.length>0),q=null,_,R=null,O=null;if(o&&(M||P)&&!k){if(_=M?Yi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):wn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let Y=ye("chevron-down",14,"currentColor",2);Y&&_.appendChild(Y)}}else o&&k?(q=v("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),_=M?Yi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):wn({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=wn({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),q.append(_,R)):o?_=wn({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):_=wn({icon:"copy",label:"Copy"});let F=o?wn({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):wn({icon:"refresh-cw",label:"Refresh"}),Z=o?wn({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):wn({icon:"x",label:"Close"}),ke=()=>{var tt,Wt,ht;let Y=(tt=he.find(ot=>ot.id===re))!=null?tt:he[he.length-1],le=(Wt=Y==null?void 0:Y.id)!=null?Wt:null,Te=(Y==null?void 0:Y.artifactType)==="markdown"&&(ht=Y.markdown)!=null?ht:"",Ye=Y?JSON.stringify({component:Y.component,props:Y.props},null,2):"";return{markdown:Te,jsonPayload:Ye,id:le}},pe=async()=>{var tt;let{markdown:Y,jsonPayload:le}=ke(),Te=(tt=he.find(Wt=>Wt.id===re))!=null?tt:he[he.length-1],Ye=(Te==null?void 0:Te.artifactType)==="markdown"?Y:Te?le:"";try{await navigator.clipboard.writeText(Ye)}catch{}};if(_.addEventListener("click",async()=>{let Y=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(Y&&k){let{markdown:le,jsonPayload:Te,id:Ye}=ke();try{await Y({actionId:"primary",artifactId:Ye,markdown:le,jsonPayload:Te})}catch{}return}await pe()}),R&&(C!=null&&C.length)){let Y=()=>{var Te;return(Te=g.closest("[data-persona-root]"))!=null?Te:document.body},le=()=>{O=Cs({items:C.map(Te=>({id:Te.id,label:Te.label})),onSelect:async Te=>{let{markdown:Ye,jsonPayload:tt,id:Wt}=ke(),ht=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{ht?await ht({actionId:Te,artifactId:Wt,markdown:Ye,jsonPayload:tt}):Te==="markdown"||Te==="md"?await navigator.clipboard.writeText(Ye):Te==="json"||Te==="source"?await navigator.clipboard.writeText(tt):await navigator.clipboard.writeText(Ye||tt)}catch{}},anchor:q!=null?q:R,position:"bottom-right",portal:Y()})};g.isConnected?le():requestAnimationFrame(le),R.addEventListener("click",Te=>{Te.stopPropagation(),O==null||O.toggle()})}F.addEventListener("click",async()=>{var Y;try{await((Y=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:Y.call(t))}catch{}de()}),Z.addEventListener("click",()=>{var Y;p(),(Y=e.onDismiss)==null||Y.call(e)});let ee=()=>{o&&(B.setAttribute("aria-pressed",w==="rendered"?"true":"false"),T.setAttribute("aria-pressed",w==="source"?"true":"false"))};B.addEventListener("click",()=>{w="rendered",ee(),de()}),T.addEventListener("click",()=>{w="source",ee(),de()});let Pe=v("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(h.replaceChildren(),E.append(B,T),q?I.append(q,F,Z):I.append(_,F,Z),h.append(E,Pe,I),ee()):(h.appendChild(m),h.appendChild(y)),s&&(h.style.paddingLeft=s,h.style.paddingRight=s);let Ie=v("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),ie=v("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Ie.style.paddingLeft=s,Ie.style.paddingRight=s,ie.style.padding=s),g.appendChild(h),g.appendChild(Ie),g.appendChild(ie);let he=[],re=null,oe=!1,de=()=>{var Ye,tt,Wt,ht;let Y=o&&he.length<=1;Ie.classList.toggle("persona-hidden",Y),Ie.replaceChildren();for(let ot of he){let me=v("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");me.type="button",me.textContent=ot.title||ot.id.slice(0,8),ot.id===re&&me.classList.add("persona-bg-persona-container","persona-border-persona-border"),me.addEventListener("click",()=>e.onSelect(ot.id)),Ie.appendChild(me)}ie.replaceChildren();let le=re&&he.find(ot=>ot.id===re)||he[he.length-1];if(!le)return;if(o){let ot=le.artifactType==="markdown"?"MD":(Ye=le.component)!=null?Ye:"Component",X=(le.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Pe.textContent=`${X} \xB7 ${ot}`}else m.textContent="Artifacts";if(le.artifactType==="markdown"){if(o&&w==="source"){let me=v("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");me.textContent=(tt=le.markdown)!=null?tt:"",ie.appendChild(me);return}let ot=v("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ot.innerHTML=d((Wt=le.markdown)!=null?Wt:""),ie.appendChild(ot);return}let Te=le.component?Go.get(le.component):void 0;if(Te){let me={message:{id:le.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:n,updateProps:()=>{}};try{let X=Te((ht=le.props)!=null?ht:{},me);if(X){ie.appendChild(X);return}}catch{}}ie.appendChild(nb(le))},Ae=()=>{var le;let Y=he.length>0;if(g.classList.toggle("persona-hidden",!Y),c){let Te=typeof g.closest=="function"?g.closest("[data-persona-root]"):null,tt=((le=Te==null?void 0:Te.classList.contains("persona-artifact-narrow-host"))!=null?le:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Y&&tt&&oe?(c.classList.remove("persona-hidden"),g.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"))}};return{element:g,backdrop:c,update(Y){var le,Te,Ye;he=Y.artifacts,re=(Ye=(Te=Y.selectedId)!=null?Te:(le=Y.artifacts[Y.artifacts.length-1])==null?void 0:le.id)!=null?Ye:null,he.length>0&&(oe=!0),de(),Ae()},setMobileOpen(Y){oe=Y,!Y&&c?(c.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):Ae()}}}function nr(n){var e,t;return((t=(e=n==null?void 0:n.features)==null?void 0:e.artifacts)==null?void 0:t.enabled)===!0}function dg(n,e){var s,a,i,d;if(n.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),n.style.removeProperty("--persona-artifact-pane-border"),n.style.removeProperty("--persona-artifact-pane-border-left"),!nr(e))return;let t=(a=(s=e.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),o=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(n.classList.add("persona-artifact-border-full"),n.style.setProperty("--persona-artifact-pane-border",r)):o&&(n.classList.add("persona-artifact-border-left"),n.style.setProperty("--persona-artifact-pane-border-left",o))}function rb(n){n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),n.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),n.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function ui(n,e){var d,c,p,g,h,m,y,w,E,B;if(!nr(e)){n.style.removeProperty("--persona-artifact-split-gap"),n.style.removeProperty("--persona-artifact-pane-width"),n.style.removeProperty("--persona-artifact-pane-max-width"),n.style.removeProperty("--persona-artifact-pane-min-width"),n.style.removeProperty("--persona-artifact-pane-bg"),n.style.removeProperty("--persona-artifact-pane-padding"),rb(n),dg(n,e);return}let t=(c=(d=e.features)==null?void 0:d.artifacts)==null?void 0:c.layout;n.style.setProperty("--persona-artifact-split-gap",(p=t==null?void 0:t.splitGap)!=null?p:"0.5rem"),n.style.setProperty("--persona-artifact-pane-width",(g=t==null?void 0:t.paneWidth)!=null?g:"40%"),n.style.setProperty("--persona-artifact-pane-max-width",(h=t==null?void 0:t.paneMaxWidth)!=null?h:"28rem"),t!=null&&t.paneMinWidth?n.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):n.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();r?n.style.setProperty("--persona-artifact-pane-bg",r):n.style.removeProperty("--persona-artifact-pane-bg");let o=(y=t==null?void 0:t.panePadding)==null?void 0:y.trim();o?n.style.setProperty("--persona-artifact-pane-padding",o):n.style.removeProperty("--persona-artifact-pane-padding");let s=(w=t==null?void 0:t.documentToolbarIconColor)==null?void 0:w.trim();s?n.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):n.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?n.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):n.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(B=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:B.trim();i?n.style.setProperty("--persona-artifact-doc-toggle-active-border",i):n.style.removeProperty("--persona-artifact-doc-toggle-active-border"),dg(n,e)}var pg=["panel","seamless"];function mi(n,e){var i,d,c,p,g,h;for(let m of pg)n.classList.remove(`persona-artifact-appearance-${m}`);if(n.classList.remove("persona-artifact-unified-split"),n.style.removeProperty("--persona-artifact-pane-radius"),n.style.removeProperty("--persona-artifact-pane-shadow"),n.style.removeProperty("--persona-artifact-unified-outer-radius"),!nr(e))return;let t=(d=(i=e.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",o=pg.includes(r)?r:"panel";n.classList.add(`persona-artifact-appearance-${o}`);let s=(p=t==null?void 0:t.paneBorderRadius)==null?void 0:p.trim();s&&n.style.setProperty("--persona-artifact-pane-radius",s);let a=(g=t==null?void 0:t.paneShadow)==null?void 0:g.trim();if(a&&n.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){n.classList.add("persona-artifact-unified-split");let m=((h=t.unifiedSplitOuterRadius)==null?void 0:h.trim())||s;m&&n.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function ug(n,e){var t,r,o;return!e||!nr(n)?!1:((o=(r=(t=n.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function ob(n,e){if(!(n!=null&&n.trim()))return e;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return t?Math.max(0,Number(t[1])):e}function sb(n){if(!(n!=null&&n.trim()))return null;let e=/^(\d+(?:\.\d+)?)px\s*$/i.exec(n.trim());return e?Math.max(0,Number(e[1])):null}function ab(n,e,t){return t<e?e:Math.min(t,Math.max(e,n))}function ib(n,e,t,r){let o=n-r-2*e-t;return Math.max(0,o)}function mg(n,e){var a;let r=(a=(e.getComputedStyle(n).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 gg(n,e,t,r,o,s){let a=ob(o,200),i=ib(e,t,r,200);i=Math.max(a,i);let d=sb(s);return d!==null&&(i=Math.min(i,d)),ab(n,a,i)}var fg={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"}},pl=(n,e,t,r)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var y,w,E;if(s.dataset.enhanced==="true")return;let a=(y=s.dataset.tvForm)!=null?y:"init";s.dataset.enhanced="true";let i=(w=fg[a])!=null?w:fg.init;s.classList.add("persona-form-card","persona-space-y-4");let d=v("div","persona-space-y-1"),c=v("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let B=v("p","persona-text-sm persona-text-persona-muted");B.textContent=i.description,d.appendChild(B)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(B=>{var C,k;let T=v("label","persona-form-field persona-flex persona-flex-col persona-gap-1");T.htmlFor=`${e.id}-${a}-${B.name}`;let I=v("span","persona-text-xs persona-font-medium persona-text-persona-muted");I.textContent=B.label,T.appendChild(I);let M=(C=B.type)!=null?C:"text",P;M==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=M),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=`${e.id}-${a}-${B.name}`,P.name=B.name,P.placeholder=(k=B.placeholder)!=null?k:"",B.required&&(P.required=!0),T.appendChild(P),p.appendChild(T)});let g=v("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),h=v("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=v("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(E=i.submitLabel)!=null?E:"Submit",g.appendChild(h),g.appendChild(m),p.appendChild(g),s.replaceChildren(d,p),p.addEventListener("submit",async B=>{var P,C;B.preventDefault();let T=(P=t.formEndpoint)!=null?P:"/form",I=new FormData(p),M={};I.forEach((k,q)=>{M[q]=k}),M.type=a,m.disabled=!0,h.textContent="Submitting\u2026";try{let k=await fetch(T,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let q=await k.json();h.textContent=(C=q.message)!=null?C:"Thanks! We'll be in touch soon.",q.success&&q.nextPrompt&&await r.sendMessage(String(q.nextPrompt))}catch(k){h.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var ul=class{constructor(){this.plugins=new Map}register(e){var t;this.plugins.has(e.id)&&console.warn(`Plugin "${e.id}" is already registered. Overwriting.`),this.plugins.set(e.id,e),(t=e.onRegister)==null||t.call(e)}unregister(e){var r;let t=this.plugins.get(e);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(e))}getAll(){return Array.from(this.plugins.values()).sort((e,t)=>{var r,o;return((r=t.priority)!=null?r:0)-((o=e.priority)!=null?o:0)})}getForInstance(e){let t=this.getAll();if(!e||e.length===0)return t;let r=new Set(e.map(s=>s.id));return[...t.filter(s=>!r.has(s.id)),...e].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(e=>{var t;return(t=e.onUnregister)==null?void 0:t.call(e)}),this.plugins.clear()}},ml=new ul;var hg=()=>{let n=new Map,e=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>t(o,s)),t=(o,s)=>{var a;(a=n.get(o))==null||a.delete(s)};return{on:e,off:t,emit:(o,s)=>{var a;(a=n.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var lb=n=>{let e=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return e?e[1]:n},cb=n=>{let e=n.trim(),t=e.indexOf("{");if(t===-1)return null;let r=0;for(let o=t;o<e.length;o+=1){let s=e[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return e.slice(t,o+1)}return null},fl=({text:n})=>{if(!n||!n.includes("{"))return null;try{let e=lb(n),t=cb(e);if(!t)return null;let r=JSON.parse(t);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=n=>typeof n=="string"?n:n==null?"":String(n),ga={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:gl(n.payload.text)},messageAndClick:(n,e)=>{var o;if(n.type!=="message_and_click")return;let t=n.payload,r=gl(t.element);if(r&&((o=e.document)!=null&&o.querySelector)){let s=e.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(t.text)}}},yg=n=>Array.isArray(n)?n.map(e=>String(e)):[],hl=n=>{let e=new Set(yg(n.getSessionMetadata().processedActionMessageIds)),t=()=>{e=new Set(yg(n.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(e);n.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||e.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?n.parsers.reduce((c,p)=>c||(p==null?void 0:p({text:a,message:s.message}))||null,null):null;if(!i)return null;e.add(s.message.id),r();let d={action:i,message:s.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let p=()=>{n.emit("action:resubmit",d)},g=c(i,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:p});if(!g)continue;if(g.handled){let h=g.persistMessage!==!1;return{text:g.displayText!==void 0?g.displayText:"",persist:h,resubmit:g.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:t}};var db=n=>{if(!n)return null;try{return JSON.parse(n)}catch(e){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",e),null}},pb=n=>n.map(e=>({...e,streaming:!1})),ub=n=>n.map(e=>({...e,status:"complete"})),bg=(n="persona-state")=>{let e=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=e();return t?db(t.getItem(n)):null},save:t=>{let r=e();if(r)try{let o={...t,messages:t.messages?pb(t.messages):void 0,artifacts:t.artifacts?ub(t.artifacts):void 0};r.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let t=e();if(t)try{t.removeItem(n)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var yl=require("partial-json");function vg(n,e){let{config:t,message:r,onPropsUpdate:o}=e,s=Go.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:i=>{o&&o(i)}};try{return s(n.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,i),null}}function wg(n){if(typeof n.rawContent=="string"&&n.rawContent.length>0)return n.rawContent;if(typeof n.content=="string"){let e=n.content.trim();if(e.startsWith("{")||e.startsWith("["))return n.content}return null}function xg(n){let e=wg(n);if(!e)return!1;try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function Cg(n){let e=wg(n);if(!e)return null;try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"){let r=t;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e}}}catch{}return null}var mb=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ag(n){let{onSubmit:e,onDismiss:t,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=mb}=n,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let g=null,h=document.createElement("div");h.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let y=document.createElement("h3");y.className="persona-feedback-title",y.textContent=r,m.appendChild(y);let w=document.createElement("p");w.className="persona-feedback-subtitle",w.textContent=o,m.appendChild(w),h.appendChild(m);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let B=[];for(let C=1;C<=5;C++){let k=document.createElement("button");k.type="button",k.className="persona-feedback-rating-btn persona-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${c[C-1]}`),k.title=c[C-1],k.dataset.rating=String(C),k.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
|
-
`,P.addEventListener("click",()=>{m=A,R.forEach((O,_)=>{let H=_<A;O.classList.toggle("selected",H),O.setAttribute("aria-checked",_===A-1?"true":"false")})}),R.push(P),k.appendChild(P)}g.appendChild(k);let E=null;if(d){let A=document.createElement("div");A.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=s,E.rows=3,E.setAttribute("aria-label","Additional comments"),A.appendChild(E),g.appendChild(A)}let L=document.createElement("div");L.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=i,M.addEventListener("click",()=>{n==null||n(),u.remove()});let I=document.createElement("button");return I.type="button",I.className="persona-feedback-btn persona-feedback-btn-submit",I.textContent=a,I.addEventListener("click",async()=>{if(m===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let A=(E==null?void 0:E.value.trim())||void 0;await e(m,A),u.remove()}catch(A){I.disabled=!1,I.textContent=a,console.error("[CSAT Feedback] Failed to submit:",A)}}),L.appendChild(M),L.appendChild(I),g.appendChild(L),u.appendChild(g),u}function Ym(t){let{onSubmit:e,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:u="Very likely"}=t,m=document.createElement("div");m.className="persona-feedback-container persona-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let w=document.createElement("div");w.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,w.appendChild(v);let k=document.createElement("p");k.className="persona-feedback-subtitle",k.textContent=o,w.appendChild(k),f.appendChild(w);let R=document.createElement("div");R.className="persona-feedback-rating persona-feedback-rating-nps",R.setAttribute("role","radiogroup"),R.setAttribute("aria-label","Likelihood rating from 0 to 10");let E=document.createElement("div");E.className="persona-feedback-labels";let L=document.createElement("span");L.className="persona-feedback-label-low",L.textContent=c;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=u,E.appendChild(L),E.appendChild(M);let I=document.createElement("div");I.className="persona-feedback-numbers";let A=[];for(let U=0;U<=10;U++){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 ${U} out of 10`),F.textContent=String(U),F.dataset.rating=String(U),U<=6?F.classList.add("persona-feedback-detractor"):U<=8?F.classList.add("persona-feedback-passive"):F.classList.add("persona-feedback-promoter"),F.addEventListener("click",()=>{g=U,A.forEach((Z,Te)=>{Z.classList.toggle("selected",Te===U),Z.setAttribute("aria-checked",Te===U?"true":"false")})}),A.push(F),I.appendChild(F)}R.appendChild(E),R.appendChild(I),f.appendChild(R);let P=null;if(d){let U=document.createElement("div");U.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=s,P.rows=3,P.setAttribute("aria-label","Additional comments"),U.appendChild(P),f.appendChild(U)}let O=document.createElement("div");O.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(),m.remove()});let H=document.createElement("button");return H.type="button",H.className="persona-feedback-btn persona-feedback-btn-submit",H.textContent=a,H.addEventListener("click",async()=>{if(g===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let U=(P==null?void 0:P.value.trim())||void 0;await e(g,U),m.remove()}catch(U){H.disabled=!1,H.textContent=a,console.error("[NPS Feedback] Failed to submit:",U)}}),O.appendChild(_),O.appendChild(H),f.appendChild(O),m.appendChild(f),m}var ys="persona-chat-history",Dy=30*1e3,Ny={"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 Fy(t){var r,o,s;if(!t)return[];let e=[],n=Array.from((r=t.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){e.push(i);continue}let d=(o=Ny[i.type])!=null?o:"png";e.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let a of Array.from((s=t.files)!=null?s:[]))a.type.startsWith("image/")&&e.push(a);return e}function ii(t){if(!t)return!1;let e=t.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function Oy(t){var e,n,r,o,s,a,i,d,c;return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(e=t.storage)!=null?e:"session",keyPrefix:(n=t.keyPrefix)!=null?n:"persona-",persist:{openState:(o=(r=t.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=t.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=t.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=t.clearOnChatClear)!=null?c:!0}:null}function _y(t){try{let e=t==="local"?localStorage:sessionStorage,n="__persist_test__";return e.setItem(n,"1"),e.removeItem(n),e}catch{return null}}var dl=t=>!t||typeof t!="object"?{}:{...t},Zm=t=>t.map(e=>({...e,streaming:!1})),eg=(t,e,n)=>{let r=t!=null&&t.markdown?ba(t.markdown):null,o=va(t==null?void 0:t.sanitize);return t!=null&&t.postprocessMessage&&o&&(t==null?void 0:t.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var u,m,g;let a=(u=s.text)!=null?u:"",i=(m=s.message.rawContent)!=null?m:null;if(e){let f=e.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});f!==null&&(a=f.text,f.persist||(s.message.__skipPersist=!0),f.resubmit&&!s.streaming&&n&&n())}let d=Po()!==null,c;if(t!=null&&t.postprocessMessage){let f=t.postprocessMessage({...s,text:a,raw:(g=i!=null?i:s.text)!=null?g:""});c=o?o(f):f}else if(r){let f=s.streaming?Xp(a):a,w=r(f);c=o&&d?o(w):w}else c=io(a);return c}};function tg(t){var i,d,c,u;let e=b("div","persona-attachment-drop-overlay");t!=null&&t.background&&e.style.setProperty("--persona-drop-overlay-bg",t.background),(t==null?void 0:t.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",t.backdropBlur),t!=null&&t.border&&e.style.setProperty("--persona-drop-overlay-border",t.border),t!=null&&t.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",t.borderRadius),t!=null&&t.inset&&e.style.setProperty("--persona-drop-overlay-inset",t.inset),t!=null&&t.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",t.labelSize),t!=null&&t.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",t.labelColor);let n=(i=t==null?void 0:t.iconName)!=null?i:"upload",r=(d=t==null?void 0:t.iconSize)!=null?d:"48px",o=(c=t==null?void 0:t.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(u=t==null?void 0:t.iconStrokeWidth)!=null?u:.5,a=be(n,r,o,s);if(a&&e.appendChild(a),t!=null&&t.label){let m=b("span","persona-drop-overlay-label");m.textContent=t.label,e.appendChild(m)}return e}var ng=(t,e,n)=>{var ql,jl,Vl,Kl,Gl,Ql,Xl,Jl,Yl,Zl,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,vc,wc,xc,Cc,Ac,Sc,Tc,Ec,Mc,kc,Lc,Pc,Ic,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc;if(t==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');t.id&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.hasAttribute("data-persona-root")||t.setAttribute("data-persona-root","true");let r=ju(e),o=sl.getForInstance(r.plugins),{plugin:s,teardown:a}=Lm();r.components&&_o.registerAll(r.components);let i=qm(),c=r.persistState===!1?null:(ql=r.storageAdapter)!=null?ql:Vm(),u={},m=null,g=!1,f=l=>{if(r.onStateLoaded)try{let p=r.onStateLoaded(l);if(p&&typeof p=="object"&&"state"in p){let{state:h,open:y}=p;return y&&(g=!0),h}return p}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return l};if(c!=null&&c.load)try{let l=c.load();if(l&&typeof l.then=="function")m=l.then(p=>{let h=p!=null?p:{messages:[],metadata:{}};return f(h)});else{let p=l!=null?l:{messages:[],metadata:{}},h=f(p);h.metadata&&(u=dl(h.metadata)),(jl=h.messages)!=null&&jl.length&&(r={...r,initialMessages:h.messages}),(Vl=h.artifacts)!=null&&Vl.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Kl=h.selectedArtifactId)!=null?Kl:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=f({messages:[],metadata:{}});(Gl=l.messages)!=null&&Gl.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let w=()=>u,v=l=>{var h;u=(h=l({...u}))!=null?h:{},tt()},k=r.actionParsers&&r.actionParsers.length?r.actionParsers:[il],R=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[aa.message,aa.messageAndClick],E=ll({parsers:k,handlers:R,getSessionMetadata:w,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let L=(Xl=(Ql=r.launcher)==null?void 0:Ql.enabled)!=null?Xl:!0,M=(Yl=(Jl=r.launcher)==null?void 0:Jl.autoExpand)!=null?Yl:!1,I=(Zl=r.autoFocusInput)!=null?Zl:!1,A=M,P=L,O=(tc=(ec=r.layout)==null?void 0:ec.header)==null?void 0:tc.layout,_=!1,H=()=>ea(r),U=()=>L||H(),F=H()?!1:L?M:!0,Z=!1,Te=null,pe=()=>{Z=!0,Te&&clearTimeout(Te),Te=setTimeout(()=>{Z&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Z=!1)},1e4)},ee=eg(r,E,pe),xe=(rc=(nc=r.features)==null?void 0:nc.showReasoning)!=null?rc:!0,Re=(sc=(oc=r.features)==null?void 0:oc.showToolCalls)!=null?sc:!0,le=(ic=(ac=r.features)==null?void 0:ac.showEventStreamToggle)!=null?ic:!1,me=(cc=(lc=r.features)==null?void 0:lc.scrollToBottom)!=null?cc:{},oe=(pc=(dc=r.features)==null?void 0:dc.scrollBehavior)!=null?pc:{},de=`${(mc=typeof r.persistState=="object"?(uc=r.persistState)==null?void 0:uc.keyPrefix:void 0)!=null?mc:"persona-"}event-stream`,Ee=le?new oa(de):null,He=(hc=(fc=(gc=r.features)==null?void 0:gc.eventStream)==null?void 0:fc.maxEvents)!=null?hc:2e3,K=le?new ra(He,Ee):null,J=le?new sa:null,Le=null,G=!1,ue=null,De=0;Ee==null||Ee.open().then(()=>K==null?void 0:K.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Xe={onCopy:l=>{var p,h;i.emit("message:copy",l),z!=null&&z.isClientTokenMode()&&z.submitMessageFeedback(l.id,"copy").catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",y)}),(h=(p=r.messageActions)==null?void 0:p.onCopy)==null||h.call(p,l)},onFeedback:l=>{var p,h;i.emit("message:feedback",l),z!=null&&z.isClientTokenMode()&&z.submitMessageFeedback(l.messageId,l.type).catch(y=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",y)}),(h=(p=r.messageActions)==null?void 0:p.onFeedback)==null||h.call(p,l)}},et=(yc=r.statusIndicator)!=null?yc:{},vt=l=>{var p,h,y,T;return l==="idle"?(p=et.idleText)!=null?p:wn.idle:l==="connecting"?(h=et.connectingText)!=null?h:wn.connecting:l==="connected"?(y=et.connectedText)!=null?y:wn.connected:l==="error"?(T=et.errorText)!=null?T:wn.error:wn[l]};function wt(l,p,h,y){if(y==="idle"&&h.idleLink){l.textContent="";let T=document.createElement("a");T.href=h.idleLink,T.target="_blank",T.rel="noopener noreferrer",T.textContent=p,T.style.color="inherit",T.style.textDecoration="none",l.appendChild(T)}else l.textContent=p}let Je=ym({config:r,showClose:U()}),{wrapper:fe,panel:Q,pillRoot:dt}=Je.shell,qe=Je.panelElements,{container:Ce,body:Me,messagesWrapper:nt,suggestions:Wt,textarea:te,sendButton:Ue,sendButtonWrapper:An,composerForm:xt,statusText:hn,introTitle:hr,introSubtitle:yr,closeButton:S,iconHolder:ne,headerTitle:Se,headerSubtitle:Ne,header:Pe,footer:Fe,actionsRow:Ke,leftActions:it,rightActions:Rt}=qe,ce=qe.setSendButtonMode,B=qe.micButton,he=qe.micButtonWrapper,_e=qe.attachmentButton,Ct=qe.attachmentButtonWrapper,Ye=qe.attachmentInput,Nt=qe.attachmentPreviewsContainer;Ce.classList.add("persona-relative"),Me.classList.add("persona-relative");let Mt=12,ht=()=>{var l;return(l=me.label)!=null?l:""},It=()=>{var l;return(l=me.iconName)!=null?l:"arrow-down"},Jt=()=>me.enabled!==!1,$t=()=>{var l;return(l=oe.mode)!=null?l:"follow"},Bn=()=>{var l;return(l=oe.anchorTopOffset)!=null?l:16},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 Dn=b("span","persona-flex persona-items-center"),Qn=b("span",""),yn=b("span","");yn.setAttribute("data-persona-scroll-to-bottom-count",""),yn.style.display="none",zt.append(Dn,Qn,yn),Ce.appendChild(zt);let Ln=b("div","persona-stream-anchor-spacer");Ln.setAttribute("aria-hidden","true"),Ln.setAttribute("data-persona-anchor-spacer",""),Ln.style.flexShrink="0",Ln.style.pointerEvents="none",Ln.style.height="0px",Me.appendChild(Ln);let Xn=()=>{let p=Fe.style.display==="none"?0:Fe.offsetHeight;zt.style.bottom=`${p+Mt}px`};Xn();let Kr=()=>{let l=!!ht();zt.setAttribute("aria-label",ht()||"Jump to latest"),zt.title=ht(),zt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Dn.innerHTML="";let p=be(It(),"14px","currentColor",2);p?(Dn.appendChild(p),Dn.style.display=""):Dn.style.display="none",Qn.textContent=ht(),Qn.style.display=l?"":"none"};Kr();let At=null,br=null,vr=o.find(l=>l.renderHeader);if(vr!=null&&vr.renderHeader){let l=vr.renderHeader({config:r,defaultRenderer:()=>{let p=Do({config:r,showClose:U()});return ta(Ce,p,r),p.header},onClose:()=>qt(!1,"user")});if(l){let p=Ce.querySelector(".persona-border-b-persona-divider");p&&(p.replaceWith(l),Pe=l,Je.header.element=l)}}let Wr=()=>{var p,h,y,T;if(!K)return;if(G=!0,!Le&&K&&(Le=Hm({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>ir(),config:r,plugins:o,getThroughput:()=>{var D;return(D=J==null?void 0:J.getMetric())!=null?D:{status:"idle"}}})),Le&&(Me.style.display="none",(p=Fe.parentNode)==null||p.insertBefore(Le.element,Fe),Le.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${kn.actionIconColor}`;let D=(T=(y=(h=r.features)==null?void 0:h.eventStream)==null?void 0:y.classNames)==null?void 0:T.toggleButtonActive;D&&D.split(/\s+/).forEach(j=>j&&ut.classList.add(j))}let l=()=>{if(!G)return;let D=Date.now();D-De>=200&&(Le==null||Le.update(),De=D),ue=requestAnimationFrame(l)};De=0,ue=requestAnimationFrame(l),st(),i.emit("eventStream:opened",{timestamp:Date.now()})},ir=()=>{var l,p,h;if(G){if(G=!1,Le&&Le.element.remove(),Me.style.display="",ut){ut.style.boxShadow="";let y=(h=(p=(l=r.features)==null?void 0:l.eventStream)==null?void 0:p.classNames)==null?void 0:h.toggleButtonActive;y&&y.split(/\s+/).forEach(T=>T&&ut.classList.remove(T))}ue!==null&&(cancelAnimationFrame(ue),ue=null),st(),i.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(le){let l=(vc=(bc=r.features)==null?void 0:bc.eventStream)==null?void 0:vc.classNames,p="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:"");ut=b("button",p),ut.style.width="28px",ut.style.height="28px",ut.style.color=kn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let h=be("activity","18px","currentColor",1.5);h&&ut.appendChild(h);let y=qe.clearChatButtonWrapper,T=qe.closeButtonWrapper,D=y||T;D&&D.parentNode===Pe?Pe.insertBefore(ut,D):Pe.appendChild(ut),ut.addEventListener("click",()=>{G?ir():Wr()})}let fo=l=>{var T,D,j,$,N;let p=r.attachments;if(!(p!=null&&p.enabled))return;let h=(T=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?T: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 ae=l.querySelector("[data-persona-composer-form]");ae!=null&&ae.parentNode?ae.parentNode.insertBefore(h,ae):l.insertBefore(h,l.firstChild)}if(!((D=l.querySelector("[data-persona-composer-attachment-input]"))!=null?D:l.querySelector('input[type="file"]'))){let ae=b("input");ae.type="file",ae.setAttribute("data-persona-composer-attachment-input",""),ae.accept=((j=p.allowedTypes)!=null?j:qr).join(","),ae.multiple=(($=p.maxFiles)!=null?$:4)>1,ae.style.display="none",ae.setAttribute("aria-label",(N=p.buttonTooltipText)!=null?N:"Attach files"),l.appendChild(ae)}},wr=o.find(l=>l.renderComposer);if(wr!=null&&wr.renderComposer){let l=r.composer,p=wr.renderComposer({config:r,defaultRenderer:()=>ti({config:r}).footer,onSubmit:h=>{var j;if(!z||z.isStreaming())return;let y=h.trim(),T=(j=At==null?void 0:At.hasAttachments())!=null?j:!1;if(!y&&!T)return;xl();let D;T&&(D=[],D.push(...At.getContentParts()),y&&D.push(Ri(y))),z.sendMessage(y,{contentParts:D}),T&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ye==null||Ye.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:((wc=r.voiceRecognition)==null?void 0:wc.enabled)===!0?()=>{br==null||br()}:void 0});p&&(Je.replaceComposer(p),Fe=Je.composer.footer)}let ho=l=>{let p=(...ie)=>{for(let Y of ie){let we=l.querySelector(Y);if(we)return we}return null},h=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),T=l.querySelector("[data-persona-composer-submit]"),D=l.querySelector("[data-persona-composer-mic]"),j=l.querySelector("[data-persona-composer-status]");h&&(xt=h),y&&(te=y),T&&(Ue=T),D&&(B=D,he=D.parentElement),j&&(hn=j);let $=p("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");$&&(Wt=$);let N=p("[data-persona-composer-attachment-button]",".persona-attachment-button");N&&(_e=N,Ct=N.parentElement),Ye=p("[data-persona-composer-attachment-input]",'input[type="file"]'),Nt=p("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ae=p("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ae&&(Ke=ae)};fo(Fe),ho(Fe);let Pn=(Tc=(xc=r.layout)==null?void 0:xc.contentMaxWidth)!=null?Tc:H()?(Sc=(Ac=(Cc=r.launcher)==null?void 0:Cc.composerBar)==null?void 0:Ac.contentMaxWidth)!=null?Sc:"720px":void 0;if(Pn&&(nt.style.maxWidth=Pn,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%"),Pn&&xt&&!H()&&(xt.style.maxWidth=Pn,xt.style.marginLeft="auto",xt.style.marginRight="auto"),Pn&&Wt&&!H()&&(Wt.style.maxWidth=Pn,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),Pn&&Nt&&!H()&&(Nt.style.maxWidth=Pn,Nt.style.marginLeft="auto",Nt.style.marginRight="auto"),(Ec=r.attachments)!=null&&Ec.enabled&&Ye&&Nt){At=Vs.fromConfig(r.attachments),At.setPreviewsContainer(Nt),Ye.addEventListener("change",h=>{let y=h.target;At==null||At.handleFileSelect(y.files),y.value=""});let l=r.attachments.dropOverlay,p=tg(l);Ce.appendChild(p)}(()=>{var y,T;let l=(T=(y=r.layout)==null?void 0:y.slots)!=null?T:{},p=D=>{switch(D){case"body-top":return Ce.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return nt;case"footer-top":return Wt;case"composer":return xt;case"footer-bottom":return hn;default:return null}},h=(D,j)=>{var $;switch(D){case"header-left":case"header-center":case"header-right":if(D==="header-left")Pe.insertBefore(j,Pe.firstChild);else if(D==="header-right")Pe.appendChild(j);else{let N=Pe.querySelector(".persona-flex-col");N?($=N.parentNode)==null||$.insertBefore(j,N.nextSibling):Pe.appendChild(j)}break;case"body-top":{let N=Me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith(j):Me.insertBefore(j,Me.firstChild);break}case"body-bottom":Me.appendChild(j);break;case"footer-top":Wt.replaceWith(j);break;case"footer-bottom":hn.replaceWith(j);break;default:break}};for(let[D,j]of Object.entries(l))if(j)try{let $=j({config:r,defaultContent:()=>p(D)});$&&h(D,$)}catch($){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${D}":`,$)}})();let Gr=l=>{var j,$;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let y=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!y)return;let T=y.getAttribute("data-message-id");if(!T)return;let D=h.getAttribute("data-bubble-type");if(D==="reasoning")gs.has(T)?gs.delete(T):gs.add(T),wm(T,y);else if(D==="tool")fs.has(T)?fs.delete(T):fs.add(T),xm(T,y,r);else if(D==="approval"){let N=r.approval!==!1?r.approval:void 0,ae=((j=N==null?void 0:N.detailsDisplay)!=null?j:"collapsed")==="expanded",ie=($=No.get(T))!=null?$:ae;No.set(T,!ie),Tm(T,y,r)}Tr.delete(T)};nt.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Gr(l))}),nt.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Gr(l))}),nt.addEventListener("copy",l=>{let{clipboardData:p}=l;if(!p)return;let h=nt.getRootNode(),y=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!y||y.isCollapsed)return;let T=y.toString(),D=Yu(T);!D||D===T||(p.setData("text/plain",D),l.preventDefault())});let Rr=new Map,Qr=null,Xr="idle",yo={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},bo=(l,p)=>{let{icon:h,label:y}=yo[p];l.setAttribute("aria-label",y),l.title=y,l.setAttribute("aria-pressed",p==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",p!=="idle"),l.classList.toggle("persona-message-action-loading",p==="loading");let T=be(h,14,"currentColor",2);T&&(l.innerHTML="",l.appendChild(T))},Jr=()=>{nt.querySelectorAll('[data-action="read-aloud"]').forEach(p=>{var D;let h=p.closest("[data-actions-for]"),y=(D=h==null?void 0:h.getAttribute("data-actions-for"))!=null?D:null;bo(p,y&&y===Qr?Xr:"idle")})};nt.addEventListener("click",l=>{var j;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.closest("[data-actions-for]");if(!y)return;let T=y.getAttribute("data-actions-for");if(!T)return;let D=h.getAttribute("data-action");if(D==="copy"){let N=z.getMessages().find(ae=>ae.id===T);if(N&&Xe.onCopy){let ae=N.content||"";navigator.clipboard.writeText(ae).then(()=>{h.classList.add("persona-message-action-success");let ie=be("check",14,"currentColor",2);ie&&(h.innerHTML="",h.appendChild(ie)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Y=be("copy",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))},2e3)}).catch(ie=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ie)}),Xe.onCopy(N)}}else if(D==="read-aloud")z.toggleReadAloud(T);else if(D==="upvote"||D==="downvote"){let N=((j=Rr.get(T))!=null?j:null)===D,ae=D==="upvote"?"thumbs-up":"thumbs-down";if(N){Rr.delete(T),h.classList.remove("persona-message-action-active");let ie=be(ae,14,"currentColor",2);ie&&(h.innerHTML="",h.appendChild(ie))}else{let ie=D==="upvote"?"downvote":"upvote",Y=y.querySelector(`[data-action="${ie}"]`);if(Y){Y.classList.remove("persona-message-action-active");let ze=be(ie==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(Y.innerHTML="",Y.appendChild(ze))}Rr.set(T,D),h.classList.add("persona-message-action-active");let we=be(ae,14,"currentColor",2);we&&(we.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(we)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Ae=z.getMessages().find(Ze=>Ze.id===T);Ae&&Xe.onFeedback&&Xe.onFeedback({type:D,messageId:Ae.id,message:Ae})}}}),nt.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.closest(".persona-approval-bubble");if(!y)return;let T=y.getAttribute("data-message-id");if(!T)return;let D=h.getAttribute("data-approval-action");if(!D)return;let j=D==="approve"?"approved":"denied",N=z.getMessages().find(ie=>ie.id===T);if(!(N!=null&&N.approval))return;let ae=y.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),N.approval.toolType==="webmcp"?z.resolveWebMcpApproval(T,j):z.resolveApproval(N.approval,j)});let bt=null,Nn=null,Fn={artifacts:[],selectedId:null},Sn=!1,St={current:null};nt.addEventListener("click",l=>{var Y,we,Oe,Ae,Ze;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let y=h.getAttribute("data-download-artifact");if(!y||((Oe=(we=(Y=r.features)==null?void 0:Y.artifacts)==null?void 0:we.onArtifactAction)==null?void 0:Oe.call(we,{type:"download",artifactId:y}))===!0)return;let D=z.getArtifactById(y),j=D==null?void 0:D.markdown,$=(D==null?void 0:D.title)||"artifact";if(!j){let ze=h.closest("[data-open-artifact]"),ct=ze==null?void 0:ze.closest("[data-message-id]"),rt=ct==null?void 0:ct.getAttribute("data-message-id");if(rt){let ke=z.getMessages().find(je=>je.id===rt);if(ke!=null&&ke.rawContent)try{let je=JSON.parse(ke.rawContent);j=(Ae=je==null?void 0:je.props)==null?void 0:Ae.markdown,$=((Ze=je==null?void 0:je.props)==null?void 0:Ze.title)||$}catch{}}}if(!j)return;let N=new Blob([j],{type:"text/markdown"}),ae=URL.createObjectURL(N),ie=document.createElement("a");ie.href=ae,ie.download=`${$}.md`,ie.click(),URL.revokeObjectURL(ae)}),nt.addEventListener("click",l=>{var D,j,$;let h=l.target.closest("[data-open-artifact]");if(!h)return;let y=h.getAttribute("data-open-artifact");!y||(($=(j=(D=r.features)==null?void 0:D.artifacts)==null?void 0:j.onArtifactAction)==null?void 0:$.call(j,{type:"open",artifactId:y}))===!0||(l.preventDefault(),l.stopPropagation(),Sn=!1,z.selectArtifact(y),In())}),nt.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let p=l.target;p.hasAttribute("data-open-artifact")&&(l.preventDefault(),p.click())});let Jn=qe.composerOverlay,Yn=(l,p,h)=>{var $,N,ae,ie;let y=p.trim();if(!y||!St.current)return;let T=($=l.getAttribute("data-tool-call-id"))!=null?$:"",D=h.source==="free-text";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:T,answer:y,answers:h.structured,values:(N=h.values)!=null?N:h.source==="multi"?y.split(", "):[y],isFreeText:D,source:h.source},bubbles:!0,composed:!0})),as(Jn,T);let j=St.current.getMessages().find(Y=>{var we;return((we=Y.toolCall)==null?void 0:we.id)===T});(ae=j==null?void 0:j.agentMetadata)!=null&&ae.awaitingLocalTool?St.current.resolveAskUserQuestion(j,(ie=h.structured)!=null?ie:y):St.current.sendMessage(y)},On=l=>{var T;let p=St.current;if(!p)return;let h=(T=l.getAttribute("data-tool-call-id"))!=null?T:"",y=p.getMessages().find(D=>{var j;return((j=D.toolCall)==null?void 0:j.id)===h});y&&p.persistAskUserQuestionProgress(y,{answers:Ca(l,y),currentIndex:sr(l)})},Yr=l=>Object.entries(l).map(([p,h])=>`${p}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Hr=l=>{var T,D,j;if(((D=(T=r.features)==null?void 0:T.askUserQuestion)==null?void 0:D.groupedAutoAdvance)===!1)return;let p=sr(l),h=ss(l);if(p>=h-1)return;let y=(j=St.current)==null?void 0:j.getMessages().find($=>{var N;return((N=$.toolCall)==null?void 0:N.id)===l.getAttribute("data-tool-call-id")});y&&(Sa(l,y,r,p+1),On(l))};Jn.addEventListener("click",l=>{var D,j,$,N,ae,ie,Y,we,Oe,Ae,Ze,ze,ct,rt;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;let T=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),T==="dismiss"){let Ie=(D=y.getAttribute("data-tool-call-id"))!=null?D:"";t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),as(Jn,Ie);let ke=(j=St.current)==null?void 0:j.getMessages().find(je=>{var Ve;return((Ve=je.toolCall)==null?void 0:Ve.id)===Ie});($=ke==null?void 0:ke.agentMetadata)!=null&&$.awaitingLocalTool&&((N=St.current)==null||N.markAskUserQuestionResolved(ke),(ae=St.current)==null||ae.resolveAskUserQuestion(ke,"(dismissed)"));return}if(T==="pick"){let Ie=h.getAttribute("data-option-label");if(!Ie)return;let ke=y.getAttribute("data-multi-select")==="true",je=co(y);if(je&&ke){let Ve=Wo(y)[sr(y)],ft=new Set(Array.isArray(Ve)?Ve:[]);ft.has(Ie)?ft.delete(Ie):ft.add(Ie),po(y,Array.from(ft)),On(y);return}if(je){po(y,Ie),On(y),Hr(y);return}if(ke){let Ve=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ve?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ve);let ft=y.querySelector('[data-ask-user-action="submit-multi"]');ft&&(ft.disabled=Mi(y).length===0);return}Yn(y,Ie,{source:"pick",values:[Ie]});return}if(T==="submit-multi"){let Ie=Mi(y);if(Ie.length===0)return;Yn(y,Ie.join(", "),{source:"multi",values:Ie});return}if(T==="open-free-text"){let Ie=y.querySelector('[data-ask-free-text-row="true"]');if(Ie){Ie.classList.remove("persona-hidden");let ke=Ie.querySelector('[data-ask-free-text-input="true"]');ke==null||ke.focus()}return}if(T==="focus-free-text"){let Ie=y.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus();return}if(T==="submit-free-text"){let Ie=y.querySelector('[data-ask-free-text-input="true"]'),ke=(ie=Ie==null?void 0:Ie.value)!=null?ie:"";if(!ke.trim())return;if(co(y)){po(y,ke.trim()),On(y),Hr(y);return}Yn(y,ke,{source:"free-text"});return}if(T==="next"||T==="back"){if(!St.current)return;let Ie=(Y=y.getAttribute("data-tool-call-id"))!=null?Y:"",ke=St.current.getMessages().find(Be=>{var We;return((We=Be.toolCall)==null?void 0:We.id)===Ie});if(!ke)return;let je=y.querySelector('[data-ask-free-text-input="true"]'),Ve=(Oe=(we=je==null?void 0:je.value)==null?void 0:we.trim())!=null?Oe:"";if(Ve){let Be=Wo(y)[sr(y)];(typeof Be!="string"||Be!==Ve)&&po(y,Ve)}let ft=T==="next"?1:-1,W=sr(y)+ft;Sa(y,ke,r,W),On(y);return}if(T==="submit-all"){if(!St.current)return;let Ie=(Ae=y.getAttribute("data-tool-call-id"))!=null?Ae:"",ke=St.current.getMessages().find(Be=>{var We;return((We=Be.toolCall)==null?void 0:We.id)===Ie});if(!ke)return;let je=y.querySelector('[data-ask-free-text-input="true"]'),Ve=(ze=(Ze=je==null?void 0:je.value)==null?void 0:Ze.trim())!=null?ze:"";Ve&&po(y,Ve);let ft=Ca(y,ke);St.current.persistAskUserQuestionProgress(ke,{answers:ft,currentIndex:sr(y)});let W=Yr(ft);Yn(y,W||"(submitted)",{source:"submit-all",structured:ft});return}if(T==="skip"){if(!St.current)return;let Ie=(ct=y.getAttribute("data-tool-call-id"))!=null?ct:"",ke=St.current.getMessages().find(We=>{var ge;return((ge=We.toolCall)==null?void 0:ge.id)===Ie});if(!ke)return;let je=co(y),Ve=sr(y),ft=ss(y),W=Ve>=ft-1;if(!je){t.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),as(Jn,Ie),(rt=ke.agentMetadata)!=null&&rt.awaitingLocalTool&&(St.current.markAskUserQuestionResolved(ke),St.current.resolveAskUserQuestion(ke,"(dismissed)"));return}po(y,"");let Be=y.querySelector('[data-ask-free-text-input="true"]');if(Be&&(Be.value=""),W){let We=Ca(y,ke),ge=Yr(We);Yn(y,ge||"(skipped)",{source:"submit-all",structured:We});return}Sa(y,ke,r,Ve+1),On(y);return}}),Jn.addEventListener("keydown",l=>{var D;if(l.key!=="Enter")return;let h=l.target;if(!((D=h.matches)!=null&&D.call(h,'[data-ask-free-text-input="true"]')))return;let y=h.closest("[data-persona-ask-sheet-for]");if(!y)return;l.preventDefault();let T=h.value;if(T.trim()){if(co(y)){po(y,T.trim()),On(y),Hr(y);return}Yn(y,T,{source:"free-text"})}});let Zr=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let p=l.target;if((p==null?void 0:p.tagName)==="INPUT"||(p==null?void 0:p.tagName)==="TEXTAREA"||p!=null&&p.isContentEditable)return;let h=Jn.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let y=Number(l.key),D=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[y-1];D&&(l.preventDefault(),D.click())};document.addEventListener("keydown",Zr);let _n=null,Ht=null,Tn=null,Zn=null,eo=()=>{};function Br(){Zn==null||Zn(),Zn=null}let to=()=>{var j;if(!_n||!Ht)return;let l=t.classList.contains("persona-artifact-appearance-seamless"),h=((j=t.ownerDocument.defaultView)!=null?j:window).innerWidth<=640;if(!l||t.classList.contains("persona-artifact-narrow-host")||h){Ht.style.removeProperty("position"),Ht.style.removeProperty("left"),Ht.style.removeProperty("top"),Ht.style.removeProperty("bottom"),Ht.style.removeProperty("width"),Ht.style.removeProperty("z-index");return}let y=_n.firstElementChild;if(!y||y===Ht)return;let T=10;Ht.style.position="absolute",Ht.style.top="0",Ht.style.bottom="0",Ht.style.width=`${T}px`,Ht.style.zIndex="5";let D=y.offsetWidth-T/2;Ht.style.left=`${Math.max(0,D)}px`},ve=()=>{},In=()=>{var h,y,T,D,j;if(!bt||!ar(r))return;si(t,r),ai(t,r),ve();let l=(D=(T=(y=(h=r.features)==null?void 0:h.artifacts)==null?void 0:y.layout)==null?void 0:T.narrowHostMaxWidth)!=null?D:520,p=Q.getBoundingClientRect().width||0;t.classList.toggle("persona-artifact-narrow-host",p>0&&p<=l),bt.update(Fn),Sn?(bt.setMobileOpen(!1),bt.element.classList.add("persona-hidden"),(j=bt.backdrop)==null||j.classList.add("persona-hidden")):Fn.artifacts.length>0&&(bt.element.classList.remove("persona-hidden"),bt.setMobileOpen(!0)),eo()};if(ar(r)){Q.style.position="relative";let l=b("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),p=b("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(Ce),bt=Nm(r,{onSelect:h=>{var y;return(y=St.current)==null?void 0:y.selectArtifact(h)},onDismiss:()=>{Sn=!0,In()}}),bt.element.classList.add("persona-hidden"),_n=p,p.appendChild(l),p.appendChild(bt.element),bt.backdrop&&Q.appendChild(bt.backdrop),Q.appendChild(p),eo=()=>{var y,T,D,j;if(!_n||!bt)return;if(!(((D=(T=(y=r.features)==null?void 0:y.artifacts)==null?void 0:T.layout)==null?void 0:D.resizable)===!0)){Tn==null||Tn(),Tn=null,Br(),Ht&&(Ht.remove(),Ht=null),bt.element.style.removeProperty("width"),bt.element.style.removeProperty("maxWidth");return}if(!Ht){let $=b("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 N=t.ownerDocument,ae=(j=N.defaultView)!=null?j:window,ie=Y=>{var ct,rt;if(!bt||Y.button!==0||t.classList.contains("persona-artifact-narrow-host")||ae.innerWidth<=640)return;Y.preventDefault(),Br();let we=Y.clientX,Oe=bt.element.getBoundingClientRect().width,Ae=(rt=(ct=r.features)==null?void 0:ct.artifacts)==null?void 0:rt.layout,Ze=Ie=>{let ke=_n.getBoundingClientRect().width,je=t.classList.contains("persona-artifact-appearance-seamless"),Ve=je?0:$m(_n,ae),ft=je?0:$.getBoundingClientRect().width||6,W=Oe-(Ie.clientX-we),Be=Um(W,ke,Ve,ft,Ae==null?void 0:Ae.resizableMinWidth,Ae==null?void 0:Ae.resizableMaxWidth);bt.element.style.width=`${Be}px`,bt.element.style.maxWidth="none",to()},ze=()=>{N.removeEventListener("pointermove",Ze),N.removeEventListener("pointerup",ze),N.removeEventListener("pointercancel",ze),Zn=null;try{$.releasePointerCapture(Y.pointerId)}catch{}};Zn=ze,N.addEventListener("pointermove",Ze),N.addEventListener("pointerup",ze),N.addEventListener("pointercancel",ze);try{$.setPointerCapture(Y.pointerId)}catch{}};$.addEventListener("pointerdown",ie),Ht=$,_n.insertBefore($,bt.element),Tn=()=>{$.removeEventListener("pointerdown",ie)}}if(Ht){let $=Fn.artifacts.length>0&&!Sn;Ht.classList.toggle("persona-hidden",!$),to()}},ve=()=>{var ae,ie,Y,we,Oe,Ae,Ze,ze,ct,rt,Ie,ke,je,Ve;if(!L||!bt||((ie=(ae=r.launcher)==null?void 0:ae.sidebarMode)!=null?ie:!1)||fn(r)&&gr(r).reveal==="emerge")return;let y=(Y=t.ownerDocument.defaultView)!=null?Y:window,T=(Oe=(we=r.launcher)==null?void 0:we.mobileFullscreen)!=null?Oe:!0,D=(Ze=(Ae=r.launcher)==null?void 0:Ae.mobileBreakpoint)!=null?Ze:640;if(T&&y.innerWidth<=D||!_m(r,L))return;let j=(rt=(ct=(ze=r.launcher)==null?void 0:ze.width)!=null?ct:r.launcherWidth)!=null?rt:jr,$=(Ve=(je=(ke=(Ie=r.features)==null?void 0:Ie.artifacts)==null?void 0:ke.layout)==null?void 0:je.expandedPanelWidth)!=null?Ve:"min(720px, calc(100vw - 24px))";Fn.artifacts.length>0&&!Sn?(Q.style.width=$,Q.style.maxWidth=$):(Q.style.width=j,Q.style.maxWidth=j)},typeof ResizeObserver!="undefined"&&(Nn=new ResizeObserver(()=>{In()}),Nn.observe(Q))}else Q.appendChild(Ce),H()&&dt&&(qe.peekBanner&&dt.appendChild(qe.peekBanner),dt.appendChild(Fe));t.appendChild(fe),dt&&t.appendChild(dt);let xr=()=>{var Be,We,ge,Ft,Bt,Gt,yt,jt,qn,en,Ge,kt,nn,rr,jn,So,To,Zo,es,Qt,Eo,oo,so,$r,Mo,pr,Lr,Qe;if(H()){Q.style.width="100%",Q.style.maxWidth="100%";let Ot=(We=(Be=r.launcher)==null?void 0:Be.composerBar)!=null?We:{},Kt=fe.dataset.state==="expanded",_t=(ge=Ot.expandedSize)!=null?ge:"anchored";if(!(Kt&&_t!=="fullscreen")){Ce.style.background="",Ce.style.border="",Ce.style.borderRadius="",Ce.style.overflow="",Ce.style.boxShadow="";return}let Lt=(Bt=(Ft=r.theme)==null?void 0:Ft.components)==null?void 0:Bt.panel,Ut=Na(r),pn=(mn,or)=>{var ao;return mn==null||mn===""?or:(ao=ps(Ut,mn))!=null?ao:mn},Vn="1px solid var(--persona-border)",Pr="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))";Ce.style.background="var(--persona-surface, #ffffff)",Ce.style.border=pn(Lt==null?void 0:Lt.border,Vn),Ce.style.borderRadius=pn(Lt==null?void 0:Lt.borderRadius,un),Ce.style.boxShadow=pn(Lt==null?void 0:Lt.shadow,Pr),Ce.style.overflow="hidden";return}let l=fn(r),p=(yt=(Gt=r.launcher)==null?void 0:Gt.sidebarMode)!=null?yt:!1,h=l||p||((qn=(jt=r.launcher)==null?void 0:jt.fullHeight)!=null?qn:!1),y=((en=r.launcher)==null?void 0:en.enabled)===!1,T=(kt=(Ge=r.theme)==null?void 0:Ge.components)==null?void 0:kt.panel,D=Na(r),j=(Ot,Kt)=>{var _t;return Ot==null||Ot===""?Kt:(_t=ps(D,Ot))!=null?_t:Ot},$=(nn=t.ownerDocument.defaultView)!=null?nn:window,N=(jn=(rr=r.launcher)==null?void 0:rr.mobileFullscreen)!=null?jn:!0,ae=(To=(So=r.launcher)==null?void 0:So.mobileBreakpoint)!=null?To:640,ie=$.innerWidth<=ae,Y=N&&ie&&L,we=(es=(Zo=r.launcher)==null?void 0:Zo.position)!=null?es:"bottom-left",Oe=we==="bottom-left"||we==="top-left",Ae=(Eo=(Qt=r.launcher)==null?void 0:Qt.zIndex)!=null?Eo:xn,Ze=p||Y?"none":"1px solid var(--persona-border)",ze=Y?"none":p?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&&(ze="none",Ze="none");let ct=p||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",rt=j(T==null?void 0:T.border,Ze),Ie=j(T==null?void 0:T.shadow,ze),ke=j(T==null?void 0:T.borderRadius,ct),je=Me.scrollTop;t.style.cssText="",fe.style.cssText="",Q.style.cssText="",Ce.style.cssText="",Me.style.cssText="",Fe.style.cssText="",G&&(Me.style.display="none");let Ve=()=>{var Kt;if(je<=0)return;((Kt=Me.ownerDocument.defaultView)!=null?Kt:window).requestAnimationFrame(()=>{if(Me.scrollTop===je)return;let _t=Me.scrollHeight-Me.clientHeight;_t<=0||(Me.scrollTop=Math.min(je,_t))})};if(Y){fe.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"),fe.style.cssText=`
|
|
34
|
+
`,k.addEventListener("click",()=>{g=C,B.forEach((q,_)=>{let R=_<C;q.classList.toggle("selected",R),q.setAttribute("aria-checked",_===C-1?"true":"false")})}),B.push(k),E.appendChild(k)}h.appendChild(E);let T=null;if(d){let C=document.createElement("div");C.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=s,T.rows=3,T.setAttribute("aria-label","Additional comments"),C.appendChild(T),h.appendChild(C)}let I=document.createElement("div");I.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=i,M.addEventListener("click",()=>{t==null||t(),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(g===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let C=(T==null?void 0:T.value.trim())||void 0;await e(g,C),p.remove()}catch(C){P.disabled=!1,P.textContent=a,console.error("[CSAT Feedback] Failed to submit:",C)}}),I.appendChild(M),I.appendChild(P),h.appendChild(I),p.appendChild(h),p}function Sg(n){let{onSubmit:e,onDismiss:t,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"}=n,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let h=null,m=document.createElement("div");m.className="persona-feedback-content";let y=document.createElement("div");y.className="persona-feedback-header";let w=document.createElement("h3");w.className="persona-feedback-title",w.textContent=r,y.appendChild(w);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=o,y.appendChild(E),m.appendChild(y);let B=document.createElement("div");B.className="persona-feedback-rating persona-feedback-rating-nps",B.setAttribute("role","radiogroup"),B.setAttribute("aria-label","Likelihood rating from 0 to 10");let T=document.createElement("div");T.className="persona-feedback-labels";let I=document.createElement("span");I.className="persona-feedback-label-low",I.textContent=c;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=p,T.appendChild(I),T.appendChild(M);let P=document.createElement("div");P.className="persona-feedback-numbers";let C=[];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",()=>{h=O,C.forEach((Z,ke)=>{Z.classList.toggle("selected",ke===O),Z.setAttribute("aria-checked",ke===O?"true":"false")})}),C.push(F),P.appendChild(F)}B.appendChild(T),B.appendChild(P),m.appendChild(B);let k=null;if(d){let O=document.createElement("div");O.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),O.appendChild(k),m.appendChild(O)}let q=document.createElement("div");q.className="persona-feedback-actions";let _=document.createElement("button");_.type="button",_.className="persona-feedback-btn persona-feedback-btn-skip",_.textContent=i,_.addEventListener("click",()=>{t==null||t(),g.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(h===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let O=(k==null?void 0:k.value.trim())||void 0;await e(h,O),g.remove()}catch(O){R.disabled=!1,R.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),q.appendChild(_),q.appendChild(R),m.appendChild(q),g.appendChild(m),g}var Es="persona-chat-history",gb=30*1e3,fb={"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 hb(n){var r,o,s;if(!n)return[];let e=[],t=Array.from((r=n.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){e.push(i);continue}let d=(o=fb[i.type])!=null?o:"png";e.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(e.length>0)return e;for(let a of Array.from((s=n.files)!=null?s:[]))a.type.startsWith("image/")&&e.push(a);return e}function gi(n){if(!n)return!1;let e=n.types;return e?typeof e.contains=="function"?e.contains("Files"):Array.from(e).includes("Files"):!1}function yb(n){var e,t,r,o,s,a,i,d,c;return n?n===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(e=n.storage)!=null?e:"session",keyPrefix:(t=n.keyPrefix)!=null?t:"persona-",persist:{openState:(o=(r=n.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=n.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=n.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=n.clearOnChatClear)!=null?c:!0}:null}function bb(n){try{let e=n==="local"?localStorage:sessionStorage,t="__persist_test__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return null}}var bl=n=>!n||typeof n!="object"?{}:{...n},Tg=n=>n.map(e=>({...e,streaming:!1})),Eg=(n,e,t)=>{let r=n!=null&&n.markdown?Sa(n.markdown):null,o=Ta(n==null?void 0:n.sanitize);return n!=null&&n.postprocessMessage&&o&&(n==null?void 0:n.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,g,h;let a=(p=s.text)!=null?p:"",i=(g=s.message.rawContent)!=null?g:null;if(e){let m=e.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});m!==null&&(a=m.text,m.persist||(s.message.__skipPersist=!0),m.resubmit&&!s.streaming&&t&&t())}let d=Oo()!==null,c;if(n!=null&&n.postprocessMessage){let m=n.postprocessMessage({...s,text:a,raw:(h=i!=null?i:s.text)!=null?h:""});c=o?o(m):m}else if(r){let m=s.streaming?xu(a):a,y=r(m);c=o&&d?o(y):y}else c=go(a);return c}};function Mg(n){var i,d,c,p;let e=v("div","persona-attachment-drop-overlay");n!=null&&n.background&&e.style.setProperty("--persona-drop-overlay-bg",n.background),(n==null?void 0:n.backdropBlur)!==void 0&&e.style.setProperty("--persona-drop-overlay-blur",n.backdropBlur),n!=null&&n.border&&e.style.setProperty("--persona-drop-overlay-border",n.border),n!=null&&n.borderRadius&&e.style.setProperty("--persona-drop-overlay-radius",n.borderRadius),n!=null&&n.inset&&e.style.setProperty("--persona-drop-overlay-inset",n.inset),n!=null&&n.labelSize&&e.style.setProperty("--persona-drop-overlay-label-size",n.labelSize),n!=null&&n.labelColor&&e.style.setProperty("--persona-drop-overlay-label-color",n.labelColor);let t=(i=n==null?void 0:n.iconName)!=null?i:"upload",r=(d=n==null?void 0:n.iconSize)!=null?d:"48px",o=(c=n==null?void 0:n.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(p=n==null?void 0:n.iconStrokeWidth)!=null?p:.5,a=ye(t,r,o,s);if(a&&e.appendChild(a),n!=null&&n.label){let g=v("span","persona-drop-overlay-label");g.textContent=n.label,e.appendChild(g)}return e}var kg=(n,e,t)=>{var ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,vc,wc,xc,Cc,Ac,Sc,Tc,Ec,Mc,kc,Lc,Pc,Ic,Rc,Wc,Hc,Bc,Dc,Nc,Fc,Oc,_c,$c,Uc,qc,zc,jc,Vc,Kc,Gc,Qc,Xc,Jc,Yc,Zc,ed,td,nd;if(n==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');n.id&&!n.getAttribute("data-persona-instance")&&n.setAttribute("data-persona-instance",n.id),n.hasAttribute("data-persona-root")||n.setAttribute("data-persona-root","true");let r=ym(e),o=ml.getForInstance(r.plugins),{plugin:s,teardown:a}=tg();r.components&&Go.registerAll(r.components);let i=hg(),c=r.persistState===!1?null:(ic=r.storageAdapter)!=null?ic:bg(),p={},g=null,h=!1,m=l=>{if(r.onStateLoaded)try{let u=r.onStateLoaded(l);if(u&&typeof u=="object"&&"state"in u){let{state:f,open:b}=u;return b&&(h=!0),f}return u}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(c!=null&&c.load)try{let l=c.load();if(l&&typeof l.then=="function")g=l.then(u=>{let f=u!=null?u:{messages:[],metadata:{}};return m(f)});else{let u=l!=null?l:{messages:[],metadata:{}},f=m(u);f.metadata&&(p=bl(f.metadata)),(lc=f.messages)!=null&&lc.length&&(r={...r,initialMessages:f.messages}),(cc=f.artifacts)!=null&&cc.length&&(r={...r,initialArtifacts:f.artifacts,initialSelectedArtifactId:(dc=f.selectedArtifactId)!=null?dc:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=m({messages:[],metadata:{}});(pc=l.messages)!=null&&pc.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let y=()=>p,w=l=>{var f;p=(f=l({...p}))!=null?f:{},In()},E=r.actionParsers&&r.actionParsers.length?r.actionParsers:[fl],B=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ga.message,ga.messageAndClick],T=hl({parsers:E,handlers:B,getSessionMetadata:y,updateSessionMetadata:w,emit:i.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let I=(mc=(uc=r.launcher)==null?void 0:uc.enabled)!=null?mc:!0,M=(fc=(gc=r.launcher)==null?void 0:gc.autoExpand)!=null?fc:!1,P=(hc=r.autoFocusInput)!=null?hc:!1,C=M,k=I,q=(bc=(yc=r.layout)==null?void 0:yc.header)==null?void 0:bc.layout,_=!1,R=()=>la(r),O=()=>I||R(),F=R()?!1:I?M:!0,Z=!1,ke=null,pe=()=>{Z=!0,ke&&clearTimeout(ke),ke=setTimeout(()=>{Z&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Z=!1)},1e4)},ee=Eg(r,T,pe),Pe=(wc=(vc=r.features)==null?void 0:vc.showReasoning)!=null?wc:!0,Ie=(Cc=(xc=r.features)==null?void 0:xc.showToolCalls)!=null?Cc:!0,ie=(Sc=(Ac=r.features)==null?void 0:Ac.showEventStreamToggle)!=null?Sc:!1,he=(Ec=(Tc=r.features)==null?void 0:Tc.scrollToBottom)!=null?Ec:{},re=(kc=(Mc=r.features)==null?void 0:Mc.scrollBehavior)!=null?kc:{},de=`${(Pc=typeof r.persistState=="object"?(Lc=r.persistState)==null?void 0:Lc.keyPrefix:void 0)!=null?Pc:"persona-"}event-stream`,Ae=ie?new ua(de):null,$e=(Wc=(Rc=(Ic=r.features)==null?void 0:Ic.eventStream)==null?void 0:Rc.maxEvents)!=null?Wc:2e3,K=ie?new pa($e,Ae):null,J=ie?new ma:null,Se=null,Y=!1,le=null,Te=0;Ae==null||Ae.open().then(()=>K==null?void 0:K.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Ye={onCopy:l=>{var u,f;i.emit("message:copy",l),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(l.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(f=(u=r.messageActions)==null?void 0:u.onCopy)==null||f.call(u,l)},onFeedback:l=>{var u,f;i.emit("message:feedback",l),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(l.messageId,l.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(f=(u=r.messageActions)==null?void 0:u.onFeedback)==null||f.call(u,l)}},tt=(Hc=r.statusIndicator)!=null?Hc:{},Wt=l=>{var u,f,b,S,W,z;return l==="idle"?(u=tt.idleText)!=null?u:nn.idle:l==="connecting"?(f=tt.connectingText)!=null?f:nn.connecting:l==="connected"?(b=tt.connectedText)!=null?b:nn.connected:l==="error"?(S=tt.errorText)!=null?S:nn.error:l==="paused"?(W=tt.pausedText)!=null?W:nn.paused:l==="resuming"?(z=tt.resumingText)!=null?z:nn.resuming:nn[l]};function ht(l,u,f,b){if(b==="idle"&&f.idleLink){l.textContent="";let S=document.createElement("a");S.href=f.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=u,S.style.color="inherit",S.style.textDecoration="none",l.appendChild(S)}else l.textContent=u}let ot=qm({config:r,showClose:O()}),{wrapper:me,panel:X,pillRoot:lt}=ot.shell,Ve=ot.panelElements,{container:Ee,body:xe,messagesWrapper:Ze,suggestions:jt,textarea:be,sendButton:ue,sendButtonWrapper:xn,composerForm:At,statusText:fn,introTitle:hr,introSubtitle:yr,closeButton:qe,iconHolder:L,headerTitle:ge,headerSubtitle:Me,header:Le,footer:He,actionsRow:nt,leftActions:Xe,rightActions:yt}=Ve,fe=Ve.setSendButtonMode,D=Ve.micButton,ve=Ve.micButtonWrapper,ce=Ve.attachmentButton,ft=Ve.attachmentButtonWrapper,Ge=Ve.attachmentInput,Pt=Ve.attachmentPreviewsContainer;Ee.classList.add("persona-relative"),xe.classList.add("persona-relative");let kt=12,wt=()=>{var l;return(l=he.label)!=null?l:""},Ht=()=>{var l;return(l=he.iconName)!=null?l:"arrow-down"},Xt=()=>he.enabled!==!1,Ot=()=>{var l;return(l=re.mode)!=null?l:"anchor-top"},en=()=>Ot()==="follow"||Ot()==="anchor-top"&&no,br=()=>{var l;return(l=re.anchorTopOffset)!=null?l:16},Wr=()=>{var l;return(l=re.restorePosition)!=null?l:"bottom"},rr=()=>re.pauseOnInteraction===!0,or=()=>re.showActivityWhilePinned!==!1,Kr=()=>re.announce===!0,Vt=v("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");Vt.type="button",Vt.style.display="none",Vt.setAttribute("data-persona-scroll-to-bottom","true");let sr=v("span","persona-flex persona-items-center"),Hr=v("span",""),Bn=v("span","");Bn.setAttribute("data-persona-scroll-to-bottom-count",""),Bn.style.display="none",Vt.append(sr,Hr,Bn),Ee.appendChild(Vt);let Ln=v("div","persona-stream-anchor-spacer");Ln.setAttribute("aria-hidden","true"),Ln.setAttribute("data-persona-anchor-spacer",""),Ln.style.flexShrink="0",Ln.style.pointerEvents="none",Ln.style.height="0px",xe.appendChild(Ln);let Dn=v("div","persona-sr-only");Dn.setAttribute("aria-live","polite"),Dn.setAttribute("aria-atomic","true"),Dn.setAttribute("role","status"),Dn.setAttribute("data-persona-live-region",""),Object.assign(Dn.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"}),Ee.appendChild(Dn);let ar=null,vr=null,Gr=l=>{!Kr()||!l||(vr=l,ar===null&&(ar=setTimeout(()=>{ar=null,vr&&Kr()&&(Dn.textContent=vr),vr=null},400)))},Vn=()=>{let u=He.style.display==="none"?0:He.offsetHeight;Vt.style.bottom=`${u+kt}px`};Vn();let Qr=()=>{let l=!!wt();Vt.setAttribute("aria-label",wt()||"Jump to latest"),Vt.title=wt(),Vt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),sr.innerHTML="";let u=ye(Ht(),"14px","currentColor",2);u?(sr.appendChild(u),sr.style.display=""):sr.style.display="none",Hr.textContent=wt(),Hr.style.display=l?"":"none"};Qr();let St=null,wr=null,xr=o.find(l=>l.renderHeader);if(xr!=null&&xr.renderHeader){let l=xr.renderHeader({config:r,defaultRenderer:()=>{let u=zo({config:r,showClose:O()});return ca(Ee,u,r),u.header},onClose:()=>$t(!1,"user")});if(l){let u=Ee.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(l),Le=l,ot.header.element=l)}}let Br=()=>{var u,f,b,S;if(!K)return;if(Y=!0,!Se&&K&&(Se=ag({buffer:K,getFullHistory:()=>K.getAllFromStore(),onClose:()=>ir(),config:r,plugins:o,getThroughput:()=>{var W;return(W=J==null?void 0:J.getMetric())!=null?W:{status:"idle"}}})),Se&&(xe.style.display="none",(u=He.parentNode)==null||u.insertBefore(Se.element,He),Se.update()),bt){bt.style.boxShadow=`inset 0 0 0 1.5px ${kn.actionIconColor}`;let W=(S=(b=(f=r.features)==null?void 0:f.eventStream)==null?void 0:b.classNames)==null?void 0:S.toggleButtonActive;W&&W.split(/\s+/).forEach(z=>z&&bt.classList.add(z))}let l=()=>{if(!Y)return;let W=Date.now();W-Te>=200&&(Se==null||Se.update(),Te=W),le=requestAnimationFrame(l)};Te=0,le=requestAnimationFrame(l),_n(),i.emit("eventStream:opened",{timestamp:Date.now()})},ir=()=>{var l,u,f;if(Y){if(Y=!1,Se&&Se.element.remove(),xe.style.display="",bt){bt.style.boxShadow="";let b=(f=(u=(l=r.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:f.toggleButtonActive;b&&b.split(/\s+/).forEach(S=>S&&bt.classList.remove(S))}le!==null&&(cancelAnimationFrame(le),le=null),_n(),i.emit("eventStream:closed",{timestamp:Date.now()})}},bt=null;if(ie){let l=(Dc=(Bc=r.features)==null?void 0:Bc.eventStream)==null?void 0:Dc.classNames,u="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");bt=v("button",u),bt.style.width="28px",bt.style.height="28px",bt.style.color=kn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let f=ye("activity","18px","currentColor",1.5);f&&bt.appendChild(f);let b=Ve.clearChatButtonWrapper,S=Ve.closeButtonWrapper,W=b||S;W&&W.parentNode===Le?Le.insertBefore(bt,W):Le.appendChild(bt),bt.addEventListener("click",()=>{Y?ir():Br()})}let Co=l=>{var S,W,z,U,N;let u=r.attachments;if(!(u!=null&&u.enabled))return;let f=(S=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?S:l.querySelector(".persona-attachment-previews");if(!f){f=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),f.setAttribute("data-persona-composer-attachment-previews",""),f.style.display="none";let ae=l.querySelector("[data-persona-composer-form]");ae!=null&&ae.parentNode?ae.parentNode.insertBefore(f,ae):l.insertBefore(f,l.firstChild)}if(!((W=l.querySelector("[data-persona-composer-attachment-input]"))!=null?W:l.querySelector('input[type="file"]'))){let ae=v("input");ae.type="file",ae.setAttribute("data-persona-composer-attachment-input",""),ae.accept=((z=u.allowedTypes)!=null?z:jr).join(","),ae.multiple=((U=u.maxFiles)!=null?U:4)>1,ae.style.display="none",ae.setAttribute("aria-label",(N=u.buttonTooltipText)!=null?N:"Attach files"),l.appendChild(ae)}},Cr=o.find(l=>l.renderComposer);if(Cr!=null&&Cr.renderComposer){let l=r.composer,u=Cr.renderComposer({config:r,defaultRenderer:()=>li({config:r}).footer,onSubmit:f=>{var z;if(!$||$.isStreaming())return;let b=f.trim(),S=(z=St==null?void 0:St.hasAttachments())!=null?z:!1;if(!b&&!S)return;Dl();let W;S&&(W=[],W.push(...St.getContentParts()),b&&W.push($i(b))),$.sendMessage(b,{contentParts:W}),S&&St.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ge==null||Ge.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:f=>{r.composer={...r.composer,selectedModelId:f},r.agent&&(r.agent={...r.agent,model:f})},onVoiceToggle:((Nc=r.voiceRecognition)==null?void 0:Nc.enabled)===!0?()=>{wr==null||wr()}:void 0});u&&(ot.replaceComposer(u),He=ot.composer.footer)}let Ao=l=>{let u=(...se)=>{for(let te of se){let we=l.querySelector(te);if(we)return we}return null},f=l.querySelector("[data-persona-composer-form]"),b=l.querySelector("[data-persona-composer-input]"),S=l.querySelector("[data-persona-composer-submit]"),W=l.querySelector("[data-persona-composer-mic]"),z=l.querySelector("[data-persona-composer-status]");f&&(At=f),b&&(be=b),S&&(ue=S),W&&(D=W,ve=W.parentElement),z&&(fn=z);let U=u("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");U&&(jt=U);let N=u("[data-persona-composer-attachment-button]",".persona-attachment-button");N&&(ce=N,ft=N.parentElement),Ge=u("[data-persona-composer-attachment-input]",'input[type="file"]'),Pt=u("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ae=u("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ae&&(nt=ae)};Co(He),Ao(He);let Pn=(Uc=(Fc=r.layout)==null?void 0:Fc.contentMaxWidth)!=null?Uc:R()?($c=(_c=(Oc=r.launcher)==null?void 0:Oc.composerBar)==null?void 0:_c.contentMaxWidth)!=null?$c:"720px":void 0;if(Pn&&(Ze.style.maxWidth=Pn,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%"),Pn&&At&&!R()&&(At.style.maxWidth=Pn,At.style.marginLeft="auto",At.style.marginRight="auto"),Pn&&jt&&!R()&&(jt.style.maxWidth=Pn,jt.style.marginLeft="auto",jt.style.marginRight="auto"),Pn&&Pt&&!R()&&(Pt.style.maxWidth=Pn,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),(qc=r.attachments)!=null&&qc.enabled&&Ge&&Pt){St=ta.fromConfig(r.attachments),St.setPreviewsContainer(Pt),Ge.addEventListener("change",f=>{let b=f.target;St==null||St.handleFileSelect(b.files),b.value=""});let l=r.attachments.dropOverlay,u=Mg(l);Ee.appendChild(u)}(()=>{var b,S;let l=(S=(b=r.layout)==null?void 0:b.slots)!=null?S:{},u=W=>{switch(W){case"body-top":return Ee.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ze;case"footer-top":return jt;case"composer":return At;case"footer-bottom":return fn;default:return null}},f=(W,z)=>{var U;switch(W){case"header-left":case"header-center":case"header-right":if(W==="header-left")Le.insertBefore(z,Le.firstChild);else if(W==="header-right")Le.appendChild(z);else{let N=Le.querySelector(".persona-flex-col");N?(U=N.parentNode)==null||U.insertBefore(z,N.nextSibling):Le.appendChild(z)}break;case"body-top":{let N=xe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith(z):xe.insertBefore(z,xe.firstChild);break}case"body-bottom":xe.appendChild(z);break;case"footer-top":jt.replaceWith(z);break;case"footer-bottom":fn.replaceWith(z);break;default:break}};for(let[W,z]of Object.entries(l))if(z)try{let U=z({config:r,defaultContent:()=>u(W)});U&&f(W,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${W}":`,U)}})();let Xr=l=>{var z,U;let f=l.target.closest('button[data-expand-header="true"]');if(!f)return;let b=f.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let W=f.getAttribute("data-bubble-type");if(W==="reasoning")As.has(S)?As.delete(S):As.add(S),Vm(S,b);else if(W==="tool")Ss.has(S)?Ss.delete(S):Ss.add(S),Km(S,b,r);else if(W==="approval"){let N=r.approval!==!1?r.approval:void 0,ae=((z=N==null?void 0:N.detailsDisplay)!=null?z:"collapsed")==="expanded",se=(U=jo.get(S))!=null?U:ae;jo.set(S,!se),Jm(S,b,r)}Er.delete(S)};Ze.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Xr(l))}),Ze.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Xr(l))}),Ze.addEventListener("copy",l=>{let{clipboardData:u}=l;if(!u)return;let f=Ze.getRootNode(),b=typeof f.getSelection=="function"?f.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let S=b.toString(),W=Sm(S);!W||W===S||(u.setData("text/plain",W),l.preventDefault())});let Dr=new Map,Jr=null,Yr="idle",So={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},To=(l,u)=>{let{icon:f,label:b}=So[u];l.setAttribute("aria-label",b),l.title=b,l.setAttribute("aria-pressed",u==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",u!=="idle"),l.classList.toggle("persona-message-action-loading",u==="loading");let S=ye(f,14,"currentColor",2);S&&(l.innerHTML="",l.appendChild(S))},Zr=()=>{Ze.querySelectorAll('[data-action="read-aloud"]').forEach(u=>{var W;let f=u.closest("[data-actions-for]"),b=(W=f==null?void 0:f.getAttribute("data-actions-for"))!=null?W:null;To(u,b&&b===Jr?Yr:"idle")})};Ze.addEventListener("click",l=>{var z;let f=l.target.closest(".persona-message-action-btn[data-action]");if(!f)return;l.preventDefault(),l.stopPropagation();let b=f.closest("[data-actions-for]");if(!b)return;let S=b.getAttribute("data-actions-for");if(!S)return;let W=f.getAttribute("data-action");if(W==="copy"){let N=$.getMessages().find(ae=>ae.id===S);if(N&&Ye.onCopy){let ae=N.content||"";navigator.clipboard.writeText(ae).then(()=>{f.classList.add("persona-message-action-success");let se=ye("check",14,"currentColor",2);se&&(f.innerHTML="",f.appendChild(se)),setTimeout(()=>{f.classList.remove("persona-message-action-success");let te=ye("copy",14,"currentColor",2);te&&(f.innerHTML="",f.appendChild(te))},2e3)}).catch(se=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",se)}),Ye.onCopy(N)}}else if(W==="read-aloud")$.toggleReadAloud(S);else if(W==="upvote"||W==="downvote"){let N=((z=Dr.get(S))!=null?z:null)===W,ae=W==="upvote"?"thumbs-up":"thumbs-down";if(N){Dr.delete(S),f.classList.remove("persona-message-action-active");let se=ye(ae,14,"currentColor",2);se&&(f.innerHTML="",f.appendChild(se))}else{let se=W==="upvote"?"downvote":"upvote",te=b.querySelector(`[data-action="${se}"]`);if(te){te.classList.remove("persona-message-action-active");let ze=ye(se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);ze&&(te.innerHTML="",te.appendChild(ze))}Dr.set(S,W),f.classList.add("persona-message-action-active");let we=ye(ae,14,"currentColor",2);we&&(we.setAttribute("fill","currentColor"),f.innerHTML="",f.appendChild(we)),f.classList.remove("persona-message-action-pop"),f.offsetWidth,f.classList.add("persona-message-action-pop");let Oe=$.getMessages().find(Ue=>Ue.id===S);Oe&&Ye.onFeedback&&Ye.onFeedback({type:W,messageId:Oe.id,message:Oe})}}}),Ze.addEventListener("click",l=>{let f=l.target.closest("button[data-approval-action]");if(!f)return;l.preventDefault(),l.stopPropagation();let b=f.closest(".persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let W=f.getAttribute("data-approval-action");if(!W)return;let z=W==="approve"?"approved":"denied",N=$.getMessages().find(se=>se.id===S);if(!(N!=null&&N.approval))return;let ae=b.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(te=>{te.disabled=!0,te.style.opacity="0.5",te.style.cursor="not-allowed"}),N.approval.toolType==="webmcp"?$.resolveWebMcpApproval(S,z):$.resolveApproval(N.approval,z)});let xt=null,Nn=null,Fn={artifacts:[],selectedId:null},Cn=!1,Tt={current:null};Ze.addEventListener("click",l=>{var te,we,Fe,Oe,Ue;let f=l.target.closest("[data-download-artifact]");if(!f)return;l.preventDefault(),l.stopPropagation();let b=f.getAttribute("data-download-artifact");if(!b||((Fe=(we=(te=r.features)==null?void 0:te.artifacts)==null?void 0:we.onArtifactAction)==null?void 0:Fe.call(we,{type:"download",artifactId:b}))===!0)return;let W=$.getArtifactById(b),z=W==null?void 0:W.markdown,U=(W==null?void 0:W.title)||"artifact";if(!z){let ze=f.closest("[data-open-artifact]"),mt=ze==null?void 0:ze.closest("[data-message-id]"),at=mt==null?void 0:mt.getAttribute("data-message-id");if(at){let Re=$.getMessages().find(je=>je.id===at);if(Re!=null&&Re.rawContent)try{let je=JSON.parse(Re.rawContent);z=(Oe=je==null?void 0:je.props)==null?void 0:Oe.markdown,U=((Ue=je==null?void 0:je.props)==null?void 0:Ue.title)||U}catch{}}}if(!z)return;let N=new Blob([z],{type:"text/markdown"}),ae=URL.createObjectURL(N),se=document.createElement("a");se.href=ae,se.download=`${U}.md`,se.click(),URL.revokeObjectURL(ae)}),Ze.addEventListener("click",l=>{var W,z,U;let f=l.target.closest("[data-open-artifact]");if(!f)return;let b=f.getAttribute("data-open-artifact");!b||((U=(z=(W=r.features)==null?void 0:W.artifacts)==null?void 0:z.onArtifactAction)==null?void 0:U.call(z,{type:"open",artifactId:b}))===!0||(l.preventDefault(),l.stopPropagation(),Cn=!1,$.selectArtifact(b),Ar())}),Ze.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let u=l.target;u.hasAttribute("data-open-artifact")&&(l.preventDefault(),u.click())});let Kn=Ve.composerOverlay,Gn=(l,u,f)=>{var U,N,ae,se;let b=u.trim();if(!b||!Tt.current)return;let S=(U=l.getAttribute("data-tool-call-id"))!=null?U:"",W=f.source==="free-text";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:b,answers:f.structured,values:(N=f.values)!=null?N:f.source==="multi"?b.split(", "):[b],isFreeText:W,source:f.source},bubbles:!0,composed:!0})),ms(Kn,S);let z=Tt.current.getMessages().find(te=>{var we;return((we=te.toolCall)==null?void 0:we.id)===S});(ae=z==null?void 0:z.agentMetadata)!=null&&ae.awaitingLocalTool?Tt.current.resolveAskUserQuestion(z,(se=f.structured)!=null?se:b):Tt.current.sendMessage(b)},On=l=>{var S;let u=Tt.current;if(!u)return;let f=(S=l.getAttribute("data-tool-call-id"))!=null?S:"",b=u.getMessages().find(W=>{var z;return((z=W.toolCall)==null?void 0:z.id)===f});b&&u.persistAskUserQuestionProgress(b,{answers:ka(l,b),currentIndex:tr(l)})},eo=l=>Object.entries(l).map(([u,f])=>`${u}: ${Array.isArray(f)?f.join(", "):f}`).join(" | "),Ce=l=>{var S,W,z;if(((W=(S=r.features)==null?void 0:S.askUserQuestion)==null?void 0:W.groupedAutoAdvance)===!1)return;let u=tr(l),f=us(l);if(u>=f-1)return;let b=(z=Tt.current)==null?void 0:z.getMessages().find(U=>{var N;return((N=U.toolCall)==null?void 0:N.id)===l.getAttribute("data-tool-call-id")});b&&(Pa(l,b,r,u+1),On(l))};Kn.addEventListener("click",l=>{var W,z,U,N,ae,se,te,we,Fe,Oe,Ue,ze,mt,at;let f=l.target.closest("[data-ask-user-action]");if(!f)return;let b=f.closest("[data-persona-ask-sheet-for]");if(!b)return;let S=f.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),S==="dismiss"){let Be=(W=b.getAttribute("data-tool-call-id"))!=null?W:"";n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),ms(Kn,Be);let Re=(z=Tt.current)==null?void 0:z.getMessages().find(je=>{var Qe;return((Qe=je.toolCall)==null?void 0:Qe.id)===Be});(U=Re==null?void 0:Re.agentMetadata)!=null&&U.awaitingLocalTool&&((N=Tt.current)==null||N.markAskUserQuestionResolved(Re),(ae=Tt.current)==null||ae.resolveAskUserQuestion(Re,"(dismissed)"));return}if(S==="pick"){let Be=f.getAttribute("data-option-label");if(!Be)return;let Re=b.getAttribute("data-multi-select")==="true",je=ho(b);if(je&&Re){let Qe=$o(b)[tr(b)],vt=new Set(Array.isArray(Qe)?Qe:[]);vt.has(Be)?vt.delete(Be):vt.add(Be),yo(b,Array.from(vt)),On(b);return}if(je){yo(b,Be),On(b),Ce(b);return}if(Re){let Qe=f.getAttribute("aria-pressed")==="true";f.setAttribute("aria-pressed",Qe?"false":"true"),f.classList.toggle("persona-ask-pill-selected",!Qe);let vt=b.querySelector('[data-ask-user-action="submit-multi"]');vt&&(vt.disabled=Bi(b).length===0);return}Gn(b,Be,{source:"pick",values:[Be]});return}if(S==="submit-multi"){let Be=Bi(b);if(Be.length===0)return;Gn(b,Be.join(", "),{source:"multi",values:Be});return}if(S==="open-free-text"){let Be=b.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(S==="focus-free-text"){let Be=b.querySelector('[data-ask-free-text-input="true"]');Be==null||Be.focus();return}if(S==="submit-free-text"){let Be=b.querySelector('[data-ask-free-text-input="true"]'),Re=(se=Be==null?void 0:Be.value)!=null?se:"";if(!Re.trim())return;if(ho(b)){yo(b,Re.trim()),On(b),Ce(b);return}Gn(b,Re,{source:"free-text"});return}if(S==="next"||S==="back"){if(!Tt.current)return;let Be=(te=b.getAttribute("data-tool-call-id"))!=null?te:"",Re=Tt.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Be});if(!Re)return;let je=b.querySelector('[data-ask-free-text-input="true"]'),Qe=(Fe=(we=je==null?void 0:je.value)==null?void 0:we.trim())!=null?Fe:"";if(Qe){let De=$o(b)[tr(b)];(typeof De!="string"||De!==Qe)&&yo(b,Qe)}let vt=S==="next"?1:-1,H=tr(b)+vt;Pa(b,Re,r,H),On(b);return}if(S==="submit-all"){if(!Tt.current)return;let Be=(Oe=b.getAttribute("data-tool-call-id"))!=null?Oe:"",Re=Tt.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Be});if(!Re)return;let je=b.querySelector('[data-ask-free-text-input="true"]'),Qe=(ze=(Ue=je==null?void 0:je.value)==null?void 0:Ue.trim())!=null?ze:"";Qe&&yo(b,Qe);let vt=ka(b,Re);Tt.current.persistAskUserQuestionProgress(Re,{answers:vt,currentIndex:tr(b)});let H=eo(vt);Gn(b,H||"(submitted)",{source:"submit-all",structured:vt});return}if(S==="skip"){if(!Tt.current)return;let Be=(mt=b.getAttribute("data-tool-call-id"))!=null?mt:"",Re=Tt.current.getMessages().find(We=>{var Je;return((Je=We.toolCall)==null?void 0:Je.id)===Be});if(!Re)return;let je=ho(b),Qe=tr(b),vt=us(b),H=Qe>=vt-1;if(!je){n.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),ms(Kn,Be),(at=Re.agentMetadata)!=null&&at.awaitingLocalTool&&(Tt.current.markAskUserQuestionResolved(Re),Tt.current.resolveAskUserQuestion(Re,"(dismissed)"));return}yo(b,"");let De=b.querySelector('[data-ask-free-text-input="true"]');if(De&&(De.value=""),H){let We=ka(b,Re),Je=eo(We);Gn(b,Je||"(skipped)",{source:"submit-all",structured:We});return}Pa(b,Re,r,Qe+1),On(b);return}}),Kn.addEventListener("keydown",l=>{var W;if(l.key!=="Enter")return;let f=l.target;if(!((W=f.matches)!=null&&W.call(f,'[data-ask-free-text-input="true"]')))return;let b=f.closest("[data-persona-ask-sheet-for]");if(!b)return;l.preventDefault();let S=f.value;if(S.trim()){if(ho(b)){yo(b,S.trim()),On(b),Ce(b);return}Gn(b,S,{source:"free-text"})}});let Nr=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let u=l.target;if((u==null?void 0:u.tagName)==="INPUT"||(u==null?void 0:u.tagName)==="TEXTAREA"||u!=null&&u.isContentEditable)return;let f=Kn.querySelector("[data-persona-ask-sheet-for]");if(!f||f.getAttribute("data-ask-layout")!=="rows"||f.getAttribute("data-multi-select")==="true")return;let b=Number(l.key),W=f.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];W&&(l.preventDefault(),W.click())};document.addEventListener("keydown",Nr);let Qn=null,_t=null,Xn=null,Fr=null,ks=()=>{};function Xo(){Fr==null||Fr(),Fr=null}let Ls=()=>{var z;if(!Qn||!_t)return;let l=n.classList.contains("persona-artifact-appearance-seamless"),f=((z=n.ownerDocument.defaultView)!=null?z:window).innerWidth<=640;if(!l||n.classList.contains("persona-artifact-narrow-host")||f){_t.style.removeProperty("position"),_t.style.removeProperty("left"),_t.style.removeProperty("top"),_t.style.removeProperty("bottom"),_t.style.removeProperty("width"),_t.style.removeProperty("z-index");return}let b=Qn.firstElementChild;if(!b||b===_t)return;let S=10;_t.style.position="absolute",_t.style.top="0",_t.style.bottom="0",_t.style.width=`${S}px`,_t.style.zIndex="5";let W=b.offsetWidth-S/2;_t.style.left=`${Math.max(0,W)}px`},Eo=()=>{},Ar=()=>{var f,b,S,W,z;if(!xt||!nr(r))return;ui(n,r),mi(n,r),Eo();let l=(W=(S=(b=(f=r.features)==null?void 0:f.artifacts)==null?void 0:b.layout)==null?void 0:S.narrowHostMaxWidth)!=null?W:520,u=X.getBoundingClientRect().width||0;n.classList.toggle("persona-artifact-narrow-host",u>0&&u<=l),xt.update(Fn),Cn?(xt.setMobileOpen(!1),xt.element.classList.add("persona-hidden"),(z=xt.backdrop)==null||z.classList.add("persona-hidden")):Fn.artifacts.length>0&&(xt.element.classList.remove("persona-hidden"),xt.setMobileOpen(!0)),ks()};if(nr(r)){X.style.position="relative";let l=v("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=v("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(Ee),xt=cg(r,{onSelect:f=>{var b;return(b=Tt.current)==null?void 0:b.selectArtifact(f)},onDismiss:()=>{Cn=!0,Ar()}}),xt.element.classList.add("persona-hidden"),Qn=u,u.appendChild(l),u.appendChild(xt.element),xt.backdrop&&X.appendChild(xt.backdrop),X.appendChild(u),ks=()=>{var b,S,W,z;if(!Qn||!xt)return;if(!(((W=(S=(b=r.features)==null?void 0:b.artifacts)==null?void 0:S.layout)==null?void 0:W.resizable)===!0)){Xn==null||Xn(),Xn=null,Xo(),_t&&(_t.remove(),_t=null),xt.element.style.removeProperty("width"),xt.element.style.removeProperty("maxWidth");return}if(!_t){let U=v("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");U.setAttribute("role","separator"),U.setAttribute("aria-orientation","vertical"),U.setAttribute("aria-label","Resize artifacts panel"),U.tabIndex=0;let N=n.ownerDocument,ae=(z=N.defaultView)!=null?z:window,se=te=>{var mt,at;if(!xt||te.button!==0||n.classList.contains("persona-artifact-narrow-host")||ae.innerWidth<=640)return;te.preventDefault(),Xo();let we=te.clientX,Fe=xt.element.getBoundingClientRect().width,Oe=(at=(mt=r.features)==null?void 0:mt.artifacts)==null?void 0:at.layout,Ue=Be=>{let Re=Qn.getBoundingClientRect().width,je=n.classList.contains("persona-artifact-appearance-seamless"),Qe=je?0:mg(Qn,ae),vt=je?0:U.getBoundingClientRect().width||6,H=Fe-(Be.clientX-we),De=gg(H,Re,Qe,vt,Oe==null?void 0:Oe.resizableMinWidth,Oe==null?void 0:Oe.resizableMaxWidth);xt.element.style.width=`${De}px`,xt.element.style.maxWidth="none",Ls()},ze=()=>{N.removeEventListener("pointermove",Ue),N.removeEventListener("pointerup",ze),N.removeEventListener("pointercancel",ze),Fr=null;try{U.releasePointerCapture(te.pointerId)}catch{}};Fr=ze,N.addEventListener("pointermove",Ue),N.addEventListener("pointerup",ze),N.addEventListener("pointercancel",ze);try{U.setPointerCapture(te.pointerId)}catch{}};U.addEventListener("pointerdown",se),_t=U,Qn.insertBefore(U,xt.element),Xn=()=>{U.removeEventListener("pointerdown",se)}}if(_t){let U=Fn.artifacts.length>0&&!Cn;_t.classList.toggle("persona-hidden",!U),Ls()}},Eo=()=>{var ae,se,te,we,Fe,Oe,Ue,ze,mt,at,Be,Re,je,Qe;if(!I||!xt||((se=(ae=r.launcher)==null?void 0:ae.sidebarMode)!=null?se:!1)||gn(r)&&gr(r).reveal==="emerge")return;let b=(te=n.ownerDocument.defaultView)!=null?te:window,S=(Fe=(we=r.launcher)==null?void 0:we.mobileFullscreen)!=null?Fe:!0,W=(Ue=(Oe=r.launcher)==null?void 0:Oe.mobileBreakpoint)!=null?Ue:640;if(S&&b.innerWidth<=W||!ug(r,I))return;let z=(at=(mt=(ze=r.launcher)==null?void 0:ze.width)!=null?mt:r.launcherWidth)!=null?at:Vr,U=(Qe=(je=(Re=(Be=r.features)==null?void 0:Be.artifacts)==null?void 0:Re.layout)==null?void 0:je.expandedPanelWidth)!=null?Qe:"min(720px, calc(100vw - 24px))";Fn.artifacts.length>0&&!Cn?(X.style.width=U,X.style.maxWidth=U):(X.style.width=z,X.style.maxWidth=z)},typeof ResizeObserver!="undefined"&&(Nn=new ResizeObserver(()=>{Ar()}),Nn.observe(X))}else X.appendChild(Ee),R()&<&&(Ve.peekBanner&<.appendChild(Ve.peekBanner),lt.appendChild(He));n.appendChild(me),lt&&n.appendChild(lt);let to=()=>{var De,We,Je,It,_e,Gt,Ct,an,Wn,Dt,un,$n,Ke,Rt,Un,Io,Ro,Wo,Ho,ss,as,Qt,Bo,po,uo,Ur,Do,et;if(R()){X.style.width="100%",X.style.maxWidth="100%";let Ft=(We=(De=r.launcher)==null?void 0:De.composerBar)!=null?We:{},Nt=me.dataset.state==="expanded",Kt=(Je=Ft.expandedSize)!=null?Je:"anchored";if(!(Nt&&Kt!=="fullscreen")){Ee.style.background="",Ee.style.border="",Ee.style.borderRadius="",Ee.style.overflow="",Ee.style.boxShadow="";return}let gt=(_e=(It=r.theme)==null?void 0:It.components)==null?void 0:_e.panel,qt=qa(r),mn=(pn,er)=>{var mo;return pn==null||pn===""?er:(mo=vs(qt,pn))!=null?mo:pn},qn="1px solid var(--persona-border)",Pr="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",dn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Ee.style.background="var(--persona-surface, #ffffff)",Ee.style.border=mn(gt==null?void 0:gt.border,qn),Ee.style.borderRadius=mn(gt==null?void 0:gt.borderRadius,dn),Ee.style.boxShadow=mn(gt==null?void 0:gt.shadow,Pr),Ee.style.overflow="hidden";return}let l=gn(r),u=(Ct=(Gt=r.launcher)==null?void 0:Gt.sidebarMode)!=null?Ct:!1,f=l||u||((Wn=(an=r.launcher)==null?void 0:an.fullHeight)!=null?Wn:!1),b=((Dt=r.launcher)==null?void 0:Dt.enabled)===!1,S=($n=(un=r.theme)==null?void 0:un.components)==null?void 0:$n.panel,W=qa(r),z=(Ft,Nt)=>{var Kt;return Ft==null||Ft===""?Nt:(Kt=vs(W,Ft))!=null?Kt:Ft},U=(Ke=n.ownerDocument.defaultView)!=null?Ke:window,N=(Un=(Rt=r.launcher)==null?void 0:Rt.mobileFullscreen)!=null?Un:!0,ae=(Ro=(Io=r.launcher)==null?void 0:Io.mobileBreakpoint)!=null?Ro:640,se=U.innerWidth<=ae,te=N&&se&&I,we=(Ho=(Wo=r.launcher)==null?void 0:Wo.position)!=null?Ho:"bottom-left",Fe=we==="bottom-left"||we==="top-left",Oe=(as=(ss=r.launcher)==null?void 0:ss.zIndex)!=null?as:vn,Ue=u||te?"none":"1px solid var(--persona-border)",ze=te?"none":u?Fe?"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&&!te&&(ze="none",Ue="none");let mt=u||te?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",at=z(S==null?void 0:S.border,Ue),Be=z(S==null?void 0:S.shadow,ze),Re=z(S==null?void 0:S.borderRadius,mt),je=xe.scrollTop;n.style.cssText="",me.style.cssText="",X.style.cssText="",Ee.style.cssText="",xe.style.cssText="",He.style.cssText="",Y&&(xe.style.display="none");let Qe=()=>{var Nt;if(je<=0)return;((Nt=xe.ownerDocument.defaultView)!=null?Nt:window).requestAnimationFrame(()=>{if(xe.scrollTop===je)return;let Kt=xe.scrollHeight-xe.clientHeight;Kt<=0||(xe.scrollTop=Math.min(je,Kt))})};if(te){me.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"),me.style.cssText=`
|
|
35
35
|
position: fixed !important;
|
|
36
36
|
inset: 0 !important;
|
|
37
37
|
width: 100% !important;
|
|
@@ -41,9 +41,9 @@ _Details: ${n.message}_`:r}var js=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
41
41
|
padding: 0 !important;
|
|
42
42
|
display: flex !important;
|
|
43
43
|
flex-direction: column !important;
|
|
44
|
-
z-index: ${
|
|
44
|
+
z-index: ${Oe} !important;
|
|
45
45
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
46
|
-
`,
|
|
46
|
+
`,X.style.cssText=`
|
|
47
47
|
position: relative !important;
|
|
48
48
|
display: flex !important;
|
|
49
49
|
flex-direction: column !important;
|
|
@@ -56,7 +56,7 @@ _Details: ${n.message}_`:r}var js=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
56
56
|
padding: 0 !important;
|
|
57
57
|
box-shadow: none !important;
|
|
58
58
|
border-radius: 0 !important;
|
|
59
|
-
`,
|
|
59
|
+
`,Ee.style.cssText=`
|
|
60
60
|
display: flex !important;
|
|
61
61
|
flex-direction: column !important;
|
|
62
62
|
flex: 1 1 0% !important;
|
|
@@ -67,20 +67,20 @@ _Details: ${n.message}_`:r}var js=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
67
67
|
overflow: hidden !important;
|
|
68
68
|
border-radius: 0 !important;
|
|
69
69
|
border: none !important;
|
|
70
|
-
`,
|
|
70
|
+
`,xe.style.flex="1 1 0%",xe.style.minHeight="0",xe.style.overflowY="auto",He.style.flexShrink="0",_=!0,Qe();return}let vt=(Bo=(Qt=r==null?void 0:r.launcher)==null?void 0:Qt.width)!=null?Bo:r==null?void 0:r.launcherWidth,H=vt!=null?vt:Vr;if(!u&&!l)b&&f?(X.style.width="100%",X.style.maxWidth="100%"):(X.style.width=H,X.style.maxWidth=H);else if(l)if(gr(r).reveal==="emerge"){let Nt=gr(r).width;X.style.width=Nt,X.style.maxWidth=Nt}else X.style.width="100%",X.style.maxWidth="100%";if(Eo(),X.style.boxShadow=Be,X.style.borderRadius=Re,Ee.style.border=at,Ee.style.borderRadius=Re,l&&!te&&(S==null?void 0:S.border)===void 0&&(Ee.style.border="none",gr(r).side==="right"?Ee.style.borderLeft="1px solid var(--persona-border)":Ee.style.borderRight="1px solid var(--persona-border)"),f&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",b&&(n.style.width="100%"),me.style.display="flex",me.style.flexDirection="column",me.style.flex="1 1 0%",me.style.minHeight="0",me.style.maxHeight="100%",me.style.height="100%",b&&(me.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",Ee.style.display="flex",Ee.style.flexDirection="column",Ee.style.flex="1 1 0%",Ee.style.minHeight="0",Ee.style.maxHeight="100%",Ee.style.overflow="hidden",xe.style.flex="1 1 0%",xe.style.minHeight="0",xe.style.overflowY="auto",He.style.flexShrink="0"),me.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!u&&!b&&!l&&((po=fr[we])!=null?po:fr["bottom-right"]).split(" ").forEach(Nt=>me.classList.add(Nt)),u){let Ft=(Ur=(uo=r.launcher)==null?void 0:uo.sidebarWidth)!=null?Ur:"420px";me.style.cssText=`
|
|
71
71
|
position: fixed !important;
|
|
72
72
|
top: 0 !important;
|
|
73
73
|
bottom: 0 !important;
|
|
74
|
-
width: ${
|
|
74
|
+
width: ${Ft} !important;
|
|
75
75
|
height: 100vh !important;
|
|
76
76
|
max-height: 100vh !important;
|
|
77
77
|
margin: 0 !important;
|
|
78
78
|
padding: 0 !important;
|
|
79
79
|
display: flex !important;
|
|
80
80
|
flex-direction: column !important;
|
|
81
|
-
z-index: ${
|
|
82
|
-
${
|
|
83
|
-
`,
|
|
81
|
+
z-index: ${Oe} !important;
|
|
82
|
+
${Fe?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
83
|
+
`,X.style.cssText=`
|
|
84
84
|
position: relative !important;
|
|
85
85
|
display: flex !important;
|
|
86
86
|
flex-direction: column !important;
|
|
@@ -91,9 +91,9 @@ _Details: ${n.message}_`:r}var js=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
91
91
|
min-height: 0 !important;
|
|
92
92
|
margin: 0 !important;
|
|
93
93
|
padding: 0 !important;
|
|
94
|
-
box-shadow: ${
|
|
95
|
-
border-radius: ${
|
|
96
|
-
`,
|
|
94
|
+
box-shadow: ${Be} !important;
|
|
95
|
+
border-radius: ${Re} !important;
|
|
96
|
+
`,X.style.setProperty("width","100%","important"),X.style.setProperty("max-width","100%","important"),Ee.style.cssText=`
|
|
97
97
|
display: flex !important;
|
|
98
98
|
flex-direction: column !important;
|
|
99
99
|
flex: 1 1 0% !important;
|
|
@@ -102,15 +102,15 @@ _Details: ${n.message}_`:r}var js=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
102
102
|
min-height: 0 !important;
|
|
103
103
|
max-height: 100% !important;
|
|
104
104
|
overflow: hidden !important;
|
|
105
|
-
border-radius: ${
|
|
106
|
-
border: ${
|
|
107
|
-
`,
|
|
105
|
+
border-radius: ${Re} !important;
|
|
106
|
+
border: ${at} !important;
|
|
107
|
+
`,He.style.cssText=`
|
|
108
108
|
flex-shrink: 0 !important;
|
|
109
109
|
border-top: none !important;
|
|
110
110
|
padding: 8px 16px 12px 16px !important;
|
|
111
|
-
`}if(!y&&!l){let Ot="max-height: -moz-available !important; max-height: stretch !important;",Kt=p?"":"padding-top: 1.25em !important;",_t=p?"":`z-index: ${(Qe=(Lr=r.launcher)==null?void 0:Lr.zIndex)!=null?Qe:xn} !important;`;fe.style.cssText+=Ot+Kt+_t}Ve()};xr(),us(t,r),si(t,r),ai(t,r);let mt=[];mt.push(()=>{document.removeEventListener("keydown",Zr)});let rn=null,on=null;mt.push(()=>{rn==null||rn(),rn=null,on==null||on(),on=null}),Nn&&mt.push(()=>{Nn==null||Nn.disconnect(),Nn=null}),mt.push(()=>{Tn==null||Tn(),Tn=null,Br(),Ht&&(Ht.remove(),Ht=null),bt==null||bt.element.style.removeProperty("width"),bt==null||bt.element.style.removeProperty("maxWidth")}),le&&mt.push(()=>{ue!==null&&(cancelAnimationFrame(ue),ue=null),Le==null||Le.destroy(),Le=null,K==null||K.destroy(),K=null,Ee=null});let Cr=null,vs=()=>{Cr&&(Cr(),Cr=null),r.colorScheme==="auto"&&(Cr=Xu(()=>{us(t,r)}))};vs(),mt.push(()=>{Cr&&(Cr(),Cr=null)}),mt.push(a);let Dr=(Mc=r.features)==null?void 0:Mc.streamAnimation;if(Dr!=null&&Dr.type&&Dr.type!=="none"){let l=Qs(Dr.type,Dr.plugins);l&&($i(l,t),mt.push(()=>dm(t)))}let vo=Pm(Wt),Ar=null,z,Uo=l=>{var y,T;if(!z)return;let p=l!=null?l:z.getMessages(),h=((T=(y=r.features)==null?void 0:y.suggestReplies)==null?void 0:T.enabled)!==!1?hu(p):null;h?vo.render(h,z,te,p,r.suggestionChipsConfig,{agentPushed:!0}):p.some(D=>D.role==="user")?vo.render([],z,te,p):vo.render(r.suggestionChips,z,te,p,r.suggestionChipsConfig)},Sr=!1,Tr=tm(),Nr=new Map,Er=new Map,lr=new Map,zo=0,la=Po()!==null,$n=_a(),Un=0,cr=null,dr=!1,wo=!1,Fr=0,bn=null,Mr=null,qo=!1,xo=!1,jo=null,ca=4,Vo=24,da=80,Ko=new Map,pt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},ws=(Lc=(kc=r.voiceRecognition)==null?void 0:kc.autoResume)!=null?Lc:!1,er=l=>{i.emit("voice:state",{active:pt.active,source:l,timestamp:Date.now()})},Wn=()=>{v(l=>({...l,voiceState:{active:pt.active,timestamp:Date.now(),manuallyDeactivated:pt.manuallyDeactivated}}))},pa=()=>{var y,T;if(((y=r.voiceRecognition)==null?void 0:y.enabled)===!1)return;let l=dl(u.voiceState),p=!!l.active,h=Number((T=l.timestamp)!=null?T:0);pt.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-h<Dy&&setTimeout(()=>{var D,j;pt.active||(pt.manuallyDeactivated=!1,((j=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:j.type)==="runtype"?z.toggleVoice().then(()=>{pt.active=z.isVoiceActive(),er("restore"),z.isVoiceActive()&&Jo()}):ma("restore"))},1e3)},Go=()=>z?Zm(z.getMessages()).filter(l=>!l.__skipPersist):[];function tt(l){if(!(c!=null&&c.save))return;let h={messages:l?Zm(l):z?Go():[],metadata:u,artifacts:Fn.artifacts,selectedArtifactId:Fn.selectedId};try{let y=c.save(h);y instanceof Promise&&y.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",y)}}let x=null,V=()=>fe.querySelector("#persona-scroll-container")||Me,q=()=>{x!==null&&(cancelAnimationFrame(x),x=null),dr=!1},X=()=>{cr!==null&&(cancelAnimationFrame(cr),cr=null),wo=!1,q()},ye=()=>{Fr>0?(yn.textContent=String(Fr),yn.style.display="",zt.setAttribute("aria-label",`${ht()||"Jump to latest"} (${Fr} new)`)):(yn.textContent="",yn.style.display="none",zt.setAttribute("aria-label",ht()||"Jump to latest"))},$e=()=>{Fr!==0&&(Fr=0,ye())},gt=()=>$t()==="follow"?!$n.isFollowing():!Bo(Me,Vo),st=()=>{if(!Jt()||G){zt.parentNode&&zt.remove(),zt.style.display="none";return}zt.parentNode!==Ce&&Ce.appendChild(zt),Xn();let p=Vr(Me)>0&>();p||$e(),zt.style.display=p?"":"none"},xs=()=>{$n.pause()&&(X(),st())},Rn=()=>{$n.resume(),$e(),st()},cn=(l=!1)=>{$t()==="follow"&&$n.isFollowing()&&(!l&&!Sr||(cr!==null&&(cancelAnimationFrame(cr),cr=null),wo=!0,cr=requestAnimationFrame(()=>{cr=null,wo=!1,$n.isFollowing()&&Co(V(),l?220:140)})))},dn=(l,p,h,y=()=>!0)=>{let T=l.scrollTop,D=p(),j=D-T;q();let $=performance.now();dr=!0;let N=ie=>1-Math.pow(1-ie,3),ae=ie=>{if(!y()){q();return}let Y=p();Y!==D&&(D=Y,j=D-T);let we=ie-$,Oe=Math.min(we/h,1),Ae=N(Oe),Ze=T+j*Ae;l.scrollTop=Ze,Un=l.scrollTop,Oe<1?x=requestAnimationFrame(ae):(l.scrollTop=D,Un=l.scrollTop,x=null,dr=!1)};x=requestAnimationFrame(ae)},Co=(l,p=500)=>{let h=Vr(l)-l.scrollTop;if(Math.abs(h)<1){Un=l.scrollTop;return}if(Math.abs(h)>=da){q(),dr=!0,l.scrollTop=Vr(l),Un=l.scrollTop,dr=!1;return}dn(l,()=>Vr(l),p,()=>$n.isFollowing())},Or=()=>{let l=V();dr=!0,l.scrollTop=Vr(l),Un=l.scrollTop,dr=!1,st()},En=l=>{Ln.style.height=`${Math.max(0,Math.round(l))}px`,bn&&(bn.spacerHeight=Math.max(0,l))},gn=()=>{Mr!==null&&(cancelAnimationFrame(Mr),Mr=null),q(),bn=null,Ln.style.height="0px"},zn=l=>{Mr!==null&&cancelAnimationFrame(Mr),Mr=requestAnimationFrame(()=>{var ae;Mr=null;let p=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/"/g,'\\"'),h=Me.querySelector(`[data-message-id="${p}"]`);if(!h)return;let y=0,T=h;for(;T&&T!==Me;)y+=T.offsetTop,T=T.offsetParent;let D=(ae=bn==null?void 0:bn.spacerHeight)!=null?ae:0,j=Me.scrollHeight-D,{targetScrollTop:$,spacerHeight:N}=am({anchorOffsetTop:y,topOffset:Bn(),viewportHeight:Me.clientHeight,contentHeight:j});bn={initialSpacerHeight:N,contentHeightAtAnchor:j,spacerHeight:N},En(N),dn(Me,()=>$,220)})},gg=()=>{if($t()==="follow"){if(!$n.isFollowing()||Bo(Me,1))return;cn(!Sr);return}if(bn&&bn.initialSpacerHeight>0){let l=Me.scrollHeight-bn.spacerHeight,p=im({initialSpacerHeight:bn.initialSpacerHeight,contentHeightAtAnchor:bn.contentHeightAtAnchor,currentContentHeight:l});p!==bn.spacerHeight&&En(p)}st()},fg=l=>{let p=$t();p==="follow"?(Rn(),cn(!0)):p==="anchor-top"&&zn(l)},hg=l=>{let p=new Map;l.forEach(h=>{let y=Ko.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!y&&h.role==="assistant"&&(i.emit("assistant:message",h),!xo&&$t()!=="anchor-top"&>()&&(Fr+=1,ye(),st())),h.role==="assistant"&&(y!=null&&y.streaming)&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(y?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),Ko.clear(),p.forEach((h,y)=>{Ko.set(y,h)})},yg=(l,p,h)=>{var rt,Ie,ke,je,Ve,ft;let y=document.createElement("div"),D=(()=>{var Be;let W=o.find(We=>We.renderLoadingIndicator);if(W!=null&&W.renderLoadingIndicator)return W.renderLoadingIndicator;if((Be=r.loadingIndicator)!=null&&Be.render)return r.loadingIndicator.render})(),j=(W,Be)=>Be==null?!1:typeof Be=="string"?(W.textContent=Be,!0):(W.appendChild(Be),!0),$=new Set,N=new Set,ae=o.some(W=>W.renderAskUserQuestion),ie=[],Y=[],we=r.enableComponentStreaming!==!1,Oe=r.approval!==!1,Ae=[];if(p.forEach(W=>{var Ge,kt,nn,rr,jn,So,To,Zo,es,Qt,Eo,oo,so,$r,Mo,pr,Lr;$.add(W.id);let Be=ae&&Io(W),We=Oe&&W.variant==="approval"&&!!W.approval,ge=!Be&&W.role==="assistant"&&!W.variant&&we&&Qm(W);if(!We&&lr.has(W.id)){let Qe=l.querySelector(`#wrapper-${W.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime"),lr.delete(W.id)}if(!ge&&Er.has(W.id)){let Qe=l.querySelector(`#wrapper-${W.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime"),Er.delete(W.id)}let Ft=Io(W)?`:${(Ge=W.agentMetadata)!=null&&Ge.askUserQuestionAnswered?"a":"u"}:${(kt=W.agentMetadata)!=null&&kt.askUserQuestionAnswers?Object.keys(W.agentMetadata.askUserQuestionAnswers).length:0}`:"",Bt=em(W,zo)+Ft,Gt=Be||We||ge?null:nm(Tr,W.id,Bt);if(Gt){y.appendChild(Gt.cloneNode(!0)),Io(W)&&((nn=W.toolCall)!=null&&nn.id)&&((rr=W.agentMetadata)==null?void 0:rr.awaitingLocalTool)===!0&&!((jn=W.agentMetadata)!=null&&jn.askUserQuestionAnswered)&&(N.add(W.toolCall.id),Aa(W,r,qe.composerOverlay));return}let yt=null,jt=o.find(Qe=>!!(W.variant==="reasoning"&&Qe.renderReasoning||W.variant==="tool"&&Qe.renderToolCall||!W.variant&&Qe.renderMessage)),qn=(So=r.layout)==null?void 0:So.messages;if(Io(W)&&((To=W.agentMetadata)==null?void 0:To.askUserQuestionAnswered)===!0){Nr.delete(W.id);let Qe=l.querySelector(`#wrapper-${W.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime");return}if(Li(W)&&((es=(Zo=r.features)==null?void 0:Zo.suggestReplies)==null?void 0:es.enabled)!==!1)return;if(Io(W)&&((Eo=(Qt=r.features)==null?void 0:Qt.askUserQuestion)==null?void 0:Eo.enabled)!==!1){let Qe=o.find(Ot=>typeof Ot.renderAskUserQuestion=="function");if(Qe&&St.current){let Ot=Nr.get(W.id),Kt=Ot!==Bt,_t=null;if(Kt){let{payload:Ut,complete:pn}=os(W),Vn=W.id,Pr=()=>{var un;return(un=St.current)==null?void 0:un.getMessages().find(mn=>mn.id===Vn)};_t=Qe.renderAskUserQuestion({message:W,payload:Ut,complete:pn,resolve:un=>{var or;let mn=Pr();mn&&((or=St.current)==null||or.resolveAskUserQuestion(mn,un))},dismiss:()=>{var mn,or,ao;let un=Pr();(mn=un==null?void 0:un.agentMetadata)!=null&&mn.awaitingLocalTool&&((or=St.current)==null||or.markAskUserQuestionResolved(un),(ao=St.current)==null||ao.resolveAskUserQuestion(un,"(dismissed)"))},config:r})}let Xt=Ot!=null;if(Kt&&_t===null&&!Xt){((oo=W.agentMetadata)==null?void 0:oo.awaitingLocalTool)===!0&&!((so=W.agentMetadata)!=null&&so.askUserQuestionAnswered)&&(N.add(W.toolCall.id),Aa(W,r,qe.composerOverlay));return}let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id=`wrapper-${W.id}`,Lt.setAttribute("data-wrapper-id",W.id),Lt.setAttribute("data-ask-plugin-stub","true"),Lt.setAttribute("data-preserve-runtime","true"),y.appendChild(Lt),ie.push({messageId:W.id,fingerprint:Bt,bubble:_t});return}else{(($r=W.agentMetadata)==null?void 0:$r.awaitingLocalTool)===!0&&!((Mo=W.agentMetadata)!=null&&Mo.askUserQuestionAnswered)&&(N.add(W.toolCall.id),Aa(W,r,qe.composerOverlay));return}}else if(We){let Qe=(pr=o.find(Xt=>typeof Xt.renderApproval=="function"))!=null?pr:s,Kt=lr.get(W.id)!==Bt,_t=null;if(Kt&&(Qe!=null&&Qe.renderApproval)){let Xt=W.id,Lt=(Ut,pn)=>{var Pr,un,mn;let Vn=(Pr=St.current)==null?void 0:Pr.getMessages().find(or=>or.id===Xt);Vn!=null&&Vn.approval&&(Vn.approval.toolType==="webmcp"?(un=St.current)==null||un.resolveWebMcpApproval(Vn.id,Ut):(mn=St.current)==null||mn.resolveApproval(Vn.approval,Ut,pn))};_t=Qe.renderApproval({message:W,defaultRenderer:()=>ri(W,r),config:r,approve:Ut=>Lt("approved",Ut),deny:Ut=>Lt("denied",Ut)})}if(Kt&&_t===null){let Xt=l.querySelector(`#wrapper-${W.id}`);Xt==null||Xt.removeAttribute("data-preserve-runtime"),lr.delete(W.id),yt=ri(W,r)}else{let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${W.id}`,Xt.setAttribute("data-wrapper-id",W.id),Xt.setAttribute("data-approval-plugin-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),y.appendChild(Xt),Ae.push({messageId:W.id,fingerprint:Bt,bubble:_t});return}}else if(jt)if(W.variant==="reasoning"&&W.reasoning&&jt.renderReasoning){if(!xe)return;yt=jt.renderReasoning({message:W,defaultRenderer:()=>Xi(W,r),config:r})}else if(W.variant==="tool"&&W.toolCall&&jt.renderToolCall){if(!Re)return;yt=jt.renderToolCall({message:W,defaultRenderer:()=>Yi(W,r),config:r})}else jt.renderMessage&&(yt=jt.renderMessage({message:W,defaultRenderer:()=>{let Qe=Qi(W,h,qn,r.messageActions,Xe,{loadingIndicatorRenderer:D,widgetConfig:r});return W.role!=="user"&&rl(Qe,W,r,z),Qe},config:r}));if(!yt&&ge){let Qe=Xm(W);if(Qe){let Ot=Er.get(W.id),Kt=Ot!==Bt,_t=r.wrapComponentDirectiveInBubble!==!1,Xt=null;if(Kt){let Lt=Km(Qe,{config:r,message:W,transform:h});if(Lt)if(_t){let Ut=document.createElement("div");if(Ut.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(" "),Ut.id=`bubble-${W.id}`,Ut.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let pn=document.createElement("div");pn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",pn.innerHTML=h({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Ut.appendChild(pn)}Ut.appendChild(Lt),Xt=Ut}else{let Ut=document.createElement("div");if(Ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ut.id=`bubble-${W.id}`,Ut.setAttribute("data-message-id",W.id),Ut.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let pn=document.createElement("div");pn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",pn.innerHTML=h({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Ut.appendChild(pn)}Ut.appendChild(Lt),Xt=Ut}}if(Xt||Ot!=null){let Lt=document.createElement("div");Lt.className="persona-flex",Lt.id=`wrapper-${W.id}`,Lt.setAttribute("data-wrapper-id",W.id),Lt.setAttribute("data-component-directive-stub","true"),Lt.setAttribute("data-preserve-runtime","true"),_t||Lt.classList.add("persona-w-full"),y.appendChild(Lt),Y.push({messageId:W.id,fingerprint:Bt,bubble:Xt});return}}}if(!yt)if(W.variant==="reasoning"&&W.reasoning){if(!xe)return;yt=Xi(W,r)}else if(W.variant==="tool"&&W.toolCall){if(!Re)return;yt=Yi(W,r)}else if(W.variant==="approval"&&W.approval){if(r.approval===!1)return;yt=ri(W,r)}else{let Qe=(Lr=r.layout)==null?void 0:Lr.messages;Qe!=null&&Qe.renderUserMessage&&W.role==="user"?yt=Qe.renderUserMessage({message:W,config:r,streaming:!!W.streaming}):Qe!=null&&Qe.renderAssistantMessage&&W.role==="assistant"?yt=Qe.renderAssistantMessage({message:W,config:r,streaming:!!W.streaming}):yt=Qi(W,h,Qe,r.messageActions,Xe,{loadingIndicatorRenderer:D,widgetConfig:r}),W.role!=="user"&&yt&&rl(yt,W,r,z)}let en=document.createElement("div");en.className="persona-flex",en.id=`wrapper-${W.id}`,en.setAttribute("data-wrapper-id",W.id),W.role==="user"&&en.classList.add("persona-justify-end"),(yt==null?void 0:yt.getAttribute("data-persona-component-directive"))==="true"&&en.classList.add("persona-w-full"),en.appendChild(yt),rm(Tr,W.id,Bt,en),y.appendChild(en)}),qe.composerOverlay&&qe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let We=Be.getAttribute("data-persona-ask-sheet-for");We&&!N.has(We)&&as(qe.composerOverlay,We)}),(Ie=(rt=r.features)==null?void 0:rt.toolCallDisplay)!=null&&Ie.grouped){let W=[],Be=[];p.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&Re){Be.push(We);return}Be.length>1&&W.push(Be),Be=[]}),Be.length>1&&W.push(Be),W.forEach((We,ge)=>{var Ge,kt;let Ft=We.map(nn=>Array.from(y.children).find(rr=>rr instanceof HTMLElement&&rr.getAttribute("data-wrapper-id")===nn.id)).filter(nn=>!!nn);if(Ft.length<2)return;let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id=`wrapper-tool-group-${ge}-${We[0].id}`,Bt.setAttribute("data-wrapper-id",`tool-group-${ge}-${We[0].id}`);let Gt=document.createElement("div");Gt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Gt.setAttribute("data-persona-tool-group","true");let yt=document.createElement("div");yt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let jt=`Called ${We.length} tools`,qn=(kt=(Ge=r.toolCall)==null?void 0:Ge.renderGroupedSummary)==null?void 0:kt.call(Ge,{messages:We,toolCalls:We.map(nn=>nn.toolCall).filter(nn=>!!nn),defaultSummary:jt,config:r});j(yt,qn)||(yt.textContent=jt);let en=document.createElement("div");en.className="persona-tool-group-stack persona-flex persona-flex-col",Gt.append(yt,en),Bt.appendChild(Gt),Ft[0].before(Bt),Ft.forEach((nn,rr)=>{let jn=document.createElement("div");jn.className="persona-tool-group-item persona-relative",jn.setAttribute("data-persona-tool-group-item","true"),rr<Ft.length-1&&jn.setAttribute("data-persona-tool-group-connector","true"),jn.appendChild(nn),en.appendChild(jn)})})}om(Tr,$);let Ze=p.some(W=>W.role==="assistant"&&W.streaming),ze=p[p.length-1],ct=(ze==null?void 0:ze.role)==="assistant"&&!ze.streaming&&ze.variant!=="approval";if(Sr&&p.some(W=>W.role==="user")&&!Ze&&!ct){let W={config:r,streaming:!0,location:"standalone",defaultRenderer:na},Be=o.find(ge=>ge.renderLoadingIndicator),We=null;if(Be!=null&&Be.renderLoadingIndicator&&(We=Be.renderLoadingIndicator(W)),We===null&&((ke=r.loadingIndicator)!=null&&ke.render)&&(We=r.loadingIndicator.render(W)),We===null&&(We=na()),We){let ge=document.createElement("div"),Ft=((je=r.loadingIndicator)==null?void 0:je.showBubble)!==!1;ge.className=Ft?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-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(" "),ge.setAttribute("data-typing-indicator","true"),ge.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ge.appendChild(We);let Bt=document.createElement("div");Bt.className="persona-flex",Bt.id="wrapper-typing-indicator",Bt.setAttribute("data-wrapper-id","typing-indicator"),Bt.appendChild(ge),y.appendChild(Bt)}}if(!Sr&&p.length>0){let W=p[p.length-1],Be={config:r,lastMessage:W,messageCount:p.length},We=o.find(Ft=>Ft.renderIdleIndicator),ge=null;if(We!=null&&We.renderIdleIndicator&&(ge=We.renderIdleIndicator(Be)),ge===null&&((Ve=r.loadingIndicator)!=null&&Ve.renderIdle)&&(ge=r.loadingIndicator.renderIdle(Be)),ge){let Ft=document.createElement("div"),Bt=((ft=r.loadingIndicator)==null?void 0:ft.showBubble)!==!1;Ft.className=Bt?["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(" "),Ft.setAttribute("data-idle-indicator","true"),Ft.appendChild(ge);let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id="wrapper-idle-indicator",Gt.setAttribute("data-wrapper-id","idle-indicator"),Gt.appendChild(Ft),y.appendChild(Gt)}}if(Fa(l,y),ie.length>0)for(let{messageId:W,fingerprint:Be,bubble:We}of ie){let ge=l.querySelector(`#wrapper-${W}`);ge&&We!==null&&(ge.replaceChildren(We),ge.setAttribute("data-bubble-fp",Be),Nr.set(W,Be))}if(Nr.size>0)for(let W of Nr.keys())$.has(W)||Nr.delete(W);if(Y.length>0)for(let{messageId:W,fingerprint:Be,bubble:We}of Y){let ge=l.querySelector(`#wrapper-${W}`);ge&&We!==null&&(ge.replaceChildren(We),ge.setAttribute("data-bubble-fp",Be),Er.set(W,Be))}if(Er.size>0)for(let W of Er.keys())$.has(W)||Er.delete(W);if(Ae.length>0)for(let{messageId:W,fingerprint:Be,bubble:We}of Ae){let ge=l.querySelector(`#wrapper-${W}`);ge&&We!==null&&(ge.replaceChildren(We),ge.setAttribute("data-bubble-fp",Be),lr.set(W,Be))}if(lr.size>0)for(let W of lr.keys())$.has(W)||lr.delete(W)},Cs=(l,p,h)=>{yg(l,p,h),Jr()},As=null,bg=()=>{var h;if(As)return;let l=y=>{let T=y.composedPath();T.includes(fe)||dt&&T.includes(dt)||qt(!1,"user")};As=l,((h=t.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},yl=()=>{var p;if(!As)return;((p=t.ownerDocument)!=null?p:document).removeEventListener("pointerdown",As,!0),As=null};mt.push(()=>yl());let Ss=null,vg=()=>{var h;if(Ss)return;let l=y=>{y.key==="Escape"&&(y.isComposing||qt(!1,"user"))};Ss=l,((h=t.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},bl=()=>{var p;if(!Ss)return;((p=t.ownerDocument)!=null?p:document).removeEventListener("keydown",Ss,!0),Ss=null};mt.push(()=>bl());let Ts=!1,vl=new Set,wg=()=>{var p,h,y,T;let l=(y=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.peek)==null?void 0:y.streamAnimation;return l||((T=r.features)==null?void 0:T.streamAnimation)},Qo=()=>{var ct,rt,Ie,ke;if(!H())return;let l=qe.peekBanner,p=qe.peekTextNode;if(!l||!p)return;if(F){l.classList.remove("persona-pill-peek--visible");return}let h=(ct=z==null?void 0:z.getMessages())!=null?ct:[],y;for(let je=h.length-1;je>=0;je--){let Ve=h[je];if(Ve.role==="assistant"&&Ve.content){y=Ve;break}}if(!y){l.classList.remove("persona-pill-peek--visible");return}let T=y.content,D=!!y.streaming,j=wg(),$=za(j),N=$.type!=="none"?Qs($.type,j==null?void 0:j.plugins):null,ae=((rt=N==null?void 0:N.isAnimating)==null?void 0:rt.call(N,y))===!0,ie=N!==null&&(D||ae);ie&&N&&!vl.has(N.name)&&($i(N,t),vl.add(N.name));let Y=ie&&(N!=null&&N.containerClass)?N.containerClass:null,we=(Ie=p.dataset.personaPeekStreamClass)!=null?Ie:null;we&&we!==Y&&(p.classList.remove(we),delete p.dataset.personaPeekStreamClass),Y&&we!==Y&&(p.classList.add(Y),p.dataset.personaPeekStreamClass=Y),ie?(p.style.setProperty("--persona-stream-step",`${$.speed}ms`),p.style.setProperty("--persona-stream-duration",`${$.duration}ms`)):(p.style.removeProperty("--persona-stream-step"),p.style.removeProperty("--persona-stream-duration"));let Oe=ie?qa(T,$.buffer,N,y,D):T;if(ie&&$.placeholder==="skeleton"&&D&&(!Oe||!Oe.trim())){let je=document.createElement("div"),Ve=Js();Ve.classList.add("persona-pill-peek__skeleton"),je.appendChild(Ve),Fa(p,je)}else{let je=Math.max(0,Oe.length-100),Ve=Oe.length>100?Oe.slice(-100):Oe,ft=io(Ve);if(!ie||!N){let W=Oe.length>100?`\u2026${Ve}`:Ve;p.textContent!==W&&(p.textContent=W)}else{let W=ft;(N.wrap==="char"||N.wrap==="word")&&(W=Xs(ft,N.wrap,`peek-${y.id}`,{skipTags:N.skipTags,startIndex:je}));let Be=document.createElement("div");if(Be.innerHTML=W,N.useCaret&&Ve.length>0){let We=ja(),ge=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ft=ge[ge.length-1];Ft!=null&&Ft.parentNode?Ft.parentNode.insertBefore(We,Ft.nextSibling):Be.appendChild(We)}Fa(p,Be),(ke=N.onAfterRender)==null||ke.call(N,{container:p,bubble:l,messageId:y.id,message:y,speed:$.speed,duration:$.duration})}}let ze=Sr||Ts;l.classList.toggle("persona-pill-peek--visible",ze)};if(H()){let l=qe.peekBanner;if(l){let y=T=>{T.preventDefault(),T.stopPropagation(),qt(!0,"user")};l.addEventListener("pointerdown",y),mt.push(()=>{l.removeEventListener("pointerdown",y)})}let p=()=>{Ts||(Ts=!0,Qo())},h=()=>{Ts&&(Ts=!1,Qo())};Q.addEventListener("pointerenter",p),Q.addEventListener("pointerleave",h),mt.push(()=>{Q.removeEventListener("pointerenter",p),Q.removeEventListener("pointerleave",h)}),dt&&(dt.addEventListener("pointerenter",p),dt.addEventListener("pointerleave",h),mt.push(()=>{dt.removeEventListener("pointerenter",p),dt.removeEventListener("pointerleave",h)}))}let xg=l=>{var we,Oe,Ae,Ze,ze,ct,rt,Ie;let p=(Oe=(we=r.launcher)==null?void 0:we.composerBar)!=null?Oe:{},h=(Ae=p.expandedSize)!=null?Ae:"anchored",y=(Ze=p.bottomOffset)!=null?Ze:"16px",T=p.collapsedMaxWidth,D=(ze=p.expandedMaxWidth)!=null?ze:"880px",j=(ct=p.expandedTopOffset)!=null?ct:"5vh",$=(rt=p.modalMaxWidth)!=null?rt:"880px",N=(Ie=p.modalMaxHeight)!=null?Ie:"min(90vh, 800px)",ae="calc(100vw - 32px)",ie="var(--persona-pill-area-height, 80px)",Y=fe.style;if(Y.left="",Y.right="",Y.top="",Y.bottom="",Y.transform="",Y.width="",Y.maxWidth="",Y.height="",Y.maxHeight="",dt){let ke=dt.style;ke.bottom=y,ke.width=T!=null?T:""}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=ae,Y.maxHeight=N,Y.height=N;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${y} + ${ie})`,Y.top=j,Y.width=D,Y.maxWidth=ae}},Es=()=>{var N,ae,ie,Y,we,Oe,Ae,Ze;if(!U())return;if(H()){let ct=(ie=((ae=(N=r.launcher)==null?void 0:N.composerBar)!=null?ae:{}).expandedSize)!=null?ie:"anchored",rt=F?"expanded":"collapsed";fe.dataset.state=rt,fe.dataset.expandedSize=ct,dt&&(dt.dataset.state=rt,dt.dataset.expandedSize=ct),fe.style.removeProperty("display"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),xg(F),Ce.style.display=F?"flex":"none",xr(),F?(bg(),vg()):(yl(),bl()),Qo();return}let l=fn(r),p=(Y=t.ownerDocument.defaultView)!=null?Y:window,h=(Oe=(we=r.launcher)==null?void 0:we.mobileBreakpoint)!=null?Oe:640,y=(Ze=(Ae=r.launcher)==null?void 0:Ae.mobileFullscreen)!=null?Ze:!0,T=p.innerWidth<=h,D=y&&T&&L,j=gr(r).reveal;F?(fe.style.removeProperty("display"),fe.style.display=l?"flex":"",fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-95","persona-opacity-0"),Q.classList.add("persona-scale-100","persona-opacity-100"),Zt?Zt.element.style.display="none":sn&&(sn.style.display="none")):(l?l&&(j==="overlay"||j==="push")&&!D?(fe.style.removeProperty("display"),fe.style.display="flex",fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.setProperty("display","none","important"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.display="",fe.classList.add("persona-pointer-events-none","persona-opacity-0"),Q.classList.remove("persona-scale-100","persona-opacity-100"),Q.classList.add("persona-scale-95","persona-opacity-0")),Zt?Zt.element.style.display=l?"none":"":sn&&(sn.style.display=l?"none":""))},qt=(l,p="user")=>{var D,j;if(!U()||F===l)return;let h=F;F=l,Es();let y=(()=>{var Ae,Ze,ze,ct,rt,Ie,ke,je,Ve,ft;let $=(Ze=(Ae=r.launcher)==null?void 0:Ae.sidebarMode)!=null?Ze:!1,N=(ze=t.ownerDocument.defaultView)!=null?ze:window,ae=(rt=(ct=r.launcher)==null?void 0:ct.mobileFullscreen)!=null?rt:!0,ie=(ke=(Ie=r.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?ke:640,Y=N.innerWidth<=ie,we=fn(r)&&ae&&Y,Oe=H()&&((ft=(Ve=(je=r.launcher)==null?void 0:je.composerBar)==null?void 0:Ve.expandedSize)!=null?ft:"fullscreen")==="fullscreen";return $||ae&&Y&&L||we||Oe})();if(F&&y){if(!rn){let $=t.getRootNode(),N=$ instanceof ShadowRoot?$.host:t.closest(".persona-host");N&&(rn=Ui(N,(j=(D=r.launcher)==null?void 0:D.zIndex)!=null?j:xn))}on||(on=zi(t.ownerDocument))}else F||(rn==null||rn(),rn=null,on==null||on(),on=null);F&&(Ms(),$t()==="follow"?cn(!0):Or());let T={open:F,source:p,timestamp:Date.now()};F&&!h?i.emit("widget:opened",T):!F&&h&&i.emit("widget:closed",T),i.emit("widget:state",{open:F,launcherEnabled:L,voiceActive:pt.active,streaming:z.isStreaming()})},ci=l=>{ce(l?"stop":"send"),B&&(B.disabled=l),vo.buttons.forEach(p=>{p.disabled=l}),Fe.dataset.personaComposerStreaming=l?"true":"false",Fe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(p=>{(p instanceof HTMLButtonElement||p instanceof HTMLInputElement||p instanceof HTMLTextAreaElement||p instanceof HTMLSelectElement)&&(p.disabled=l)})},di=()=>{pt.active||te&&te.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>di(),200)});let wl=()=>{var h,y,T,D,j,$,N,ae,ie,Y,we;hr.textContent=(y=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?y:"Hello \u{1F44B}",yr.textContent=(D=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",te.placeholder=($=(j=r.copy)==null?void 0:j.inputPlaceholder)!=null?$:"How can I help...";let l=Me.querySelector("[data-persona-intro-card]");if(l){let Oe=((N=r.copy)==null?void 0:N.showWelcomeCard)!==!1;l.style.display=Oe?"":"none",Oe?(Me.classList.remove("persona-gap-3"),Me.classList.add("persona-gap-6")):(Me.classList.remove("persona-gap-6"),Me.classList.add("persona-gap-3"))}!((ie=(ae=r.sendButton)==null?void 0:ae.useIcon)!=null&&ie)&&!(z!=null&&z.isStreaming())&&(Ue.textContent=(we=(Y=r.copy)==null?void 0:Y.sendButtonLabel)!=null?we:"Send"),te.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',te.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=u.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{v(p=>({...p,sessionId:l}))}});let Ao=null,Cg=()=>{Ao==null&&(Ao=setInterval(()=>{let l=nt.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Ao),Ao=null;return}let p=Date.now();l.forEach(h=>{let y=Number(h.getAttribute("data-tool-elapsed"));y&&(h.textContent=Ta(p-y))})},100))};z=new Ba(r,{onMessagesChanged(l){var y;Cs(nt,l,ee),Cg(),Uo(l),cn(!Sr),hg(l);let p=[...l].reverse().find(T=>T.role==="user");l.length===0&&gn(),!qo||xo?(qo=!0,jo=(y=p==null?void 0:p.id)!=null?y:null):p&&p.id!==jo&&(jo=p.id,fg(p.id));let h=pt.lastUserMessageId;p&&p.id!==h&&(pt.lastUserMessageId=p.id,i.emit("user:message",p)),pt.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),tt(l),Qo()},onStatusChanged(l){var y;let p=(y=r.statusIndicator)!=null?y:{};wt(hn,(T=>{var D,j,$,N;return T==="idle"?(D=p.idleText)!=null?D:wn.idle:T==="connecting"?(j=p.connectingText)!=null?j:wn.connecting:T==="connected"?($=p.connectedText)!=null?$:wn.connected:T==="error"?(N=p.errorText)!=null?N:wn.error:wn[T]})(l),p,l)},onStreamingChanged(l){Sr=l,ci(l),z&&Cs(nt,z.getMessages(),ee),l||cn(!0),Qo()},onVoiceStatusChanged(l){var p,h;if(i.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":_r(),Jo();break;case"processing":_r(),Mg();break;case"speaking":_r(),kg();break;default:l==="idle"&&z.isBargeInActive()?(_r(),Jo(),B==null||B.setAttribute("aria-label","End voice session")):(pt.active=!1,_r(),er("system"),Wn());break}},onArtifactsState(l){Fn=l,In(),tt()}}),St.current=z;let pi=null;if(z.onReadAloudChange((l,p)=>{var T;Qr=l,Xr=p,Jr();let h=l!=null?l:pi;l&&(pi=l);let y=h&&(T=z.getMessages().find(D=>D.id===h))!=null?T:null;i.emit("message:read-aloud",{messageId:h,message:y,state:p,timestamp:Date.now()}),p==="idle"&&(pi=null)}),qo=!0,((Ic=(Pc=r.voiceRecognition)==null?void 0:Pc.provider)==null?void 0:Ic.type)==="runtype")try{z.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&z.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(K||r.onSSEEvent)&&z.setSSEEventCallback((l,p)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,p),J==null||J.processEvent(l,p),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(p)})}),m&&m.then(l=>{var p,h,y;if(l){if(l.metadata&&(u=dl(l.metadata),E.syncFromMetadata()),(p=l.messages)!=null&&p.length){xo=!0;try{z.hydrateMessages(l.messages)}finally{xo=!1}}(h=l.artifacts)!=null&&h.length&&z.hydrateArtifacts(l.artifacts,(y=l.selectedArtifactId)!=null?y:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let xl=()=>{var p,h,y;!H()||F||!((y=(h=(p=r.launcher)==null?void 0:p.composerBar)==null?void 0:h.expandOnSubmit)==null||y)||qt(!0,"auto")},Cl=l=>{var T;if(l.preventDefault(),z.isStreaming()){z.cancel(),J==null||J.reset(),Le==null||Le.update();return}let p=te.value.trim(),h=(T=At==null?void 0:At.hasAttachments())!=null?T:!1;if(!p&&!h)return;xl();let y;h&&(y=[],y.push(...At.getContentParts()),p&&y.push(Ri(p))),te.value="",te.style.height="auto",ua(),z.sendMessage(p,{contentParts:y}),h&&At.clearAttachments()},Ag=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},ui={...Oa},mi=!1,ua=()=>{ui={...Oa}},Sg=()=>z.getMessages().filter(l=>l.role==="user").map(l=>{var p;return(p=l.content)!=null?p:""}).filter(l=>l.length>0),Tg=l=>{if(!te)return;mi=!0,te.value=l,te.dispatchEvent(new Event("input",{bubbles:!0})),mi=!1;let p=te.value.length;te.setSelectionRange(p,p)},Al=()=>{mi||ua()},Sl=l=>{if(te){if(Ag()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let p=te.selectionStart===0&&te.selectionEnd===0,h=Zu({direction:l.key==="ArrowUp"?"up":"down",history:Sg(),currentValue:te.value,atStart:p,state:ui});if(ui=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Tg(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(z.isStreaming()){l.preventDefault();return}ua(),l.preventDefault(),Ue.click()}}},Tl=l=>{l.key!=="Escape"||l.isComposing||z.isStreaming()&&l.composedPath().includes(Ce)&&(z.cancel(),J==null||J.reset(),Le==null||Le.update(),ua(),l.preventDefault(),l.stopImmediatePropagation())},El=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!At)return;let p=Fy(l.clipboardData);p.length!==0&&(l.preventDefault(),await At.handleFiles(p))},tr=null,kr=!1,Xo=null,lt=null,Ml=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ma=(l="user")=>{var D,j,$,N,ae,ie,Y;if(kr||z.isStreaming())return;let p=Ml();if(!p)return;tr=new p;let y=(j=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?j:2e3;tr.continuous=!0,tr.interimResults=!0,tr.lang="en-US";let T=te.value;tr.onresult=we=>{let Oe="",Ae="";for(let ze=0;ze<we.results.length;ze++){let ct=we.results[ze],rt=ct[0].transcript;ct.isFinal?Oe+=rt+" ":Ae=rt}let Ze=T+Oe+Ae;te.value=Ze,Xo&&clearTimeout(Xo),(Oe||Ae)&&(Xo=window.setTimeout(()=>{let ze=te.value.trim();ze&&tr&&kr&&(no(),te.value="",te.style.height="auto",z.sendMessage(ze,{viaVoice:!0}))},y))},tr.onerror=we=>{we.error!=="no-speech"&&no()},tr.onend=()=>{if(kr){let we=te.value.trim();we&&we!==T.trim()&&(te.value="",te.style.height="auto",z.sendMessage(we,{viaVoice:!0})),no()}};try{if(tr.start(),kr=!0,pt.active=!0,l!=="system"&&(pt.manuallyDeactivated=!1),er(l),Wn(),B){let we=($=r.voiceRecognition)!=null?$:{};lt={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(N=we.iconName)!=null?N:"mic",iconSize:parseFloat((Y=(ie=we.iconSize)!=null?ie:(ae=r.sendButton)==null?void 0:ae.size)!=null?Y:"40")||24};let Oe=we.recordingBackgroundColor,Ae=we.recordingIconColor,Ze=we.recordingBorderColor;if(B.classList.add("persona-voice-recording"),B.style.backgroundColor=Oe!=null?Oe:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=Ae!=null?Ae:"var(--persona-voice-recording-indicator, #ffffff)",Ae){let ze=B.querySelector("svg");ze&&ze.setAttribute("stroke",Ae)}Ze&&(B.style.borderColor=Ze),B.setAttribute("aria-label","Stop voice recognition")}}catch{no("system")}},no=(l="user")=>{if(kr){if(kr=!1,Xo&&(clearTimeout(Xo),Xo=null),tr){try{tr.stop()}catch{}tr=null}if(pt.active=!1,er(l),Wn(),B){if(B.classList.remove("persona-voice-recording"),lt){B.style.backgroundColor=lt.backgroundColor,B.style.color=lt.color,B.style.borderColor=lt.borderColor;let p=B.querySelector("svg");p&&p.setAttribute("stroke",lt.color||"currentColor"),lt=null}B.setAttribute("aria-label","Start voice recognition")}}},Eg=(l,p)=>{var rt,Ie,ke,je,Ve,ft,W,Be,We;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),y=((rt=l==null?void 0:l.provider)==null?void 0:rt.type)==="runtype",T=((Ie=l==null?void 0:l.provider)==null?void 0:Ie.type)==="custom";if(!(h||y||T))return null;let j=b("div","persona-send-button-wrapper"),$=b("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 N=(ke=l==null?void 0:l.iconName)!=null?ke:"mic",ae=(je=p==null?void 0:p.size)!=null?je:"40px",ie=(Ve=l==null?void 0:l.iconSize)!=null?Ve:ae,Y=parseFloat(ie)||24,we=(ft=l==null?void 0:l.backgroundColor)!=null?ft:p==null?void 0:p.backgroundColor,Oe=(W=l==null?void 0:l.iconColor)!=null?W:p==null?void 0:p.textColor;$.style.width=ie,$.style.height=ie,$.style.minWidth=ie,$.style.minHeight=ie,$.style.fontSize="18px",$.style.lineHeight="1",Oe?$.style.color=Oe:$.style.color="var(--persona-text, #111827)";let Ze=be(N,Y,Oe||"currentColor",1.5);Ze?$.appendChild(Ze):$.textContent="\u{1F3A4}",we?$.style.backgroundColor=we:$.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),j.appendChild($);let ze=(Be=l==null?void 0:l.tooltipText)!=null?Be:"Start voice recognition";if(((We=l==null?void 0:l.showTooltip)!=null?We:!1)&&ze){let ge=b("div","persona-send-button-tooltip");ge.textContent=ze,j.appendChild(ge)}return{micButton:$,micButtonWrapper:j}},gi=()=>{var p,h,y,T,D;if(!B||lt)return;let l=(p=r.voiceRecognition)!=null?p:{};lt={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((D=(T=l.iconSize)!=null?T:(y=r.sendButton)==null?void 0:y.size)!=null?D:"40")||24}},fi=(l,p)=>{var D,j,$,N,ae;if(!B)return;let h=B.querySelector("svg");h&&h.remove();let y=(ae=lt==null?void 0:lt.iconSize)!=null?ae:parseFloat((N=($=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?$:(j=r.sendButton)==null?void 0:j.size)!=null?N:"40")||24,T=be(l,y,p,1.5);T&&B.appendChild(T)},ga=()=>{B&&B.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Jo=()=>{var T;if(!B)return;gi();let l=(T=r.voiceRecognition)!=null?T:{},p=l.recordingBackgroundColor,h=l.recordingIconColor,y=l.recordingBorderColor;if(ga(),B.classList.add("persona-voice-recording"),B.style.backgroundColor=p!=null?p:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let D=B.querySelector("svg");D&&D.setAttribute("stroke",h)}y&&(B.style.borderColor=y),B.setAttribute("aria-label","Stop voice recognition")},Mg=()=>{var $,N,ae,ie,Y,we,Oe,Ae;if(!B)return;gi();let l=($=r.voiceRecognition)!=null?$:{},p=z.getVoiceInterruptionMode(),h=(N=l.processingIconName)!=null?N:"loader",y=(ie=(ae=l.processingIconColor)!=null?ae:lt==null?void 0:lt.color)!=null?ie:"",T=(we=(Y=l.processingBackgroundColor)!=null?Y:lt==null?void 0:lt.backgroundColor)!=null?we:"",D=(Ae=(Oe=l.processingBorderColor)!=null?Oe:lt==null?void 0:lt.borderColor)!=null?Ae:"";ga(),B.classList.add("persona-voice-processing"),B.style.backgroundColor=T,B.style.borderColor=D;let j=y||"currentColor";B.style.color=j,fi(h,j),B.setAttribute("aria-label","Processing voice input"),p==="none"&&(B.style.cursor="default")},kg=()=>{var ae,ie,Y,we,Oe,Ae,Ze,ze,ct,rt,Ie,ke;if(!B)return;gi();let l=(ae=r.voiceRecognition)!=null?ae:{},p=z.getVoiceInterruptionMode(),h=p==="cancel"?"square":p==="barge-in"?"mic":"volume-2",y=(ie=l.speakingIconName)!=null?ie:h,T=(Ae=l.speakingIconColor)!=null?Ae:p==="barge-in"?(we=(Y=l.recordingIconColor)!=null?Y:lt==null?void 0:lt.color)!=null?we:"":(Oe=lt==null?void 0:lt.color)!=null?Oe:"",D=(ct=l.speakingBackgroundColor)!=null?ct:p==="barge-in"?(Ze=l.recordingBackgroundColor)!=null?Ze:"var(--persona-voice-recording-bg, #ef4444)":(ze=lt==null?void 0:lt.backgroundColor)!=null?ze:"",j=(ke=l.speakingBorderColor)!=null?ke:p==="barge-in"?(rt=l.recordingBorderColor)!=null?rt:"":(Ie=lt==null?void 0:lt.borderColor)!=null?Ie:"";ga(),B.classList.add("persona-voice-speaking"),B.style.backgroundColor=D,B.style.borderColor=j;let $=T||"currentColor";B.style.color=$,fi(y,$);let N=p==="cancel"?"Stop playback and re-record":p==="barge-in"?"Speak to interrupt":"Agent is speaking";B.setAttribute("aria-label",N),p==="none"&&(B.style.cursor="default"),p==="barge-in"&&B.classList.add("persona-voice-recording")},_r=()=>{var l,p,h;B&&(ga(),lt&&(B.style.backgroundColor=(l=lt.backgroundColor)!=null?l:"",B.style.color=(p=lt.color)!=null?p:"",B.style.borderColor=(h=lt.borderColor)!=null?h:"",fi(lt.iconName,lt.color||"currentColor"),lt=null),B.style.cursor="",B.setAttribute("aria-label","Start voice recognition"))},fa=()=>{var l,p;if(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"){let h=z.getVoiceStatus(),y=z.getVoiceInterruptionMode();if(y==="none"&&(h==="processing"||h==="speaking"))return;if(y==="cancel"&&(h==="processing"||h==="speaking")){z.stopVoicePlayback();return}if(z.isBargeInActive()){z.stopVoicePlayback(),z.deactivateBargeIn().then(()=>{pt.active=!1,pt.manuallyDeactivated=!0,Wn(),er("user"),_r()});return}z.toggleVoice().then(()=>{pt.active=z.isVoiceActive(),pt.manuallyDeactivated=!z.isVoiceActive(),Wn(),er("user"),z.isVoiceActive()?Jo():_r()});return}if(kr){let h=te.value.trim();pt.manuallyDeactivated=!0,Wn(),no("user"),h&&(te.value="",te.style.height="auto",z.sendMessage(h))}else pt.manuallyDeactivated=!1,Wn(),ma("user")};br=fa,B&&(B.addEventListener("click",fa),mt.push(()=>{var l,p;((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?(z.isVoiceActive()&&z.toggleVoice(),_r()):no("system"),B&&B.removeEventListener("click",fa)}));let Lg=i.on("assistant:complete",()=>{ws&&(pt.active||pt.manuallyDeactivated||ws==="assistant"&&!pt.lastUserMessageWasVoice||setTimeout(()=>{var l,p;!pt.active&&!pt.manuallyDeactivated&&(((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?z.toggleVoice().then(()=>{pt.active=z.isVoiceActive(),er("auto"),z.isVoiceActive()&&Jo()}):ma("auto"))},600))});mt.push(Lg);let Pg=i.on("action:resubmit",()=>{setTimeout(()=>{z&&!z.isStreaming()&&z.continueConversation()},100)});mt.push(Pg);let kl=()=>{qt(!F,"user")},Zt=null,sn=null;if(L&&!H()){let{instance:l,element:p}=Vi({config:r,plugins:o,onToggle:kl});Zt=l,l||(sn=p)}Zt?t.appendChild(Zt.element):sn&&t.appendChild(sn),Es(),Uo(),wl(),ci(z.isStreaming()),$t()==="follow"?cn(!0):Or(),pa(),I&&(!L||H()?setTimeout(()=>di(),0):F&&setTimeout(()=>di(),200));let Ms=()=>{var N,ae,ie,Y,we,Oe,Ae,Ze,ze,ct,rt,Ie,ke,je,Ve,ft,W,Be,We,ge,Ft,Bt;if(H()){Xn(),Es();return}let l=fn(r),p=(ae=(N=r.launcher)==null?void 0:N.sidebarMode)!=null?ae:!1,h=l||p||((Y=(ie=r.launcher)==null?void 0:ie.fullHeight)!=null?Y:!1),y=(we=t.ownerDocument.defaultView)!=null?we:window,T=(Ae=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?Ae:!0,D=(ze=(Ze=r.launcher)==null?void 0:Ze.mobileBreakpoint)!=null?ze:640,j=y.innerWidth<=D,$=T&&j&&L;try{if($){xr(),us(t,r);return}if(_&&(_=!1,xr(),us(t,r)),!L&&!l){Q.style.height="",Q.style.width="";return}if(!p&&!l){let Gt=(rt=(ct=r==null?void 0:r.launcher)==null?void 0:ct.width)!=null?rt:r==null?void 0:r.launcherWidth,yt=Gt!=null?Gt:jr;Q.style.width=yt,Q.style.maxWidth=yt}if(ve(),!h){let Gt=y.innerHeight,yt=64,jt=(ke=(Ie=r.launcher)==null?void 0:Ie.heightOffset)!=null?ke:0,qn=Math.max(200,Gt-yt),en=Math.min(640,qn),Ge=Math.max(200,en-jt);Q.style.height=`${Ge}px`}}finally{if(Xn(),Es(),F&&L){let yt=((je=t.ownerDocument.defaultView)!=null?je:window).innerWidth<=((ft=(Ve=r.launcher)==null?void 0:Ve.mobileBreakpoint)!=null?ft:640),jt=(Be=(W=r.launcher)==null?void 0:W.sidebarMode)!=null?Be:!1,qn=(ge=(We=r.launcher)==null?void 0:We.mobileFullscreen)!=null?ge:!0,en=fn(r)&&qn&&yt,Ge=jt||qn&&yt&&L||en;if(Ge&&!on){let kt=t.getRootNode(),nn=kt instanceof ShadowRoot?kt.host:t.closest(".persona-host");nn&&!rn&&(rn=Ui(nn,(Bt=(Ft=r.launcher)==null?void 0:Ft.zIndex)!=null?Bt:xn)),on=zi(t.ownerDocument)}else Ge||(rn==null||rn(),rn=null,on==null||on(),on=null)}}};Ms();let Ll=(Wc=t.ownerDocument.defaultView)!=null?Wc:window;if(Ll.addEventListener("resize",Ms),mt.push(()=>Ll.removeEventListener("resize",Ms)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Xn()});l.observe(Fe),mt.push(()=>l.disconnect())}Un=Me.scrollTop;let Pl=Vr(Me),Ig=()=>{let l=Me.getRootNode(),p=typeof l.getSelection=="function"?l.getSelection():null;return p!=null?p:Me.ownerDocument.getSelection()},hi=()=>sm(Ig(),Me),Il=()=>{let l=Me.scrollTop,p=Vr(Me),h=p<Pl;if(Pl=p,$t()!=="follow"){Un=l,st();return}let{action:y,nextLastScrollTop:T}=$a({following:$n.isFollowing(),currentScrollTop:l,lastScrollTop:Un,nearBottom:Bo(Me,Vo),userScrollThreshold:ca,isAutoScrolling:dr||wo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Un=T,y==="resume"){hi()||Rn();return}y==="pause"&&xs()};if(Me.addEventListener("scroll",Il,{passive:!0}),mt.push(()=>Me.removeEventListener("scroll",Il)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{gg()});l.observe(nt),l.observe(Me),mt.push(()=>l.disconnect())}let Wl=()=>{$t()==="follow"&&$n.isFollowing()&&hi()&&xs()},Rl=Me.ownerDocument;Rl.addEventListener("selectionchange",Wl),mt.push(()=>{Rl.removeEventListener("selectionchange",Wl)});let Hl=l=>{if($t()!=="follow")return;let p=Ua({following:$n.isFollowing(),deltaY:l.deltaY,nearBottom:Bo(Me,Vo),resumeWhenNearBottom:!0});p==="pause"?xs():p==="resume"&&!hi()&&Rn()};Me.addEventListener("wheel",Hl,{passive:!0}),mt.push(()=>Me.removeEventListener("wheel",Hl)),zt.addEventListener("click",()=>{gn(),Me.scrollTop=Me.scrollHeight,Un=Me.scrollTop,Rn(),cn(!0),st()}),mt.push(()=>zt.remove()),mt.push(()=>{X(),gn()});let Bl=()=>{S&&(Ar&&(S.removeEventListener("click",Ar),Ar=null),U()?(S.style.display="",Ar=()=>{qt(!1,"user")},S.addEventListener("click",Ar)):S.style.display="none")};Bl(),(()=>{let{clearChatButton:l}=qe;l&&l.addEventListener("click",()=>{z.clearMessages(),Tr.clear(),Rn(),as(qe.composerOverlay);try{localStorage.removeItem(ys),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ys}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ys)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 p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),c!=null&&c.clear)try{let h=c.clear();h instanceof Promise&&h.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}u={},E.syncFromMetadata(),K==null||K.clear(),J==null||J.reset(),Le==null||Le.update()})})(),xt&&xt.addEventListener("submit",Cl),te==null||te.addEventListener("keydown",Sl),te==null||te.addEventListener("input",Al),te==null||te.addEventListener("paste",El);let Dl=(Rc=t.ownerDocument)!=null?Rc:document;Dl.addEventListener("keydown",Tl,!0);let Nl="persona-attachment-drop-active",ks=0,yi=()=>{ks=0,Ce.classList.remove(Nl)},Yo=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&At!==null},Fl=l=>{!ii(l.dataTransfer)||!Yo()||(ks++,ks===1&&Ce.classList.add(Nl))},Ol=l=>{!ii(l.dataTransfer)||!Yo()||(ks--,ks<=0&&yi())},_l=l=>{!ii(l.dataTransfer)||!Yo()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},$l=l=>{var h;if(!ii(l.dataTransfer)||!Yo())return;l.preventDefault(),l.stopPropagation(),yi();let p=Array.from((h=l.dataTransfer.files)!=null?h:[]);p.length!==0&&At.handleFiles(p)},ro=!0;Ce.addEventListener("dragenter",Fl,ro),Ce.addEventListener("dragleave",Ol,ro),t.addEventListener("dragover",_l,ro),t.addEventListener("drop",$l,ro);let ha=t.ownerDocument,Ul=l=>{Yo()&&l.preventDefault()},zl=l=>{Yo()&&l.preventDefault()};ha.addEventListener("dragover",Ul),ha.addEventListener("drop",zl),mt.push(()=>{xt&&xt.removeEventListener("submit",Cl),te==null||te.removeEventListener("keydown",Sl),te==null||te.removeEventListener("input",Al),te==null||te.removeEventListener("paste",El),Dl.removeEventListener("keydown",Tl,!0)}),mt.push(()=>{Ce.removeEventListener("dragenter",Fl,ro),Ce.removeEventListener("dragleave",Ol,ro),t.removeEventListener("dragover",_l,ro),t.removeEventListener("drop",$l,ro),ha.removeEventListener("dragover",Ul),ha.removeEventListener("drop",zl),yi()}),mt.push(()=>{z.cancel()}),Zt?mt.push(()=>{Zt==null||Zt.destroy()}):sn&&mt.push(()=>{sn==null||sn.remove()});let tn={update(l){var Ut,pn,Vn,Pr,un,mn,or,ao,_c,$c,Uc,zc,qc,jc,Vc,Kc,Gc,Qc,Xc,Jc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,vd,wd,xd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Wd,Rd,Hd,Bd,Dd,Nd,Fd,Od,_d,$d,Ud,zd,qd,jd,Vd,Kd,Gd,Qd,Xd,Jd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,vp,wp,xp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Wp,Rp,Hp,Bp,Dp,Np,Fp;let p=r.toolCall,h=r.messageActions,y=(Ut=r.layout)==null?void 0:Ut.messages,T=r.colorScheme,D=r.loadingIndicator,j=r.iterationDisplay,$=(pn=r.features)==null?void 0:pn.showReasoning,N=(Vn=r.features)==null?void 0:Vn.showToolCalls,ae=(Pr=r.features)==null?void 0:Pr.toolCallDisplay,ie=(un=r.features)==null?void 0:un.reasoningDisplay;r={...r,...l},xr(),us(t,r),si(t,r),ai(t,r),In(),r.colorScheme!==T&&vs();let Y=sl.getForInstance(r.plugins);o.length=0,o.push(...Y),L=(or=(mn=r.launcher)==null?void 0:mn.enabled)!=null?or:!0,M=(_c=(ao=r.launcher)==null?void 0:ao.autoExpand)!=null?_c:!1,xe=(Uc=($c=r.features)==null?void 0:$c.showReasoning)!=null?Uc:!0,Re=(qc=(zc=r.features)==null?void 0:zc.showToolCalls)!=null?qc:!0,me=(Vc=(jc=r.features)==null?void 0:jc.scrollToBottom)!=null?Vc:{};let we=$t();oe=(Gc=(Kc=r.features)==null?void 0:Kc.scrollBehavior)!=null?Gc:{},we!==$t()&&(gn(),Rn()),Kr(),st();let Oe=le;if(le=(Xc=(Qc=r.features)==null?void 0:Qc.showEventStreamToggle)!=null?Xc:!1,le&&!Oe){if(K||(Ee=new oa(de),K=new ra(He,Ee),J=J!=null?J:new sa,Ee.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),z.setSSEEventCallback((re,Tt)=>{var Vt;(Vt=r.onSSEEvent)==null||Vt.call(r,re,Tt),J==null||J.processEvent(re,Tt),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:re,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!ut&&Pe){let re=(Yc=(Jc=r.features)==null?void 0:Jc.eventStream)==null?void 0:Yc.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"+(re!=null&&re.toggleButton?" "+re.toggleButton:"");ut=b("button",Tt),ut.style.width="28px",ut.style.height="28px",ut.style.color=kn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let Vt=be("activity","18px","currentColor",1.5);Vt&&ut.appendChild(Vt);let ot=qe.clearChatButtonWrapper,Pt=qe.closeButtonWrapper,an=ot||Pt;an&&an.parentNode===Pe?Pe.insertBefore(ut,an):Pe.appendChild(ut),ut.addEventListener("click",()=>{G?ir():Wr()})}}else!le&&Oe&&(ir(),ut&&(ut.remove(),ut=null),K==null||K.clear(),Ee==null||Ee.destroy(),K=null,Ee=null,J==null||J.reset(),J=null);if(((Zc=r.launcher)==null?void 0:Zc.enabled)===!1&&Zt&&(Zt.destroy(),Zt=null),((ed=r.launcher)==null?void 0:ed.enabled)===!1&&sn&&(sn.remove(),sn=null),((td=r.launcher)==null?void 0:td.enabled)!==!1&&!Zt&&!sn){let{instance:re,element:Tt}=Vi({config:r,plugins:o,onToggle:kl});Zt=re,re||(sn=Tt),t.appendChild(Tt)}Zt&&Zt.update(r),Se&&((nd=r.launcher)==null?void 0:nd.title)!==void 0&&(Se.textContent=r.launcher.title),Ne&&((rd=r.launcher)==null?void 0:rd.subtitle)!==void 0&&(Ne.textContent=r.launcher.subtitle);let Ae=(od=r.layout)==null?void 0:od.header;if((Ae==null?void 0:Ae.layout)!==O&&Pe){let re=Ae?Ga(r,Ae,{showClose:U(),onClose:()=>qt(!1,"user")}):Do({config:r,showClose:U(),onClose:()=>qt(!1,"user")});Je.replaceHeader(re),Pe=Je.header.element,ne=Je.header.iconHolder,Se=Je.header.headerTitle,Ne=Je.header.headerSubtitle,S=Je.header.closeButton,O=Ae==null?void 0:Ae.layout}else if(Ae&&(ne&&(ne.style.display=Ae.showIcon===!1?"none":""),Se&&(Se.style.display=Ae.showTitle===!1?"none":""),Ne&&(Ne.style.display=Ae.showSubtitle===!1?"none":""),S&&(S.style.display=Ae.showCloseButton===!1?"none":""),qe.clearChatButtonWrapper)){let re=Ae.showClearChat;if(re!==void 0){qe.clearChatButtonWrapper.style.display=re?"":"none";let{closeButtonWrapper:Tt}=qe;Tt&&!Tt.classList.contains("persona-absolute")&&(re?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let ze=((sd=r.layout)==null?void 0:sd.showHeader)!==!1;Pe&&(Pe.style.display=ze?"":"none");let ct=((ad=r.layout)==null?void 0:ad.showFooter)!==!1;Fe&&(Fe.style.display=ct?"":"none"),Xn(),st(),L!==P?L?qt(M,"auto"):(F=!0,Es()):M!==A&&qt(M,"auto"),A=M,P=L,Ms(),Bl();let ke=JSON.stringify(l.toolCall)!==JSON.stringify(p),je=JSON.stringify(r.messageActions)!==JSON.stringify(h),Ve=JSON.stringify((id=r.layout)==null?void 0:id.messages)!==JSON.stringify(y),ft=((ld=r.loadingIndicator)==null?void 0:ld.render)!==(D==null?void 0:D.render)||((cd=r.loadingIndicator)==null?void 0:cd.renderIdle)!==(D==null?void 0:D.renderIdle)||((dd=r.loadingIndicator)==null?void 0:dd.showBubble)!==(D==null?void 0:D.showBubble),W=r.iterationDisplay!==j,Be=((ud=(pd=r.features)==null?void 0:pd.showReasoning)!=null?ud:!0)!==($!=null?$:!0)||((gd=(md=r.features)==null?void 0:md.showToolCalls)!=null?gd:!0)!==(N!=null?N:!0)||JSON.stringify((fd=r.features)==null?void 0:fd.toolCallDisplay)!==JSON.stringify(ae)||JSON.stringify((hd=r.features)==null?void 0:hd.reasoningDisplay)!==JSON.stringify(ie);(ke||je||Ve||ft||W||Be)&&z&&(zo++,Cs(nt,z.getMessages(),ee));let ge=(yd=r.launcher)!=null?yd:{},Ft=(bd=ge.headerIconHidden)!=null?bd:!1,Bt=(wd=(vd=r.layout)==null?void 0:vd.header)==null?void 0:wd.showIcon,Gt=Ft||Bt===!1,yt=ge.headerIconName,jt=(xd=ge.headerIconSize)!=null?xd:"48px";if(ne){let re=Ce.querySelector(".persona-border-b-persona-divider"),Tt=re==null?void 0:re.querySelector(".persona-flex-col");if(Gt)ne.style.display="none",re&&Tt&&!re.contains(Tt)&&re.insertBefore(Tt,re.firstChild);else{if(ne.style.display="",ne.style.height=jt,ne.style.width=jt,re&&Tt&&(re.contains(ne)?ne.nextSibling!==Tt&&(ne.remove(),re.insertBefore(ne,Tt)):re.insertBefore(ne,Tt)),yt){let ot=parseFloat(jt)||24,Pt=be(yt,ot*.6,"currentColor",1);Pt?ne.replaceChildren(Pt):ne.textContent=(Cd=ge.agentIconText)!=null?Cd:"\u{1F4AC}"}else if(ge.iconUrl){let ot=ne.querySelector("img");if(ot)ot.src=ge.iconUrl,ot.style.height=jt,ot.style.width=jt;else{let Pt=document.createElement("img");Pt.src=ge.iconUrl,Pt.alt="",Pt.className="persona-rounded-xl persona-object-cover",Pt.style.height=jt,Pt.style.width=jt,ne.replaceChildren(Pt)}}else{let ot=ne.querySelector("svg"),Pt=ne.querySelector("img");(ot||Pt)&&ne.replaceChildren(),ne.textContent=(Ad=ge.agentIconText)!=null?Ad:"\u{1F4AC}"}let Vt=ne.querySelector("img");Vt&&(Vt.style.height=jt,Vt.style.width=jt)}}let qn=(Td=(Sd=r.layout)==null?void 0:Sd.header)==null?void 0:Td.showTitle,en=(Md=(Ed=r.layout)==null?void 0:Ed.header)==null?void 0:Md.showSubtitle;if(Se&&(Se.style.display=qn===!1?"none":""),Ne&&(Ne.style.display=en===!1?"none":""),S){((Ld=(kd=r.layout)==null?void 0:kd.header)==null?void 0:Ld.showCloseButton)===!1?S.style.display="none":S.style.display="";let Tt=(Pd=ge.closeButtonSize)!=null?Pd:"32px",Vt=(Id=ge.closeButtonPlacement)!=null?Id:"inline";S.style.height=Tt,S.style.width=Tt;let{closeButtonWrapper:ot}=qe,Pt=Vt==="top-right",an=ot==null?void 0:ot.classList.contains("persona-absolute");if(ot&&Pt!==an)if(ot.remove(),Pt)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Ce.style.position="relative",Ce.appendChild(ot);else{let at=(Rd=(Wd=ge.clearChat)==null?void 0:Wd.placement)!=null?Rd:"inline",ln=(Bd=(Hd=ge.clearChat)==null?void 0:Hd.enabled)!=null?Bd:!0;ot.className=ln&&at==="inline"?"":"persona-ml-auto";let Hn=Ce.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(ot)}if(S.style.color=ge.closeButtonColor||kn.actionIconColor,ge.closeButtonBackgroundColor?(S.style.backgroundColor=ge.closeButtonBackgroundColor,S.classList.remove("hover:persona-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:persona-bg-gray-100")),ge.closeButtonBorderWidth||ge.closeButtonBorderColor){let at=ge.closeButtonBorderWidth||"0px",ln=ge.closeButtonBorderColor||"transparent";S.style.border=`${at} solid ${ln}`,S.classList.remove("persona-border-none")}else S.style.border="",S.classList.add("persona-border-none");ge.closeButtonBorderRadius?(S.style.borderRadius=ge.closeButtonBorderRadius,S.classList.remove("persona-rounded-full")):(S.style.borderRadius="",S.classList.add("persona-rounded-full")),ge.closeButtonPaddingX?(S.style.paddingLeft=ge.closeButtonPaddingX,S.style.paddingRight=ge.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),ge.closeButtonPaddingY?(S.style.paddingTop=ge.closeButtonPaddingY,S.style.paddingBottom=ge.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom="");let vn=(Dd=ge.closeButtonIconName)!=null?Dd:"x",ur=(Nd=ge.closeButtonIconText)!=null?Nd:"\xD7";S.innerHTML="";let Mn=be(vn,"28px","currentColor",1);Mn?S.appendChild(Mn):S.textContent=ur;let Yt=(Fd=ge.closeButtonTooltipText)!=null?Fd:"Close chat",Kn=(Od=ge.closeButtonShowTooltip)!=null?Od:!0;if(S.setAttribute("aria-label",Yt),ot&&(ot._cleanupTooltip&&(ot._cleanupTooltip(),delete ot._cleanupTooltip),Kn&&Yt)){let at=null,ln=()=>{if(at||!S)return;let ko=S.ownerDocument,Ls=ko.body;if(!Ls)return;at=Ir(ko,"div","persona-clear-chat-tooltip"),at.textContent=Yt;let Ps=Ir(ko,"div");Ps.className="persona-clear-chat-tooltip-arrow",at.appendChild(Ps);let Lo=S.getBoundingClientRect();at.style.position="fixed",at.style.zIndex=String(mo),at.style.left=`${Lo.left+Lo.width/2}px`,at.style.top=`${Lo.top-8}px`,at.style.transform="translate(-50%, -100%)",Ls.appendChild(at)},Hn=()=>{at&&at.parentNode&&(at.parentNode.removeChild(at),at=null)};ot.addEventListener("mouseenter",ln),ot.addEventListener("mouseleave",Hn),S.addEventListener("focus",ln),S.addEventListener("blur",Hn),ot._cleanupTooltip=()=>{Hn(),ot&&(ot.removeEventListener("mouseenter",ln),ot.removeEventListener("mouseleave",Hn)),S&&(S.removeEventListener("focus",ln),S.removeEventListener("blur",Hn))}}}let{clearChatButton:Ge,clearChatButtonWrapper:kt}=qe;if(Ge){let re=(_d=ge.clearChat)!=null?_d:{},Tt=($d=re.enabled)!=null?$d:!0,Vt=(zd=(Ud=r.layout)==null?void 0:Ud.header)==null?void 0:zd.showClearChat,ot=Vt!==void 0?Vt:Tt,Pt=(qd=re.placement)!=null?qd:"inline";if(kt){kt.style.display=ot?"":"none";let{closeButtonWrapper:an}=qe;!H()&&an&&!an.classList.contains("persona-absolute")&&(ot?an.classList.remove("persona-ml-auto"):an.classList.add("persona-ml-auto"));let vn=Pt==="top-right",ur=kt.classList.contains("persona-absolute");if(!H()&&vn!==ur&&ot){if(kt.remove(),vn)kt.className="persona-absolute persona-top-4 persona-z-50",kt.style.right="48px",Ce.style.position="relative",Ce.appendChild(kt);else{kt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",kt.style.right="";let Yt=Ce.querySelector(".persona-border-b-persona-divider"),Kn=qe.closeButtonWrapper;Yt&&Kn&&Kn.parentElement===Yt?Yt.insertBefore(kt,Kn):Yt&&Yt.appendChild(kt)}let Mn=qe.closeButtonWrapper;Mn&&!Mn.classList.contains("persona-absolute")&&(vn?Mn.classList.add("persona-ml-auto"):Mn.classList.remove("persona-ml-auto"))}}if(ot){if(!H()){let at=(jd=re.size)!=null?jd:"32px";Ge.style.height=at,Ge.style.width=at}let an=(Vd=re.iconName)!=null?Vd:"refresh-cw",vn=(Kd=re.iconColor)!=null?Kd:"";Ge.style.color=vn||kn.actionIconColor,Ge.innerHTML="";let ur=H()?"14px":"20px",Mn=be(an,ur,"currentColor",2);if(Mn&&Ge.appendChild(Mn),re.backgroundColor?(Ge.style.backgroundColor=re.backgroundColor,Ge.classList.remove("hover:persona-bg-gray-100")):(Ge.style.backgroundColor="",Ge.classList.add("hover:persona-bg-gray-100")),re.borderWidth||re.borderColor){let at=re.borderWidth||"0px",ln=re.borderColor||"transparent";Ge.style.border=`${at} solid ${ln}`,Ge.classList.remove("persona-border-none")}else Ge.style.border="",Ge.classList.add("persona-border-none");re.borderRadius?(Ge.style.borderRadius=re.borderRadius,Ge.classList.remove("persona-rounded-full")):(Ge.style.borderRadius="",Ge.classList.add("persona-rounded-full")),re.paddingX?(Ge.style.paddingLeft=re.paddingX,Ge.style.paddingRight=re.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),re.paddingY?(Ge.style.paddingTop=re.paddingY,Ge.style.paddingBottom=re.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let Yt=(Gd=re.tooltipText)!=null?Gd:"Clear chat",Kn=(Qd=re.showTooltip)!=null?Qd:!0;if(Ge.setAttribute("aria-label",Yt),kt&&(kt._cleanupTooltip&&(kt._cleanupTooltip(),delete kt._cleanupTooltip),Kn&&Yt)){let at=null,ln=()=>{if(at||!Ge)return;let ko=Ge.ownerDocument,Ls=ko.body;if(!Ls)return;at=Ir(ko,"div","persona-clear-chat-tooltip"),at.textContent=Yt;let Ps=Ir(ko,"div");Ps.className="persona-clear-chat-tooltip-arrow",at.appendChild(Ps);let Lo=Ge.getBoundingClientRect();at.style.position="fixed",at.style.zIndex=String(mo),at.style.left=`${Lo.left+Lo.width/2}px`,at.style.top=`${Lo.top-8}px`,at.style.transform="translate(-50%, -100%)",Ls.appendChild(at)},Hn=()=>{at&&at.parentNode&&(at.parentNode.removeChild(at),at=null)};kt.addEventListener("mouseenter",ln),kt.addEventListener("mouseleave",Hn),Ge.addEventListener("focus",ln),Ge.addEventListener("blur",Hn),kt._cleanupTooltip=()=>{Hn(),kt&&(kt.removeEventListener("mouseenter",ln),kt.removeEventListener("mouseleave",Hn)),Ge&&(Ge.removeEventListener("focus",ln),Ge.removeEventListener("blur",Hn))}}}}let nn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[il],rr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[aa.message,aa.messageAndClick];E=ll({parsers:nn,handlers:rr,getSessionMetadata:w,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),ee=eg(r,E,pe),z.updateConfig(r),Cs(nt,z.getMessages(),ee),Uo(),wl(),ci(z.isStreaming());let jn=((Xd=r.voiceRecognition)==null?void 0:Xd.enabled)===!0,So=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),To=((Yd=(Jd=r.voiceRecognition)==null?void 0:Jd.provider)==null?void 0:Yd.type)==="runtype";if(jn&&(So||To))if(!B||!he){let re=Eg(r.voiceRecognition,r.sendButton);re&&(B=re.micButton,he=re.micButtonWrapper,Rt.insertBefore(he,An),B.addEventListener("click",fa),B.disabled=z.isStreaming())}else{let re=(Zd=r.voiceRecognition)!=null?Zd:{},Tt=(ep=r.sendButton)!=null?ep:{},Vt=(tp=re.iconName)!=null?tp:"mic",ot=(np=Tt.size)!=null?np:"40px",Pt=(rp=re.iconSize)!=null?rp:ot,an=parseFloat(Pt)||24;B.style.width=Pt,B.style.height=Pt,B.style.minWidth=Pt,B.style.minHeight=Pt;let vn=(sp=(op=re.iconColor)!=null?op:Tt.textColor)!=null?sp:"currentColor";B.innerHTML="";let ur=be(Vt,an,vn,2);ur?B.appendChild(ur):B.textContent="\u{1F3A4}";let Mn=(ap=re.backgroundColor)!=null?ap:Tt.backgroundColor;Mn?B.style.backgroundColor=Mn:B.style.backgroundColor="",vn?B.style.color=vn:B.style.color="var(--persona-text, #111827)",re.borderWidth?(B.style.borderWidth=re.borderWidth,B.style.borderStyle="solid"):(B.style.borderWidth="",B.style.borderStyle=""),re.borderColor?B.style.borderColor=re.borderColor:B.style.borderColor="",re.paddingX?(B.style.paddingLeft=re.paddingX,B.style.paddingRight=re.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),re.paddingY?(B.style.paddingTop=re.paddingY,B.style.paddingBottom=re.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let Yt=he==null?void 0:he.querySelector(".persona-send-button-tooltip"),Kn=(ip=re.tooltipText)!=null?ip:"Start voice recognition";if(((lp=re.showTooltip)!=null?lp:!1)&&Kn)if(Yt)Yt.textContent=Kn,Yt.style.display="";else{let ln=document.createElement("div");ln.className="persona-send-button-tooltip",ln.textContent=Kn,he==null||he.insertBefore(ln,B)}else Yt&&(Yt.style.display="none");he.style.display="",B.disabled=z.isStreaming()}else B&&he&&(he.style.display="none",((dp=(cp=r.voiceRecognition)==null?void 0:cp.provider)==null?void 0:dp.type)==="runtype"?z.isVoiceActive()&&z.toggleVoice():kr&&no());if(((pp=r.attachments)==null?void 0:pp.enabled)===!0)if(!Ct||!_e){let re=(up=r.attachments)!=null?up:{},Vt=(gp=((mp=r.sendButton)!=null?mp:{}).size)!=null?gp:"40px";Nt||(Nt=b("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Nt.style.display="none",xt.insertBefore(Nt,te)),Ye||(Ye=document.createElement("input"),Ye.type="file",Ye.accept=((fp=re.allowedTypes)!=null?fp:qr).join(","),Ye.multiple=((hp=re.maxFiles)!=null?hp:4)>1,Ye.style.display="none",Ye.setAttribute("aria-label","Attach files"),xt.insertBefore(Ye,te)),Ct=b("div","persona-send-button-wrapper"),_e=b("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),_e.type="button",_e.setAttribute("aria-label",(yp=re.buttonTooltipText)!=null?yp:"Attach file");let ot=(bp=re.buttonIconName)!=null?bp:"paperclip",Pt=Vt,an=parseFloat(Pt)||40,vn=Math.round(an*.6);_e.style.width=Pt,_e.style.height=Pt,_e.style.minWidth=Pt,_e.style.minHeight=Pt,_e.style.fontSize="18px",_e.style.lineHeight="1",_e.style.backgroundColor="transparent",_e.style.color="var(--persona-primary, #111827)",_e.style.border="none",_e.style.borderRadius="6px",_e.style.transition="background-color 0.15s ease",_e.addEventListener("mouseenter",()=>{_e.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),_e.addEventListener("mouseleave",()=>{_e.style.backgroundColor="transparent"});let ur=be(ot,vn,"currentColor",1.5);ur?_e.appendChild(ur):_e.textContent="\u{1F4CE}",_e.addEventListener("click",Kn=>{Kn.preventDefault(),Ye==null||Ye.click()}),Ct.appendChild(_e);let Mn=(vp=re.buttonTooltipText)!=null?vp:"Attach file",Yt=b("div","persona-send-button-tooltip");Yt.textContent=Mn,Ct.appendChild(Yt),it.append(Ct),!At&&Ye&&Nt&&(At=Vs.fromConfig(re),At.setPreviewsContainer(Nt),Ye.addEventListener("change",async()=>{At&&(Ye!=null&&Ye.files)&&(await At.handleFileSelect(Ye.files),Ye.value="")})),Ce.querySelector(".persona-attachment-drop-overlay")||Ce.appendChild(tg(re.dropOverlay))}else{Ct.style.display="";let re=(wp=r.attachments)!=null?wp:{};Ye&&(Ye.accept=((xp=re.allowedTypes)!=null?xp:qr).join(","),Ye.multiple=((Cp=re.maxFiles)!=null?Cp:4)>1),At&&At.updateConfig({allowedTypes:re.allowedTypes,maxFileSize:re.maxFileSize,maxFiles:re.maxFiles})}else Ct&&(Ct.style.display="none"),At&&At.clearAttachments(),(Ap=Ce.querySelector(".persona-attachment-drop-overlay"))==null||Ap.remove();let Qt=(Sp=r.sendButton)!=null?Sp:{},Eo=(Tp=Qt.useIcon)!=null?Tp:!1,oo=(Ep=Qt.iconText)!=null?Ep:"\u2191",so=Qt.iconName,$r=(Mp=Qt.tooltipText)!=null?Mp:"Send message",Mo=(kp=Qt.showTooltip)!=null?kp:!1,pr=(Lp=Qt.size)!=null?Lp:"40px",Lr=Qt.backgroundColor,Qe=Qt.textColor;if(Eo){if(Ue.style.width=pr,Ue.style.height=pr,Ue.style.minWidth=pr,Ue.style.minHeight=pr,Ue.style.fontSize="18px",Ue.style.lineHeight="1",Ue.innerHTML="",Qe?Ue.style.color=Qe:Ue.style.color="var(--persona-button-primary-fg, #ffffff)",so){let re=parseFloat(pr)||24,Tt=(Qe==null?void 0:Qe.trim())||"currentColor",Vt=be(so,re,Tt,2);Vt?Ue.appendChild(Vt):Ue.textContent=oo}else Ue.textContent=oo;Ue.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Lr?(Ue.style.backgroundColor=Lr,Ue.classList.remove("persona-bg-persona-primary")):(Ue.style.backgroundColor="",Ue.classList.add("persona-bg-persona-primary"))}else Ue.textContent=(Ip=(Pp=r.copy)==null?void 0:Pp.sendButtonLabel)!=null?Ip:"Send",Ue.style.width="",Ue.style.height="",Ue.style.minWidth="",Ue.style.minHeight="",Ue.style.fontSize="",Ue.style.lineHeight="",Ue.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",Lr?(Ue.style.backgroundColor=Lr,Ue.classList.remove("persona-bg-persona-accent")):Ue.classList.add("persona-bg-persona-accent"),Qe?Ue.style.color=Qe:Ue.classList.add("persona-text-white");Qt.borderWidth?(Ue.style.borderWidth=Qt.borderWidth,Ue.style.borderStyle="solid"):(Ue.style.borderWidth="",Ue.style.borderStyle=""),Qt.borderColor?Ue.style.borderColor=Qt.borderColor:Ue.style.borderColor="",Qt.paddingX?(Ue.style.paddingLeft=Qt.paddingX,Ue.style.paddingRight=Qt.paddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),Qt.paddingY?(Ue.style.paddingTop=Qt.paddingY,Ue.style.paddingBottom=Qt.paddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let Ot=An==null?void 0:An.querySelector(".persona-send-button-tooltip");if(Mo&&$r)if(Ot)Ot.textContent=$r,Ot.style.display="";else{let re=document.createElement("div");re.className="persona-send-button-tooltip",re.textContent=$r,An==null||An.insertBefore(re,Ue)}else Ot&&(Ot.style.display="none");let Kt=(Dp=(Wp=r.layout)==null?void 0:Wp.contentMaxWidth)!=null?Dp:H()?(Bp=(Hp=(Rp=r.launcher)==null?void 0:Rp.composerBar)==null?void 0:Hp.contentMaxWidth)!=null?Bp:"720px":void 0;Kt?(nt.style.maxWidth=Kt,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%",xt&&(xt.style.maxWidth=Kt,xt.style.marginLeft="auto",xt.style.marginRight="auto"),Wt&&(Wt.style.maxWidth=Kt,Wt.style.marginLeft="auto",Wt.style.marginRight="auto")):(nt.style.maxWidth="",nt.style.marginLeft="",nt.style.marginRight="",nt.style.width="",xt&&(xt.style.maxWidth="",xt.style.marginLeft="",xt.style.marginRight=""),Wt&&(Wt.style.maxWidth="",Wt.style.marginLeft="",Wt.style.marginRight=""));let _t=(Np=r.statusIndicator)!=null?Np:{},Xt=(Fp=_t.visible)!=null?Fp:!0;if(hn.style.display=Xt?"":"none",z){let re=z.getStatus();wt(hn,(Vt=>{var ot,Pt,an,vn;return Vt==="idle"?(ot=_t.idleText)!=null?ot:wn.idle:Vt==="connecting"?(Pt=_t.connectingText)!=null?Pt:wn.connecting:Vt==="connected"?(an=_t.connectedText)!=null?an:wn.connected:Vt==="error"?(vn=_t.errorText)!=null?vn:wn.error:wn[Vt]})(re),_t,re)}hn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Lt=_t.align==="left"?"persona-text-left":_t.align==="center"?"persona-text-center":"persona-text-right";hn.classList.add(Lt)},open(){U()&&qt(!0,"api")},close(){U()&&qt(!1,"api")},toggle(){U()&&qt(!F,"api")},clearChat(){Sn=!1,z.clearMessages(),Tr.clear(),Rn();try{localStorage.removeItem(ys),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ys}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==ys)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),c!=null&&c.clear)try{let p=c.clear();p instanceof Promise&&p.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}u={},E.syncFromMetadata(),K==null||K.clear(),J==null||J.reset(),Le==null||Le.update()},setMessage(l){return!te||z.isStreaming()?!1:(!F&&U()&&qt(!0,"system"),te.value=l,te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(z.isStreaming())return!1;let p=(l==null?void 0:l.trim())||te.value.trim();return p?(!F&&U()&&qt(!0,"system"),te.value="",te.style.height="auto",z.sendMessage(p),!0):!1},startVoiceRecognition(){var p,h;return z.isStreaming()?!1:((h=(p=r.voiceRecognition)==null?void 0:p.provider)==null?void 0:h.type)==="runtype"?(z.isVoiceActive()||(!F&&U()&&qt(!0,"system"),pt.manuallyDeactivated=!1,Wn(),z.toggleVoice().then(()=>{pt.active=z.isVoiceActive(),er("user"),z.isVoiceActive()&&Jo()})),!0):kr?!0:Ml()?(!F&&U()&&qt(!0,"system"),pt.manuallyDeactivated=!1,Wn(),ma("user"),!0):!1},stopVoiceRecognition(){var l,p;return((p=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?z.isVoiceActive()?(z.toggleVoice().then(()=>{pt.active=!1,pt.manuallyDeactivated=!0,Wn(),er("user"),_r()}),!0):!1:kr?(pt.manuallyDeactivated=!0,Wn(),no("user"),!0):!1},injectMessage(l){return!F&&U()&&qt(!0,"system"),z.injectMessage(l)},injectAssistantMessage(l){!F&&U()&&qt(!0,"system");let p=z.injectAssistantMessage(l);return Z&&(Z=!1,Te&&(clearTimeout(Te),Te=null),setTimeout(()=>{z&&!z.isStreaming()&&z.continueConversation()},100)),p},injectUserMessage(l){return!F&&U()&&qt(!0,"system"),z.injectUserMessage(l)},injectSystemMessage(l){return!F&&U()&&qt(!0,"system"),z.injectSystemMessage(l)},injectMessageBatch(l){return!F&&U()&&qt(!0,"system"),z.injectMessageBatch(l)},injectComponentDirective(l){return!F&&U()&&qt(!0,"system"),z.injectComponentDirective(l)},injectTestMessage(l){!F&&U()&&qt(!0,"system"),z.injectTestEvent(l)},async connectStream(l,p){return z.connectStream(l,p)},__pushEventStreamEvent(l){K&&(J==null||J.processEvent(l.type,l.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!le||!K||Wr()},hideEventStream(){G&&ir()},isEventStreamVisible(){return G},showArtifacts(){ar(r)&&(Sn=!1,In(),bt==null||bt.setMobileOpen(!0))},hideArtifacts(){ar(r)&&(Sn=!0,In())},upsertArtifact(l){return ar(r)?(Sn=!1,z.upsertArtifact(l)):null},selectArtifact(l){ar(r)&&z.selectArtifact(l)},clearArtifacts(){ar(r)&&z.clearArtifacts()},getArtifacts(){var l;return(l=z==null?void 0:z.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=z==null?void 0:z.getSelectedArtifactId())!=null?l:null},focusInput(){return L&&!F&&!H()||!te?!1:(te.focus(),!0)},async resolveApproval(l,p,h){let T=z.getMessages().find(D=>{var j;return D.variant==="approval"&&((j=D.approval)==null?void 0:j.id)===l});if(!(T!=null&&T.approval))throw new Error(`Approval not found: ${l}`);if(T.approval.toolType==="webmcp"){z.resolveWebMcpApproval(T.id,p);return}return z.resolveApproval(T.approval,p,h)},getMessages(){return z.getMessages()},getStatus(){return z.getStatus()},getPersistentMetadata(){return{...u}},updatePersistentMetadata(l){v(l)},on(l,p){return i.on(l,p)},off(l,p){i.off(l,p)},isOpen(){return U()&&F},isVoiceActive(){return pt.active},toggleReadAloud(l){z.toggleReadAloud(l)},stopReadAloud(){z.stopSpeaking()},getReadAloudState(l){return z.getReadAloudState(l)},onReadAloudChange(l){return z.onReadAloudChange(l)},getState(){return{open:U()&&F,launcherEnabled:L,voiceActive:pt.active,streaming:z.isStreaming()}},showCSATFeedback(l){!F&&U()&&qt(!0,"system");let p=nt.querySelector(".persona-feedback-container");p&&p.remove();let h=Jm({onSubmit:async(y,T)=>{var D;z.isClientTokenMode()&&await z.submitCSATFeedback(y,T),(D=l==null?void 0:l.onSubmit)==null||D.call(l,y,T)},onDismiss:l==null?void 0:l.onDismiss,...l});nt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!F&&U()&&qt(!0,"system");let p=nt.querySelector(".persona-feedback-container");p&&p.remove();let h=Ym({onSubmit:async(y,T)=>{var D;z.isClientTokenMode()&&await z.submitNPSFeedback(y,T),(D=l==null?void 0:l.onSubmit)==null||D.call(l,y,T)},onDismiss:l==null?void 0:l.onDismiss,...l});nt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,p){return z.submitCSATFeedback(l,p)},async submitNPSFeedback(l,p){return z.submitNPSFeedback(l,p)},destroy(){Ao!=null&&(clearInterval(Ao),Ao=null),mt.forEach(l=>l()),fe.remove(),dt==null||dt.remove(),Zt==null||Zt.destroy(),sn==null||sn.remove(),Ar&&S.removeEventListener("click",Ar)}};if((((Hc=n==null?void 0:n.debugTools)!=null?Hc:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={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=p,mt.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),p=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",p),mt.push(()=>{window.removeEventListener("persona:focusInput",p)}),le){let $=ae=>{let ie=ae.detail;(!(ie!=null&&ie.instanceId)||ie.instanceId===l)&&tn.showEventStream()},N=ae=>{let ie=ae.detail;(!(ie!=null&&ie.instanceId)||ie.instanceId===l)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",$),window.addEventListener("persona:hideEventStream",N),mt.push(()=>{window.removeEventListener("persona:showEventStream",$),window.removeEventListener("persona:hideEventStream",N)})}let h=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&tn.showArtifacts()},y=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&tn.hideArtifacts()},T=$=>{let N=$.detail;N!=null&&N.instanceId&&N.instanceId!==l||N!=null&&N.artifact&&tn.upsertArtifact(N.artifact)},D=$=>{let N=$.detail;N!=null&&N.instanceId&&N.instanceId!==l||typeof(N==null?void 0:N.id)=="string"&&tn.selectArtifact(N.id)},j=$=>{let N=$.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",y),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",j),mt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",y),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",j)})}let nr=Oy(r.persistState);if(nr&&U()){let l=_y(nr.storage),p=`${nr.keyPrefix}widget-open`,h=`${nr.keyPrefix}widget-voice`,y=`${nr.keyPrefix}widget-voice-mode`;if(l){let T=((Bc=nr.persist)==null?void 0:Bc.openState)&&l.getItem(p)==="true",D=((Dc=nr.persist)==null?void 0:Dc.voiceState)&&l.getItem(h)==="true",j=((Nc=nr.persist)==null?void 0:Nc.voiceState)&&l.getItem(y)==="true";if(T&&setTimeout(()=>{tn.open(),setTimeout(()=>{var $;if(D||j)tn.startVoiceRecognition();else if(($=nr.persist)!=null&&$.focusInput){let N=t.querySelector("textarea");N&&N.focus()}},100)},0),(Fc=nr.persist)!=null&&Fc.openState&&(i.on("widget:opened",()=>{l.setItem(p,"true")}),i.on("widget:closed",()=>{l.setItem(p,"false")})),(Oc=nr.persist)!=null&&Oc.voiceState&&(i.on("voice:state",$=>{l.setItem(h,$.active?"true":"false")}),i.on("user:message",$=>{l.setItem(y,$.viaVoice?"true":"false")})),nr.clearOnChatClear){let $=()=>{l.removeItem(p),l.removeItem(h),l.removeItem(y)},N=()=>$();window.addEventListener("persona:clear-chat",N),mt.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return g&&U()&&setTimeout(()=>{tn.open()},0),Qo(),la||Vp().then(()=>{z&&(zo++,Tr.clear(),Cs(nt,z.getMessages(),ee))}).catch(()=>{}),tn};var $y=(t,e)=>{let n=t.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,e*parseFloat(o[1])/100):420},Uy=(t,e)=>{if(e===!1){t.style.maxHeight="";return}t.style.maxHeight="100vh",t.style.maxHeight=e},zy=(t,e)=>{e===!1?(t.style.position="relative",t.style.top=""):(t.style.position="sticky",t.style.top="0")},qy=(t,e)=>{let n=t.parentElement;if(!n)return;let r=t.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."+(e.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${e.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},rg=(t,e)=>{var r,o;let n=(o=(r=e==null?void 0:e.launcher)==null?void 0:r.enabled)!=null?o:!0;t.className="persona-host",t.style.height=n?"":"100%",t.style.display=n?"":"flex",t.style.flexDirection=n?"":"column",t.style.flex=n?"":"1 1 auto",t.style.minHeight=n?"":"0"},gl=t=>{t.style.position="",t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.zIndex="",t.style.transform="",t.style.pointerEvents=""},og=t=>{t.style.inset="",t.style.width="",t.style.height="",t.style.maxWidth="",t.style.maxHeight="",t.style.minWidth="",gl(t)},pl=t=>{t.style.transition=""},ul=t=>{t.style.display="",t.style.flexDirection="",t.style.flex="",t.style.minHeight="",t.style.minWidth="",t.style.width="",t.style.height="",t.style.alignItems="",t.style.transition="",t.style.transform="",t.style.marginLeft=""},ml=t=>{t.style.width="",t.style.maxWidth="",t.style.minWidth="",t.style.flex="1 1 auto"},li=(t,e)=>{t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.boxSizing="",e.style.alignItems=""},jy=(t,e,n,r,o)=>{o?n.parentElement!==e&&(t.replaceChildren(),e.replaceChildren(n,r),t.appendChild(e)):n.parentElement===e&&(e.replaceChildren(),t.appendChild(n),t.appendChild(r))},Vy=(t,e,n,r,o,s)=>{let a=s?e:t;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},sg=(t,e,n,r,o,s,a)=>{var w,v,k,R,E,L;let i=gr(s),d=i.reveal==="push";jy(t,e,n,r,d),Vy(t,e,n,r,i.side,d),t.dataset.personaHostLayout="docked",t.dataset.personaDockSide=i.side,t.dataset.personaDockOpen=a?"true":"false",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0",t.style.height="100%",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",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=t.ownerDocument.defaultView,u=(v=(w=s==null?void 0:s.launcher)==null?void 0:w.mobileFullscreen)!=null?v:!0,m=(R=(k=s==null?void 0:s.launcher)==null?void 0:k.mobileBreakpoint)!=null?R:640,g=c!=null?c.innerWidth<=m:!1;if(u&&g&&a){t.dataset.personaDockMobileFullscreen="true",t.removeAttribute("data-persona-dock-reveal"),ul(e),pl(r),og(r),ml(n),li(o,r),t.style.display="flex",t.style.flexDirection="column",t.style.alignItems="stretch",t.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",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((L=(E=s==null?void 0:s.launcher)==null?void 0:E.zIndex)!=null?L:xn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(t.removeAttribute("data-persona-dock-mobile-fullscreen"),og(r),Uy(r,i.maxHeight),i.reveal==="overlay"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="overlay",ul(e),pl(r),ml(n),li(o,r);let M=i.animate?"transform 180ms ease":"none",I=i.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":I;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=M,r.style.transform=A,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"){t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="hidden",t.dataset.personaDockReveal="push",pl(r),gl(r),li(o,r);let M=$y(i.width,t.clientWidth),I=Math.max(0,t.clientWidth),A=i.animate?"margin-left 180ms ease":"none",P=i.side==="right"?a?-M:0:a?0:-M;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${I+M}px`,e.style.transition=A,e.style.marginLeft=`${P}px`,e.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${I}px`,n.style.maxWidth=`${I}px`,n.style.minWidth=`${I}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{t.style.display="flex",t.style.flexDirection="row",t.style.alignItems="stretch",t.style.overflow="",ul(e),gl(r),ml(n),li(o,r);let M=i.reveal==="emerge";M?t.dataset.personaDockReveal="emerge":t.removeAttribute("data-persona-dock-reveal");let I=a?i.width:"0px",A=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",P=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${I}`,r.style.width=I,r.style.maxWidth=I,r.style.minWidth=I,r.style.minHeight="0",zy(r,i.maxHeight),r.style.overflow=M||P?"hidden":"visible",r.style.transition=A,M&&(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")}},Ky=(t,e)=>{let n=t.ownerDocument.createElement("div");return rg(n,e),t.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){rg(n,r)},destroy(){n.remove()}}},Gy=(t,e)=>{var L,M,I,A;let{ownerDocument:n}=t,r=t.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=t.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=t.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),c=n.createElement("aside"),u=n.createElement("div"),m=(M=(L=e==null?void 0:e.launcher)==null?void 0:L.enabled)==null||M?(A=(I=e==null?void 0:e.launcher)==null?void 0:I.autoExpand)!=null?A:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",c.appendChild(u),r.insertBefore(a,t),d.appendChild(t);let g=null,f=()=>{g==null||g.disconnect(),g=null},w=()=>{f(),gr(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{sg(a,i,d,c,u,e,m)}),g.observe(a))},v=!1,k=()=>{sg(a,i,d,c,u,e,m),w(),m&&!v&&a.dataset.personaDockMobileFullscreen!=="true"&&(v=!0,qy(a,gr(e)))},R=a.ownerDocument.defaultView,E=()=>{k()};return R==null||R.addEventListener("resize",E),gr(e).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),k(),{mode:"docked",host:u,shell:a,syncWidgetState(P){let O=P.launcherEnabled?P.open:!0;m!==O&&(m=O,k())},updateConfig(P){var O,_;e=P,((_=(O=e==null?void 0:e.launcher)==null?void 0:O.enabled)!=null?_:!0)===!1&&(m=!0),k()},destroy(){R==null||R.removeEventListener("resize",E),f(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(t,s):r.appendChild(t)),a.remove()}}},ag=(t,e)=>fn(e)?Gy(t,e):Ky(t,e);var ia={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ig=.15,lg=1.5,fl="persona-preview-shell-theme",Qy={load:()=>null,save:()=>{},clear:()=>{}},Xy=["How do I get started?","Pricing & plans","Talk to support"];function hl(t){return t.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Jy(t){return t==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function cg(t){let e=Jy(t);return`* { box-sizing: border-box; }
|
|
111
|
+
`}if(!b&&!l){let Ft="max-height: -moz-available !important; max-height: stretch !important;",Nt=u?"":"padding-top: 1.25em !important;",Kt=u?"":`z-index: ${(et=(Do=r.launcher)==null?void 0:Do.zIndex)!=null?et:vn} !important;`;me.style.cssText+=Ft+Nt+Kt}Qe()};to(),ws(n,r),ui(n,r),mi(n,r);let ct=[];ct.push(()=>{document.removeEventListener("keydown",Nr)}),ct.push(()=>{ar!==null&&clearTimeout(ar)});let rn=null,on=null;ct.push(()=>{rn==null||rn(),rn=null,on==null||on(),on=null}),Nn&&ct.push(()=>{Nn==null||Nn.disconnect(),Nn=null}),ct.push(()=>{Xn==null||Xn(),Xn=null,Xo(),_t&&(_t.remove(),_t=null),xt==null||xt.element.style.removeProperty("width"),xt==null||xt.element.style.removeProperty("maxWidth")}),ie&&ct.push(()=>{le!==null&&(cancelAnimationFrame(le),le=null),Se==null||Se.destroy(),Se=null,K==null||K.destroy(),K=null,Ae=null});let Sr=null,Ps=()=>{Sr&&(Sr(),Sr=null),r.colorScheme==="auto"&&(Sr=Cm(()=>{ws(n,r)}))};Ps(),ct.push(()=>{Sr&&(Sr(),Sr=null)}),ct.push(a);let Or=(zc=r.features)==null?void 0:zc.streamAnimation;if(Or!=null&&Or.type&&Or.type!=="none"){let l=xs(Or.type,Or.plugins);l&&(Ya(l,n),ct.push(()=>Dm(n)))}let Mo=ng(jt),Tr=null,$,Jo=l=>{var b,S;if(!$)return;let u=l!=null?l:$.getMessages(),f=((S=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:S.enabled)!==!1?$u(u):null;f?Mo.render(f,$,be,u,r.suggestionChipsConfig,{agentPushed:!0}):u.some(W=>W.role==="user")?Mo.render([],$,be,u):Mo.render(r.suggestionChips,$,be,u,r.suggestionChipsConfig)},lr=!1,Er=Mm(),_r=new Map,Mr=new Map,cr=new Map,Yo=0,ha=Oo()!==null,hn=Va(),An=0,dr=null,Sn=!1,ko=!1,pr=0,yn=null,kr=null,Zo=!1,Lo=!1,es=null,no=!0,ro=!1,st=null,x=4,V=24,j=80,Q=new Map,G={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ne=(Vc=(jc=r.voiceRecognition)==null?void 0:jc.autoResume)!=null?Vc:!1,rt=l=>{i.emit("voice:state",{active:G.active,source:l,timestamp:Date.now()})},dt=()=>{w(l=>({...l,voiceState:{active:G.active,timestamp:Date.now(),manuallyDeactivated:G.manuallyDeactivated}}))},hi=()=>{var b,S;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let l=bl(p.voiceState),u=!!l.active,f=Number((S=l.timestamp)!=null?S:0);G.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-f<gb&&setTimeout(()=>{var W,z;G.active||(G.manuallyDeactivated=!1,((z=(W=r.voiceRecognition)==null?void 0:W.provider)==null?void 0:z.type)==="runtype"?$.toggleVoice().then(()=>{G.active=$.isVoiceActive(),rt("restore"),$.isVoiceActive()&&rs()}):ba("restore"))},1e3)},oo=()=>$?Tg($.getMessages()).filter(l=>!l.__skipPersist):[];function In(l){if(!(c!=null&&c.save))return;let f={messages:l?Tg(l):$?oo():[],metadata:p,artifacts:Fn.artifacts,selectedArtifactId:Fn.selectedId};try{let b=c.save(f);b instanceof Promise&&b.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)}}let Jt=null,so=()=>me.querySelector("#persona-scroll-container")||xe,Jn=()=>{Jt!==null&&(cancelAnimationFrame(Jt),Jt=null),Sn=!1},Tn=()=>{dr!==null&&(cancelAnimationFrame(dr),dr=null),ko=!1,Jn()},Rn=()=>lr&&yi()&&(Ot()!=="anchor-top"||or()),En=()=>{let l=wt()||"Jump to latest",u=Rn();Vt.toggleAttribute("data-persona-scroll-to-bottom-streaming",u),pr>0?(Bn.textContent=String(pr),Bn.style.display="",Vt.setAttribute("aria-label",`${l} (${pr} new)`)):(Bn.textContent="",Bn.style.display="none",Vt.setAttribute("aria-label",u?`${l} (response streaming below)`:l))},Tl=()=>{pr!==0&&(pr=0,En())},yi=()=>en()?!hn.isFollowing():!vo(xe,V),_n=()=>{if(!Xt()||Y){Vt.parentNode&&Vt.remove(),Vt.style.display="none";return}Vt.parentNode!==Ee&&Ee.appendChild(Vt),Vn();let u=Rr(xe)>0&&yi();u?En():Tl(),Vt.style.display=u?"":"none"},Is=()=>{hn.pause()&&(Tn(),_n())},ao=()=>{hn.resume(),Tl(),_n()},io=(l=!1)=>{en()&&hn.isFollowing()&&(!l&&!lr||(dr!==null&&(cancelAnimationFrame(dr),dr=null),ko=!0,dr=requestAnimationFrame(()=>{dr=null,ko=!1,hn.isFollowing()&&_g(so(),l?220:140)})))},El=(l,u,f,b=()=>!0)=>{let S=l.scrollTop,W=u(),z=W-S;if(Jn(),Math.abs(z)<1){Sn=!0,l.scrollTop=W,An=l.scrollTop,Sn=!1;return}let U=performance.now();Sn=!0;let N=se=>1-Math.pow(1-se,3),ae=se=>{if(!b()){Jn();return}let te=u();te!==W&&(W=te,z=W-S);let we=se-U,Fe=Math.min(we/f,1),Oe=N(Fe),Ue=S+z*Oe;l.scrollTop=Ue,An=l.scrollTop,Fe<1?Jt=requestAnimationFrame(ae):(l.scrollTop=W,An=l.scrollTop,Jt=null,Sn=!1)};Jt=requestAnimationFrame(ae)},_g=(l,u=500)=>{let f=Rr(l)-l.scrollTop;if(Math.abs(f)<1){An=l.scrollTop;return}if(Math.abs(f)>=j){Jn(),Sn=!0,l.scrollTop=Rr(l),An=l.scrollTop,Sn=!1;return}El(l,()=>Rr(l),u,()=>hn.isFollowing())},Ml=()=>{let l=so();Sn=!0,l.scrollTop=Rr(l),An=l.scrollTop,Sn=!1,_n()},kl=l=>{let u=0,f=l;for(;f&&f!==xe;)u+=f.offsetTop,f=f.offsetParent;return u},Ll=()=>{var W;if(Wr()!=="last-user-turn")return!1;let l=(W=$==null?void 0:$.getMessages())!=null?W:[];if(l.length<2)return!1;let u=[...l].reverse().find(z=>z.role==="user");if(!u)return!1;let f=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(u.id):u.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=xe.querySelector(`[data-message-id="${f}"]`);if(!b)return!1;let S=Math.min(Math.max(0,kl(b)-br()),Rr(xe));return Sn=!0,xe.scrollTop=S,An=xe.scrollTop,Sn=!1,Ot()==="follow"&&!vo(xe,V)&&hn.pause(),_n(),!0},Pl=l=>{Ln.style.height=`${Math.max(0,Math.round(l))}px`,yn&&(yn.spacerHeight=Math.max(0,l))},Rs=()=>{kr!==null&&(cancelAnimationFrame(kr),kr=null),Jn(),yn=null,Ln.style.height="0px"},$g=l=>{kr!==null&&cancelAnimationFrame(kr),kr=requestAnimationFrame(()=>{var N;kr=null;let u=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),f=xe.querySelector(`[data-message-id="${u}"]`);if(!f)return;let b=kl(f),S=(N=yn==null?void 0:yn.spacerHeight)!=null?N:0,W=xe.scrollHeight-S,{targetScrollTop:z,spacerHeight:U}=Rm({anchorOffsetTop:b,topOffset:br(),viewportHeight:xe.clientHeight,contentHeight:W});yn={initialSpacerHeight:U,contentHeightAtAnchor:W,spacerHeight:U},Pl(U),El(xe,()=>z,220)})},Ug=()=>{if(en()){if(!hn.isFollowing()||vo(xe,1))return;io(!lr);return}if(yn&&yn.initialSpacerHeight>0){let l=xe.scrollHeight-yn.spacerHeight,u=Wm({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:l});u!==yn.spacerHeight&&Pl(u)}_n()},qg=l=>{let u=Ot();u==="follow"?(ao(),io(!0)):u==="anchor-top"&&(no=!1,ro=!0,$g(l))},zg=()=>{if(Ot()==="anchor-top"){if(ro){no=!1;return}no=!0,Rs(),ao(),io(!0)}},jg=l=>{let u=new Map;l.forEach(f=>{let b=Q.get(f.id);u.set(f.id,{streaming:f.streaming,role:f.role}),!b&&f.role==="assistant"&&(i.emit("assistant:message",f),!Lo&&(Ot()!=="anchor-top"||or())&&yi()&&(pr+=1,En(),_n(),Gr(pr===1?"1 new message below.":`${pr} new messages below.`))),f.role==="assistant"&&(b!=null&&b.streaming)&&f.streaming===!1&&i.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(b?f.approval.status!=="pending"&&i.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):i.emit("approval:requested",{approval:f.approval,message:f}))}),Q.clear(),u.forEach((f,b)=>{Q.set(b,f)})},Vg=(l,u,f)=>{var at,Be,Re,je,Qe,vt;let b=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})(),z=(H,De)=>De==null?!1:typeof De=="string"?(H.textContent=De,!0):(H.appendChild(De),!0),U=new Set,N=new Set,ae=o.some(H=>H.renderAskUserQuestion),se=[],te=[],we=r.enableComponentStreaming!==!1,Fe=r.approval!==!1,Oe=[];if(u.forEach(H=>{var un,$n,Ke,Rt,Un,Io,Ro,Wo,Ho,ss,as,Qt,Bo,po,uo,Ur,Do;U.add(H.id);let De=ae&&_o(H),We=Fe&&H.variant==="approval"&&!!H.approval,Je=!De&&H.role==="assistant"&&!H.variant&&we&&xg(H);if(!We&&cr.has(H.id)){let et=l.querySelector(`#wrapper-${H.id}`);et==null||et.removeAttribute("data-preserve-runtime"),cr.delete(H.id)}if(!Je&&Mr.has(H.id)){let et=l.querySelector(`#wrapper-${H.id}`);et==null||et.removeAttribute("data-preserve-runtime"),Mr.delete(H.id)}let It=_o(H)?`:${(un=H.agentMetadata)!=null&&un.askUserQuestionAnswered?"a":"u"}:${($n=H.agentMetadata)!=null&&$n.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",_e=Em(H,Yo)+It,Gt=De||We||Je?null:km(Er,H.id,_e);if(Gt){b.appendChild(Gt.cloneNode(!0)),_o(H)&&((Ke=H.toolCall)!=null&&Ke.id)&&((Rt=H.agentMetadata)==null?void 0:Rt.awaitingLocalTool)===!0&&!((Un=H.agentMetadata)!=null&&Un.askUserQuestionAnswered)&&(N.add(H.toolCall.id),La(H,r,Ve.composerOverlay));return}let Ct=null,an=o.find(et=>!!(H.variant==="reasoning"&&et.renderReasoning||H.variant==="tool"&&et.renderToolCall||!H.variant&&et.renderMessage)),Wn=(Io=r.layout)==null?void 0:Io.messages;if(_o(H)&&((Ro=H.agentMetadata)==null?void 0:Ro.askUserQuestionAnswered)===!0){_r.delete(H.id);let et=l.querySelector(`#wrapper-${H.id}`);et==null||et.removeAttribute("data-preserve-runtime");return}if(Ni(H)&&((Ho=(Wo=r.features)==null?void 0:Wo.suggestReplies)==null?void 0:Ho.enabled)!==!1)return;if(_o(H)&&((as=(ss=r.features)==null?void 0:ss.askUserQuestion)==null?void 0:as.enabled)!==!1){let et=o.find(Ft=>typeof Ft.renderAskUserQuestion=="function");if(et&&Tt.current){let Ft=_r.get(H.id),Nt=Ft!==_e,Kt=null;if(Nt){let{payload:qt,complete:mn}=ps(H),qn=H.id,Pr=()=>{var dn;return(dn=Tt.current)==null?void 0:dn.getMessages().find(pn=>pn.id===qn)};Kt=et.renderAskUserQuestion({message:H,payload:qt,complete:mn,resolve:dn=>{var er;let pn=Pr();pn&&((er=Tt.current)==null||er.resolveAskUserQuestion(pn,dn))},dismiss:()=>{var pn,er,mo;let dn=Pr();(pn=dn==null?void 0:dn.agentMetadata)!=null&&pn.awaitingLocalTool&&((er=Tt.current)==null||er.markAskUserQuestionResolved(dn),(mo=Tt.current)==null||mo.resolveAskUserQuestion(dn,"(dismissed)"))},config:r})}let Ut=Ft!=null;if(Nt&&Kt===null&&!Ut){((Qt=H.agentMetadata)==null?void 0:Qt.awaitingLocalTool)===!0&&!((Bo=H.agentMetadata)!=null&&Bo.askUserQuestionAnswered)&&(N.add(H.toolCall.id),La(H,r,Ve.composerOverlay));return}let gt=document.createElement("div");gt.className="persona-flex",gt.id=`wrapper-${H.id}`,gt.setAttribute("data-wrapper-id",H.id),gt.setAttribute("data-ask-plugin-stub","true"),gt.setAttribute("data-preserve-runtime","true"),b.appendChild(gt),se.push({messageId:H.id,fingerprint:_e,bubble:Kt});return}else{((po=H.agentMetadata)==null?void 0:po.awaitingLocalTool)===!0&&!((uo=H.agentMetadata)!=null&&uo.askUserQuestionAnswered)&&(N.add(H.toolCall.id),La(H,r,Ve.composerOverlay));return}}else if(We){let et=(Ur=o.find(Ut=>typeof Ut.renderApproval=="function"))!=null?Ur:s,Nt=cr.get(H.id)!==_e,Kt=null;if(Nt&&(et!=null&&et.renderApproval)){let Ut=H.id,gt=(qt,mn)=>{var Pr,dn,pn;let qn=(Pr=Tt.current)==null?void 0:Pr.getMessages().find(er=>er.id===Ut);qn!=null&&qn.approval&&(qn.approval.toolType==="webmcp"?(dn=Tt.current)==null||dn.resolveWebMcpApproval(qn.id,qt):(pn=Tt.current)==null||pn.resolveApproval(qn.approval,qt,mn))};Kt=et.renderApproval({message:H,defaultRenderer:()=>di(H,r),config:r,approve:qt=>gt("approved",qt),deny:qt=>gt("denied",qt)})}if(Nt&&Kt===null){let Ut=l.querySelector(`#wrapper-${H.id}`);Ut==null||Ut.removeAttribute("data-preserve-runtime"),cr.delete(H.id),Ct=di(H,r)}else{let Ut=document.createElement("div");Ut.className="persona-flex",Ut.id=`wrapper-${H.id}`,Ut.setAttribute("data-wrapper-id",H.id),Ut.setAttribute("data-approval-plugin-stub","true"),Ut.setAttribute("data-preserve-runtime","true"),b.appendChild(Ut),Oe.push({messageId:H.id,fingerprint:_e,bubble:Kt});return}}else if(an)if(H.variant==="reasoning"&&H.reasoning&&an.renderReasoning){if(!Pe)return;Ct=an.renderReasoning({message:H,defaultRenderer:()=>ol(H,r),config:r})}else if(H.variant==="tool"&&H.toolCall&&an.renderToolCall){if(!Ie)return;Ct=an.renderToolCall({message:H,defaultRenderer:()=>al(H,r),config:r})}else an.renderMessage&&(Ct=an.renderMessage({message:H,defaultRenderer:()=>{let et=rl(H,f,Wn,r.messageActions,Ye,{loadingIndicatorRenderer:W,widgetConfig:r});return H.role!=="user"&&pl(et,H,r,$),et},config:r}));if(!Ct&&Je){let et=Cg(H);if(et){let Ft=Mr.get(H.id),Nt=Ft!==_e,Kt=r.wrapComponentDirectiveInBubble!==!1,Ut=null;if(Nt){let gt=vg(et,{config:r,message:H,transform:f});if(gt)if(Kt){let qt=document.createElement("div");if(qt.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(" "),qt.id=`bubble-${H.id}`,qt.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let mn=document.createElement("div");mn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",mn.innerHTML=f({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),qt.appendChild(mn)}qt.appendChild(gt),Ut=qt}else{let qt=document.createElement("div");if(qt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",qt.id=`bubble-${H.id}`,qt.setAttribute("data-message-id",H.id),qt.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let mn=document.createElement("div");mn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",mn.innerHTML=f({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),qt.appendChild(mn)}qt.appendChild(gt),Ut=qt}}if(Ut||Ft!=null){let gt=document.createElement("div");gt.className="persona-flex",gt.id=`wrapper-${H.id}`,gt.setAttribute("data-wrapper-id",H.id),gt.setAttribute("data-component-directive-stub","true"),gt.setAttribute("data-preserve-runtime","true"),Kt||gt.classList.add("persona-w-full"),b.appendChild(gt),te.push({messageId:H.id,fingerprint:_e,bubble:Ut});return}}}if(!Ct)if(H.variant==="reasoning"&&H.reasoning){if(!Pe)return;Ct=ol(H,r)}else if(H.variant==="tool"&&H.toolCall){if(!Ie)return;Ct=al(H,r)}else if(H.variant==="approval"&&H.approval){if(r.approval===!1)return;Ct=di(H,r)}else{let et=(Do=r.layout)==null?void 0:Do.messages;et!=null&&et.renderUserMessage&&H.role==="user"?Ct=et.renderUserMessage({message:H,config:r,streaming:!!H.streaming}):et!=null&&et.renderAssistantMessage&&H.role==="assistant"?Ct=et.renderAssistantMessage({message:H,config:r,streaming:!!H.streaming}):Ct=rl(H,f,et,r.messageActions,Ye,{loadingIndicatorRenderer:W,widgetConfig:r}),H.role!=="user"&&Ct&&pl(Ct,H,r,$)}let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-${H.id}`,Dt.setAttribute("data-wrapper-id",H.id),H.role==="user"&&Dt.classList.add("persona-justify-end"),(Ct==null?void 0:Ct.getAttribute("data-persona-component-directive"))==="true"&&Dt.classList.add("persona-w-full"),Dt.appendChild(Ct),Lm(Er,H.id,_e,Dt),b.appendChild(Dt)}),Ve.composerOverlay&&Ve.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let We=De.getAttribute("data-persona-ask-sheet-for");We&&!N.has(We)&&ms(Ve.composerOverlay,We)}),(Be=(at=r.features)==null?void 0:at.toolCallDisplay)!=null&&Be.grouped){let H=[],De=[];u.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&Ie){De.push(We);return}De.length>1&&H.push(De),De=[]}),De.length>1&&H.push(De),H.forEach((We,Je)=>{var un,$n;let It=We.map(Ke=>Array.from(b.children).find(Rt=>Rt instanceof HTMLElement&&Rt.getAttribute("data-wrapper-id")===Ke.id)).filter(Ke=>!!Ke);if(It.length<2)return;let _e=document.createElement("div");_e.className="persona-flex",_e.id=`wrapper-tool-group-${Je}-${We[0].id}`,_e.setAttribute("data-wrapper-id",`tool-group-${Je}-${We[0].id}`);let Gt=document.createElement("div");Gt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Gt.setAttribute("data-persona-tool-group","true");let Ct=document.createElement("div");Ct.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let an=`Called ${We.length} tools`,Wn=($n=(un=r.toolCall)==null?void 0:un.renderGroupedSummary)==null?void 0:$n.call(un,{messages:We,toolCalls:We.map(Ke=>Ke.toolCall).filter(Ke=>!!Ke),defaultSummary:an,config:r});z(Ct,Wn)||(Ct.textContent=an);let Dt=document.createElement("div");Dt.className="persona-tool-group-stack persona-flex persona-flex-col",Gt.append(Ct,Dt),_e.appendChild(Gt),It[0].before(_e),It.forEach((Ke,Rt)=>{let Un=document.createElement("div");Un.className="persona-tool-group-item persona-relative",Un.setAttribute("data-persona-tool-group-item","true"),Rt<It.length-1&&Un.setAttribute("data-persona-tool-group-connector","true"),Un.appendChild(Ke),Dt.appendChild(Un)})})}Pm(Er,U);let Ue=u.some(H=>H.role==="assistant"&&H.streaming),ze=u[u.length-1],mt=(ze==null?void 0:ze.role)==="assistant"&&!ze.streaming&&ze.variant!=="approval";if(lr&&u.some(H=>H.role==="user")&&!Ue&&!mt){let H={config:r,streaming:!0,location:"standalone",defaultRenderer:da},De=o.find(Je=>Je.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=da()),We){let Je=document.createElement("div"),It=((je=r.loadingIndicator)==null?void 0:je.showBubble)!==!1;Je.className=It?["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(" "),Je.setAttribute("data-typing-indicator","true"),Je.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Je.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(Je),b.appendChild(_e)}}if(!lr&&u.length>0){let H=u[u.length-1],De={config:r,lastMessage:H,messageCount:u.length},We=o.find(It=>It.renderIdleIndicator),Je=null;if(We!=null&&We.renderIdleIndicator&&(Je=We.renderIdleIndicator(De)),Je===null&&((Qe=r.loadingIndicator)!=null&&Qe.renderIdle)&&(Je=r.loadingIndicator.renderIdle(De)),Je){let It=document.createElement("div"),_e=((vt=r.loadingIndicator)==null?void 0:vt.showBubble)!==!1;It.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(" "),It.setAttribute("data-idle-indicator","true"),It.appendChild(Je);let Gt=document.createElement("div");Gt.className="persona-flex",Gt.id="wrapper-idle-indicator",Gt.setAttribute("data-wrapper-id","idle-indicator"),Gt.appendChild(It),b.appendChild(Gt)}}if(za(l,b),se.length>0)for(let{messageId:H,fingerprint:De,bubble:We}of se){let Je=l.querySelector(`#wrapper-${H}`);Je&&We!==null&&(Je.replaceChildren(We),Je.setAttribute("data-bubble-fp",De),_r.set(H,De))}if(_r.size>0)for(let H of _r.keys())U.has(H)||_r.delete(H);if(te.length>0)for(let{messageId:H,fingerprint:De,bubble:We}of te){let Je=l.querySelector(`#wrapper-${H}`);Je&&We!==null&&(Je.replaceChildren(We),Je.setAttribute("data-bubble-fp",De),Mr.set(H,De))}if(Mr.size>0)for(let H of Mr.keys())U.has(H)||Mr.delete(H);if(Oe.length>0)for(let{messageId:H,fingerprint:De,bubble:We}of Oe){let Je=l.querySelector(`#wrapper-${H}`);Je&&We!==null&&(Je.replaceChildren(We),Je.setAttribute("data-bubble-fp",De),cr.set(H,De))}if(cr.size>0)for(let H of cr.keys())U.has(H)||cr.delete(H)},Ws=(l,u,f)=>{Vg(l,u,f),Zr()},Hs=null,Kg=()=>{var f;if(Hs)return;let l=b=>{let S=b.composedPath();S.includes(me)||lt&&S.includes(lt)||$t(!1,"user")};Hs=l,((f=n.ownerDocument)!=null?f:document).addEventListener("pointerdown",l,!0)},Il=()=>{var u;if(!Hs)return;((u=n.ownerDocument)!=null?u:document).removeEventListener("pointerdown",Hs,!0),Hs=null};ct.push(()=>Il());let Bs=null,Gg=()=>{var f;if(Bs)return;let l=b=>{b.key==="Escape"&&(b.isComposing||$t(!1,"user"))};Bs=l,((f=n.ownerDocument)!=null?f:document).addEventListener("keydown",l,!0)},Rl=()=>{var u;if(!Bs)return;((u=n.ownerDocument)!=null?u:document).removeEventListener("keydown",Bs,!0),Bs=null};ct.push(()=>Rl());let Ds=!1,Wl=new Set,Qg=()=>{var u,f,b,S;let l=(b=(f=(u=r.launcher)==null?void 0:u.composerBar)==null?void 0:f.peek)==null?void 0:b.streamAnimation;return l||((S=r.features)==null?void 0:S.streamAnimation)},ts=()=>{var mt,at,Be,Re;if(!R())return;let l=Ve.peekBanner,u=Ve.peekTextNode;if(!l||!u)return;if(F){l.classList.remove("persona-pill-peek--visible");return}let f=(mt=$==null?void 0:$.getMessages())!=null?mt:[],b;for(let je=f.length-1;je>=0;je--){let Qe=f[je];if(Qe.role==="assistant"&&Qe.content){b=Qe;break}}if(!b){l.classList.remove("persona-pill-peek--visible");return}let S=b.content,W=!!b.streaming,z=Qg(),U=Qa(z),N=U.type!=="none"?xs(U.type,z==null?void 0:z.plugins):null,ae=((at=N==null?void 0:N.isAnimating)==null?void 0:at.call(N,b))===!0,se=N!==null&&(W||ae);se&&N&&!Wl.has(N.name)&&(Ya(N,n),Wl.add(N.name));let te=se&&(N!=null&&N.containerClass)?N.containerClass:null,we=(Be=u.dataset.personaPeekStreamClass)!=null?Be:null;we&&we!==te&&(u.classList.remove(we),delete u.dataset.personaPeekStreamClass),te&&we!==te&&(u.classList.add(te),u.dataset.personaPeekStreamClass=te),se?(u.style.setProperty("--persona-stream-step",`${U.speed}ms`),u.style.setProperty("--persona-stream-duration",`${U.duration}ms`)):(u.style.removeProperty("--persona-stream-step"),u.style.removeProperty("--persona-stream-duration"));let Fe=se?Xa(S,U.buffer,N,b,W):S;if(se&&U.placeholder==="skeleton"&&W&&(!Fe||!Fe.trim())){let je=document.createElement("div"),Qe=sa();Qe.classList.add("persona-pill-peek__skeleton"),je.appendChild(Qe),za(u,je)}else{let je=Math.max(0,Fe.length-100),Qe=Fe.length>100?Fe.slice(-100):Fe,vt=go(Qe);if(!se||!N){let H=Fe.length>100?`\u2026${Qe}`:Qe;u.textContent!==H&&(u.textContent=H)}else{let H=vt;(N.wrap==="char"||N.wrap==="word")&&(H=oa(vt,N.wrap,`peek-${b.id}`,{skipTags:N.skipTags,startIndex:je}));let De=document.createElement("div");if(De.innerHTML=H,N.useCaret&&Qe.length>0){let We=Ja(),Je=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),It=Je[Je.length-1];It!=null&&It.parentNode?It.parentNode.insertBefore(We,It.nextSibling):De.appendChild(We)}za(u,De),(Re=N.onAfterRender)==null||Re.call(N,{container:u,bubble:l,messageId:b.id,message:b,speed:U.speed,duration:U.duration})}}let ze=lr||Ds;l.classList.toggle("persona-pill-peek--visible",ze)};if(R()){let l=Ve.peekBanner;if(l){let b=S=>{S.preventDefault(),S.stopPropagation(),$t(!0,"user")};l.addEventListener("pointerdown",b),ct.push(()=>{l.removeEventListener("pointerdown",b)})}let u=()=>{Ds||(Ds=!0,ts())},f=()=>{Ds&&(Ds=!1,ts())};X.addEventListener("pointerenter",u),X.addEventListener("pointerleave",f),ct.push(()=>{X.removeEventListener("pointerenter",u),X.removeEventListener("pointerleave",f)}),lt&&(lt.addEventListener("pointerenter",u),lt.addEventListener("pointerleave",f),ct.push(()=>{lt.removeEventListener("pointerenter",u),lt.removeEventListener("pointerleave",f)}))}let Xg=l=>{var we,Fe,Oe,Ue,ze,mt,at,Be;let u=(Fe=(we=r.launcher)==null?void 0:we.composerBar)!=null?Fe:{},f=(Oe=u.expandedSize)!=null?Oe:"anchored",b=(Ue=u.bottomOffset)!=null?Ue:"16px",S=u.collapsedMaxWidth,W=(ze=u.expandedMaxWidth)!=null?ze:"880px",z=(mt=u.expandedTopOffset)!=null?mt:"5vh",U=(at=u.modalMaxWidth)!=null?at:"880px",N=(Be=u.modalMaxHeight)!=null?Be:"min(90vh, 800px)",ae="calc(100vw - 32px)",se="var(--persona-pill-area-height, 80px)",te=me.style;if(te.left="",te.right="",te.top="",te.bottom="",te.transform="",te.width="",te.maxWidth="",te.height="",te.maxHeight="",lt){let Re=lt.style;Re.bottom=b,Re.width=S!=null?S:""}if(l&&f!=="fullscreen"){if(f==="modal"){te.top="50%",te.left="50%",te.transform="translate(-50%, -50%)",te.bottom="auto",te.right="auto",te.width=U,te.maxWidth=ae,te.maxHeight=N,te.height=N;return}te.left="50%",te.transform="translateX(-50%)",te.bottom=`calc(${b} + ${se})`,te.top=z,te.width=W,te.maxWidth=ae}},Ns=()=>{var N,ae,se,te,we,Fe,Oe,Ue;if(!O())return;if(R()){let mt=(se=((ae=(N=r.launcher)==null?void 0:N.composerBar)!=null?ae:{}).expandedSize)!=null?se:"anchored",at=F?"expanded":"collapsed";me.dataset.state=at,me.dataset.expandedSize=mt,lt&&(lt.dataset.state=at,lt.dataset.expandedSize=mt),me.style.removeProperty("display"),me.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Xg(F),Ee.style.display=F?"flex":"none",to(),F?(Kg(),Gg()):(Il(),Rl()),ts();return}let l=gn(r),u=(te=n.ownerDocument.defaultView)!=null?te:window,f=(Fe=(we=r.launcher)==null?void 0:we.mobileBreakpoint)!=null?Fe:640,b=(Ue=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?Ue:!0,S=u.innerWidth<=f,W=b&&S&&I,z=gr(r).reveal;F?(me.style.removeProperty("display"),me.style.display=l?"flex":"",me.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&&(z==="overlay"||z==="push")&&!W?(me.style.removeProperty("display"),me.style.display="flex",me.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(me.style.setProperty("display","none","important"),me.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(me.style.display="",me.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,u="user")=>{var W,z;if(!O()||F===l)return;let f=F;F=l,Ns();let b=(()=>{var Oe,Ue,ze,mt,at,Be,Re,je,Qe,vt;let U=(Ue=(Oe=r.launcher)==null?void 0:Oe.sidebarMode)!=null?Ue:!1,N=(ze=n.ownerDocument.defaultView)!=null?ze:window,ae=(at=(mt=r.launcher)==null?void 0:mt.mobileFullscreen)!=null?at:!0,se=(Re=(Be=r.launcher)==null?void 0:Be.mobileBreakpoint)!=null?Re:640,te=N.innerWidth<=se,we=gn(r)&&ae&&te,Fe=R()&&((vt=(Qe=(je=r.launcher)==null?void 0:je.composerBar)==null?void 0:Qe.expandedSize)!=null?vt:"fullscreen")==="fullscreen";return U||ae&&te&&I||we||Fe})();if(F&&b){if(!rn){let U=n.getRootNode(),N=U instanceof ShadowRoot?U.host:n.closest(".persona-host");N&&(rn=Xi(N,(z=(W=r.launcher)==null?void 0:W.zIndex)!=null?z:vn))}on||(on=Ji(n.ownerDocument))}else F||(rn==null||rn(),rn=null,on==null||on(),on=null);F&&(Fs(),Ll()||(Ot()==="follow"?io(!0):Ml()));let S={open:F,source:u,timestamp:Date.now()};F&&!f?i.emit("widget:opened",S):!F&&f&&i.emit("widget:closed",S),i.emit("widget:state",{open:F,launcherEnabled:I,voiceActive:G.active,streaming:$.isStreaming()})},bi=l=>{fe(l?"stop":"send"),D&&(D.disabled=l),Mo.buttons.forEach(u=>{u.disabled=l}),He.dataset.personaComposerStreaming=l?"true":"false",He.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=l)})},vi=()=>{G.active||be&&be.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>vi(),200)});let Hl=()=>{var f,b,S,W,z,U,N,ae,se,te,we;hr.textContent=(b=(f=r.copy)==null?void 0:f.welcomeTitle)!=null?b:"Hello \u{1F44B}",yr.textContent=(W=(S=r.copy)==null?void 0:S.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",be.placeholder=(U=(z=r.copy)==null?void 0:z.inputPlaceholder)!=null?U:"How can I help...";let l=xe.querySelector("[data-persona-intro-card]");if(l){let Fe=((N=r.copy)==null?void 0:N.showWelcomeCard)!==!1;l.style.display=Fe?"":"none",Fe?(xe.classList.remove("persona-gap-3"),xe.classList.add("persona-gap-6")):(xe.classList.remove("persona-gap-6"),xe.classList.add("persona-gap-3"))}!((se=(ae=r.sendButton)==null?void 0:ae.useIcon)!=null&&se)&&!($!=null&&$.isStreaming())&&(ue.textContent=(we=(te=r.copy)==null?void 0:te.sendButtonLabel)!=null?we:"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=>{w(u=>({...u,sessionId:l}))}});let Po=null,Jg=()=>{Po==null&&(Po=setInterval(()=>{let l=Ze.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Po),Po=null;return}let u=Date.now();l.forEach(f=>{let b=Number(f.getAttribute("data-tool-elapsed"));b&&(f.textContent=Ia(u-b))})},100))};$=new $a(r,{onMessagesChanged(l){var S,W;Ws(Ze,l,ee),Jg(),Jo(l),io(!lr),jg(l);let u=[...l].reverse().find(z=>z.role==="user"),f=[...l].reverse().find(z=>z.role==="assistant");l.length===0&&(Rs(),no=!0,ro=!1),!Zo||Lo?(Zo=!0,es=(S=u==null?void 0:u.id)!=null?S:null,st=(W=f==null?void 0:f.id)!=null?W:null):u&&u.id!==es?(es=u.id,qg(u.id)):f&&f.id!==st&&zg(),f&&(st=f.id);let b=G.lastUserMessageId;u&&u.id!==b&&(G.lastUserMessageId=u.id,i.emit("user:message",u)),G.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),In(l),ts()},onStatusChanged(l){var b;let u=(b=r.statusIndicator)!=null?b:{};ht(fn,(S=>{var W,z,U,N,ae,se;return S==="idle"?(W=u.idleText)!=null?W:nn.idle:S==="connecting"?(z=u.connectingText)!=null?z:nn.connecting:S==="connected"?(U=u.connectedText)!=null?U:nn.connected:S==="error"?(N=u.errorText)!=null?N:nn.error:S==="paused"?(ae=u.pausedText)!=null?ae:nn.paused:S==="resuming"?(se=u.resumingText)!=null?se:nn.resuming:nn[S]})(l),u,l)},onStreamingChanged(l){lr=l,bi(l),$&&Ws(Ze,$.getMessages(),ee),l||io(!0),_n(),Gr(l?"Responding\u2026":"Response complete."),ts()},onVoiceStatusChanged(l){var u,f;if(i.emit("voice:status",{status:l,timestamp:Date.now()}),((f=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:f.type)==="runtype")switch(l){case"listening":$r(),rs();break;case"processing":$r(),nf();break;case"speaking":$r(),rf();break;default:l==="idle"&&$.isBargeInActive()?($r(),rs(),D==null||D.setAttribute("aria-label","End voice session")):(G.active=!1,$r(),rt("system"),dt());break}},onArtifactsState(l){Fn=l,Ar(),In()},onReconnect(l){var b;let{executionId:u,lastEventId:f}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:u,after:f}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:u,after:f,attempt:(b=l.attempt)!=null?b:1}):i.emit("stream:resumed",{executionId:u,after:f})}}),Tt.current=$,ct.push(()=>$.cancel());let wi=null;if($.onReadAloudChange((l,u)=>{var S;Jr=l,Yr=u,Zr();let f=l!=null?l:wi;l&&(wi=l);let b=f&&(S=$.getMessages().find(W=>W.id===f))!=null?S:null;i.emit("message:read-aloud",{messageId:f,message:b,state:u,timestamp:Date.now()}),u==="idle"&&(wi=null)}),Zo=!0,((Gc=(Kc=r.voiceRecognition)==null?void 0:Kc.provider)==null?void 0:Gc.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)}),(K||r.onSSEEvent)&&$.setSSEEventCallback((l,u)=>{var f;(f=r.onSSEEvent)==null||f.call(r,l,u),J==null||J.processEvent(l,u),K==null||K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})});let Bl=()=>{r.resume&&typeof r.reconnectStream=="function"&&$.resumeFromHandle(r.resume)};g?g.then(l=>{var u,f,b;if(l){if(l.metadata&&(p=bl(l.metadata),T.syncFromMetadata()),(u=l.messages)!=null&&u.length){Lo=!0;try{$.hydrateMessages(l.messages)}finally{Lo=!1}}(f=l.artifacts)!=null&&f.length&&$.hydrateArtifacts(l.artifacts,(b=l.selectedArtifactId)!=null?b:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>Bl()):Bl();let Dl=()=>{var u,f,b;!R()||F||!((b=(f=(u=r.launcher)==null?void 0:u.composerBar)==null?void 0:f.expandOnSubmit)==null||b)||$t(!0,"auto")},Nl=l=>{var S;if(l.preventDefault(),$.isStreaming()){$.cancel(),J==null||J.reset(),Se==null||Se.update();return}let u=be.value.trim(),f=(S=St==null?void 0:St.hasAttachments())!=null?S:!1;if(!u&&!f)return;Dl();let b;f&&(b=[],b.push(...St.getContentParts()),u&&b.push($i(u))),be.value="",be.style.height="auto",ya(),$.sendMessage(u,{contentParts:b}),f&&St.clearAttachments()},Yg=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},xi={...ja},Ci=!1,ya=()=>{xi={...ja}},Zg=()=>$.getMessages().filter(l=>l.role==="user").map(l=>{var u;return(u=l.content)!=null?u:""}).filter(l=>l.length>0),ef=l=>{if(!be)return;Ci=!0,be.value=l,be.dispatchEvent(new Event("input",{bubbles:!0})),Ci=!1;let u=be.value.length;be.setSelectionRange(u,u)},Fl=()=>{Ci||ya()},Ol=l=>{if(be){if(Yg()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let u=be.selectionStart===0&&be.selectionEnd===0,f=Tm({direction:l.key==="ArrowUp"?"up":"down",history:Zg(),currentValue:be.value,atStart:u,state:xi});if(xi=f.state,f.handled){l.preventDefault(),f.value!==void 0&&ef(f.value);return}}if(l.key==="Enter"&&!l.shiftKey){if($.isStreaming()){l.preventDefault();return}ya(),l.preventDefault(),ue.click()}}},_l=l=>{l.key!=="Escape"||l.isComposing||$.isStreaming()&&l.composedPath().includes(Ee)&&($.cancel(),J==null||J.reset(),Se==null||Se.update(),ya(),l.preventDefault(),l.stopImmediatePropagation())},$l=async l=>{var f;if(((f=r.attachments)==null?void 0:f.enabled)!==!0||!St)return;let u=hb(l.clipboardData);u.length!==0&&(l.preventDefault(),await St.handleFiles(u))},Yn=null,Lr=!1,ns=null,ut=null,Ul=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,ba=(l="user")=>{var W,z,U,N,ae,se,te;if(Lr||$.isStreaming())return;let u=Ul();if(!u)return;Yn=new u;let b=(z=((W=r.voiceRecognition)!=null?W:{}).pauseDuration)!=null?z:2e3;Yn.continuous=!0,Yn.interimResults=!0,Yn.lang="en-US";let S=be.value;Yn.onresult=we=>{let Fe="",Oe="";for(let ze=0;ze<we.results.length;ze++){let mt=we.results[ze],at=mt[0].transcript;mt.isFinal?Fe+=at+" ":Oe=at}let Ue=S+Fe+Oe;be.value=Ue,ns&&clearTimeout(ns),(Fe||Oe)&&(ns=window.setTimeout(()=>{let ze=be.value.trim();ze&&Yn&&Lr&&(lo(),be.value="",be.style.height="auto",$.sendMessage(ze,{viaVoice:!0}))},b))},Yn.onerror=we=>{we.error!=="no-speech"&&lo()},Yn.onend=()=>{if(Lr){let we=be.value.trim();we&&we!==S.trim()&&(be.value="",be.style.height="auto",$.sendMessage(we,{viaVoice:!0})),lo()}};try{if(Yn.start(),Lr=!0,G.active=!0,l!=="system"&&(G.manuallyDeactivated=!1),rt(l),dt(),D){let we=(U=r.voiceRecognition)!=null?U:{};ut={backgroundColor:D.style.backgroundColor,color:D.style.color,borderColor:D.style.borderColor,iconName:(N=we.iconName)!=null?N:"mic",iconSize:parseFloat((te=(se=we.iconSize)!=null?se:(ae=r.sendButton)==null?void 0:ae.size)!=null?te:"40")||24};let Fe=we.recordingBackgroundColor,Oe=we.recordingIconColor,Ue=we.recordingBorderColor;if(D.classList.add("persona-voice-recording"),D.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",D.style.color=Oe!=null?Oe:"var(--persona-voice-recording-indicator, #ffffff)",Oe){let ze=D.querySelector("svg");ze&&ze.setAttribute("stroke",Oe)}Ue&&(D.style.borderColor=Ue),D.setAttribute("aria-label","Stop voice recognition")}}catch{lo("system")}},lo=(l="user")=>{if(Lr){if(Lr=!1,ns&&(clearTimeout(ns),ns=null),Yn){try{Yn.stop()}catch{}Yn=null}if(G.active=!1,rt(l),dt(),D){if(D.classList.remove("persona-voice-recording"),ut){D.style.backgroundColor=ut.backgroundColor,D.style.color=ut.color,D.style.borderColor=ut.borderColor;let u=D.querySelector("svg");u&&u.setAttribute("stroke",ut.color||"currentColor"),ut=null}D.setAttribute("aria-label","Start voice recognition")}}},tf=(l,u)=>{var at,Be,Re,je,Qe,vt,H,De,We;let f=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((at=l==null?void 0:l.provider)==null?void 0:at.type)==="runtype",S=((Be=l==null?void 0:l.provider)==null?void 0:Be.type)==="custom";if(!(f||b||S))return null;let z=v("div","persona-send-button-wrapper"),U=v("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");U.type="button",U.setAttribute("aria-label","Start voice recognition");let N=(Re=l==null?void 0:l.iconName)!=null?Re:"mic",ae=(je=u==null?void 0:u.size)!=null?je:"40px",se=(Qe=l==null?void 0:l.iconSize)!=null?Qe:ae,te=parseFloat(se)||24,we=(vt=l==null?void 0:l.backgroundColor)!=null?vt:u==null?void 0:u.backgroundColor,Fe=(H=l==null?void 0:l.iconColor)!=null?H:u==null?void 0:u.textColor;U.style.width=se,U.style.height=se,U.style.minWidth=se,U.style.minHeight=se,U.style.fontSize="18px",U.style.lineHeight="1",Fe?U.style.color=Fe:U.style.color="var(--persona-text, #111827)";let Ue=ye(N,te,Fe||"currentColor",1.5);Ue?U.appendChild(Ue):U.textContent="\u{1F3A4}",we?U.style.backgroundColor=we:U.style.backgroundColor="",l!=null&&l.borderWidth&&(U.style.borderWidth=l.borderWidth,U.style.borderStyle="solid"),l!=null&&l.borderColor&&(U.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(U.style.paddingLeft=l.paddingX,U.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(U.style.paddingTop=l.paddingY,U.style.paddingBottom=l.paddingY),z.appendChild(U);let ze=(De=l==null?void 0:l.tooltipText)!=null?De:"Start voice recognition";if(((We=l==null?void 0:l.showTooltip)!=null?We:!1)&&ze){let Je=v("div","persona-send-button-tooltip");Je.textContent=ze,z.appendChild(Je)}return{micButton:U,micButtonWrapper:z}},Ai=()=>{var u,f,b,S,W;if(!D||ut)return;let l=(u=r.voiceRecognition)!=null?u:{};ut={backgroundColor:D.style.backgroundColor,color:D.style.color,borderColor:D.style.borderColor,iconName:(f=l.iconName)!=null?f:"mic",iconSize:parseFloat((W=(S=l.iconSize)!=null?S:(b=r.sendButton)==null?void 0:b.size)!=null?W:"40")||24}},Si=(l,u)=>{var W,z,U,N,ae;if(!D)return;let f=D.querySelector("svg");f&&f.remove();let b=(ae=ut==null?void 0:ut.iconSize)!=null?ae:parseFloat((N=(U=(W=r.voiceRecognition)==null?void 0:W.iconSize)!=null?U:(z=r.sendButton)==null?void 0:z.size)!=null?N:"40")||24,S=ye(l,b,u,1.5);S&&D.appendChild(S)},va=()=>{D&&D.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},rs=()=>{var S;if(!D)return;Ai();let l=(S=r.voiceRecognition)!=null?S:{},u=l.recordingBackgroundColor,f=l.recordingIconColor,b=l.recordingBorderColor;if(va(),D.classList.add("persona-voice-recording"),D.style.backgroundColor=u!=null?u:"var(--persona-voice-recording-bg, #ef4444)",D.style.color=f!=null?f:"var(--persona-voice-recording-indicator, #ffffff)",f){let W=D.querySelector("svg");W&&W.setAttribute("stroke",f)}b&&(D.style.borderColor=b),D.setAttribute("aria-label","Stop voice recognition")},nf=()=>{var U,N,ae,se,te,we,Fe,Oe;if(!D)return;Ai();let l=(U=r.voiceRecognition)!=null?U:{},u=$.getVoiceInterruptionMode(),f=(N=l.processingIconName)!=null?N:"loader",b=(se=(ae=l.processingIconColor)!=null?ae:ut==null?void 0:ut.color)!=null?se:"",S=(we=(te=l.processingBackgroundColor)!=null?te:ut==null?void 0:ut.backgroundColor)!=null?we:"",W=(Oe=(Fe=l.processingBorderColor)!=null?Fe:ut==null?void 0:ut.borderColor)!=null?Oe:"";va(),D.classList.add("persona-voice-processing"),D.style.backgroundColor=S,D.style.borderColor=W;let z=b||"currentColor";D.style.color=z,Si(f,z),D.setAttribute("aria-label","Processing voice input"),u==="none"&&(D.style.cursor="default")},rf=()=>{var ae,se,te,we,Fe,Oe,Ue,ze,mt,at,Be,Re;if(!D)return;Ai();let l=(ae=r.voiceRecognition)!=null?ae:{},u=$.getVoiceInterruptionMode(),f=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",b=(se=l.speakingIconName)!=null?se:f,S=(Oe=l.speakingIconColor)!=null?Oe:u==="barge-in"?(we=(te=l.recordingIconColor)!=null?te:ut==null?void 0:ut.color)!=null?we:"":(Fe=ut==null?void 0:ut.color)!=null?Fe:"",W=(mt=l.speakingBackgroundColor)!=null?mt:u==="barge-in"?(Ue=l.recordingBackgroundColor)!=null?Ue:"var(--persona-voice-recording-bg, #ef4444)":(ze=ut==null?void 0:ut.backgroundColor)!=null?ze:"",z=(Re=l.speakingBorderColor)!=null?Re:u==="barge-in"?(at=l.recordingBorderColor)!=null?at:"":(Be=ut==null?void 0:ut.borderColor)!=null?Be:"";va(),D.classList.add("persona-voice-speaking"),D.style.backgroundColor=W,D.style.borderColor=z;let U=S||"currentColor";D.style.color=U,Si(b,U);let N=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";D.setAttribute("aria-label",N),u==="none"&&(D.style.cursor="default"),u==="barge-in"&&D.classList.add("persona-voice-recording")},$r=()=>{var l,u,f;D&&(va(),ut&&(D.style.backgroundColor=(l=ut.backgroundColor)!=null?l:"",D.style.color=(u=ut.color)!=null?u:"",D.style.borderColor=(f=ut.borderColor)!=null?f:"",Si(ut.iconName,ut.color||"currentColor"),ut=null),D.style.cursor="",D.setAttribute("aria-label","Start voice recognition"))},wa=()=>{var l,u;if(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"){let f=$.getVoiceStatus(),b=$.getVoiceInterruptionMode();if(b==="none"&&(f==="processing"||f==="speaking"))return;if(b==="cancel"&&(f==="processing"||f==="speaking")){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{G.active=!1,G.manuallyDeactivated=!0,dt(),rt("user"),$r()});return}$.toggleVoice().then(()=>{G.active=$.isVoiceActive(),G.manuallyDeactivated=!$.isVoiceActive(),dt(),rt("user"),$.isVoiceActive()?rs():$r()});return}if(Lr){let f=be.value.trim();G.manuallyDeactivated=!0,dt(),lo("user"),f&&(be.value="",be.style.height="auto",$.sendMessage(f))}else G.manuallyDeactivated=!1,dt(),ba("user")};wr=wa,D&&(D.addEventListener("click",wa),ct.push(()=>{var l,u;((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),$r()):lo("system"),D&&D.removeEventListener("click",wa)}));let of=i.on("assistant:complete",()=>{Ne&&(G.active||G.manuallyDeactivated||Ne==="assistant"&&!G.lastUserMessageWasVoice||setTimeout(()=>{var l,u;!G.active&&!G.manuallyDeactivated&&(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?$.toggleVoice().then(()=>{G.active=$.isVoiceActive(),rt("auto"),$.isVoiceActive()&&rs()}):ba("auto"))},600))});ct.push(of);let sf=i.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});ct.push(sf);let ql=()=>{$t(!F,"user")},Zt=null,sn=null;if(I&&!R()){let{instance:l,element:u}=el({config:r,plugins:o,onToggle:ql});Zt=l,l||(sn=u)}Zt?n.appendChild(Zt.element):sn&&n.appendChild(sn),Ns(),Jo(),Hl(),bi($.isStreaming()),Ll()||(Ot()==="follow"?io(!0):Ml()),hi(),P&&(!I||R()?setTimeout(()=>vi(),0):F&&setTimeout(()=>vi(),200));let Fs=()=>{var N,ae,se,te,we,Fe,Oe,Ue,ze,mt,at,Be,Re,je,Qe,vt,H,De,We,Je,It,_e;if(R()){Vn(),Ns();return}let l=gn(r),u=(ae=(N=r.launcher)==null?void 0:N.sidebarMode)!=null?ae:!1,f=l||u||((te=(se=r.launcher)==null?void 0:se.fullHeight)!=null?te:!1),b=(we=n.ownerDocument.defaultView)!=null?we:window,S=(Oe=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Oe:!0,W=(ze=(Ue=r.launcher)==null?void 0:Ue.mobileBreakpoint)!=null?ze:640,z=b.innerWidth<=W,U=S&&z&&I;try{if(U){to(),ws(n,r);return}if(_&&(_=!1,to(),ws(n,r)),!I&&!l){X.style.height="",X.style.width="";return}if(!u&&!l){let Gt=(at=(mt=r==null?void 0:r.launcher)==null?void 0:mt.width)!=null?at:r==null?void 0:r.launcherWidth,Ct=Gt!=null?Gt:Vr;X.style.width=Ct,X.style.maxWidth=Ct}if(Eo(),!f){let Gt=b.innerHeight,Ct=64,an=(Re=(Be=r.launcher)==null?void 0:Be.heightOffset)!=null?Re:0,Wn=Math.max(200,Gt-Ct),Dt=Math.min(640,Wn),un=Math.max(200,Dt-an);X.style.height=`${un}px`}}finally{if(Vn(),Ns(),F&&I){let Ct=((je=n.ownerDocument.defaultView)!=null?je:window).innerWidth<=((vt=(Qe=r.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?vt:640),an=(De=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?De:!1,Wn=(Je=(We=r.launcher)==null?void 0:We.mobileFullscreen)!=null?Je:!0,Dt=gn(r)&&Wn&&Ct,un=an||Wn&&Ct&&I||Dt;if(un&&!on){let $n=n.getRootNode(),Ke=$n instanceof ShadowRoot?$n.host:n.closest(".persona-host");Ke&&!rn&&(rn=Xi(Ke,(_e=(It=r.launcher)==null?void 0:It.zIndex)!=null?_e:vn)),on=Ji(n.ownerDocument)}else un||(rn==null||rn(),rn=null,on==null||on(),on=null)}}};Fs();let zl=(Qc=n.ownerDocument.defaultView)!=null?Qc:window;if(zl.addEventListener("resize",Fs),ct.push(()=>zl.removeEventListener("resize",Fs)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Vn()});l.observe(He),ct.push(()=>l.disconnect())}An=xe.scrollTop;let jl=Rr(xe),af=()=>{let l=xe.getRootNode(),u=typeof l.getSelection=="function"?l.getSelection():null;return u!=null?u:xe.ownerDocument.getSelection()},Ti=()=>Im(af(),xe),Vl=()=>{let l=xe.scrollTop,u=Rr(xe),f=u<jl;if(jl=u,!en()){An=l,_n();return}let{action:b,nextLastScrollTop:S}=Ka({following:hn.isFollowing(),currentScrollTop:l,lastScrollTop:An,nearBottom:vo(xe,V),userScrollThreshold:x,isAutoScrolling:Sn||ko||f,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(An=S,b==="resume"){Ti()||ao();return}b==="pause"&&Is()};if(xe.addEventListener("scroll",Vl,{passive:!0}),ct.push(()=>xe.removeEventListener("scroll",Vl)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Ug()});l.observe(Ze),l.observe(xe),ct.push(()=>l.disconnect())}let Kl=()=>{en()&&hn.isFollowing()&&Ti()&&Is()},Gl=xe.ownerDocument;Gl.addEventListener("selectionchange",Kl),ct.push(()=>{Gl.removeEventListener("selectionchange",Kl)});let lf=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Ql=l=>{rr()&&en()&&hn.isFollowing()&&lf.has(l.key)&&Is()},Xl=l=>{if(!rr()||!en()||!hn.isFollowing())return;let u=l.target;u&&u.closest("a, button, [tabindex], input, textarea, select")&&Is()};xe.addEventListener("keydown",Ql),xe.addEventListener("focusin",Xl),ct.push(()=>{xe.removeEventListener("keydown",Ql),xe.removeEventListener("focusin",Xl)});let Jl=l=>{if(!en())return;let u=Ga({following:hn.isFollowing(),deltaY:l.deltaY,nearBottom:vo(xe,V),resumeWhenNearBottom:!0});u==="pause"?Is():u==="resume"&&!Ti()&&ao()};xe.addEventListener("wheel",Jl,{passive:!0}),ct.push(()=>xe.removeEventListener("wheel",Jl)),Vt.addEventListener("click",()=>{Rs(),xe.scrollTop=xe.scrollHeight,An=xe.scrollTop,ao(),io(!0),_n()}),ct.push(()=>Vt.remove()),ct.push(()=>{Tn(),Rs()});let Yl=()=>{qe&&(Tr&&(qe.removeEventListener("click",Tr),Tr=null),O()?(qe.style.display="",Tr=()=>{$t(!1,"user")},qe.addEventListener("click",Tr)):qe.style.display="none")};Yl(),(()=>{let{clearChatButton:l}=Ve;l&&l.addEventListener("click",()=>{$.clearMessages(),Er.clear(),ao(),ms(Ve.composerOverlay);try{localStorage.removeItem(Es),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Es}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Es)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),c!=null&&c.clear)try{let f=c.clear();f instanceof Promise&&f.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}p={},T.syncFromMetadata(),K==null||K.clear(),J==null||J.reset(),Se==null||Se.update()})})(),At&&At.addEventListener("submit",Nl),be==null||be.addEventListener("keydown",Ol),be==null||be.addEventListener("input",Fl),be==null||be.addEventListener("paste",$l);let Zl=(Xc=n.ownerDocument)!=null?Xc:document;Zl.addEventListener("keydown",_l,!0);let ec="persona-attachment-drop-active",Os=0,Ei=()=>{Os=0,Ee.classList.remove(ec)},os=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&St!==null},tc=l=>{!gi(l.dataTransfer)||!os()||(Os++,Os===1&&Ee.classList.add(ec))},nc=l=>{!gi(l.dataTransfer)||!os()||(Os--,Os<=0&&Ei())},rc=l=>{!gi(l.dataTransfer)||!os()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},oc=l=>{var f;if(!gi(l.dataTransfer)||!os())return;l.preventDefault(),l.stopPropagation(),Ei();let u=Array.from((f=l.dataTransfer.files)!=null?f:[]);u.length!==0&&St.handleFiles(u)},co=!0;Ee.addEventListener("dragenter",tc,co),Ee.addEventListener("dragleave",nc,co),n.addEventListener("dragover",rc,co),n.addEventListener("drop",oc,co);let xa=n.ownerDocument,sc=l=>{os()&&l.preventDefault()},ac=l=>{os()&&l.preventDefault()};xa.addEventListener("dragover",sc),xa.addEventListener("drop",ac),ct.push(()=>{At&&At.removeEventListener("submit",Nl),be==null||be.removeEventListener("keydown",Ol),be==null||be.removeEventListener("input",Fl),be==null||be.removeEventListener("paste",$l),Zl.removeEventListener("keydown",_l,!0)}),ct.push(()=>{Ee.removeEventListener("dragenter",tc,co),Ee.removeEventListener("dragleave",nc,co),n.removeEventListener("dragover",rc,co),n.removeEventListener("drop",oc,co),xa.removeEventListener("dragover",sc),xa.removeEventListener("drop",ac),Ei()}),ct.push(()=>{$.cancel()}),Zt?ct.push(()=>{Zt==null||Zt.destroy()}):sn&&ct.push(()=>{sn==null||sn.remove()});let tn={update(l){var qn,Pr,dn,pn,er,mo,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,vd,wd,xd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Rd,Wd,Hd,Bd,Dd,Nd,Fd,Od,_d,$d,Ud,qd,zd,jd,Vd,Kd,Gd,Qd,Xd,Jd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,vp,wp,xp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Np,Fp,Op,_p,$p,Up,qp,zp,jp,Vp,Kp,Gp,Qp,Xp,Jp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu;let u=r.toolCall,f=r.messageActions,b=(qn=r.layout)==null?void 0:qn.messages,S=r.colorScheme,W=r.loadingIndicator,z=r.iterationDisplay,U=(Pr=r.features)==null?void 0:Pr.showReasoning,N=(dn=r.features)==null?void 0:dn.showToolCalls,ae=(pn=r.features)==null?void 0:pn.toolCallDisplay,se=(er=r.features)==null?void 0:er.reasoningDisplay,te=(rd=(mo=r.features)==null?void 0:mo.streamAnimation)==null?void 0:rd.type;r={...r,...l},to(),ws(n,r),ui(n,r),mi(n,r),Ar(),r.colorScheme!==S&&Ps();let we=ml.getForInstance(r.plugins);o.length=0,o.push(...we),I=(sd=(od=r.launcher)==null?void 0:od.enabled)!=null?sd:!0,M=(id=(ad=r.launcher)==null?void 0:ad.autoExpand)!=null?id:!1,Pe=(cd=(ld=r.features)==null?void 0:ld.showReasoning)!=null?cd:!0,Ie=(pd=(dd=r.features)==null?void 0:dd.showToolCalls)!=null?pd:!0,he=(md=(ud=r.features)==null?void 0:ud.scrollToBottom)!=null?md:{};let Fe=Ot();re=(fd=(gd=r.features)==null?void 0:gd.scrollBehavior)!=null?fd:{},Fe!==Ot()&&(Rs(),ao()),Qr(),_n();let Oe=ie;if(ie=(yd=(hd=r.features)==null?void 0:hd.showEventStreamToggle)!=null?yd:!1,ie&&!Oe){if(K||(Ae=new ua(de),K=new pa($e,Ae),J=J!=null?J:new ma,Ae.open().then(()=>K==null?void 0:K.restore()).catch(()=>{}),$.setSSEEventCallback((ne,Et)=>{var zt;(zt=r.onSSEEvent)==null||zt.call(r,ne,Et),J==null||J.processEvent(ne,Et),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(Et)})})),!bt&&Le){let ne=(vd=(bd=r.features)==null?void 0:bd.eventStream)==null?void 0:vd.classNames,Et="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"+(ne!=null&&ne.toggleButton?" "+ne.toggleButton:"");bt=v("button",Et),bt.style.width="28px",bt.style.height="28px",bt.style.color=kn.actionIconColor,bt.type="button",bt.setAttribute("aria-label","Event Stream"),bt.title="Event Stream";let zt=ye("activity","18px","currentColor",1.5);zt&&bt.appendChild(zt);let it=Ve.clearChatButtonWrapper,Lt=Ve.closeButtonWrapper,ln=it||Lt;ln&&ln.parentNode===Le?Le.insertBefore(bt,ln):Le.appendChild(bt),bt.addEventListener("click",()=>{Y?ir():Br()})}}else!ie&&Oe&&(ir(),bt&&(bt.remove(),bt=null),K==null||K.clear(),Ae==null||Ae.destroy(),K=null,Ae=null,J==null||J.reset(),J=null);if(((wd=r.launcher)==null?void 0:wd.enabled)===!1&&Zt&&(Zt.destroy(),Zt=null),((xd=r.launcher)==null?void 0:xd.enabled)===!1&&sn&&(sn.remove(),sn=null),((Cd=r.launcher)==null?void 0:Cd.enabled)!==!1&&!Zt&&!sn){let{instance:ne,element:Et}=el({config:r,plugins:o,onToggle:ql});Zt=ne,ne||(sn=Et),n.appendChild(Et)}Zt&&Zt.update(r),ge&&((Ad=r.launcher)==null?void 0:Ad.title)!==void 0&&(ge.textContent=r.launcher.title),Me&&((Sd=r.launcher)==null?void 0:Sd.subtitle)!==void 0&&(Me.textContent=r.launcher.subtitle);let Ue=(Td=r.layout)==null?void 0:Td.header;if((Ue==null?void 0:Ue.layout)!==q&&Le){let ne=Ue?ti(r,Ue,{showClose:O(),onClose:()=>$t(!1,"user")}):zo({config:r,showClose:O(),onClose:()=>$t(!1,"user")});ot.replaceHeader(ne),Le=ot.header.element,L=ot.header.iconHolder,ge=ot.header.headerTitle,Me=ot.header.headerSubtitle,qe=ot.header.closeButton,q=Ue==null?void 0:Ue.layout}else if(Ue&&(L&&(L.style.display=Ue.showIcon===!1?"none":""),ge&&(ge.style.display=Ue.showTitle===!1?"none":""),Me&&(Me.style.display=Ue.showSubtitle===!1?"none":""),qe&&(qe.style.display=Ue.showCloseButton===!1?"none":""),Ve.clearChatButtonWrapper)){let ne=Ue.showClearChat;if(ne!==void 0){Ve.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:Et}=Ve;Et&&!Et.classList.contains("persona-absolute")&&(ne?Et.classList.remove("persona-ml-auto"):Et.classList.add("persona-ml-auto"))}}let mt=((Ed=r.layout)==null?void 0:Ed.showHeader)!==!1;Le&&(Le.style.display=mt?"":"none");let at=((Md=r.layout)==null?void 0:Md.showFooter)!==!1;He&&(He.style.display=at?"":"none"),Vn(),_n(),I!==k?I?$t(M,"auto"):(F=!0,Ns()):M!==C&&$t(M,"auto"),C=M,k=I,Fs(),Yl();let je=JSON.stringify(l.toolCall)!==JSON.stringify(u),Qe=JSON.stringify(r.messageActions)!==JSON.stringify(f),vt=JSON.stringify((kd=r.layout)==null?void 0:kd.messages)!==JSON.stringify(b),H=((Ld=r.loadingIndicator)==null?void 0:Ld.render)!==(W==null?void 0:W.render)||((Pd=r.loadingIndicator)==null?void 0:Pd.renderIdle)!==(W==null?void 0:W.renderIdle)||((Id=r.loadingIndicator)==null?void 0:Id.showBubble)!==(W==null?void 0:W.showBubble),De=r.iterationDisplay!==z,We=((Wd=(Rd=r.features)==null?void 0:Rd.showReasoning)!=null?Wd:!0)!==(U!=null?U:!0)||((Bd=(Hd=r.features)==null?void 0:Hd.showToolCalls)!=null?Bd:!0)!==(N!=null?N:!0)||JSON.stringify((Dd=r.features)==null?void 0:Dd.toolCallDisplay)!==JSON.stringify(ae)||JSON.stringify((Nd=r.features)==null?void 0:Nd.reasoningDisplay)!==JSON.stringify(se);(je||Qe||vt||H||De||We)&&$&&(Yo++,Ws(Ze,$.getMessages(),ee));let It=(Od=(Fd=r.features)==null?void 0:Fd.streamAnimation)==null?void 0:Od.type;if(It!==te&&It&&It!=="none"){let ne=xs(It,($d=(_d=r.features)==null?void 0:_d.streamAnimation)==null?void 0:$d.plugins);ne&&Ya(ne,n)}let _e=(Ud=r.launcher)!=null?Ud:{},Gt=(qd=_e.headerIconHidden)!=null?qd:!1,Ct=(jd=(zd=r.layout)==null?void 0:zd.header)==null?void 0:jd.showIcon,an=Gt||Ct===!1,Wn=_e.headerIconName,Dt=(Vd=_e.headerIconSize)!=null?Vd:"48px";if(L){let ne=Ee.querySelector(".persona-border-b-persona-divider"),Et=ne==null?void 0:ne.querySelector(".persona-flex-col");if(an)L.style.display="none",ne&&Et&&!ne.contains(Et)&&ne.insertBefore(Et,ne.firstChild);else{if(L.style.display="",L.style.height=Dt,L.style.width=Dt,ne&&Et&&(ne.contains(L)?L.nextSibling!==Et&&(L.remove(),ne.insertBefore(L,Et)):ne.insertBefore(L,Et)),Wn){let it=parseFloat(Dt)||24,Lt=ye(Wn,it*.6,"currentColor",1);Lt?L.replaceChildren(Lt):L.textContent=(Kd=_e.agentIconText)!=null?Kd:"\u{1F4AC}"}else if(_e.iconUrl){let it=L.querySelector("img");if(it)it.src=_e.iconUrl,it.style.height=Dt,it.style.width=Dt;else{let Lt=document.createElement("img");Lt.src=_e.iconUrl,Lt.alt="",Lt.className="persona-rounded-xl persona-object-cover",Lt.style.height=Dt,Lt.style.width=Dt,L.replaceChildren(Lt)}}else{let it=L.querySelector("svg"),Lt=L.querySelector("img");(it||Lt)&&L.replaceChildren(),L.textContent=(Gd=_e.agentIconText)!=null?Gd:"\u{1F4AC}"}let zt=L.querySelector("img");zt&&(zt.style.height=Dt,zt.style.width=Dt)}}let un=(Xd=(Qd=r.layout)==null?void 0:Qd.header)==null?void 0:Xd.showTitle,$n=(Yd=(Jd=r.layout)==null?void 0:Jd.header)==null?void 0:Yd.showSubtitle;if(ge&&(ge.style.display=un===!1?"none":""),Me&&(Me.style.display=$n===!1?"none":""),qe){((ep=(Zd=r.layout)==null?void 0:Zd.header)==null?void 0:ep.showCloseButton)===!1?qe.style.display="none":qe.style.display="";let Et=(tp=_e.closeButtonSize)!=null?tp:"32px",zt=(np=_e.closeButtonPlacement)!=null?np:"inline";qe.style.height=Et,qe.style.width=Et;let{closeButtonWrapper:it}=Ve,Lt=zt==="top-right",ln=it==null?void 0:it.classList.contains("persona-absolute");if(it&&Lt!==ln)if(it.remove(),Lt)it.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Ee.style.position="relative",Ee.appendChild(it);else{let pt=(op=(rp=_e.clearChat)==null?void 0:rp.placement)!=null?op:"inline",cn=(ap=(sp=_e.clearChat)==null?void 0:sp.enabled)!=null?ap:!0;it.className=cn&&pt==="inline"?"":"persona-ml-auto";let Hn=Ee.querySelector(".persona-border-b-persona-divider");Hn&&Hn.appendChild(it)}if(qe.style.color=_e.closeButtonColor||kn.actionIconColor,_e.closeButtonBackgroundColor?(qe.style.backgroundColor=_e.closeButtonBackgroundColor,qe.classList.remove("hover:persona-bg-gray-100")):(qe.style.backgroundColor="",qe.classList.add("hover:persona-bg-gray-100")),_e.closeButtonBorderWidth||_e.closeButtonBorderColor){let pt=_e.closeButtonBorderWidth||"0px",cn=_e.closeButtonBorderColor||"transparent";qe.style.border=`${pt} solid ${cn}`,qe.classList.remove("persona-border-none")}else qe.style.border="",qe.classList.add("persona-border-none");_e.closeButtonBorderRadius?(qe.style.borderRadius=_e.closeButtonBorderRadius,qe.classList.remove("persona-rounded-full")):(qe.style.borderRadius="",qe.classList.add("persona-rounded-full")),_e.closeButtonPaddingX?(qe.style.paddingLeft=_e.closeButtonPaddingX,qe.style.paddingRight=_e.closeButtonPaddingX):(qe.style.paddingLeft="",qe.style.paddingRight=""),_e.closeButtonPaddingY?(qe.style.paddingTop=_e.closeButtonPaddingY,qe.style.paddingBottom=_e.closeButtonPaddingY):(qe.style.paddingTop="",qe.style.paddingBottom="");let bn=(ip=_e.closeButtonIconName)!=null?ip:"x",ur=(lp=_e.closeButtonIconText)!=null?lp:"\xD7";qe.innerHTML="";let Mn=ye(bn,"28px","currentColor",1);Mn?qe.appendChild(Mn):qe.textContent=ur;let Yt=(cp=_e.closeButtonTooltipText)!=null?cp:"Close chat",zn=(dp=_e.closeButtonShowTooltip)!=null?dp:!0;if(qe.setAttribute("aria-label",Yt),it&&(it._cleanupTooltip&&(it._cleanupTooltip(),delete it._cleanupTooltip),zn&&Yt)){let pt=null,cn=()=>{if(pt||!qe)return;let No=qe.ownerDocument,_s=No.body;if(!_s)return;pt=Ir(No,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let $s=Ir(No,"div");$s.className="persona-clear-chat-tooltip-arrow",pt.appendChild($s);let Fo=qe.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(wo),pt.style.left=`${Fo.left+Fo.width/2}px`,pt.style.top=`${Fo.top-8}px`,pt.style.transform="translate(-50%, -100%)",_s.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};it.addEventListener("mouseenter",cn),it.addEventListener("mouseleave",Hn),qe.addEventListener("focus",cn),qe.addEventListener("blur",Hn),it._cleanupTooltip=()=>{Hn(),it&&(it.removeEventListener("mouseenter",cn),it.removeEventListener("mouseleave",Hn)),qe&&(qe.removeEventListener("focus",cn),qe.removeEventListener("blur",Hn))}}}let{clearChatButton:Ke,clearChatButtonWrapper:Rt}=Ve;if(Ke){let ne=(pp=_e.clearChat)!=null?pp:{},Et=(up=ne.enabled)!=null?up:!0,zt=(gp=(mp=r.layout)==null?void 0:mp.header)==null?void 0:gp.showClearChat,it=zt!==void 0?zt:Et,Lt=(fp=ne.placement)!=null?fp:"inline";if(Rt){Rt.style.display=it?"":"none";let{closeButtonWrapper:ln}=Ve;!R()&&ln&&!ln.classList.contains("persona-absolute")&&(it?ln.classList.remove("persona-ml-auto"):ln.classList.add("persona-ml-auto"));let bn=Lt==="top-right",ur=Rt.classList.contains("persona-absolute");if(!R()&&bn!==ur&&it){if(Rt.remove(),bn)Rt.className="persona-absolute persona-top-4 persona-z-50",Rt.style.right="48px",Ee.style.position="relative",Ee.appendChild(Rt);else{Rt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Rt.style.right="";let Yt=Ee.querySelector(".persona-border-b-persona-divider"),zn=Ve.closeButtonWrapper;Yt&&zn&&zn.parentElement===Yt?Yt.insertBefore(Rt,zn):Yt&&Yt.appendChild(Rt)}let Mn=Ve.closeButtonWrapper;Mn&&!Mn.classList.contains("persona-absolute")&&(bn?Mn.classList.add("persona-ml-auto"):Mn.classList.remove("persona-ml-auto"))}}if(it){if(!R()){let pt=(hp=ne.size)!=null?hp:"32px";Ke.style.height=pt,Ke.style.width=pt}let ln=(yp=ne.iconName)!=null?yp:"refresh-cw",bn=(bp=ne.iconColor)!=null?bp:"";Ke.style.color=bn||kn.actionIconColor,Ke.innerHTML="";let ur=R()?"14px":"20px",Mn=ye(ln,ur,"currentColor",2);if(Mn&&Ke.appendChild(Mn),ne.backgroundColor?(Ke.style.backgroundColor=ne.backgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let pt=ne.borderWidth||"0px",cn=ne.borderColor||"transparent";Ke.style.border=`${pt} solid ${cn}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");ne.borderRadius?(Ke.style.borderRadius=ne.borderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),ne.paddingX?(Ke.style.paddingLeft=ne.paddingX,Ke.style.paddingRight=ne.paddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),ne.paddingY?(Ke.style.paddingTop=ne.paddingY,Ke.style.paddingBottom=ne.paddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let Yt=(vp=ne.tooltipText)!=null?vp:"Clear chat",zn=(wp=ne.showTooltip)!=null?wp:!0;if(Ke.setAttribute("aria-label",Yt),Rt&&(Rt._cleanupTooltip&&(Rt._cleanupTooltip(),delete Rt._cleanupTooltip),zn&&Yt)){let pt=null,cn=()=>{if(pt||!Ke)return;let No=Ke.ownerDocument,_s=No.body;if(!_s)return;pt=Ir(No,"div","persona-clear-chat-tooltip"),pt.textContent=Yt;let $s=Ir(No,"div");$s.className="persona-clear-chat-tooltip-arrow",pt.appendChild($s);let Fo=Ke.getBoundingClientRect();pt.style.position="fixed",pt.style.zIndex=String(wo),pt.style.left=`${Fo.left+Fo.width/2}px`,pt.style.top=`${Fo.top-8}px`,pt.style.transform="translate(-50%, -100%)",_s.appendChild(pt)},Hn=()=>{pt&&pt.parentNode&&(pt.parentNode.removeChild(pt),pt=null)};Rt.addEventListener("mouseenter",cn),Rt.addEventListener("mouseleave",Hn),Ke.addEventListener("focus",cn),Ke.addEventListener("blur",Hn),Rt._cleanupTooltip=()=>{Hn(),Rt&&(Rt.removeEventListener("mouseenter",cn),Rt.removeEventListener("mouseleave",Hn)),Ke&&(Ke.removeEventListener("focus",cn),Ke.removeEventListener("blur",Hn))}}}}let Un=r.actionParsers&&r.actionParsers.length?r.actionParsers:[fl],Io=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ga.message,ga.messageAndClick];T=hl({parsers:Un,handlers:Io,getSessionMetadata:y,updateSessionMetadata:w,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),ee=Eg(r,T,pe),$.updateConfig(r),Ws(Ze,$.getMessages(),ee),Jo(),Hl(),bi($.isStreaming());let Ro=((xp=r.voiceRecognition)==null?void 0:xp.enabled)===!0,Wo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ho=((Ap=(Cp=r.voiceRecognition)==null?void 0:Cp.provider)==null?void 0:Ap.type)==="runtype";if(Ro&&(Wo||Ho))if(!D||!ve){let ne=tf(r.voiceRecognition,r.sendButton);ne&&(D=ne.micButton,ve=ne.micButtonWrapper,yt.insertBefore(ve,xn),D.addEventListener("click",wa),D.disabled=$.isStreaming())}else{let ne=(Sp=r.voiceRecognition)!=null?Sp:{},Et=(Tp=r.sendButton)!=null?Tp:{},zt=(Ep=ne.iconName)!=null?Ep:"mic",it=(Mp=Et.size)!=null?Mp:"40px",Lt=(kp=ne.iconSize)!=null?kp:it,ln=parseFloat(Lt)||24;D.style.width=Lt,D.style.height=Lt,D.style.minWidth=Lt,D.style.minHeight=Lt;let bn=(Pp=(Lp=ne.iconColor)!=null?Lp:Et.textColor)!=null?Pp:"currentColor";D.innerHTML="";let ur=ye(zt,ln,bn,2);ur?D.appendChild(ur):D.textContent="\u{1F3A4}";let Mn=(Ip=ne.backgroundColor)!=null?Ip:Et.backgroundColor;Mn?D.style.backgroundColor=Mn:D.style.backgroundColor="",bn?D.style.color=bn:D.style.color="var(--persona-text, #111827)",ne.borderWidth?(D.style.borderWidth=ne.borderWidth,D.style.borderStyle="solid"):(D.style.borderWidth="",D.style.borderStyle=""),ne.borderColor?D.style.borderColor=ne.borderColor:D.style.borderColor="",ne.paddingX?(D.style.paddingLeft=ne.paddingX,D.style.paddingRight=ne.paddingX):(D.style.paddingLeft="",D.style.paddingRight=""),ne.paddingY?(D.style.paddingTop=ne.paddingY,D.style.paddingBottom=ne.paddingY):(D.style.paddingTop="",D.style.paddingBottom="");let Yt=ve==null?void 0:ve.querySelector(".persona-send-button-tooltip"),zn=(Rp=ne.tooltipText)!=null?Rp:"Start voice recognition";if(((Wp=ne.showTooltip)!=null?Wp:!1)&&zn)if(Yt)Yt.textContent=zn,Yt.style.display="";else{let cn=document.createElement("div");cn.className="persona-send-button-tooltip",cn.textContent=zn,ve==null||ve.insertBefore(cn,D)}else Yt&&(Yt.style.display="none");ve.style.display="",D.disabled=$.isStreaming()}else D&&ve&&(ve.style.display="none",((Bp=(Hp=r.voiceRecognition)==null?void 0:Hp.provider)==null?void 0:Bp.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():Lr&&lo());if(((Dp=r.attachments)==null?void 0:Dp.enabled)===!0)if(!ft||!ce){let ne=(Np=r.attachments)!=null?Np:{},zt=(Op=((Fp=r.sendButton)!=null?Fp:{}).size)!=null?Op:"40px";Pt||(Pt=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Pt.style.display="none",At.insertBefore(Pt,be)),Ge||(Ge=document.createElement("input"),Ge.type="file",Ge.accept=((_p=ne.allowedTypes)!=null?_p:jr).join(","),Ge.multiple=(($p=ne.maxFiles)!=null?$p:4)>1,Ge.style.display="none",Ge.setAttribute("aria-label","Attach files"),At.insertBefore(Ge,be)),ft=v("div","persona-send-button-wrapper"),ce=v("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",(Up=ne.buttonTooltipText)!=null?Up:"Attach file");let it=(qp=ne.buttonIconName)!=null?qp:"paperclip",Lt=zt,ln=parseFloat(Lt)||40,bn=Math.round(ln*.6);ce.style.width=Lt,ce.style.height=Lt,ce.style.minWidth=Lt,ce.style.minHeight=Lt,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(it,bn,"currentColor",1.5);ur?ce.appendChild(ur):ce.textContent="\u{1F4CE}",ce.addEventListener("click",zn=>{zn.preventDefault(),Ge==null||Ge.click()}),ft.appendChild(ce);let Mn=(zp=ne.buttonTooltipText)!=null?zp:"Attach file",Yt=v("div","persona-send-button-tooltip");Yt.textContent=Mn,ft.appendChild(Yt),Xe.append(ft),!St&&Ge&&Pt&&(St=ta.fromConfig(ne),St.setPreviewsContainer(Pt),Ge.addEventListener("change",async()=>{St&&(Ge!=null&&Ge.files)&&(await St.handleFileSelect(Ge.files),Ge.value="")})),Ee.querySelector(".persona-attachment-drop-overlay")||Ee.appendChild(Mg(ne.dropOverlay))}else{ft.style.display="";let ne=(jp=r.attachments)!=null?jp:{};Ge&&(Ge.accept=((Vp=ne.allowedTypes)!=null?Vp:jr).join(","),Ge.multiple=((Kp=ne.maxFiles)!=null?Kp:4)>1),St&&St.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}else ft&&(ft.style.display="none"),St&&St.clearAttachments(),(Gp=Ee.querySelector(".persona-attachment-drop-overlay"))==null||Gp.remove();let Qt=(Qp=r.sendButton)!=null?Qp:{},Bo=(Xp=Qt.useIcon)!=null?Xp:!1,po=(Jp=Qt.iconText)!=null?Jp:"\u2191",uo=Qt.iconName,Ur=(Yp=Qt.tooltipText)!=null?Yp:"Send message",Do=(Zp=Qt.showTooltip)!=null?Zp:!1,et=(eu=Qt.size)!=null?eu:"40px",Ft=Qt.backgroundColor,Nt=Qt.textColor;if(Bo){if(ue.style.width=et,ue.style.height=et,ue.style.minWidth=et,ue.style.minHeight=et,ue.style.fontSize="18px",ue.style.lineHeight="1",ue.innerHTML="",Nt?ue.style.color=Nt:ue.style.color="var(--persona-button-primary-fg, #ffffff)",uo){let ne=parseFloat(et)||24,Et=(Nt==null?void 0:Nt.trim())||"currentColor",zt=ye(uo,ne,Et,2);zt?ue.appendChild(zt):ue.textContent=po}else ue.textContent=po;ue.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ft?(ue.style.backgroundColor=Ft,ue.classList.remove("persona-bg-persona-primary")):(ue.style.backgroundColor="",ue.classList.add("persona-bg-persona-primary"))}else ue.textContent=(nu=(tu=r.copy)==null?void 0:tu.sendButtonLabel)!=null?nu:"Send",ue.style.width="",ue.style.height="",ue.style.minWidth="",ue.style.minHeight="",ue.style.fontSize="",ue.style.lineHeight="",ue.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",Ft?(ue.style.backgroundColor=Ft,ue.classList.remove("persona-bg-persona-accent")):ue.classList.add("persona-bg-persona-accent"),Nt?ue.style.color=Nt:ue.classList.add("persona-text-white");Qt.borderWidth?(ue.style.borderWidth=Qt.borderWidth,ue.style.borderStyle="solid"):(ue.style.borderWidth="",ue.style.borderStyle=""),Qt.borderColor?ue.style.borderColor=Qt.borderColor:ue.style.borderColor="",Qt.paddingX?(ue.style.paddingLeft=Qt.paddingX,ue.style.paddingRight=Qt.paddingX):(ue.style.paddingLeft="",ue.style.paddingRight=""),Qt.paddingY?(ue.style.paddingTop=Qt.paddingY,ue.style.paddingBottom=Qt.paddingY):(ue.style.paddingTop="",ue.style.paddingBottom="");let Kt=xn==null?void 0:xn.querySelector(".persona-send-button-tooltip");if(Do&&Ur)if(Kt)Kt.textContent=Ur,Kt.style.display="";else{let ne=document.createElement("div");ne.className="persona-send-button-tooltip",ne.textContent=Ur,xn==null||xn.insertBefore(ne,ue)}else Kt&&(Kt.style.display="none");let Ut=(iu=(ru=r.layout)==null?void 0:ru.contentMaxWidth)!=null?iu:R()?(au=(su=(ou=r.launcher)==null?void 0:ou.composerBar)==null?void 0:su.contentMaxWidth)!=null?au:"720px":void 0;Ut?(Ze.style.maxWidth=Ut,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%",At&&(At.style.maxWidth=Ut,At.style.marginLeft="auto",At.style.marginRight="auto"),jt&&(jt.style.maxWidth=Ut,jt.style.marginLeft="auto",jt.style.marginRight="auto")):(Ze.style.maxWidth="",Ze.style.marginLeft="",Ze.style.marginRight="",Ze.style.width="",At&&(At.style.maxWidth="",At.style.marginLeft="",At.style.marginRight=""),jt&&(jt.style.maxWidth="",jt.style.marginLeft="",jt.style.marginRight=""));let gt=(lu=r.statusIndicator)!=null?lu:{},qt=(cu=gt.visible)!=null?cu:!0;if(fn.style.display=qt?"":"none",$){let ne=$.getStatus();ht(fn,(zt=>{var it,Lt,ln,bn;return zt==="idle"?(it=gt.idleText)!=null?it:nn.idle:zt==="connecting"?(Lt=gt.connectingText)!=null?Lt:nn.connecting:zt==="connected"?(ln=gt.connectedText)!=null?ln:nn.connected:zt==="error"?(bn=gt.errorText)!=null?bn:nn.error:nn[zt]})(ne),gt,ne)}fn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let mn=gt.align==="left"?"persona-text-left":gt.align==="center"?"persona-text-center":"persona-text-right";fn.classList.add(mn)},open(){O()&&$t(!0,"api")},close(){O()&&$t(!1,"api")},toggle(){O()&&$t(!F,"api")},reconnect(){$.reconnectNow()},clearChat(){Cn=!1,$.clearMessages(),Er.clear(),ao();try{localStorage.removeItem(Es),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Es}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Es)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),c!=null&&c.clear)try{let u=c.clear();u instanceof Promise&&u.catch(f=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}p={},T.syncFromMetadata(),K==null||K.clear(),J==null||J.reset(),Se==null||Se.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 u=(l==null?void 0:l.trim())||be.value.trim();return u?(!F&&O()&&$t(!0,"system"),be.value="",be.style.height="auto",$.sendMessage(u),!0):!1},startVoiceRecognition(){var u,f;return $.isStreaming()?!1:((f=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:f.type)==="runtype"?($.isVoiceActive()||(!F&&O()&&$t(!0,"system"),G.manuallyDeactivated=!1,dt(),$.toggleVoice().then(()=>{G.active=$.isVoiceActive(),rt("user"),$.isVoiceActive()&&rs()})),!0):Lr?!0:Ul()?(!F&&O()&&$t(!0,"system"),G.manuallyDeactivated=!1,dt(),ba("user"),!0):!1},stopVoiceRecognition(){var l,u;return((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{G.active=!1,G.manuallyDeactivated=!0,dt(),rt("user"),$r()}),!0):!1:Lr?(G.manuallyDeactivated=!0,dt(),lo("user"),!0):!1},injectMessage(l){return!F&&O()&&$t(!0,"system"),$.injectMessage(l)},injectAssistantMessage(l){!F&&O()&&$t(!0,"system");let u=$.injectAssistantMessage(l);return Z&&(Z=!1,ke&&(clearTimeout(ke),ke=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),u},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,u){return $.connectStream(l,u)},__pushEventStreamEvent(l){K&&(J==null||J.processEvent(l.type,l.payload),K.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!ie||!K||Br()},hideEventStream(){Y&&ir()},isEventStreamVisible(){return Y},showArtifacts(){nr(r)&&(Cn=!1,Ar(),xt==null||xt.setMobileOpen(!0))},hideArtifacts(){nr(r)&&(Cn=!0,Ar())},upsertArtifact(l){return nr(r)?(Cn=!1,$.upsertArtifact(l)):null},selectArtifact(l){nr(r)&&$.selectArtifact(l)},clearArtifacts(){nr(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 I&&!F&&!R()||!be?!1:(be.focus(),!0)},async resolveApproval(l,u,f){let S=$.getMessages().find(W=>{var z;return W.variant==="approval"&&((z=W.approval)==null?void 0:z.id)===l});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${l}`);if(S.approval.toolType==="webmcp"){$.resolveWebMcpApproval(S.id,u);return}return $.resolveApproval(S.approval,u,f)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(l){w(l)},on(l,u){return i.on(l,u)},off(l,u){i.off(l,u)},isOpen(){return O()&&F},isVoiceActive(){return G.active},toggleReadAloud(l){$.toggleReadAloud(l)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(l){return $.getReadAloudState(l)},onReadAloudChange(l){return $.onReadAloudChange(l)},getState(){return{open:O()&&F,launcherEnabled:I,voiceActive:G.active,streaming:$.isStreaming()}},showCSATFeedback(l){!F&&O()&&$t(!0,"system");let u=Ze.querySelector(".persona-feedback-container");u&&u.remove();let f=Ag({onSubmit:async(b,S)=>{var W;$.isClientTokenMode()&&await $.submitCSATFeedback(b,S),(W=l==null?void 0:l.onSubmit)==null||W.call(l,b,S)},onDismiss:l==null?void 0:l.onDismiss,...l});Ze.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!F&&O()&&$t(!0,"system");let u=Ze.querySelector(".persona-feedback-container");u&&u.remove();let f=Sg({onSubmit:async(b,S)=>{var W;$.isClientTokenMode()&&await $.submitNPSFeedback(b,S),(W=l==null?void 0:l.onSubmit)==null||W.call(l,b,S)},onDismiss:l==null?void 0:l.onDismiss,...l});Ze.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return $.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return $.submitNPSFeedback(l,u)},destroy(){Po!=null&&(clearInterval(Po),Po=null),ct.forEach(l=>l()),me.remove(),lt==null||lt.remove(),Zt==null||Zt.destroy(),sn==null||sn.remove(),Tr&&qe.removeEventListener("click",Tr)}};if((((Jc=t==null?void 0:t.debugTools)!=null?Jc:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:f=>f?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=u,ct.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=n.getAttribute("data-persona-instance")||n.id||"persona-"+Math.random().toString(36).slice(2,8),u=U=>{let N=U.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",u),ct.push(()=>{window.removeEventListener("persona:focusInput",u)}),ie){let U=ae=>{let se=ae.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&tn.showEventStream()},N=ae=>{let se=ae.detail;(!(se!=null&&se.instanceId)||se.instanceId===l)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",N),ct.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",N)})}let f=U=>{let N=U.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&tn.showArtifacts()},b=U=>{let N=U.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&tn.hideArtifacts()},S=U=>{let N=U.detail;N!=null&&N.instanceId&&N.instanceId!==l||N!=null&&N.artifact&&tn.upsertArtifact(N.artifact)},W=U=>{let N=U.detail;N!=null&&N.instanceId&&N.instanceId!==l||typeof(N==null?void 0:N.id)=="string"&&tn.selectArtifact(N.id)},z=U=>{let N=U.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",f),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",z),ct.push(()=>{window.removeEventListener("persona:showArtifacts",f),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",z)})}let Zn=yb(r.persistState);if(Zn&&O()){let l=bb(Zn.storage),u=`${Zn.keyPrefix}widget-open`,f=`${Zn.keyPrefix}widget-voice`,b=`${Zn.keyPrefix}widget-voice-mode`;if(l){let S=((Yc=Zn.persist)==null?void 0:Yc.openState)&&l.getItem(u)==="true",W=((Zc=Zn.persist)==null?void 0:Zc.voiceState)&&l.getItem(f)==="true",z=((ed=Zn.persist)==null?void 0:ed.voiceState)&&l.getItem(b)==="true";if(S&&setTimeout(()=>{tn.open(),setTimeout(()=>{var U;if(W||z)tn.startVoiceRecognition();else if((U=Zn.persist)!=null&&U.focusInput){let N=n.querySelector("textarea");N&&N.focus()}},100)},0),(td=Zn.persist)!=null&&td.openState&&(i.on("widget:opened",()=>{l.setItem(u,"true")}),i.on("widget:closed",()=>{l.setItem(u,"false")})),(nd=Zn.persist)!=null&&nd.voiceState&&(i.on("voice:state",U=>{l.setItem(f,U.active?"true":"false")}),i.on("user:message",U=>{l.setItem(b,U.viaVoice?"true":"false")})),Zn.clearOnChatClear){let U=()=>{l.removeItem(u),l.removeItem(f),l.removeItem(b)},N=()=>U();window.addEventListener("persona:clear-chat",N),ct.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return h&&O()&&setTimeout(()=>{tn.open()},0),ts(),ha||yu().then(()=>{$&&(Yo++,Er.clear(),Ws(Ze,$.getMessages(),ee))}).catch(()=>{}),tn};var vb=(n,e)=>{let t=n.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(t);return o?Math.max(0,e*parseFloat(o[1])/100):420},wb=(n,e)=>{if(e===!1){n.style.maxHeight="";return}n.style.maxHeight="100vh",n.style.maxHeight=e},xb=(n,e)=>{e===!1?(n.style.position="relative",n.style.top=""):(n.style.position="sticky",n.style.top="0")},Cb=(n,e)=>{let t=n.parentElement;if(!t)return;let r=n.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",t.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."+(e.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${e.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Lg=(n,e)=>{var r,o;let t=(o=(r=e==null?void 0:e.launcher)==null?void 0:r.enabled)!=null?o:!0;n.className="persona-host",n.style.height=t?"":"100%",n.style.display=t?"":"flex",n.style.flexDirection=t?"":"column",n.style.flex=t?"":"1 1 auto",n.style.minHeight=t?"":"0"},Cl=n=>{n.style.position="",n.style.top="",n.style.bottom="",n.style.left="",n.style.right="",n.style.zIndex="",n.style.transform="",n.style.pointerEvents=""},Pg=n=>{n.style.inset="",n.style.width="",n.style.height="",n.style.maxWidth="",n.style.maxHeight="",n.style.minWidth="",Cl(n)},vl=n=>{n.style.transition=""},wl=n=>{n.style.display="",n.style.flexDirection="",n.style.flex="",n.style.minHeight="",n.style.minWidth="",n.style.width="",n.style.height="",n.style.alignItems="",n.style.transition="",n.style.transform="",n.style.marginLeft=""},xl=n=>{n.style.width="",n.style.maxWidth="",n.style.minWidth="",n.style.flex="1 1 auto"},fi=(n,e)=>{n.style.width="",n.style.minWidth="",n.style.maxWidth="",n.style.boxSizing="",e.style.alignItems=""},Ab=(n,e,t,r,o)=>{o?t.parentElement!==e&&(n.replaceChildren(),e.replaceChildren(t,r),n.appendChild(e)):t.parentElement===e&&(e.replaceChildren(),n.appendChild(t),n.appendChild(r))},Sb=(n,e,t,r,o,s)=>{let a=s?e:n;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},Ig=(n,e,t,r,o,s,a)=>{var y,w,E,B,T,I;let i=gr(s),d=i.reveal==="push";Ab(n,e,t,r,d),Sb(n,e,t,r,i.side,d),n.dataset.personaHostLayout="docked",n.dataset.personaDockSide=i.side,n.dataset.personaDockOpen=a?"true":"false",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.height="100%",n.style.minHeight="0",n.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.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=n.ownerDocument.defaultView,p=(w=(y=s==null?void 0:s.launcher)==null?void 0:y.mobileFullscreen)!=null?w:!0,g=(B=(E=s==null?void 0:s.launcher)==null?void 0:E.mobileBreakpoint)!=null?B:640,h=c!=null?c.innerWidth<=g:!1;if(p&&h&&a){n.dataset.personaDockMobileFullscreen="true",n.removeAttribute("data-persona-dock-reveal"),wl(e),vl(r),Pg(r),xl(t),fi(o,r),n.style.display="flex",n.style.flexDirection="column",n.style.alignItems="stretch",n.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.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((I=(T=s==null?void 0:s.launcher)==null?void 0:T.zIndex)!=null?I:vn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(e.style.display="flex",e.style.flexDirection="column",e.style.width="100%",e.style.height="100%",e.style.minHeight="0",e.style.minWidth="0",e.style.flex="1 1 auto",e.style.alignItems="stretch",e.style.transform="none",e.style.marginLeft="0",e.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(n.removeAttribute("data-persona-dock-mobile-fullscreen"),Pg(r),wb(r,i.maxHeight),i.reveal==="overlay"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="overlay",wl(e),vl(r),xl(t),fi(o,r);let M=i.animate?"transform 180ms ease":"none",P=i.side==="right"?"translateX(100%)":"translateX(-100%)",C=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=M,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"){n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="hidden",n.dataset.personaDockReveal="push",vl(r),Cl(r),fi(o,r);let M=vb(i.width,n.clientWidth),P=Math.max(0,n.clientWidth),C=i.animate?"margin-left 180ms ease":"none",k=i.side==="right"?a?-M:0:a?0:-M;e.style.display="flex",e.style.flexDirection="row",e.style.flex="0 0 auto",e.style.minHeight="0",e.style.minWidth="0",e.style.alignItems="stretch",e.style.height="100%",e.style.width=`${P+M}px`,e.style.transition=C,e.style.marginLeft=`${k}px`,e.style.transform="",t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${P}px`,t.style.maxWidth=`${P}px`,t.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{n.style.display="flex",n.style.flexDirection="row",n.style.alignItems="stretch",n.style.overflow="",wl(e),Cl(r),xl(t),fi(o,r);let M=i.reveal==="emerge";M?n.dataset.personaDockReveal="emerge":n.removeAttribute("data-persona-dock-reveal");let P=a?i.width:"0px",C=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",k=!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",xb(r,i.maxHeight),r.style.overflow=M||k?"hidden":"visible",r.style.transition=C,M&&(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")}},Tb=(n,e)=>{let t=n.ownerDocument.createElement("div");return Lg(t,e),n.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Lg(t,r)},destroy(){t.remove()}}},Eb=(n,e)=>{var I,M,P,C;let{ownerDocument:t}=n,r=n.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=n.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=n.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),c=t.createElement("aside"),p=t.createElement("div"),g=(M=(I=e==null?void 0:e.launcher)==null?void 0:I.enabled)==null||M?(C=(P=e==null?void 0:e.launcher)==null?void 0:P.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,n),d.appendChild(n);let h=null,m=()=>{h==null||h.disconnect(),h=null},y=()=>{m(),gr(e).reveal==="push"&&typeof ResizeObserver!="undefined"&&(h=new ResizeObserver(()=>{Ig(a,i,d,c,p,e,g)}),h.observe(a))},w=!1,E=()=>{Ig(a,i,d,c,p,e,g),y(),g&&!w&&a.dataset.personaDockMobileFullscreen!=="true"&&(w=!0,Cb(a,gr(e)))},B=a.ownerDocument.defaultView,T=()=>{E()};return B==null||B.addEventListener("resize",T),gr(e).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),E(),{mode:"docked",host:p,shell:a,syncWidgetState(k){let q=k.launcherEnabled?k.open:!0;g!==q&&(g=q,E())},updateConfig(k){var q,_;e=k,((_=(q=e==null?void 0:e.launcher)==null?void 0:q.enabled)!=null?_:!0)===!1&&(g=!0),E()},destroy(){B==null||B.removeEventListener("resize",T),m(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(n,s):r.appendChild(n)),a.remove()}}},Rg=(n,e)=>gn(e)?Eb(n,e):Tb(n,e);var fa={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Wg=.15,Hg=1.5,Al="persona-preview-shell-theme",Mb={load:()=>null,save:()=>{},clear:()=>{}},kb=["How do I get started?","Pricing & plans","Talk to support"];function Sl(n){return n.replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function Lb(n){return n==="dark"?{pageBg:"linear-gradient(180deg, #0f172a 0%, #020617 100%)",chromeBg:"#111827",chromeBorder:"#1f2937",dot:"#475569",skeleton:"#334155",cardBg:"#1e293b",cardBorder:"rgba(148, 163, 184, 0.16)"}:{pageBg:"linear-gradient(180deg, #ffffff 0%, #f8fafc 100%)",chromeBg:"#ffffff",chromeBorder:"#e5e7eb",dot:"#cbd5e1",skeleton:"#e2e8f0",cardBg:"#e2e8f0",cardBorder:"rgba(148, 163, 184, 0.18)"}}function Bg(n){let e=Lb(n);return`* { box-sizing: border-box; }
|
|
112
112
|
html, body { margin: 0; padding: 0; height: 100%; overflow: hidden; }
|
|
113
|
-
html { color-scheme: ${
|
|
113
|
+
html { color-scheme: ${n}; }
|
|
114
114
|
body { font-family: system-ui, sans-serif; background: ${e.pageBg}; }
|
|
115
115
|
.preview-iframe-mock { min-height: 100%; }
|
|
116
116
|
.preview-iframe-chrome { height: 44px; border-bottom: 1px solid ${e.chromeBorder}; background: ${e.chromeBg}; display: flex; align-items: center; gap: 8px; padding: 0 14px; }
|
|
@@ -132,7 +132,7 @@ _Details: ${n.message}_`:r}var js=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
132
132
|
.preview-workspace-content-shell { position: relative; z-index: 1; flex: 1 1 auto; min-height: 100%; padding: 24px; }
|
|
133
133
|
.preview-workspace-row { display: flex; gap: 16px; margin-top: 20px; }
|
|
134
134
|
.preview-workspace-card { flex: 1; min-width: 0; height: 168px; border-radius: 18px; background: ${e.cardBg}; box-shadow: inset 0 0 0 1px ${e.cardBorder}; }
|
|
135
|
-
.preview-workspace-card.short { height: 96px; }`}function
|
|
135
|
+
.preview-workspace-card.short { height: 96px; }`}function Dg(n,e){let t=n.contentDocument;if(!(t!=null&&t.documentElement))return;let r=t.getElementById(Al);r||(r=t.createElement("style"),r.id=Al,t.head.appendChild(r)),r.textContent=Bg(e)}var Pb=`
|
|
136
136
|
<div class="preview-iframe-mock" aria-hidden="true">
|
|
137
137
|
<div class="preview-iframe-chrome">
|
|
138
138
|
<span class="preview-iframe-dot"></span>
|
|
@@ -151,7 +151,7 @@ _Details: ${n.message}_`:r}var js=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
151
151
|
<div class="preview-iframe-line body"></div>
|
|
152
152
|
<div class="preview-iframe-line body"></div>
|
|
153
153
|
</div>
|
|
154
|
-
</div>`,
|
|
154
|
+
</div>`,Ib=`
|
|
155
155
|
<div class="preview-workspace-content-shell" aria-hidden="true">
|
|
156
156
|
<div class="preview-iframe-line hero"></div>
|
|
157
157
|
<div class="preview-iframe-line body"></div>
|
|
@@ -164,9 +164,9 @@ _Details: ${n.message}_`:r}var js=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
164
164
|
<div class="preview-workspace-card short"></div>
|
|
165
165
|
<div class="preview-workspace-card short"></div>
|
|
166
166
|
</div>
|
|
167
|
-
</div>`;function
|
|
168
|
-
${
|
|
169
|
-
<div style="position:fixed;inset:0;z-index:9999;"><div id="${
|
|
167
|
+
</div>`;function Ng(n,e,t,r){let o=`
|
|
168
|
+
${Pb}
|
|
169
|
+
<div style="position:fixed;inset:0;z-index:9999;"><div id="${n}" data-mount-id="${n}"></div></div>`,s=`
|
|
170
170
|
<div class="preview-workspace-shell">
|
|
171
171
|
<div class="preview-workspace-topbar">
|
|
172
172
|
<div class="preview-workspace-topbar-left">
|
|
@@ -176,8 +176,8 @@ _Details: ${n.message}_`:r}var js=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
176
176
|
<span class="preview-workspace-topbar-pill"></span>
|
|
177
177
|
</div>
|
|
178
178
|
<div class="preview-workspace-body">
|
|
179
|
-
<div id="preview-content-${
|
|
180
|
-
${
|
|
179
|
+
<div id="preview-content-${n}" class="preview-workspace-content" data-mount-id="${n}">
|
|
180
|
+
${Ib}
|
|
181
181
|
</div>
|
|
182
182
|
</div>
|
|
183
183
|
</div>`;return`<!DOCTYPE html>
|
|
@@ -185,16 +185,16 @@ _Details: ${n.message}_`:r}var js=t=>({isError:!0,content:[{type:"text",text:t}]
|
|
|
185
185
|
<head>
|
|
186
186
|
<meta charset="UTF-8">
|
|
187
187
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
188
|
-
<link rel="stylesheet" href="${
|
|
189
|
-
<style id="${
|
|
188
|
+
<link rel="stylesheet" href="${Sl(r)}">
|
|
189
|
+
<style id="${Al}">${Bg(e)}</style>
|
|
190
190
|
</head>
|
|
191
191
|
<body>
|
|
192
|
-
${
|
|
192
|
+
${t?s:o}
|
|
193
193
|
</body>
|
|
194
|
-
</html>`}var
|
|
195
|
-
${
|
|
196
|
-
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${
|
|
197
|
-
</div>`,
|
|
194
|
+
</html>`}var Rb=()=>[{id:"preview-adv-1",role:"user",content:"Can you create the product and gather the docs?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-adv-2",role:"assistant",content:"",createdAt:new Date(Date.now()-15e4).toISOString(),streaming:!0,variant:"reasoning",reasoning:{id:"preview-reasoning",status:"streaming",chunks:["Now let me get the Persona embed documentation and builtin tools catalog."]}},{id:"preview-adv-3",role:"assistant",content:"",createdAt:new Date(Date.now()-12e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-1",name:"Load tools",status:"running",chunks:["Loaded tools, used Runtype integration"]}},{id:"preview-adv-4",role:"assistant",content:"",createdAt:new Date(Date.now()-9e4).toISOString(),streaming:!0,variant:"tool",toolCall:{id:"preview-tool-2",name:"Get platform documentation",status:"running",chunks:["Get platform documentation"]}},{id:"preview-adv-5",role:"assistant",content:"I loaded the tools and fetched the docs. Next I can assemble the product details.",createdAt:new Date(Date.now()-3e4).toISOString()}],Wb=n=>{var e,t,r,o,s,a,i,d;return!!((t=(e=n==null?void 0:n.features)==null?void 0:e.toolCallDisplay)!=null&&t.activePreview||(o=(r=n==null?void 0:n.features)==null?void 0:r.toolCallDisplay)!=null&&o.grouped||(a=(s=n==null?void 0:n.features)==null?void 0:s.toolCallDisplay)!=null&&a.collapsedMode&&n.features.toolCallDisplay.collapsedMode!=="tool-call"||(d=(i=n==null?void 0:n.features)==null?void 0:i.reasoningDisplay)!=null&&d.activePreview)};function Hb(n,e,t=[]){return n==="home"?[{id:"preview-home-1",role:"assistant",content:"Hi there! How can we help today?",createdAt:new Date().toISOString()}]:n==="minimized"?[{id:"preview-min-1",role:"assistant",content:"We are here whenever you are ready.",createdAt:new Date().toISOString()}]:n==="artifact"?[{id:"preview-art-1",role:"user",content:"Can you draft a quick overview of the project?",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-art-2",role:"assistant",content:"Here\u2019s a project overview document for you.",createdAt:new Date(Date.now()-6e4).toISOString()}]:n==="conversation"&&Wb(e)?[...Rb(),...t]:[{id:"preview-conv-1",role:"assistant",content:"Hello! How can I help you today?",createdAt:new Date(Date.now()-18e4).toISOString()},{id:"preview-conv-2",role:"user",content:"I want to customize the theme editor preview.",createdAt:new Date(Date.now()-12e4).toISOString()},{id:"preview-conv-3",role:"assistant",content:"Absolutely. Check out the [getting started guide](https://example.com) to see what\u2019s possible, then adjust colors and tokens to match your brand.",createdAt:new Date(Date.now()-6e4).toISOString()},...t]}function Bb(n,e,t=[]){var s,a;let r={...n.launcher,enabled:!0,autoExpand:e!=="minimized"},o={...n,launcher:r,suggestionChips:e==="home"?(s=n.suggestionChips)!=null&&s.length?n.suggestionChips:kb:n.suggestionChips,initialMessages:Hb(e,n,t),storageAdapter:Mb};return e==="artifact"&&(o.features={...o.features,artifacts:{...(a=o.features)==null?void 0:a.artifacts,enabled:!0}}),o}function Db(n,e){var r,o;let t=n.theme?qo(n.theme,{validate:!1}):qo();return{...Bt,...n.config,theme:t,darkTheme:n.darkTheme,colorScheme:(o=e!=null?e:(r=n.config)==null?void 0:r.colorScheme)!=null?o:"light"}}function Ms(n,e){var r,o;let t=(r=n.scene)!=null?r:"conversation";return Bb(Db(n,e),t,(o=n.appendedMessages)!=null?o:[])}function Fg(n){var r,o,s,a,i;let e=(r=n.compareMode)!=null?r:"off",t=(o=n.shellMode)!=null?o:"light";if(e==="themes")return[{mountId:"preview-light",label:"Light",config:Ms(n,"light"),shellMode:"light"},{mountId:"preview-dark",label:"Dark",config:Ms(n,"dark"),shellMode:"dark"}];if(e==="baseline"&&(n.baselineConfig||n.baselineTheme)){let d={...n,config:(s=n.baselineConfig)!=null?s:n.config,theme:(a=n.baselineTheme)!=null?a:n.theme,darkTheme:(i=n.baselineDarkTheme)!=null?i:n.darkTheme};return[{mountId:"preview-baseline",label:"Baseline",config:Ms(d,t),shellMode:t},{mountId:"preview-current",label:"Current",config:Ms(n,t),shellMode:t}]}return[{mountId:"preview-current",label:"Current",config:Ms(n,t),shellMode:t}]}function Og(n,e){let t={...e},r=[],o=[],s=null,a=!1,i=1,d=1,c=0;function p(){var T;return(T=t.device)!=null?T:"desktop"}function g(){var T;return(T=t.zoom)!=null?T:i}function h(){var R,O;let T=getComputedStyle(n),I=parseFloat(T.paddingLeft)+parseFloat(T.paddingRight),M=parseFloat(T.paddingTop)+parseFloat(T.paddingBottom),P=40,C=((R=t.compareMode)!=null?R:"off")!=="off",k=(n.clientWidth-I-P)/(C?2:1),q=n.clientHeight-M-P;if(k<=0||q<=0)return 1;let _=(O=fa[p()])!=null?O:fa.desktop;return Math.min(k/_.w,q/_.h,1)}function m(){var M,P,C;i=h();let T=Math.max(Wg,Math.min(Hg,g()));d=T;let I=Array.from(n.querySelectorAll(".preview-iframe-wrapper"));for(let k of I){let q=(M=k.dataset.device)!=null?M:"desktop",_=(P=fa[q])!=null?P:fa.desktop;k.style.width=`${_.w*T}px`,k.style.height=`${_.h*T}px`,q==="mobile"&&(k.style.borderRadius=`${32*T}px`);let R=k.querySelector("iframe");R&&(R.style.width=`${_.w}px`,R.style.height=`${_.h}px`,R.style.transformOrigin="top left",R.style.transition="none",R.style.transform=`scale(${T})`)}(C=t.onScaleChange)==null||C.call(t,T)}function y(){var T;(T=t.onBeforeDestroy)==null||T.call(t);for(let I of r)I.destroy();for(let I of o)I();r=[],o=[]}function w(){return Array.from(n.querySelectorAll("iframe[data-mount-id]"))}function E(){var ee,Pe,Ie,ie;if(a)return;y();let T=++c,I=Fg(t),M=p(),P=((ee=t.compareMode)!=null?ee:"off")!=="off",C=((Pe=t.scene)!=null?Pe:"conversation")==="minimized",k=(Ie=t.widgetCssPath)!=null?Ie:"/widget-dist/widget.css",q=(ie=t.buildSrcdoc)!=null?ie:Ng,_=M==="mobile"?"preview-iframe-wrapper preview-iframe-wrapper-mobile":"preview-iframe-wrapper",R=he=>`<div class="${_}" data-mount-id="${he.mountId}" data-device="${M}" data-shell-mode="${he.shellMode}">
|
|
195
|
+
${P?`<div class="preview-frame-meta"><span class="preview-frame-label">${Sl(he.label)}</span></div>`:""}
|
|
196
|
+
<iframe class="preview-iframe" sandbox="allow-scripts allow-same-origin" data-mount-id="${he.mountId}"></iframe>
|
|
197
|
+
</div>`,O=P?`<div class="preview-compare-grid">${I.map(he=>`<div class="preview-compare-cell">${R(he)}</div>`).join("")}</div>`:`<div class="preview-single">${R(I[0])}</div>`;t.morphContainer?t.morphContainer(n,O):n.innerHTML=O,m();let F=w(),Z=0,ke=F.length,pe=()=>{var re,oe,de,Ae,$e;if(a||T!==c)return;for(let K of F){let J=K.dataset.mountId;if(!J||!K.contentDocument)continue;let Se=I.find(tt=>tt.mountId===J);if(!Se)continue;let Y=()=>{},le=gn(Se.config),Te=le?(()=>{var X;let tt=(X=K.contentDocument)==null?void 0:X.getElementById(`preview-content-${J}`);if(!tt)return null;let Wt=Rg(tt,Se.config),ht=K.contentDocument.createElement("div");ht.id=J,ht.style.height="100%",ht.style.display="flex",ht.style.flexDirection="column",ht.style.flex="1",ht.style.minHeight="0",Wt.host.appendChild(ht);let ot=()=>Wt.syncWidgetState(Ye.getState()),me=Y;return Y=()=>{Wt.destroy(),me()},ht.__syncDock=ot,ht.__hostLayout=Wt,ht})():K.contentDocument.getElementById(J);if(!Te)continue;let Ye=kg(Te,Se.config);if(r.push(Ye),le&&Te.__syncDock){let tt=Te.__syncDock,Wt=Ye.on("widget:opened",tt),ht=Ye.on("widget:closed",tt),ot=Y;Y=()=>{Wt(),ht(),ot()},tt()}o.push(Y),C&&Ye.close()}if(((re=t.scene)!=null?re:"conversation")==="artifact"||(Ae=(de=(oe=t.config)==null?void 0:oe.features)==null?void 0:de.artifacts)!=null&&Ae.enabled)for(let K of r)K.upsertArtifact({id:"preview-sample",artifactType:"markdown",title:"Sample Document",content:`# Sample Artifact
|
|
198
198
|
|
|
199
199
|
This is a preview of the artifact sidebar.
|
|
200
200
|
|
|
@@ -202,4 +202,4 @@ This is a preview of the artifact sidebar.
|
|
|
202
202
|
|
|
203
203
|
- Markdown rendering
|
|
204
204
|
- Document toolbar
|
|
205
|
-
- Resizable panes`});(
|
|
205
|
+
- Resizable panes`});($e=t.onAfterMount)==null||$e.call(t,{iframes:F,controllers:[...r]})};for(let he of F){let re=he.dataset.mountId;if(!re)continue;let oe=I.find(de=>de.mountId===re);oe&&(he.addEventListener("load",()=>{Z++,Z>=ke&&pe()},{once:!0}),he.srcdoc=q(re,oe.shellMode,gn(oe.config),k))}ke===0&&pe()}function B(){var M;if(a)return;let T=Fg(t);if(r.length!==T.length){E();return}if(T.some(P=>{let C=n.querySelector(`.preview-iframe-wrapper[data-mount-id="${P.mountId}"]`);return!C||C.dataset.shellMode!==P.shellMode})){E();return}r.forEach((P,C)=>{var k;P.update(T[C].config),((k=t.scene)!=null?k:"conversation")==="minimized"&&P.close()});for(let P of T){let C=n.querySelector(`iframe[data-mount-id="${P.mountId}"]`);C&&Dg(C,P.shellMode)}(M=t.onAfterUpdate)==null||M.call(t,{iframes:w(),controllers:[...r]})}return typeof ResizeObserver!="undefined"&&(s=new ResizeObserver(()=>{a||m()}),s.observe(n)),E(),{update(T){if(a)return;let I=T.device!==void 0&&T.device!==t.device||T.scene!==void 0&&T.scene!==t.scene||T.compareMode!==void 0&&T.compareMode!==t.compareMode||T.widgetCssPath!==void 0&&T.widgetCssPath!==t.widgetCssPath;t={...t,...T},I?E():B()},destroy(){a||(a=!0,y(),s==null||s.disconnect(),n.innerHTML="")},getControllers(){return[...r]},fitToContainer(){a||(t={...t,zoom:void 0},m())},getIframes(){return w()},getScale(){return d},setZoom(T){a||(t={...t,zoom:T},m())}}}0&&(module.exports={createThemePreview});
|