@runtypelabs/persona 4.5.0 → 4.6.1

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.
Files changed (42) hide show
  1. package/dist/animations/glyph-cycle.d.cts +1 -1
  2. package/dist/animations/glyph-cycle.d.ts +1 -1
  3. package/dist/animations/{types-C6tFDxKy.d.cts → types-CSmiKRVa.d.cts} +11 -0
  4. package/dist/animations/{types-C6tFDxKy.d.ts → types-CSmiKRVa.d.ts} +11 -0
  5. package/dist/animations/wipe.d.cts +1 -1
  6. package/dist/animations/wipe.d.ts +1 -1
  7. package/dist/chunk-DFBSCFYN.js +1 -0
  8. package/dist/codegen.cjs +4 -4
  9. package/dist/codegen.js +4 -4
  10. package/dist/index.cjs +51 -51
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +238 -3
  13. package/dist/index.d.ts +238 -3
  14. package/dist/index.global.js +37 -37
  15. package/dist/index.global.js.map +1 -1
  16. package/dist/index.js +51 -51
  17. package/dist/index.js.map +1 -1
  18. package/dist/launcher.global.js.map +1 -1
  19. package/dist/markdown-parsers-entry-NVFT3TE6.js +1 -0
  20. package/dist/runtype-tts-entry-HFUV2UF7.js +1 -0
  21. package/dist/session-reconnect-U77QFUR7.js +1 -0
  22. package/dist/smart-dom-reader.d.cts +95 -0
  23. package/dist/smart-dom-reader.d.ts +95 -0
  24. package/dist/theme-editor-preview.cjs +48 -48
  25. package/dist/theme-editor-preview.d.cts +135 -1
  26. package/dist/theme-editor-preview.d.ts +135 -1
  27. package/dist/theme-editor-preview.js +48 -48
  28. package/dist/theme-editor.d.cts +95 -0
  29. package/dist/theme-editor.d.ts +95 -0
  30. package/package.json +5 -3
  31. package/src/client.ts +55 -9
  32. package/src/generated/runtype-openapi-contract.ts +16 -1
  33. package/src/reconnect-wake.test.ts +162 -0
  34. package/src/reconnect.test.ts +430 -0
  35. package/src/session-reconnect.ts +282 -0
  36. package/src/session.ts +408 -5
  37. package/src/types.ts +107 -1
  38. package/src/ui.stream-animation-update.test.ts +99 -0
  39. package/src/ui.ts +71 -1
  40. package/src/utils/constants.ts +3 -1
  41. package/src/utils/morph.test.ts +47 -0
  42. package/src/utils/morph.ts +18 -0
package/dist/index.js CHANGED
@@ -1,22 +1,22 @@
1
- var Xf=Object.defineProperty;var Gs=(e,t)=>()=>(e&&(t=e(e=0)),t);var Wu=(e,t)=>{for(var n in t)Xf(e,n,{get:t[n],enumerable:!0})};var Hu={};Wu(Hu,{DOMPurify:()=>Yf,Marked:()=>Qf});import{Marked as Qf}from"marked";import Yf from"dompurify";var Bu=Gs(()=>{"use strict"});var As,ll=Gs(()=>{"use strict";As=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var o;this.sampleRate=t;let r=Math.max(0,(o=n.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(t*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let o=new Uint8Array(this.remainder.length+t.length);o.set(this.remainder),o.set(t,this.remainder.length),n=o,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.pcmToFloat32(n);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),r=n.createBuffer(1,t.length,this.sampleRate);r.getChannelData(0).set(t);let o=n.createBufferSource();o.buffer=r,o.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),o.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(o),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}o.onended=()=>{let a=this.activeSources.indexOf(o);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function by(e){return e.replace(/\/+$/,"")}async function xy(e){var t,n;try{let r=await e.json();return r.detail?`${(t=r.error)!=null?t:`Runtype TTS ${e.status}`}: ${r.detail}`:(n=r.error)!=null?n:`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Xa,Pm=Gs(()=>{"use strict";ll();Xa=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var t,n;return(n=this.playerPromise)!=null?n:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new As(24e3,{prebufferMs:(t=this.opts.prebufferMs)!=null?t:200})).then(r=>this.player=r)}speak(t,n){let r=++this.generation;this.run(r,t,n)}async run(t,n,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(t!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var g;t===this.generation&&((g=r.onStart)==null||g.call(r))}),d.onFinished(()=>{var g;t===this.generation&&((g=r.onEnd)==null||g.call(r))});let l=`${by(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,p=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:(o=n.voice)!=null?o:this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!p.ok||!p.body)throw new Error(await xy(p));let u=p.body.getReader();for(;;){let{done:g,value:f}=await u.read();if(t!==this.generation){await u.cancel().catch(()=>{});return}if(g)break;f&&f.byteLength>0&&d.enqueue(f)}d.markStreamEnd()}catch(d){if(t!==this.generation)return;let l=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,l),(i=r.onError)==null||i.call(r,l)}}pause(){var t;(t=this.player)==null||t.pause()}resume(){var t;(t=this.player)==null||t.resume()}stop(){var t;this.generation++,(t=this.player)==null||t.flush()}destroy(){var t;this.generation++,(t=this.player)==null||t.destroy(),this.player=null,this.playerPromise=null}}});var Qa,Im=Gs(()=>{"use strict";Qa=class{constructor(t,n,r={}){this.primary=t;this.fallback=n;this.options=r;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let r=!1;this.primary.speak(t,{onStart:()=>{var o;r=!0,(o=n.onStart)==null||o.call(n)},onEnd:()=>{var o;return(o=n.onEnd)==null?void 0:o.call(n)},onError:o=>{var s,a,i;if(r){(s=n.onError)==null||s.call(n,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var t,n,r,o;(n=(t=this.primary).destroy)==null||n.call(t),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var Rm={};Wu(Rm,{FallbackSpeechEngine:()=>Qa,RuntypeSpeechEngine:()=>Xa});var Wm=Gs(()=>{"use strict";Pm();Im()});import{Marked as Zf}from"marked";import eh from"dompurify";var Du=null,ys=null,hs=null;var Nu=e=>{ys=e},Ou=()=>ys?Promise.resolve(ys):hs||(Du?(hs=Du().then(e=>(ys=e,e)),hs):(hs=Promise.resolve().then(()=>(Bu(),Hu)).then(e=>(ys=e,e)),hs)),Vo=()=>ys;Nu({Marked:Zf,DOMPurify:eh});var th=e=>{if(e)return e},Wa=e=>{let t=null;return n=>{var o,s;let r=Vo();if(!r)return Yr(n);if(!t){let{Marked:a}=r,i=e==null?void 0:e.markedOptions;t=new a({gfm:(o=i==null?void 0:i.gfm)!=null?o:!0,breaks:(s=i==null?void 0:i.breaks)!=null?s:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=th(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},bs=e=>e?Wa({markedOptions:e.options,renderer:e.renderer}):Wa(),nh=Wa(),_u=e=>nh(e),Yr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),$u=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Fu=e=>`%%FORM_PLACEHOLDER_${e}%%`,ju=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Fu(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=Fu(t.length);return t.push({token:s,type:o}),s}),n},rh=e=>{let t=bs(e);return n=>{let r=[],o=ju(n,r),s=t(o);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${$u(i)}"></div>`;s=s.replace(d,p)}),s}},oh=e=>{let t=[],n=ju(e,t),r=_u(n);return t.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${$u(s)}"></div>`;r=r.replace(a,d)}),r};var sh={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"]},ah=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Uu=()=>{let e=null;return t=>{let n=Vo();if(!n)return Yr(t);if(!e){let{DOMPurify:r}=n;e=r(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!ah.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,sh)}},Js=e=>e===!1?null:typeof e=="function"?e:Uu();var qu=/^\s*\|?[\s:|-]*-[\s:|-]*$/,zu=e=>e.includes("|"),Vu=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},ih=e=>`| ${e.join(" | ")} |`,lh=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,ch=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Ku=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
- `),n=!1;for(let r=0;r<t.length-1;r++){let o=t[r],s=t[r+1];if(!zu(o)||qu.test(o)||!qu.test(s))continue;let a=Vu(o).length;if(a<1)continue;let i=lh(a);t[r+1]!==i&&(t[r+1]=i,n=!0);let d=r+2;for(;d<t.length;d++){let l=t[d];if(l.trim()===""||!zu(l))break;let p=ih(ch(Vu(l),a));t[d]!==p&&(t[d]=p,n=!0)}r=d-1}return n?t.join(`
3
- `):e};var Dr="webmcp:",Vi=new Map,Gu=e=>{var t;Vi.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&Vi.set(n.name,r)}},Qs=e=>Vi.get(Ki(e)),Ha={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Ju=null;function Qu(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,o;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(o=n.origin)!=null?o:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${dh(t.join(""))}`}function Xu(e,t){let n=3735928559^t,r=1103547991^t;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);n=Math.imul(n^s,2654435761),r=Math.imul(r^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function dh(e){let t=Xu(e,0).toString(36),n=Xu(e,2654435761).toString(36);return`${t}.${n}`}var Xs=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(o){return Ha.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}Gu(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=uh(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return hr("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let v=typeof document!="undefined"&&!!document.modelContext;return hr(v?"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=Ki(t),a;try{a=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return hr(`Failed to read WebMCP registry: ${x}`)}Gu(a);let i=a.find(v=>v.name===s);if(!i)return hr(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return hr(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let d=Qs(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return hr("User declined the tool call.");if(r!=null&&r.aborted)return hr("Aborted by cancel()");let p=new AbortController,u=!1,g=setTimeout(()=>{u=!0,p.abort()},this.timeoutMs),f=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",f,{once:!0}));try{let v=await o.executeTool(i,hh(n),{signal:p.signal});return mh(v)}catch(v){if(u)return hr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return hr("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return hr(x)}finally{clearTimeout(g),r&&r.removeEventListener("abort",f)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(Ju?await Ju():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ha.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Ha.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var r;let n=(r=this.confirmHandler)!=null?r:gh;try{return await n(t)}catch(o){return Ha.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>ph(t,r))}},Ki=e=>e.startsWith(Dr)?e.slice(Dr.length):e,Ko=e=>e.startsWith(Dr),ph=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},uh=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},mh=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:yh(t)}]}},hr=e=>({isError:!0,content:[{type:"text",text:e}]}),gh=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=fh(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
1
+ var ih=Object.defineProperty;var ys=(e,t)=>()=>(e&&(t=e(e=0)),t);var Ki=(e,t)=>{for(var n in t)ih(e,n,{get:t[n],enumerable:!0})};var qu={};Ki(qu,{DOMPurify:()=>ch,Marked:()=>lh});import{Marked as lh}from"marked";import ch from"dompurify";var zu=ys(()=>{"use strict"});var Ss,dl=ys(()=>{"use strict";Ss=class{constructor(t=24e3,n={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var o;this.sampleRate=t;let r=Math.max(0,(o=n.prebufferMs)!=null?o:0);this.waterlineSamples=Math.round(t*r/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let o=new Uint8Array(this.remainder.length+t.length);o.set(this.remainder),o.set(t,this.remainder.length),n=o,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.pcmToFloat32(n);r.length!==0&&(this.buffering?(this.pendingBuffers.push(r),this.pendingSamples+=r.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(r))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let n of t)this.scheduleSamples(n)}scheduleSamples(t){if(t.length===0)return;let n=this.ensureContext(),r=n.createBuffer(1,t.length,this.sampleRate);r.getChannelData(0).set(t);let o=n.createBufferSource();o.buffer=r,o.connect(n.destination);let s=n.currentTime;if(this.nextStartTime===0?this.nextStartTime=s:this.nextStartTime<s&&(this.nextStartTime=s,this.waterlineSamples>0&&(this.buffering=!0)),o.start(this.nextStartTime),this.nextStartTime+=r.duration,this.activeSources.push(o),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let a=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of a)i()}o.onended=()=>{let a=this.activeSources.indexOf(o);a!==-1&&this.activeSources.splice(a,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}}});function Ly(e){return e.replace(/\/+$/,"")}async function Py(e){var t,n;try{let r=await e.json();return r.detail?`${(t=r.error)!=null?t:`Runtype TTS ${e.status}`}: ${r.detail}`:(n=r.error)!=null?n:`Runtype TTS request failed (${e.status})`}catch{return`Runtype TTS request failed (${e.status})`}}var Xa,_m=ys(()=>{"use strict";dl();Xa=class{constructor(t){this.opts=t;this.id="runtype-tts";this.supportsPause=!0;this.player=null;this.playerPromise=null;this.generation=0}ensurePlayer(){var t,n;return(n=this.playerPromise)!=null?n:this.playerPromise=Promise.resolve(this.opts.createPlaybackEngine?this.opts.createPlaybackEngine():new Ss(24e3,{prebufferMs:(t=this.opts.prebufferMs)!=null?t:200})).then(r=>this.player=r)}speak(t,n){let r=++this.generation;this.run(r,t,n)}async run(t,n,r){var o,s,a,i;try{let d=await this.ensurePlayer();if(t!==this.generation)return;d.flush(),d.resume(),d.onStarted(()=>{var f;t===this.generation&&((f=r.onStart)==null||f.call(r))}),d.onFinished(()=>{var f;t===this.generation&&((f=r.onEnd)==null||f.call(r))});let c=`${Ly(this.opts.host)}/v1/agents/${encodeURIComponent(this.opts.agentId)}/speak`,p=await fetch(c,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.opts.clientToken}`},body:JSON.stringify({text:n.text,voice:(o=n.voice)!=null?o:this.opts.voice,format:"pcm"})});if(t!==this.generation)return;if(!p.ok||!p.body)throw new Error(await Py(p));let u=p.body.getReader();for(;;){let{done:f,value:g}=await u.read();if(t!==this.generation){await u.cancel().catch(()=>{});return}if(f)break;g&&g.byteLength>0&&d.enqueue(g)}d.markStreamEnd()}catch(d){if(t!==this.generation)return;let c=d instanceof Error?d:new Error(String(d));(a=(s=this.opts).onError)==null||a.call(s,c),(i=r.onError)==null||i.call(r,c)}}pause(){var t;(t=this.player)==null||t.pause()}resume(){var t;(t=this.player)==null||t.resume()}stop(){var t;this.generation++,(t=this.player)==null||t.flush()}destroy(){var t;this.generation++,(t=this.player)==null||t.destroy(),this.player=null,this.playerPromise=null}}});var Qa,$m=ys(()=>{"use strict";Qa=class{constructor(t,n,r={}){this.primary=t;this.fallback=n;this.options=r;this.id="fallback";this.active=t}get supportsPause(){return this.active.supportsPause}speak(t,n){this.active=this.primary;let r=!1;this.primary.speak(t,{onStart:()=>{var o;r=!0,(o=n.onStart)==null||o.call(n)},onEnd:()=>{var o;return(o=n.onEnd)==null?void 0:o.call(n)},onError:o=>{var s,a,i;if(r){(s=n.onError)==null||s.call(n,o);return}(i=(a=this.options).onFallback)==null||i.call(a,o),this.active=this.fallback,this.fallback.speak(t,n)}})}pause(){this.active.pause()}resume(){this.active.resume()}stop(){this.active.stop()}destroy(){var t,n,r,o;(n=(t=this.primary).destroy)==null||n.call(t),(o=(r=this.fallback).destroy)==null||o.call(r)}}});var jm={};Ki(jm,{FallbackSpeechEngine:()=>Qa,RuntypeSpeechEngine:()=>Xa});var Um=ys(()=>{"use strict";_m();$m()});var zm={};Ki(zm,{createReconnectController:()=>Ry});function Ry(e){let t=0,n=null,r=null,o=!1,s=()=>{if(r&&(clearTimeout(r),r=null),n){let b=n;n=null,b()}},a=()=>{let b=e.getStatus();b!=="resuming"&&b!=="paused"||s()},i=()=>{typeof document!="undefined"&&document.visibilityState==="hidden"||a()},d=()=>{a()},c=()=>{o||(typeof document!="undefined"&&document.addEventListener("visibilitychange",i),typeof window!="undefined"&&window.addEventListener("online",d),o=!0)},p=()=>{o&&(typeof document!="undefined"&&document.removeEventListener("visibilitychange",i),typeof window!="undefined"&&window.removeEventListener("online",d),o=!1)},u=b=>new Promise(v=>{n=v,r=setTimeout(()=>{r=null,n=null,v()},b)}),f=()=>{var T;let b=e.getResumable();e.clearResumable(),e.setReconnecting(!1),t=0,p(),e.setAbortController(null);let v=!1;for(let L of e.getMessages())L.streaming&&(L.streaming=!1,v=!0);let S=e.buildErrorContent("Connection lost and the response could not be resumed.");S?e.appendMessage({id:`reconnect-failed-${(T=b==null?void 0:b.executionId)!=null?T:e.nextSequence()}`,role:"assistant",content:S,createdAt:new Date().toISOString(),streaming:!1,sequence:e.nextSequence()}):v&&e.notifyMessagesChanged(),e.setStreaming(!1),e.setStatus("idle"),e.onError(new Error("Durable session reconnect failed."))},g=async()=>{var T,L,P,E,k,C;let b=(L=(T=e.config.reconnect)==null?void 0:T.backoffMs)!=null?L:Iy,v=(E=(P=e.config.reconnect)==null?void 0:P.maxAttempts)!=null?E:b.length,S=e.config.reconnectStream;if(!S){e.setReconnecting(!1);return}for(;e.getResumable()&&t<v;){t+=1,e.setStatus("resuming");let I=e.getResumable(),j=I.lastEventId,$=new AbortController;e.setAbortController($),e.emitReconnect({phase:"resuming",handle:I,attempt:t});let R=null;try{let N=await S({executionId:I.executionId,after:I.lastEventId,signal:$.signal});N&&N.ok&&N.body&&(R=N.body)}catch{R=null}if($.signal.aborted)return;if(R){let N=(k=e.getMessages().find(Z=>Z.id===I.assistantMessageId))==null?void 0:k.content,O=typeof N=="string"?N:"";try{await e.resumeConnect(R,I.assistantMessageId,O)}catch{}if($.signal.aborted)return;if(!e.getResumable()){e.setReconnecting(!1),t=0,p(),e.emitReconnect({phase:"resumed",handle:I});return}e.getResumable().lastEventId!==j&&(t=0)}if(e.getResumable()&&t<v&&(e.setStatus("paused"),await u((C=b[Math.min(t-1,b.length-1)])!=null?C:1e3),$.signal.aborted))return}e.getResumable()&&f()};return{begin(){t=0,c(),g()},teardown(){r&&(clearTimeout(r),r=null),n=null,t=0,p()},wake:s}}var Iy,Vm=ys(()=>{"use strict";Iy=[1e3,2e3,4e3,8e3,8e3]});import{Marked as dh}from"marked";import ph from"dompurify";var Vu=null,xs=null,bs=null;var Ku=e=>{xs=e},Gu=()=>xs?Promise.resolve(xs):bs||(Vu?(bs=Vu().then(e=>(xs=e,e)),bs):(bs=Promise.resolve().then(()=>(zu(),qu)).then(e=>(xs=e,e)),bs)),Vo=()=>xs;Ku({Marked:dh,DOMPurify:ph});var uh=e=>{if(e)return e},Wa=e=>{let t=null;return n=>{var o,s;let r=Vo();if(!r)return Kr(n);if(!t){let{Marked:a}=r,i=e==null?void 0:e.markedOptions;t=new a({gfm:(o=i==null?void 0:i.gfm)!=null?o:!0,breaks:(s=i==null?void 0:i.breaks)!=null?s:!0,pedantic:i==null?void 0:i.pedantic,silent:i==null?void 0:i.silent});let d=uh(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},vs=e=>e?Wa({markedOptions:e.options,renderer:e.renderer}):Wa(),mh=Wa(),Xu=e=>mh(e),Kr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Qu=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Ju=e=>`%%FORM_PLACEHOLDER_${e}%%`,Yu=(e,t)=>{let n=e;return n=n.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Ju(t.length);return t.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),n=n.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=Ju(t.length);return t.push({token:s,type:o}),s}),n},gh=e=>{let t=vs(e);return n=>{let r=[],o=Yu(n,r),s=t(o);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Qu(i)}"></div>`;s=s.replace(d,p)}),s}},fh=e=>{let t=[],n=Yu(e,t),r=Xu(n);return t.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Qu(s)}"></div>`;r=r.replace(a,d)}),r};var hh={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},yh=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Zu=()=>{let e=null;return t=>{let n=Vo();if(!n)return Kr(t);if(!e){let{DOMPurify:r}=n;e=r(typeof window!="undefined"?window:void 0),e.addHook("uponSanitizeAttribute",(o,s)=>{if(s.attrName==="src"||s.attrName==="href"){let a=s.attrValue;a.toLowerCase().startsWith("data:")&&!yh.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,hh)}},Xs=e=>e===!1?null:typeof e=="function"?e:Zu();var em=/^\s*\|?[\s:|-]*-[\s:|-]*$/,tm=e=>e.includes("|"),nm=e=>{let t=e.trim();return t.startsWith("|")&&(t=t.slice(1)),t.endsWith("|")&&(t=t.slice(0,-1)),t.split("|").map(n=>n.trim())},bh=e=>`| ${e.join(" | ")} |`,xh=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,vh=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),rm=e=>{if(!e||!e.includes("|"))return e;let t=e.split(`
2
+ `),n=!1;for(let r=0;r<t.length-1;r++){let o=t[r],s=t[r+1];if(!tm(o)||em.test(o)||!em.test(s))continue;let a=nm(o).length;if(a<1)continue;let i=xh(a);t[r+1]!==i&&(t[r+1]=i,n=!0);let d=r+2;for(;d<t.length;d++){let c=t[d];if(c.trim()===""||!tm(c))break;let p=bh(vh(nm(c),a));t[d]!==p&&(t[d]=p,n=!0)}r=d-1}return n?t.join(`
3
+ `):e};var Rr="webmcp:",Gi=new Map,om=e=>{var t;Gi.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&Gi.set(n.name,r)}},Ys=e=>Gi.get(Ji(e)),Ha={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},sm=null;function im(e){if(e.length===0)return"0:empty";let t=e.map(n=>{var r,o;return[n.name,(r=n.description)!=null?r:"",n.parametersSchema?JSON.stringify(n.parametersSchema):"",(o=n.origin)!=null?o:"",n.annotations?JSON.stringify(n.annotations):""].join("")}).sort();return`${e.length}:${wh(t.join(""))}`}function am(e,t){let n=3735928559^t,r=1103547991^t;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);n=Math.imul(n^s,2654435761),r=Math.imul(r^s,1597334677)}return n=Math.imul(n^n>>>16,2246822507),n^=Math.imul(r^r>>>13,3266489909),r=Math.imul(r^r>>>16,2246822507),r^=Math.imul(n^n>>>13,3266489909),4294967296*(2097151&r)+(n>>>0)}function wh(e){let t=am(e,0).toString(36),n=am(e,2654435761).toString(36);return`${t}.${n}`}var Qs=class{constructor(t){this.config=t;this.installed=!1;this.readyPromise=null;this.incompatibleContextWarned=!1;var n;this.confirmHandler=(n=t.onConfirm)!=null?n:null,this.timeoutMs=3e4}setConfirmHandler(t){this.confirmHandler=t}isOperational(){return this.config.enabled!==!0||!this.installed?!1:this.getModelContext()!==null}async snapshotForDispatch(){if(await this.ensureReady(),this.config.enabled!==!0)return[];let t=this.getModelContext();if(!t)return[];let n;try{n=await t.getTools()}catch(o){return Ha.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}om(n);let r=typeof location!="undefined"?location.origin:"";return n.filter(o=>this.passesClientAllowlist(o.name)).map(o=>{let s={name:o.name,description:o.description,origin:"webmcp",...r?{pageOrigin:r}:{}},a=Ah(o.inputSchema);return a&&(s.parametersSchema=a),s})}async executeToolCall(t,n,r){if(await this.ensureReady(),this.config.enabled!==!0)return gr("WebMCP is not enabled on this widget.");let o=this.getModelContext();if(!o){let b=typeof document!="undefined"&&!!document.modelContext;return gr(b?"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=Ji(t),a;try{a=await o.getTools()}catch(b){let v=b instanceof Error?b.message:String(b);return gr(`Failed to read WebMCP registry: ${v}`)}om(a);let i=a.find(b=>b.name===s);if(!i)return gr(`WebMCP tool not registered on this page: ${s}`);if(!this.passesClientAllowlist(s))return gr(`WebMCP tool not allowed by client allowlist: ${s}`);if(r!=null&&r.aborted)return gr("Aborted by cancel()");let d=Ys(s),c={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(c))return gr("User declined the tool call.");if(r!=null&&r.aborted)return gr("Aborted by cancel()");let p=new AbortController,u=!1,f=setTimeout(()=>{u=!0,p.abort()},this.timeoutMs),g=()=>p.abort();r&&(r.aborted?p.abort():r.addEventListener("abort",g,{once:!0}));try{let b=await o.executeTool(i,Mh(n),{signal:p.signal});return Sh(b)}catch(b){if(u)return gr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return gr("Aborted by cancel()");let v=b instanceof Error?b.message:String(b);return gr(v)}finally{clearTimeout(f),r&&r.removeEventListener("abort",g)}}ensureReady(){return this.config.enabled!==!0?Promise.resolve():(this.readyPromise||(this.readyPromise=this.install()),this.readyPromise)}async install(){try{if(this.getModelContext()){this.installed=!0;return}(sm?await sm():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){Ha.warn("Failed to load @mcp-b/webmcp-polyfill: WebMCP consumption disabled.",t),this.installed=!1}}getModelContext(){if(typeof document=="undefined")return null;let t=document.modelContext;if(!t||typeof t!="object")return null;let n=t;return typeof n.getTools!="function"||typeof n.executeTool!="function"?(this.incompatibleContextWarned||(this.incompatibleContextWarned=!0,Ha.warn("document.modelContext is present but does not expose getTools()/executeTool(): WebMCP consumption is disabled. Another (incompatible or older) WebMCP polyfill likely installed document.modelContext before Persona. Remove it, or use a polyfill implementing the strict standard surface (e.g. @mcp-b/webmcp-polyfill).")),null):t}async requestConfirm(t){var r;let n=(r=this.confirmHandler)!=null?r:Th;try{return await n(t)}catch(o){return Ha.warn(`Confirm handler threw for WebMCP tool '${t.toolName}'; declining.`,o),!1}}passesClientAllowlist(t){let n=this.config.allowlist;return!n||n.length===0?!0:n.some(r=>Ch(t,r))}},Ji=e=>e.startsWith(Rr)?e.slice(Rr.length):e,Ko=e=>e.startsWith(Rr),Ch=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Ah=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Sh=e=>{if(e==null)return{content:[{type:"text",text:""}]};let t;try{t=JSON.parse(e)}catch{return{content:[{type:"text",text:e}]}}return t!==null&&typeof t=="object"&&Array.isArray(t.content)?t:{content:[{type:"text",text:typeof t=="string"?t:kh(t)}]}},gr=e=>({isError:!0,content:[{type:"text",text:e}]}),Th=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Eh(e.args),n=`Allow the AI to call ${e.toolName}`+(t?`
4
4
 
5
5
  Arguments:
6
6
  ${t}`:"")+(e.description?`
7
7
 
8
- ${e.description}`:"");return window.confirm(n)},fh=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},hh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},yh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var bh="agent_",xh="flow_";function Yu(e){return e.startsWith(bh)?{kind:"agentId",agentId:e}:e.startsWith(xh)?{kind:"flowId",flowId:e}:null}function Zu(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let r=n.indexOf(":");if(r>0){let a=n.slice(0,r),i=n.slice(r+1);if(a==="runtype"){let l=Yu(i);if(l)return l;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=t==null?void 0:t[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(i).payload}}let o=Yu(n);if(o)return o;let s=t==null?void 0:t.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as vh,ARR as wh,OBJ as Ch,STR as Ah}from"partial-json";var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Nr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var At=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))r.setAttribute(s,a);if(t.style){let s=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=n.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Ys=(...e)=>e.filter(Boolean).join(" ");var Ba="ask_user_question",Zs=8,xs="data-persona-ask-sheet-for",Sh="Other",Th="Other\u2026",tm="Type your own answer here",nm="Send",Eh="Next",Mh="Back",kh="Submit all",Lh="Skip",Ph=3,Gi="data-ask-current-index",Ji="data-ask-question-count",rm="data-ask-answers",Xi="data-ask-grouped",om="data-ask-layout",Ih=e=>e.layout==="pills"?"pills":"rows",Rh=e=>e.getAttribute(om)==="pills"?"pills":"rows",em=!1,sm=e=>e.replace(/["\\]/g,"\\$&"),xo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ba,Da=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},vo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=vh(o,Ah|Ch|wh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ea=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>Zs&&!em&&(em=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${Zs}.`)),t.slice(0,Zs)},Wh=e=>{var t;return(t=ea(e)[0])!=null?t:null},Hh=(e,t)=>{var n;return(n=ea(e)[t])!=null?n:null},am=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},im=(e,t,n)=>{if(e!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let o=y("span","persona-ask-row-check");r.appendChild(o)}else{let o=y("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},Bh=(e,t,n,r)=>{let s=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=y("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=im(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Dh=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Nh=(e,t,n,r)=>{var p,u,g;let s=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!n){for(let f=0;f<Ph;f++)s.appendChild(Dh(r));return s}if(d.forEach((f,v)=>{s.appendChild(Bh(f,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let f=r==="rows"?Sh:Th;if(r==="rows"){let v=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=y("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=t.freeTextPlaceholder)!=null?p:tm,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:f),x.appendChild(E),v.appendChild(x);let T=im(r,a,d.length);T&&v.appendChild(T),s.appendChild(v)}else{let v=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(g=t.freeTextLabel)!=null?g:f,s.appendChild(v)}}return s},lm=(e,t)=>{var s,a;let r=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:tm,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:nm,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Oh=e=>{var r;let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:nm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Fh=(e,t,n)=>{var l,p,u,g;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=n.backLabel)!=null?l:Mh,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:Lh,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:kh:(g=n.nextLabel)!=null?g:Eh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Go=e=>{let t=e.getAttribute(rm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},cm=(e,t)=>{e.setAttribute(rm,JSON.stringify(t))},tr=e=>{var n;let t=Number((n=e.getAttribute(Gi))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},_h=(e,t)=>{e.setAttribute(Gi,String(Math.max(0,Math.floor(t))))},vs=e=>{var n;let t=Number((n=e.getAttribute(Ji))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},wo=e=>e.getAttribute(Xi)==="true",$h=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},jh=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Na=(e,t)=>{let{payload:n}=vo(t),r=ea(n),o=Go(e),s={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(s[l]=o[d]))}),s},dm=e=>{let t=Go(e),n=tr(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(l);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 l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},pm=e=>{if(!wo(e))return;let t=Go(e),n=tr(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Qi=(e,t,n)=>{let r=Da(n),o=Rh(e),{payload:s,complete:a}=vo(t),i=wo(e),d=tr(e),l=vs(e),p=i?Hh(s,d):Wh(s),u=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let L=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=L,v.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let L=Nh(p,r,a,o);x.replaceWith(L)}if(o!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(lm(r,o))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!E?e.appendChild(Oh(r)):(!u||i)&&E&&E.remove(),e.setAttribute("data-multi-select",u?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=Fh(d,l,r);T?T.replaceWith(L):e.appendChild(L)}else T&&T.remove();dm(e),pm(e)},Uh=(e,t,n)=>{let r=Da(t),o=Ih(r),s=e.toolCall.id,a=ea(n),i=Math.max(1,a.length),d=i>1,l=$h(e,a),p=d?jh(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(xs,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Ji,String(i)),u.setAttribute(Gi,String(p)),u.setAttribute(Xi,d?"true":"false"),u.setAttribute(om,o),cm(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),am(u,r);let g=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let v=y("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),u.appendChild(g);let E=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),u.appendChild(E),o!=="rows"&&u.appendChild(lm(r,o)),Qi(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},qh=(e,t,n)=>{let{payload:r}=vo(t),o=Math.max(1,ea(r).length);o>vs(e)&&(e.setAttribute(Ji,String(o)),o>1&&!wo(e)&&e.setAttribute(Xi,"true")),Qi(e,t,n)},zh=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=Da(t);am(n,r);let o=y("span","persona-ask-stub-label"),{complete:s}=vo(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},ta=(e,t,n)=>{if(!n||!xo(e)||Da(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${xs}]`).forEach(l=>{l.getAttribute(xs)!==o&&l.remove()});let a=n.querySelector(`[${xs}="${sm(o)}"]`);if(a){qh(a,e,t);return}let{payload:i}=vo(e),d=Uh(e,t,i);n.appendChild(d)},Jo=(e,t)=>{if(!e)return;let n=t?`[${xs}="${sm(t)}"]`:`[${xs}]`;e.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},Yi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),Co=(e,t)=>{let n=Go(e),r=tr(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,cm(e,n),dm(e),pm(e)},Oa=(e,t,n,r)=>{let o=vs(e),s=Math.max(0,Math.min(o-1,r));_h(e,s),Qi(e,t,n)};var Or="suggest_replies";var um={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},Zi={name:Or,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:um,origin:"sdk",annotations:{readOnlyHint:!0}},el=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Fa=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Or},mm=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},tl=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!Fa(r))continue;let o=mm((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},gm=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var fm={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:Zs,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},hm={name:Ba,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:fm,origin:"sdk",annotations:{readOnlyHint:!0}},_a=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(hm),gm(e)&&t.push(Zi),t};import{parse as ym,STR as bm,OBJ as xm}from"partial-json";var $a=e=>e.replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ao=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Vh=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},vm=e=>e.status==="complete"?Vh(e):e.status==="pending"?"Waiting":"",Kh=e=>{var o,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var wm=e=>e.status==="complete"?Kh(e):"Using tool...",ja=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},ra=e=>{var n,r,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ja(t)},Ua=e=>{var n,r,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ja(t)},nl=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=ra(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},qa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&na(r,n.slice(s,a.index),[]),a[1]!==void 0?na(r,a[1],["bold"]):a[2]!==void 0?na(r,a[2],["italic"]):a[3]!==void 0&&na(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&na(r,n.slice(s),[]),r},na=(e,t,n)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:n}),o<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Gh=()=>{let e=null,t=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
8
+ ${e.description}`:"");return window.confirm(n)},Eh=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Mh=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},kh=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Lh="agent_",Ph="flow_";function lm(e){return e.startsWith(Lh)?{kind:"agentId",agentId:e}:e.startsWith(Ph)?{kind:"flowId",flowId:e}:null}function cm(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let r=n.indexOf(":");if(r>0){let a=n.slice(0,r),i=n.slice(r+1);if(a==="runtype"){let c=lm(i);if(c)return c;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=t==null?void 0:t[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(i).payload}}let o=lm(n);if(o)return o;let s=t==null?void 0:t.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as Ih,ARR as Rh,OBJ as Wh,STR as Hh}from"partial-json";var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Wr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var Et=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))r.setAttribute(s,a);if(t.style){let s=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=n.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Zs=(...e)=>e.filter(Boolean).join(" ");var Ba="ask_user_question",ea=8,ws="data-persona-ask-sheet-for",Bh="Other",Dh="Other\u2026",pm="Type your own answer here",um="Send",Nh="Next",Oh="Back",Fh="Submit all",_h="Skip",$h=3,Xi="data-ask-current-index",Qi="data-ask-question-count",mm="data-ask-answers",Yi="data-ask-grouped",gm="data-ask-layout",jh=e=>e.layout==="pills"?"pills":"rows",Uh=e=>e.getAttribute(gm)==="pills"?"pills":"rows",dm=!1,fm=e=>e.replace(/["\\]/g,"\\$&"),yo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Ba,Da=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},bo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=Ih(o,Hh|Wh|Rh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ta=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>ea&&!dm&&(dm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ea}.`)),t.slice(0,ea)},qh=e=>{var t;return(t=ta(e)[0])!=null?t:null},zh=(e,t)=>{var n;return(n=ta(e)[t])!=null?n:null},hm=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},ym=(e,t,n)=>{if(e!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let o=y("span","persona-ask-row-check");r.appendChild(o)}else{let o=y("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},Vh=(e,t,n,r)=>{let s=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let c=y("span","persona-ask-row-description");c.textContent=e.description,a.appendChild(c)}s.appendChild(a);let d=ym(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Kh=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Gh=(e,t,n,r)=>{var p,u,f;let s=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<$h;g++)s.appendChild(Kh(r));return s}if(d.forEach((g,b)=>{s.appendChild(Vh(g,b,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?Bh:Dh;if(r==="rows"){let b=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");b.setAttribute("data-ask-user-action","focus-free-text"),b.setAttribute("data-option-index",String(d.length)),b.setAttribute("data-ask-other-row","true");let v=y("span","persona-ask-row-content"),S=document.createElement("input");S.type="text",S.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",S.placeholder=(p=t.freeTextPlaceholder)!=null?p:pm,S.setAttribute("data-ask-free-text-input","true"),S.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:g),v.appendChild(S),b.appendChild(v);let T=ym(r,a,d.length);T&&b.appendChild(T),s.appendChild(b)}else{let b=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");b.type="button",b.setAttribute("data-ask-user-action","open-free-text"),b.textContent=(f=t.freeTextLabel)!=null?f:g,s.appendChild(b)}}return s},bm=(e,t)=>{var s,a;let r=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:pm,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:um,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Jh=e=>{var r;let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:um,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Xh=(e,t,n)=>{var c,p,u,f;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=n.backLabel)!=null?c:Oh,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:_h,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:Fh:(f=n.nextLabel)!=null?f:Nh,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Go=e=>{let t=e.getAttribute(mm);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},xm=(e,t)=>{e.setAttribute(mm,JSON.stringify(t))},er=e=>{var n;let t=Number((n=e.getAttribute(Xi))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Qh=(e,t)=>{e.setAttribute(Xi,String(Math.max(0,Math.floor(t))))},Cs=e=>{var n;let t=Number((n=e.getAttribute(Qi))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},xo=e=>e.getAttribute(Yi)==="true",Yh=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Zh=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Na=(e,t)=>{let{payload:n}=bo(t),r=ta(n),o=Go(e),s={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},vm=e=>{let t=Go(e),n=er(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let c=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(c);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},wm=e=>{if(!xo(e))return;let t=Go(e),n=er(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Zi=(e,t,n)=>{let r=Da(n),o=Uh(e),{payload:s,complete:a}=bo(t),i=xo(e),d=er(e),c=Cs(e),p=i?zh(s,d):qh(s),u=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${c}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let b=e.querySelector('[data-ask-question="true"]');if(b){let L=typeof(p==null?void 0:p.question)=="string"?p.question:"";b.textContent=L,b.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let L=Gh(p,r,a,o);v.replaceWith(L)}if(o!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(bm(r,o))}let S=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!S?e.appendChild(Jh(r)):(!u||i)&&S&&S.remove(),e.setAttribute("data-multi-select",u?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=Xh(d,c,r);T?T.replaceWith(L):e.appendChild(L)}else T&&T.remove();vm(e),wm(e)},ey=(e,t,n)=>{let r=Da(t),o=jh(r),s=e.toolCall.id,a=ta(n),i=Math.max(1,a.length),d=i>1,c=Yh(e,a),p=d?Zh(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(ws,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Qi,String(i)),u.setAttribute(Xi,String(p)),u.setAttribute(Yi,d?"true":"false"),u.setAttribute(gm,o),xm(u,c),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),hm(u,r);let f=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=y("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let b=y("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",f.appendChild(b),u.appendChild(f);let S=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return S.setAttribute("data-ask-pill-list","true"),S.setAttribute("role","group"),u.appendChild(S),o!=="rows"&&u.appendChild(bm(r,o)),Zi(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},ty=(e,t,n)=>{let{payload:r}=bo(t),o=Math.max(1,ta(r).length);o>Cs(e)&&(e.setAttribute(Qi,String(o)),o>1&&!xo(e)&&e.setAttribute(Yi,"true")),Zi(e,t,n)},ny=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=Da(t);hm(n,r);let o=y("span","persona-ask-stub-label"),{complete:s}=bo(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},na=(e,t,n)=>{if(!n||!yo(e)||Da(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${ws}]`).forEach(c=>{c.getAttribute(ws)!==o&&c.remove()});let a=n.querySelector(`[${ws}="${fm(o)}"]`);if(a){ty(a,e,t);return}let{payload:i}=bo(e),d=ey(e,t,i);n.appendChild(d)},Jo=(e,t)=>{if(!e)return;let n=t?`[${ws}="${fm(t)}"]`:`[${ws}]`;e.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},el=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),vo=(e,t)=>{let n=Go(e),r=er(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,xm(e,n),vm(e),wm(e)},Oa=(e,t,n,r)=>{let o=Cs(e),s=Math.max(0,Math.min(o-1,r));Qh(e,s),Zi(e,t,n)};var Hr="suggest_replies";var Cm={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},tl={name:Hr,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:Cm,origin:"sdk",annotations:{readOnlyHint:!0}},nl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Fa=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Hr},Am=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},rl=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!Fa(r))continue;let o=Am((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},Sm=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var Tm={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ea,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},Em={name:Ba,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:Tm,origin:"sdk",annotations:{readOnlyHint:!0}},_a=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(Em),Sm(e)&&t.push(tl),t};import{parse as Mm,STR as km,OBJ as Lm}from"partial-json";var $a=e=>e.replace(/\\n/g,`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),wo=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},ry=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Pm=e=>e.status==="complete"?ry(e):e.status==="pending"?"Waiting":"",oy=e=>{var o,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Im=e=>e.status==="complete"?oy(e):"Using tool...",ja=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},oa=e=>{var n,r,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ja(t)},Ua=e=>{var n,r,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ja(t)},ol=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=oa(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},qa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&ra(r,n.slice(s,a.index),[]),a[1]!==void 0?ra(r,a[1],["bold"]):a[2]!==void 0?ra(r,a[2],["italic"]):a[3]!==void 0&&ra(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&ra(r,n.slice(s),[]),r},ra=(e,t,n)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:n}),o<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},sy=()=>{let e=null,t=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
10
10
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
11
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},oa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},rl=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ol=()=>{var t;let e=Gh();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},sl=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=ym(n,bm|xm);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?$a(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=$a(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Jh=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?$a(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?$a(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=ym(s,bm|xm),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},al=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Cm="4.5.0";var yr=Cm;var Qh="https://api.runtype.com/v1/dispatch",za="https://api.runtype.com";function Yh(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var il=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Zh(e){switch(e){case"json":return sl;case"regex-json":return ol;case"xml":return al;default:return rl}}var Am=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function ey(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=Am(n);if(!Am(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=oa(e);return oa(t)!==null&&a===null?t:e}var ws=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=t.apiUrl)!=null?n:Qh,this.headers={"Content-Type":"application/json","X-Persona-Version":yr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Zh(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Xs(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=Zu(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,l;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(l=n.agentId)!=null?l:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":yr},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":yr},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let M=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:M}),M}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(il).map(M=>{var P,C,R;return{id:M.id,role:M.role,content:(R=(C=(P=M.contentParts)!=null?P:M.llmContent)!=null?C:M.rawContent)!=null?R:M.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,f=!!(g&&g.length>0),v=f?Qu(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,E=f&&x&&this.lastSentClientToolsFingerprint===v,T=!1,L=null,k;for(let M=0;;M++){let C={...u,...f&&(T||!E)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":yr},body:JSON.stringify(C),signal:r.signal}),k.status===409&&M===0&&f){let R=await k.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}L=R!=null?R:{error:"Chat request failed"}}break}if(!k.ok){let M=L!=null?L:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(k.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let P=new Error(M.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!k.body){let M=new Error("No response body received");throw n({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(k.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||za}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(il).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let u=new Date(l.createdAt).getTime(),g=new Date(p.createdAt).getTime();return u-g}).map(l=>{var p,u,g;return{role:l.role,content:(g=(u=(p=l.contentParts)!=null?p:l.llmContent)!=null?u:l.rawContent)!=null?g:l.content,createdAt:l.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[..._a(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let l={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(l,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(l).length&&(o.context=l)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(il).sort((d,l)=>{let p=new Date(d.createdAt).getTime(),u=new Date(l.createdAt).getTime();return p-u}).map(d=>{var l,p,u;return{role:d.role,content:(u=(p=(l=d.contentParts)!=null?l:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,l]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=l);let s=[..._a(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let l=d;return o.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=o.clientTools),l}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},l=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=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var bt,fn,xr,vr;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=A=>{let te=A.reasoning?{...A.reasoning,chunks:[...A.reasoning.chunks]}:void 0,Me=A.toolCall?{...A.toolCall,chunks:A.toolCall.chunks?[...A.toolCall.chunks]:void 0}:void 0,Ne=A.tools?A.tools.map(Ie=>({...Ie,chunks:Ie.chunks?[...Ie.chunks]:void 0})):void 0;return{...A,reasoning:te,toolCall:Me,tools:Ne}},u=A=>{if(A.role!=="assistant"||A.variant)return!0;let te=Array.isArray(A.contentParts)&&A.contentParts.length>0,Me=typeof A.rawContent=="string"&&A.rawContent.trim()!=="";return typeof A.content=="string"&&A.content.trim()!==""||te||Me||!!A.stopReason},g=A=>{u(A)&&n({type:"message",message:p(A)})},f=null,v=null,x={current:null},E={current:null},T=null,L="",k=new Map,M=new Map,P=new Map,C=new Map,R=new Map,F={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},H=A=>{if(A==null)return null;try{return String(A)}catch{return null}},O=A=>{var te,Me,Ne,Ie,Oe;return H((Oe=(Ie=(Ne=(Me=(te=A.stepId)!=null?te:A.step_id)!=null?Me:A.step)!=null?Ne:A.parentId)!=null?Ie:A.flowStepId)!=null?Oe:A.flow_step_id)},N=A=>{var te,Me,Ne,Ie,Oe,Ge,at;return H((at=(Ge=(Oe=(Ie=(Ne=(Me=(te=A.callId)!=null?te:A.call_id)!=null?Me:A.requestId)!=null?Ne:A.request_id)!=null?Ie:A.toolCallId)!=null?Oe:A.tool_call_id)!=null?Ge:A.stepId)!=null?at:A.step_id)},Y=r,ke=!1,pe=()=>{if(f)return f;let A,te=T;return!ke&&Y?(A=Y,ke=!0):Y&&te?A=`${Y}_${te}`:A=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:A,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(f),f},Z=(A,te)=>{F.lastId=te,A&&F.byStep.set(A,te)},Te=(A,te)=>{var Oe;let Me=(Oe=A.reasoningId)!=null?Oe:A.id,Ne=O(A);if(Me){let Ge=String(Me);return Z(Ne,Ge),Ge}if(Ne){let Ge=F.byStep.get(Ne);if(Ge)return F.lastId=Ge,Ge}if(F.lastId&&!te)return F.lastId;if(!te)return null;let Ie=`reason-${l()}`;return Z(Ne,Ie),Ie},Le=A=>{let te=C.get(A);if(te)return te;let Me={id:`reason-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:A,status:"streaming",chunks:[]}};return C.set(A,Me),g(Me),Me},oe=(A,te)=>{j.lastId=te,A&&j.byCall.set(A,te)},Ae=new Set,se=new Map,ie=new Set,ae=new Map,xe=A=>{if(!A)return!1;let te=A.replace(/_+/g,"_").replace(/^_|_$/g,"");return te==="emit_artifact_markdown"||te==="emit_artifact_component"},Be=(A,te)=>{var Oe;let Me=(Oe=A.toolId)!=null?Oe:A.id,Ne=N(A);if(Me){let Ge=String(Me);return oe(Ne,Ge),Ge}if(Ne){let Ge=j.byCall.get(Ne);if(Ge)return j.lastId=Ge,Ge}if(j.lastId&&!te)return j.lastId;if(!te)return null;let Ie=`tool-${l()}`;return oe(Ne,Ie),Ie},V=A=>{let te=R.get(A);if(te)return te;let Me={id:`tool-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:A,status:"pending"}};return R.set(A,Me),g(Me),Me},X=A=>{if(typeof A=="number"&&Number.isFinite(A))return A;if(typeof A=="string"){let te=Number(A);if(!Number.isNaN(te)&&Number.isFinite(te))return te;let Me=Date.parse(A);if(!Number.isNaN(Me))return Me}return Date.now()},He=A=>{if(typeof A=="string")return A;if(A==null)return"";try{return JSON.stringify(A)}catch{return String(A)}},K=new Map,ue=new Map,$e=new Map,fe=(A,te,Me)=>{var at;let Ne=$e.get(A);Ne||(Ne=[],$e.set(A,Ne));let Ie=0,Oe=Ne.length;for(;Ie<Oe;){let Pt=Ie+Oe>>>1;Ne[Pt].seq<te?Ie=Pt+1:Oe=Pt}((at=Ne[Ie])==null?void 0:at.seq)===te?Ne[Ie]={seq:te,text:Me}:Ne.splice(Ie,0,{seq:te,text:Me});let Ge="";for(let Pt=0;Pt<Ne.length;Pt++)Ge+=Ne[Pt].text;return Ge},Ve=(A,te)=>{let Me=He(te),Ne=ue.get(A.id),Ie=ey(Ne,Me);A.rawContent=Ie;let Oe=K.get(A.id),Ge=be=>{var xt;let _e=(xt=A.content)!=null?xt:"";be.trim()!==""&&(_e.trim().length===0||be.startsWith(_e)||be.trimStart().startsWith(_e.trim()))&&(A.content=be)},at=()=>{var be;if(Oe){let _e=(be=Oe.close)==null?void 0:be.call(Oe);_e instanceof Promise&&_e.catch(()=>{})}K.delete(A.id),ue.delete(A.id),A.streaming=!1,g(A)};if(!Oe){Ge(Me),at();return}let Pt=oa(Ie);if(Pt!==null&&Pt.trim()!==""){Ge(Pt),at();return}let ce=be=>{var Ye;let _e=typeof be=="string"?be:(Ye=be==null?void 0:be.text)!=null?Ye:null;if(_e!==null&&_e.trim()!=="")return _e;let xt=Oe.getExtractedText();return xt!==null&&xt.trim()!==""?xt:Me},B;try{B=Oe.processChunk(Ie)}catch{Ge(Me),at();return}if(B instanceof Promise){B.then(be=>{Ge(ce(be)),at()}).catch(()=>{Ge(Me),at()});return}Ge(ce(B)),at()},et=null,Ot=(A,te,Me,Ne)=>{var Pt;A.rawContent=te,K.has(A.id)||K.set(A.id,this.createStreamParser());let Ie=K.get(A.id),Oe=te.trim().startsWith("{")||te.trim().startsWith("[");if(Oe&&ue.set(A.id,te),Ie.__isPlainTextParser===!0){A.content=Ne!==void 0?te:A.content+Me,ue.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A);return}let at=Ie.processChunk(te);if(at instanceof Promise)at.then(ce=>{var be;let B=typeof ce=="string"?ce:(be=ce==null?void 0:ce.text)!=null?be:null;B!==null&&B.trim()!==""?(A.content=B,g(A)):!Oe&&!te.trim().startsWith("<")&&(A.content=Ne!==void 0?te:A.content+Me,ue.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A))}).catch(()=>{A.content=Ne!==void 0?te:A.content+Me,ue.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A)});else{let ce=typeof at=="string"?at:(Pt=at==null?void 0:at.text)!=null?Pt:null;ce!==null&&ce.trim()!==""?(A.content=ce,g(A)):!Oe&&!te.trim().startsWith("<")&&(A.content=Ne!==void 0?te:A.content+Me,ue.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A))}},Xe=(A,te)=>{var Pt,ce;let Me=te!=null?te:A.content;if(Me==null||Me===""){A.streaming=!1,g(A);return}let Ne=ue.get(A.id),Ie=Ne!=null?Ne:He(Me);A.rawContent=Ie;let Oe=K.get(A.id),Ge=null,at=!1;if(Oe&&(Ge=Oe.getExtractedText(),Ge===null&&(Ge=oa(Ie)),Ge===null)){let B=Oe.processChunk(Ie);B instanceof Promise?(at=!0,B.then(be=>{var xt;let _e=typeof be=="string"?be:(xt=be==null?void 0:be.text)!=null?xt:null;_e!==null&&(A.content=_e,A.streaming=!1,K.delete(A.id),ue.delete(A.id),g(A))}).catch(()=>{})):Ge=typeof B=="string"?B:(Pt=B==null?void 0:B.text)!=null?Pt:null}if(!at){Ge!==null&&Ge.trim()!==""?A.content=Ge:ue.has(A.id)||(A.content=He(Me));let B=K.get(A.id);if(B){let be=(ce=B.close)==null?void 0:ce.call(B);be instanceof Promise&&be.catch(()=>{}),K.delete(A.id)}ue.delete(A.id),A.streaming=!1,g(A)}},ye=(A,te,Me)=>{let Ne=M.get(A);if(Ne)return Ne;let Ie={id:`nested-${te}-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Me?{variant:Me}:{},...Me==="reasoning"?{reasoning:{id:A,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:te}};return M.set(A,Ie),g(Ie),Ie},J=[],dt,qe=new Map,Se=0,ve="agent",nt=!1,Lt=null,ee=null,je=new Map,wn=(bt=this.config.iterationDisplay)!=null?bt:"separate";for(dt=()=>{var A,te,Me,Ne,Ie,Oe,Ge,at,Pt,ce,B,be,_e,xt,Ye,Rt,St,ht,kt,Xt,Ft,en,wr,$r,sr,ar,to,qt,ir,jr,In,kn,Rn,lr,Cr,no,qn,ro,vt,Ar,Sr,Ur,cr,ut,Io,Tr,Ro,Ln,os,oo,qr,so,ao,Wo,Ho,io,yt,Wn,Hn,Cn,wt,zn,Vn,Bn,lo,Ce,zr,Kn,_t,Gn,Vr,Hs,ss,Bs,Bo,Er,co,it,rn,on,Mr,Ds,Kr,Do,kr,$,as,dr,Lr,Gr,Pr,pr,is,Ma,hn,An,ur,Sn,No,mr,yn,Ir,ls,Oo,cs;for(let Rr=0;Rr<J.length;Rr++){let tt=J[Rr].payloadType,w=J[Rr].payload;if(!nt&&ve!=="flow"&&typeof w.stepType=="string"&&(ve="flow"),tt==="reasoning_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U),ye(z,U,"reasoning");continue}let G=(A=Te(w,!0))!=null?A:`reason-${l()}`,he=Le(G);he.reasoning=(te=he.reasoning)!=null?te:{id:G,status:"streaming",chunks:[]},he.reasoning.startedAt=(Ne=he.reasoning.startedAt)!=null?Ne:X((Me=w.startedAt)!=null?Me:w.timestamp),he.reasoning.completedAt=void 0,he.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(he.reasoning.scope=w.scope),he.streaming=!0,he.reasoning.status="streaming",g(he)}else if(tt==="reasoning_delta"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let re=M.get(z),mt=(Ge=(Oe=(Ie=w.reasoningText)!=null?Ie:w.text)!=null?Oe:w.delta)!=null?Ge:"";mt&&w.hidden!==!0&&re.reasoning&&(re.reasoning.chunks.push(String(mt)),g(re));continue}let U=(Pt=(at=Te(w,!1))!=null?at:Te(w,!0))!=null?Pt:`reason-${l()}`,G=Le(U);G.reasoning=(ce=G.reasoning)!=null?ce:{id:U,status:"streaming",chunks:[]},G.reasoning.startedAt=(be=G.reasoning.startedAt)!=null?be:X((B=w.startedAt)!=null?B:w.timestamp);let he=(Ye=(xt=(_e=w.reasoningText)!=null?_e:w.text)!=null?xt:w.delta)!=null?Ye:"";if(he&&w.hidden!==!0){let re=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(re!==void 0){let mt=fe(U,re,String(he));G.reasoning.chunks=[mt]}else G.reasoning.chunks.push(String(he))}if(G.reasoning.status=w.done?"complete":"streaming",w.done){G.reasoning.completedAt=X((Rt=w.completedAt)!=null?Rt:w.timestamp);let re=(St=G.reasoning.startedAt)!=null?St:Date.now();G.reasoning.durationMs=Math.max(0,((ht=G.reasoning.completedAt)!=null?ht:Date.now())-re)}G.streaming=G.reasoning.status!=="complete",g(G)}else if(tt==="reasoning_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let mt=M.get(z);if(mt.reasoning){let pt=typeof w.text=="string"?w.text:"";pt&&mt.reasoning.chunks.length===0&&mt.reasoning.chunks.push(pt),mt.reasoning.status="complete",mt.streaming=!1,g(mt)}k.delete(z),M.delete(z);continue}let U=(Xt=(kt=Te(w,!1))!=null?kt:Te(w,!0))!=null?Xt:`reason-${l()}`,G=typeof w.text=="string"?w.text:"";!C.get(U)&&(G||w.scope==="loop")&&Le(U);let he=C.get(U);if(he!=null&&he.reasoning){(w.scope==="loop"||w.scope==="turn")&&(he.reasoning.scope=w.scope),G&&he.reasoning.chunks.length===0&&he.reasoning.chunks.push(G),he.reasoning.status="complete",he.reasoning.completedAt=X((Ft=w.completedAt)!=null?Ft:w.timestamp);let mt=(en=he.reasoning.startedAt)!=null?en:Date.now();he.reasoning.durationMs=Math.max(0,((wr=he.reasoning.completedAt)!=null?wr:Date.now())-mt),he.streaming=!1,g(he)}let re=O(w);re&&F.byStep.delete(re)}else if(tt==="tool_start"){f&&(f.streaming=!1,g(f),f=null),typeof w.iteration=="number"&&(Se=w.iteration);let z=(sr=($r=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?$r:Be(w,!0))!=null?sr:`tool-${l()}`,U=(ar=w.toolName)!=null?ar:w.name;if(xe(U)){Ae.add(z);continue}oe(N(w),z);let G=V(z),he=(to=G.toolCall)!=null?to:{id:z,status:"pending"};he.name=U!=null?U:he.name,he.status="running",w.parameters!==void 0?he.args=w.parameters:w.args!==void 0&&(he.args=w.args),he.startedAt=(ir=he.startedAt)!=null?ir:X((qt=w.startedAt)!=null?qt:w.timestamp),he.completedAt=void 0,he.durationMs=void 0,G.toolCall=he,G.streaming=!0,w.executionId&&(G.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(G)}else if(tt==="tool_output_delta"){let z=(In=(jr=Be(w,!1))!=null?jr:Be(w,!0))!=null?In:`tool-${l()}`;if(Ae.has(z))continue;let U=V(z),G=(kn=U.toolCall)!=null?kn:{id:z,status:"running"};G.startedAt=(lr=G.startedAt)!=null?lr:X((Rn=w.startedAt)!=null?Rn:w.timestamp);let he=(qn=(no=(Cr=w.text)!=null?Cr:w.delta)!=null?no:w.message)!=null?qn:"";he&&(G.chunks=(ro=G.chunks)!=null?ro:[],G.chunks.push(String(he))),G.status="running",U.toolCall=G,U.streaming=!0;let re=w.agentContext;(re||w.executionId)&&(U.agentMetadata=(Sr=U.agentMetadata)!=null?Sr:{executionId:(vt=re==null?void 0:re.executionId)!=null?vt:w.executionId,iteration:(Ar=re==null?void 0:re.iteration)!=null?Ar:w.iteration}),g(U)}else if(tt==="tool_complete"){let z=(cr=(Ur=Be(w,!1))!=null?Ur:Be(w,!0))!=null?cr:`tool-${l()}`;if(Ae.has(z)){Ae.delete(z);continue}let U=V(z),G=(ut=U.toolCall)!=null?ut:{id:z,status:"running"};G.status="complete",w.result!==void 0&&(G.result=w.result),typeof w.duration=="number"&&(G.duration=w.duration),G.completedAt=X((Io=w.completedAt)!=null?Io:w.timestamp);let he=(Tr=w.duration)!=null?Tr:w.executionTime;if(typeof he=="number")G.durationMs=he;else{let pt=(Ro=G.startedAt)!=null?Ro:Date.now();G.durationMs=Math.max(0,((Ln=G.completedAt)!=null?Ln:Date.now())-pt)}U.toolCall=G,U.streaming=!1;let re=w.agentContext;(re||w.executionId)&&(U.agentMetadata=(qr=U.agentMetadata)!=null?qr:{executionId:(os=re==null?void 0:re.executionId)!=null?os:w.executionId,iteration:(oo=re==null?void 0:re.iteration)!=null?oo:w.iteration}),g(U);let mt=N(w);mt&&j.byCall.delete(mt)}else if(tt==="await"&&w.toolName){let z=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,U=(so=z!=null?z:w.toolId)!=null?so:`local-${l()}`,G=V(U),he=w.toolName,re=w.origin==="webmcp"&&!Ko(he)?`webmcp:${he}`:he,mt=Ko(re),pt=(ao=G.toolCall)!=null?ao:{id:U,status:"pending"};pt.name=re,pt.args=w.parameters,pt.status=mt?"running":"complete",pt.chunks=(Wo=pt.chunks)!=null?Wo:[],pt.startedAt=(yt=pt.startedAt)!=null?yt:X((io=(Ho=w.startedAt)!=null?Ho:w.timestamp)!=null?io:w.awaitedAt),mt?(pt.completedAt=void 0,pt.duration=void 0,pt.durationMs=void 0):pt.completedAt=(Wn=pt.completedAt)!=null?Wn:pt.startedAt,G.toolCall=pt,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(Cn=w.executionId)!=null?Cn:(Hn=G.agentMetadata)==null?void 0:Hn.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},g(G)}else if(tt==="text_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U);continue}let G=f;G&&(ve==="flow"?(Xe(G),et=G):(G.streaming=!1,g(G)),f=null),T=typeof w.id=="string"?w.id:T,L=""}else if(tt==="text_delta"){let z=typeof w.id=="string"?w.id:null,U=z?k.get(z):void 0;if(z&&U){let he=typeof w.delta=="string"?w.delta:"",re=((wt=P.get(z))!=null?wt:"")+he;if(P.set(z,re),re.trim()==="")continue;let mt=ye(z,U);mt.agentMetadata={...mt.agentMetadata,executionId:w.executionId,parentToolId:U},Ot(mt,re,he,void 0);continue}if(T=typeof w.id=="string"?w.id:T,ve==="flow"){let he=typeof w.delta=="string"?w.delta:"";if(L+=he,L.trim()==="")continue;let re=pe();re.agentMetadata={executionId:w.executionId,iteration:w.iteration},Ot(re,L,he,void 0),v=re;continue}let G=pe();G.content+=(zn=w.delta)!=null?zn:"",G.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Lt!=null?Lt:void 0,agentName:ee==null?void 0:ee.agentName},v=G,g(G)}else if(tt==="text_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)){let G=M.get(z);G&&Xe(G),k.delete(z),P.delete(z),M.delete(z);continue}let U=f;U&&(ve==="flow"?(Xe(U),et=U):(((Vn=U.content)!=null?Vn:"")===""&&typeof w.text=="string"&&(U.content=w.text),U.streaming=!1,g(U)),f=null),T=null,L=""}else if(tt==="step_complete"){let z=w.stepType,U=w.executionType;if(z==="tool"||U==="context")continue;if(w.success===!1){let G=w.error,he=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&"message"in G?String((Bn=G.message)!=null?Bn:"Step failed"):"Step failed";n({type:"error",error:new Error(he)});let re=f;re&&re.streaming&&(re.streaming=!1,g(re)),n({type:"status",status:"idle"});continue}{let G=et;et=null;let he=w.stopReason,re=(lo=w.result)==null?void 0:lo.response;if(G)he&&(G.stopReason=he),re!=null?Ve(G,re):G.streaming!==!1&&(K.delete(G.id),ue.delete(G.id),G.streaming=!1,g(G));else{let mt=re!=null&&re!=="";if(mt||he){let pt=pe();he&&(pt.stopReason=he),mt?Xe(pt,re):(pt.streaming=!1,g(pt))}}continue}}else if(tt==="execution_start")ve=w.kind==="flow"?"flow":"agent",nt=!0,ve==="agent"&&(ee={executionId:w.executionId,agentId:(Ce=w.agentId)!=null?Ce:"virtual",agentName:(zr=w.agentName)!=null?zr:"",status:"running",currentIteration:0,maxTurns:(Kn=w.maxTurns)!=null?Kn:1,startedAt:X(w.startedAt)});else if(tt==="turn_start"){let z=typeof w.iteration=="number"?w.iteration:Se;if(z!==Se){if(ee&&(ee.currentIteration=z),wn==="separate"&&z>1){let U=f;U&&(U.streaming=!1,g(U),je.set(z-1,U),f=null)}Se=z}Lt=typeof w.id=="string"?w.id:null,v=null}else if(tt==="tool_input_delta"){let z=(_t=w.toolCallId)!=null?_t:j.lastId;if(z){let U=R.get(z);U!=null&&U.toolCall&&(U.toolCall.chunks=(Gn=U.toolCall.chunks)!=null?Gn:[],U.toolCall.chunks.push((Vr=w.delta)!=null?Vr:""),g(U))}}else{if(tt==="tool_input_complete")continue;if(tt==="turn_complete"){let z=w.stopReason,U=f!=null?f:v;if(z&&U!==null){let G=w.id;(!G||((Hs=U.agentMetadata)==null?void 0:Hs.turnId)===G)&&(U.stopReason=z,g(U))}Lt===w.id&&(Lt=null)}else if(tt==="media_start"){let z=String(w.id);qe.set(z,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(tt==="media_delta"){let z=qe.get(String(w.id));z&&typeof w.delta=="string"&&z.parts.push(w.delta)}else if(tt==="media_complete"){let z=String(w.id),U=qe.get(z);qe.delete(z);let G=(Bs=(ss=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?ss:U==null?void 0:U.mediaType)!=null?Bs:"application/octet-stream",he=typeof w.data=="string"?w.data:void 0,re=typeof w.url=="string"?w.url:U&&U.parts.length>0?U.parts.join(""):void 0,mt=null;if(he)mt={type:"media",data:he,mediaType:G};else if(re){let Jn=G.toLowerCase();mt={type:Jn==="image"||Jn.startsWith("image/")?"image-url":"file-url",url:re,mediaType:G}}let pt=(Bo=w.toolCallId)!=null?Bo:U==null?void 0:U.toolCallId,Dn=mt?[mt]:[],po=[];for(let Jn of Dn){if(!Jn||typeof Jn!="object")continue;let sn=Jn,Xn=typeof sn.type=="string"?sn.type:void 0,Jr=typeof sn.mediaType=="string"?sn.mediaType.toLowerCase():"",pn=null,Tn="";if(Xn==="media"){let Nn=typeof sn.data=="string"?sn.data:void 0;if(!Nn)continue;Tn=Jr.length>0?Jr:"application/octet-stream",pn=`data:${Tn};base64,${Nn}`}else if(Xn==="image-url"){let Nn=typeof sn.url=="string"?sn.url:void 0;if(!Nn)continue;Tn=Jr,pn=Nn}else if(Xn==="file-url"){let Nn=typeof sn.url=="string"?sn.url:void 0;if(!Nn)continue;Tn=Jr,pn=Nn}else continue;if(pn)if(Xn==="image-url"||Tn.startsWith("image/"))po.push({type:"image",image:pn,...Tn.includes("/")?{mimeType:Tn}:{}});else if(Tn.startsWith("audio/"))po.push({type:"audio",audio:pn,mimeType:Tn});else if(Tn.startsWith("video/"))po.push({type:"video",video:pn,mimeType:Tn});else{let Nn=Tn||"application/octet-stream";po.push({type:"file",data:pn,mimeType:Nn,filename:Yh(Nn)})}}if(po.length>0){let Jn=l(),sn=pt,Jr={id:`agent-media-${typeof sn=="string"&&sn.length>0?`${sn}-${Jn}`:String(Jn)}`,role:"assistant",content:"",contentParts:po,createdAt:new Date().toISOString(),streaming:!1,sequence:Jn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:Se}};g(Jr);let pn=f;pn&&(pn.streaming=!1,g(pn)),f=null,x.current=null}}else if(tt==="execution_complete"){let z=(Er=w.kind)!=null?Er:ve;z==="agent"&&ee&&(ee.status=w.success?"complete":"error",ee.completedAt=X(w.completedAt),ee.stopReason=w.stopReason);let U=f;U&&(z==="flow"&&U.streaming!==!1?Xe(U):(U.streaming=!1,g(U)),f=null),T=null,L="",et=null,n({type:"status",status:"idle"})}else if(tt==="execution_error"){let z=typeof w.error=="string"?w.error:(it=(co=w.error)==null?void 0:co.message)!=null?it:"Execution error";n({type:"error",error:new Error(z)})}else if(tt!=="ping"){if(tt==="approval_start"){let z=(rn=w.approvalId)!=null?rn:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(on=ee==null?void 0:ee.agentId)!=null?on:"virtual",executionId:(Ds=(Mr=w.executionId)!=null?Mr:ee==null?void 0:ee.executionId)!=null?Ds:"",toolName:(Kr=w.toolName)!=null?Kr:"",toolType:w.toolType,description:(kr=w.description)!=null?kr:`Execute ${(Do=w.toolName)!=null?Do:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(tt==="step_await"&&w.awaitReason==="approval_required"){let z=($=w.approvalId)!=null?$:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(as=ee==null?void 0:ee.agentId)!=null?as:"virtual",executionId:(Lr=(dr=w.executionId)!=null?dr:ee==null?void 0:ee.executionId)!=null?Lr:"",toolName:(Gr=w.toolName)!=null?Gr:"",toolType:w.toolType,description:(pr=w.description)!=null?pr:`Execute ${(Pr=w.toolName)!=null?Pr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(tt==="approval_complete"){let z=w.approvalId;if(z){let G={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(is=w.decision)!=null?is:"approved",agentId:(Ma=ee==null?void 0:ee.agentId)!=null?Ma:"virtual",executionId:(An=(hn=w.executionId)!=null?hn:ee==null?void 0:ee.executionId)!=null?An:"",toolName:(ur=w.toolName)!=null?ur:"",description:(Sn=w.description)!=null?Sn:"",resolvedAt:Date.now()}};g(G)}}else if(tt==="artifact_start"||tt==="artifact_delta"||tt==="artifact_update"||tt==="artifact_complete"){if(tt==="artifact_start"){let z=w.artifactType,U=String(w.id),G=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:U,artifactType:z,title:G,component:typeof w.component=="string"?w.component:void 0}),ae.set(U,{markdown:"",title:G}),!ie.has(U)){ie.add(U);let he={id:`artifact-ref-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:U,title:G,artifactType:z,status:"streaming"}})};se.set(U,he),g(he)}}else if(tt==="artifact_delta"){let z=String(w.id),U=typeof w.delta=="string"?w.delta:String((No=w.delta)!=null?No:"");n({type:"artifact_delta",id:z,artDelta:U});let G=ae.get(z);G&&(G.markdown+=U)}else if(tt==="artifact_update"){let z=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:z,component:typeof w.component=="string"?w.component:void 0})}else if(tt==="artifact_complete"){let z=String(w.id);n({type:"artifact_complete",id:z});let U=se.get(z);if(U){U.streaming=!1;try{let G=JSON.parse((mr=U.rawContent)!=null?mr:"{}");if(G.props){G.props.status="complete";let he=ae.get(z);he!=null&&he.markdown&&(G.props.markdown=he.markdown)}U.rawContent=JSON.stringify(G)}catch{}ae.delete(z),g(U),se.delete(z)}}}else if(tt==="transcript_insert"){let z=w.message;if(!z||typeof z!="object")continue;let U=String((yn=z.id)!=null?yn:`msg-${l()}`),G=z.role,re={id:U,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(g(re),re.rawContent)try{let mt=JSON.parse(re.rawContent),pt=(Ir=mt==null?void 0:mt.props)==null?void 0:Ir.artifactId;typeof pt=="string"&&ie.add(pt)}catch{}f=null,x.current=null,K.delete(U),ue.delete(U)}else if(tt==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let z=typeof w.error=="string"?w.error:((ls=w.error)==null?void 0:ls.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(z)});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}else if(tt==="step_error"||tt==="dispatch_error"||tt==="flow_error"){let z=null;if(w.error instanceof Error)z=w.error;else if(tt==="dispatch_error"){let U=(Oo=w.message)!=null?Oo:w.error;U!=null&&U!==""&&(z=new Error(String(U)))}else{let U=w.error;typeof U=="string"&&U!==""?z=new Error(U):U!=null&&typeof U=="object"&&"message"in U&&(z=new Error(String((cs=U.message)!=null?cs:U)))}if(z){n({type:"error",error:z});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}}}}J.length=0};;){let{done:A,value:te}=await o.read();if(A)break;a+=s.decode(te,{stream:!0});let Me=a.split(`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},sa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},sl=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},al=()=>{var t;let e=sy();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},il=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=Mm(n,km|Lm);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?$a(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=$a(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},ay=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?$a(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?$a(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=Mm(s,km|Lm),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ll=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Rm="4.6.1";var fr=Rm;var ly="https://api.runtype.com/v1/dispatch",za="https://api.runtype.com";function cy(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var cl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function dy(e){switch(e){case"json":return il;case"regex-json":return al;case"xml":return ll;default:return sl}}var Wm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function py(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=Wm(n);if(!Wm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=sa(e);return sa(t)!==null&&a===null?t:e}var As=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=t.apiUrl)!=null?n:ly,this.headers={"Content-Type":"application/json","X-Persona-Version":fr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:dy(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Qs(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=cm(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(c=n.agentId)!=null?c:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let E=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:E}),E}let c=await this.buildPayload(t.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(cl).map(E=>{var k,C,I;return{id:E.id,role:E.role,content:(I=(C=(k=E.contentParts)!=null?k:E.llmContent)!=null?C:E.rawContent)!=null?I:E.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},f=c.clientTools,g=!!(f&&f.length>0),b=g?im(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,S=g&&v&&this.lastSentClientToolsFingerprint===b,T=!1,L=null,P;for(let E=0;;E++){let C={...u,...g&&(T||!S)&&f?{clientTools:f}:{},...b?{clientToolsFingerprint:b}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(C),signal:r.signal}),P.status===409&&E===0&&g){let I=await P.json().catch(()=>null);if((I==null?void 0:I.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}L=I!=null?I:{error:"Chat request failed"}}break}if(!P.ok){let E=L!=null?L:await P.json().catch(()=>({error:"Chat request failed"}));if(P.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(P.status===429){let C=new Error(E.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let k=new Error(E.error||"Failed to send message");throw n({type:"error",error:k}),k}if(!P.body){let E=new Error("No response body received");throw n({type:"error",error:E}),E}this.lastSentClientToolsFingerprint=b!=null?b:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(P.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&n({type:"error",error:c}),c}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var c,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||za}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(cl).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,p)=>{let u=new Date(c.createdAt).getTime(),f=new Date(p.createdAt).getTime();return u-f}).map(c=>{var p,u,f;return{role:c.role,content:(f=(u=(p=c.contentParts)!=null?p:c.llmContent)!=null?u:c.rawContent)!=null?f:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[..._a(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(c,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(cl).sort((d,c)=>{let p=new Date(d.createdAt).getTime(),u=new Date(c.createdAt).getTime();return p-u}).map(d=>{var c,p,u;return{role:d.role,content:(u=(p=(c=d.contentParts)!=null?c:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,c]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=c);let s=[..._a(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async c=>{try{let p=await c({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let c=d;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},c=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r,o){var fn,yr,br,Ue;let s=t.getReader(),a=new TextDecoder,i="",d=Date.now(),c=0,p=()=>d+c++,u=M=>{let ue=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,Te=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,ke=M.tools?M.tools.map(He=>({...He,chunks:He.chunks?[...He.chunks]:void 0})):void 0;return{...M,reasoning:ue,toolCall:Te,tools:ke}},f=M=>{if(M.role!=="assistant"||M.variant)return!0;let ue=Array.isArray(M.contentParts)&&M.contentParts.length>0,Te=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||ue||Te||!!M.stopReason},g=M=>{f(M)&&n({type:"message",message:u(M)})},b=null,v=null,S={current:null},T={current:null},L=null,P="",E=new Map,k=new Map,C=new Map,I=new Map,j=new Map,$={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},N=M=>{if(M==null)return null;try{return String(M)}catch{return null}},O=M=>{var ue,Te,ke,He,nt;return N((nt=(He=(ke=(Te=(ue=M.stepId)!=null?ue:M.step_id)!=null?Te:M.step)!=null?ke:M.parentId)!=null?He:M.flowStepId)!=null?nt:M.flow_step_id)},Z=M=>{var ue,Te,ke,He,nt,Qe,ht;return N((ht=(Qe=(nt=(He=(ke=(Te=(ue=M.callId)!=null?ue:M.call_id)!=null?Te:M.requestId)!=null?ke:M.request_id)!=null?He:M.toolCallId)!=null?nt:M.tool_call_id)!=null?Qe:M.stepId)!=null?ht:M.step_id)},Ee=r,de=!1,ee=()=>{if(b)return b;let M,ue="",Te=L;return!de&&Ee?(M=Ee,de=!0,ue=o!=null?o:""):Ee&&Te?M=`${Ee}_${Te}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:M,role:"assistant",content:ue,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},g(b),b},Le=(M,ue)=>{$.lastId=ue,M&&$.byStep.set(M,ue)},Pe=(M,ue)=>{var nt;let Te=(nt=M.reasoningId)!=null?nt:M.id,ke=O(M);if(Te){let Qe=String(Te);return Le(ke,Qe),Qe}if(ke){let Qe=$.byStep.get(ke);if(Qe)return $.lastId=Qe,Qe}if($.lastId&&!ue)return $.lastId;if(!ue)return null;let He=`reason-${p()}`;return Le(ke,He),He},ne=M=>{let ue=I.get(M);if(ue)return ue;let Te={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:M,status:"streaming",chunks:[]}};return I.set(M,Te),g(Te),Te},Ae=(M,ue)=>{R.lastId=ue,M&&R.byCall.set(M,ue)},re=new Set,se=new Map,ae=new Set,fe=new Map,$e=M=>{if(!M)return!1;let ue=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return ue==="emit_artifact_markdown"||ue==="emit_artifact_component"},V=(M,ue)=>{var nt;let Te=(nt=M.toolId)!=null?nt:M.id,ke=Z(M);if(Te){let Qe=String(Te);return Ae(ke,Qe),Qe}if(ke){let Qe=R.byCall.get(ke);if(Qe)return R.lastId=Qe,Qe}if(R.lastId&&!ue)return R.lastId;if(!ue)return null;let He=`tool-${p()}`;return Ae(ke,He),He},Q=M=>{let ue=j.get(M);if(ue)return ue;let Te={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:M,status:"pending"}};return j.set(M,Te),g(Te),Te},Me=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let ue=Number(M);if(!Number.isNaN(ue)&&Number.isFinite(ue))return ue;let Te=Date.parse(M);if(!Number.isNaN(Te))return Te}return Date.now()},J=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},le=new Map,Ie=new Map,he=new Map,Ke=(M,ue,Te)=>{var ht;let ke=he.get(M);ke||(ke=[],he.set(M,ke));let He=0,nt=ke.length;for(;He<nt;){let me=He+nt>>>1;ke[me].seq<ue?He=me+1:nt=me}((ht=ke[He])==null?void 0:ht.seq)===ue?ke[He]={seq:ue,text:Te}:ke.splice(He,0,{seq:ue,text:Te});let Qe="";for(let me=0;me<ke.length;me++)Qe+=ke[me].text;return Qe},gt=(M,ue)=>{let Te=J(ue),ke=Ie.get(M.id),He=py(ke,Te);M.rawContent=He;let nt=le.get(M.id),Qe=ce=>{var Je;let ft=(Je=M.content)!=null?Je:"";ce.trim()!==""&&(ft.trim().length===0||ce.startsWith(ft)||ce.trimStart().startsWith(ft.trim()))&&(M.content=ce)},ht=()=>{var ce;if(nt){let ft=(ce=nt.close)==null?void 0:ce.call(nt);ft instanceof Promise&&ft.catch(()=>{})}le.delete(M.id),Ie.delete(M.id),M.streaming=!1,g(M)};if(!nt){Qe(Te),ht();return}let me=sa(He);if(me!==null&&me.trim()!==""){Qe(me),ht();return}let B=ce=>{var Lt;let ft=typeof ce=="string"?ce:(Lt=ce==null?void 0:ce.text)!=null?Lt:null;if(ft!==null&&ft.trim()!=="")return ft;let Je=nt.getExtractedText();return Je!==null&&Je.trim()!==""?Je:Te},xe;try{xe=nt.processChunk(He)}catch{Qe(Te),ht();return}if(xe instanceof Promise){xe.then(ce=>{Qe(B(ce)),ht()}).catch(()=>{Qe(Te),ht()});return}Qe(B(xe)),ht()},Wt=null,tt=(M,ue,Te,ke)=>{var me;M.rawContent=ue,le.has(M.id)||le.set(M.id,this.createStreamParser());let He=le.get(M.id),nt=ue.trim().startsWith("{")||ue.trim().startsWith("[");if(nt&&Ie.set(M.id,ue),He.__isPlainTextParser===!0){M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M);return}let ht=He.processChunk(ue);if(ht instanceof Promise)ht.then(B=>{var ce;let xe=typeof B=="string"?B:(ce=B==null?void 0:B.text)!=null?ce:null;xe!==null&&xe.trim()!==""?(M.content=xe,g(M)):!nt&&!ue.trim().startsWith("<")&&(M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M))}).catch(()=>{M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M)});else{let B=typeof ht=="string"?ht:(me=ht==null?void 0:ht.text)!=null?me:null;B!==null&&B.trim()!==""?(M.content=B,g(M)):!nt&&!ue.trim().startsWith("<")&&(M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M))}},ge=(M,ue)=>{var me,B;let Te=ue!=null?ue:M.content;if(Te==null||Te===""){M.streaming=!1,g(M);return}let ke=Ie.get(M.id),He=ke!=null?ke:J(Te);M.rawContent=He;let nt=le.get(M.id),Qe=null,ht=!1;if(nt&&(Qe=nt.getExtractedText(),Qe===null&&(Qe=sa(He)),Qe===null)){let xe=nt.processChunk(He);xe instanceof Promise?(ht=!0,xe.then(ce=>{var Je;let ft=typeof ce=="string"?ce:(Je=ce==null?void 0:ce.text)!=null?Je:null;ft!==null&&(M.content=ft,M.streaming=!1,le.delete(M.id),Ie.delete(M.id),g(M))}).catch(()=>{})):Qe=typeof xe=="string"?xe:(me=xe==null?void 0:xe.text)!=null?me:null}if(!ht){Qe!==null&&Qe.trim()!==""?M.content=Qe:Ie.has(M.id)||(M.content=J(Te));let xe=le.get(M.id);if(xe){let ce=(B=xe.close)==null?void 0:B.call(xe);ce instanceof Promise&&ce.catch(()=>{}),le.delete(M.id)}Ie.delete(M.id),M.streaming=!1,g(M)}},X=(M,ue,Te)=>{let ke=k.get(M);if(ke)return ke;let He={id:`nested-${ue}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Te?{variant:Te}:{},...Te==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ue}};return k.set(M,He),g(He),He},it=[],Ve,Se=new Map,we=0,Ze="agent",qt=!1,be=null,pe=null,vn=new Map,Ct=(fn=this.config.iterationDisplay)!=null?fn:"separate";for(Ve=()=>{var M,ue,Te,ke,He,nt,Qe,ht,me,B,xe,ce,ft,Je,Lt,Mt,xt,Rt,Xt,Ot,en,xr,Nr,or,sr,Xr,zt,ar,Or,Hn,kn,Bn,ir,vr,Qr,zn,Yr,At,wr,Cr,Fr,lr,yt,Lo,Ar,Po,Ln,ss,Zr,_r,eo,to,Io,Ro,no,vt,Dn,Nn,wn,St,Vn,Kn,On,ro,Ce,$r,Gn,Ft,Jn,jr,Ds,as,Ns,Wo,Sr,oo,lt,rn,on,Tr,Os,Ur,Ho,Er,F,is,cr,Mr,qr,kr,dr,ls,Ma,hn,Cn,pr,An,Bo,ur,yn,Lr,cs,Do,ds,so;for(let ao=0;ao<it.length;ao++){let ot=it[ao].payloadType,w=it[ao].payload;if(!qt&&Ze!=="flow"&&typeof w.stepType=="string"&&(Ze="flow"),ot==="reasoning_start"){let z=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&q){E.set(z,q),X(z,q,"reasoning");continue}let G=(M=Pe(w,!0))!=null?M:`reason-${p()}`,K=ne(G);K.reasoning=(ue=K.reasoning)!=null?ue:{id:G,status:"streaming",chunks:[]},K.reasoning.startedAt=(ke=K.reasoning.startedAt)!=null?ke:Me((Te=w.startedAt)!=null?Te:w.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(K.reasoning.scope=w.scope),K.streaming=!0,K.reasoning.status="streaming",g(K)}else if(ot==="reasoning_delta"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)&&k.has(z)){let Ne=k.get(z),rt=(Qe=(nt=(He=w.reasoningText)!=null?He:w.text)!=null?nt:w.delta)!=null?Qe:"";rt&&w.hidden!==!0&&Ne.reasoning&&(Ne.reasoning.chunks.push(String(rt)),g(Ne));continue}let q=(me=(ht=Pe(w,!1))!=null?ht:Pe(w,!0))!=null?me:`reason-${p()}`,G=ne(q);G.reasoning=(B=G.reasoning)!=null?B:{id:q,status:"streaming",chunks:[]},G.reasoning.startedAt=(ce=G.reasoning.startedAt)!=null?ce:Me((xe=w.startedAt)!=null?xe:w.timestamp);let K=(Lt=(Je=(ft=w.reasoningText)!=null?ft:w.text)!=null?Je:w.delta)!=null?Lt:"";if(K&&w.hidden!==!0){let Ne=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Ne!==void 0){let rt=Ke(q,Ne,String(K));G.reasoning.chunks=[rt]}else G.reasoning.chunks.push(String(K))}if(G.reasoning.status=w.done?"complete":"streaming",w.done){G.reasoning.completedAt=Me((Mt=w.completedAt)!=null?Mt:w.timestamp);let Ne=(xt=G.reasoning.startedAt)!=null?xt:Date.now();G.reasoning.durationMs=Math.max(0,((Rt=G.reasoning.completedAt)!=null?Rt:Date.now())-Ne)}G.streaming=G.reasoning.status!=="complete",g(G)}else if(ot==="reasoning_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)&&k.has(z)){let rt=k.get(z);if(rt.reasoning){let ct=typeof w.text=="string"?w.text:"";ct&&rt.reasoning.chunks.length===0&&rt.reasoning.chunks.push(ct),rt.reasoning.status="complete",rt.streaming=!1,g(rt)}E.delete(z),k.delete(z);continue}let q=(Ot=(Xt=Pe(w,!1))!=null?Xt:Pe(w,!0))!=null?Ot:`reason-${p()}`,G=typeof w.text=="string"?w.text:"";!I.get(q)&&(G||w.scope==="loop")&&ne(q);let K=I.get(q);if(K!=null&&K.reasoning){(w.scope==="loop"||w.scope==="turn")&&(K.reasoning.scope=w.scope),G&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(G),K.reasoning.status="complete",K.reasoning.completedAt=Me((en=w.completedAt)!=null?en:w.timestamp);let rt=(xr=K.reasoning.startedAt)!=null?xr:Date.now();K.reasoning.durationMs=Math.max(0,((Nr=K.reasoning.completedAt)!=null?Nr:Date.now())-rt),K.streaming=!1,g(K)}let Ne=O(w);Ne&&$.byStep.delete(Ne)}else if(ot==="tool_start"){b&&(b.streaming=!1,g(b),b=null),typeof w.iteration=="number"&&(we=w.iteration);let z=(sr=(or=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?or:V(w,!0))!=null?sr:`tool-${p()}`,q=(Xr=w.toolName)!=null?Xr:w.name;if($e(q)){re.add(z);continue}Ae(Z(w),z);let G=Q(z),K=(zt=G.toolCall)!=null?zt:{id:z,status:"pending"};K.name=q!=null?q:K.name,K.status="running",w.parameters!==void 0?K.args=w.parameters:w.args!==void 0&&(K.args=w.args),K.startedAt=(Or=K.startedAt)!=null?Or:Me((ar=w.startedAt)!=null?ar:w.timestamp),K.completedAt=void 0,K.durationMs=void 0,G.toolCall=K,G.streaming=!0,w.executionId&&(G.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(G)}else if(ot==="tool_output_delta"){let z=(kn=(Hn=V(w,!1))!=null?Hn:V(w,!0))!=null?kn:`tool-${p()}`;if(re.has(z))continue;let q=Q(z),G=(Bn=q.toolCall)!=null?Bn:{id:z,status:"running"};G.startedAt=(vr=G.startedAt)!=null?vr:Me((ir=w.startedAt)!=null?ir:w.timestamp);let K=(Yr=(zn=(Qr=w.text)!=null?Qr:w.delta)!=null?zn:w.message)!=null?Yr:"";K&&(G.chunks=(At=G.chunks)!=null?At:[],G.chunks.push(String(K))),G.status="running",q.toolCall=G,q.streaming=!0;let Ne=w.agentContext;(Ne||w.executionId)&&(q.agentMetadata=(Fr=q.agentMetadata)!=null?Fr:{executionId:(wr=Ne==null?void 0:Ne.executionId)!=null?wr:w.executionId,iteration:(Cr=Ne==null?void 0:Ne.iteration)!=null?Cr:w.iteration}),g(q)}else if(ot==="tool_complete"){let z=(yt=(lr=V(w,!1))!=null?lr:V(w,!0))!=null?yt:`tool-${p()}`;if(re.has(z)){re.delete(z);continue}let q=Q(z),G=(Lo=q.toolCall)!=null?Lo:{id:z,status:"running"};G.status="complete",w.result!==void 0&&(G.result=w.result),typeof w.duration=="number"&&(G.duration=w.duration),G.completedAt=Me((Ar=w.completedAt)!=null?Ar:w.timestamp);let K=(Po=w.duration)!=null?Po:w.executionTime;if(typeof K=="number")G.durationMs=K;else{let ct=(Ln=G.startedAt)!=null?Ln:Date.now();G.durationMs=Math.max(0,((ss=G.completedAt)!=null?ss:Date.now())-ct)}q.toolCall=G,q.streaming=!1;let Ne=w.agentContext;(Ne||w.executionId)&&(q.agentMetadata=(eo=q.agentMetadata)!=null?eo:{executionId:(Zr=Ne==null?void 0:Ne.executionId)!=null?Zr:w.executionId,iteration:(_r=Ne==null?void 0:Ne.iteration)!=null?_r:w.iteration}),g(q);let rt=Z(w);rt&&R.byCall.delete(rt)}else if(ot==="await"&&w.toolName){let z=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,q=(to=z!=null?z:w.toolId)!=null?to:`local-${p()}`,G=Q(q),K=w.toolName,Ne=w.origin==="webmcp"&&!Ko(K)?`webmcp:${K}`:K,rt=Ko(Ne),ct=(Io=G.toolCall)!=null?Io:{id:q,status:"pending"};ct.name=Ne,ct.args=w.parameters,ct.status=rt?"running":"complete",ct.chunks=(Ro=ct.chunks)!=null?Ro:[],ct.startedAt=(Dn=ct.startedAt)!=null?Dn:Me((vt=(no=w.startedAt)!=null?no:w.timestamp)!=null?vt:w.awaitedAt),rt?(ct.completedAt=void 0,ct.duration=void 0,ct.durationMs=void 0):ct.completedAt=(Nn=ct.completedAt)!=null?Nn:ct.startedAt,G.toolCall=ct,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(St=w.executionId)!=null?St:(wn=G.agentMetadata)==null?void 0:wn.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},g(G)}else if(ot==="text_start"){let z=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&q){E.set(z,q);continue}let G=b;G&&(Ze==="flow"?(ge(G),Wt=G):(G.streaming=!1,g(G)),b=null),L=typeof w.id=="string"?w.id:L,P=""}else if(ot==="text_delta"){let z=typeof w.id=="string"?w.id:null,q=z?E.get(z):void 0;if(z&&q){let K=typeof w.delta=="string"?w.delta:"",Ne=((Vn=C.get(z))!=null?Vn:"")+K;if(C.set(z,Ne),Ne.trim()==="")continue;let rt=X(z,q);rt.agentMetadata={...rt.agentMetadata,executionId:w.executionId,parentToolId:q},tt(rt,Ne,K,void 0);continue}if(L=typeof w.id=="string"?w.id:L,Ze==="flow"){let K=typeof w.delta=="string"?w.delta:"";if(P+=K,P.trim()==="")continue;let Ne=ee();Ne.agentMetadata={executionId:w.executionId,iteration:w.iteration},tt(Ne,P,K,void 0),v=Ne;continue}let G=ee();G.content+=(Kn=w.delta)!=null?Kn:"",G.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:be!=null?be:void 0,agentName:pe==null?void 0:pe.agentName},v=G,g(G)}else if(ot==="text_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)){let G=k.get(z);G&&ge(G),E.delete(z),C.delete(z),k.delete(z);continue}let q=b;q&&(Ze==="flow"?(ge(q),Wt=q):(((On=q.content)!=null?On:"")===""&&typeof w.text=="string"&&(q.content=w.text),q.streaming=!1,g(q)),b=null),L=null,P=""}else if(ot==="step_complete"){let z=w.stepType,q=w.executionType;if(z==="tool"||q==="context")continue;if(w.success===!1){let G=w.error,K=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&Reflect.has(G,"message")?String((ro=G.message)!=null?ro:"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let Ne=b;Ne&&Ne.streaming&&(Ne.streaming=!1,g(Ne)),n({type:"status",status:"idle"});continue}{let G=Wt;Wt=null;let K=w.stopReason,Ne=(Ce=w.result)==null?void 0:Ce.response;if(G)K&&(G.stopReason=K),Ne!=null?gt(G,Ne):G.streaming!==!1&&(le.delete(G.id),Ie.delete(G.id),G.streaming=!1,g(G));else{let rt=Ne!=null&&Ne!=="";if(rt||K){let ct=ee();K&&(ct.stopReason=K),rt?ge(ct,Ne):(ct.streaming=!1,g(ct))}}continue}}else if(ot==="execution_start")Ze=w.kind==="flow"?"flow":"agent",qt=!0,Ze==="agent"&&(pe={executionId:w.executionId,agentId:($r=w.agentId)!=null?$r:"virtual",agentName:(Gn=w.agentName)!=null?Gn:"",status:"running",currentIteration:0,maxTurns:(Ft=w.maxTurns)!=null?Ft:1,startedAt:Me(w.startedAt)});else if(ot==="turn_start"){let z=typeof w.iteration=="number"?w.iteration:we;if(z!==we){if(pe&&(pe.currentIteration=z),Ct==="separate"&&z>1){let q=b;q&&(q.streaming=!1,g(q),vn.set(z-1,q),b=null)}we=z}be=typeof w.id=="string"?w.id:null,v=null}else if(ot==="tool_input_delta"){let z=(Jn=w.toolCallId)!=null?Jn:R.lastId;if(z){let q=j.get(z);q!=null&&q.toolCall&&(q.toolCall.chunks=(jr=q.toolCall.chunks)!=null?jr:[],q.toolCall.chunks.push((Ds=w.delta)!=null?Ds:""),g(q))}}else{if(ot==="tool_input_complete")continue;if(ot==="turn_complete"){let z=w.stopReason,q=b!=null?b:v;if(z&&q!==null){let G=w.id;(!G||((as=q.agentMetadata)==null?void 0:as.turnId)===G)&&(q.stopReason=z,g(q))}be===w.id&&(be=null)}else if(ot==="media_start"){let z=String(w.id);Se.set(z,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(ot==="media_delta"){let z=Se.get(String(w.id));z&&typeof w.delta=="string"&&z.parts.push(w.delta)}else if(ot==="media_complete"){let z=String(w.id),q=Se.get(z);Se.delete(z);let G=(Wo=(Ns=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Ns:q==null?void 0:q.mediaType)!=null?Wo:"application/octet-stream",K=typeof w.data=="string"?w.data:void 0,Ne=typeof w.url=="string"?w.url:q&&q.parts.length>0?q.parts.join(""):void 0,rt=null;if(K)rt={type:"media",data:K,mediaType:G};else if(Ne){let Pn=G.toLowerCase();rt={type:Pn==="image"||Pn.startsWith("image/")?"image-url":"file-url",url:Ne,mediaType:G}}let ct=(Sr=w.toolCallId)!=null?Sr:q==null?void 0:q.toolCallId,Di=rt?[rt]:[],io=[];for(let Pn of Di){if(!Pn||typeof Pn!="object")continue;let Qt=Pn,lo=typeof Qt.type=="string"?Qt.type:void 0,Xn=typeof Qt.mediaType=="string"?Qt.mediaType.toLowerCase():"",Sn=null,In="";if(lo==="media"){let Tn=typeof Qt.data=="string"?Qt.data:void 0;if(!Tn)continue;In=Xn.length>0?Xn:"application/octet-stream",Sn=`data:${In};base64,${Tn}`}else if(lo==="image-url"){let Tn=typeof Qt.url=="string"?Qt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else if(lo==="file-url"){let Tn=typeof Qt.url=="string"?Qt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else continue;if(Sn)if(lo==="image-url"||In.startsWith("image/"))io.push({type:"image",image:Sn,...In.includes("/")?{mimeType:In}:{}});else if(In.startsWith("audio/"))io.push({type:"audio",audio:Sn,mimeType:In});else if(In.startsWith("video/"))io.push({type:"video",video:Sn,mimeType:In});else{let Tn=In||"application/octet-stream";io.push({type:"file",data:Sn,mimeType:Tn,filename:cy(Tn)})}}if(io.length>0){let Pn=p(),Qt=ct,Xn={id:`agent-media-${typeof Qt=="string"&&Qt.length>0?`${Qt}-${Pn}`:String(Pn)}`,role:"assistant",content:"",contentParts:io,createdAt:new Date().toISOString(),streaming:!1,sequence:Pn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:we}};g(Xn);let Sn=b;Sn&&(Sn.streaming=!1,g(Sn)),b=null,S.current=null}}else if(ot==="execution_complete"){let z=(oo=w.kind)!=null?oo:Ze;z==="agent"&&pe&&(pe.status=w.success?"complete":"error",pe.completedAt=Me(w.completedAt),pe.stopReason=w.stopReason);let q=b;q&&(z==="flow"&&q.streaming!==!1?ge(q):(q.streaming=!1,g(q)),b=null),L=null,P="",Wt=null,n({type:"status",status:"idle",terminal:!0})}else if(ot==="execution_error"){let z=typeof w.error=="string"?w.error:(rn=(lt=w.error)==null?void 0:lt.message)!=null?rn:"Execution error";n({type:"error",error:new Error(z)})}else if(ot!=="ping"){if(ot==="approval_start"){let z=(on=w.approvalId)!=null?on:`approval-${p()}`,q={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:"pending",agentId:(Tr=pe==null?void 0:pe.agentId)!=null?Tr:"virtual",executionId:(Ur=(Os=w.executionId)!=null?Os:pe==null?void 0:pe.executionId)!=null?Ur:"",toolName:(Ho=w.toolName)!=null?Ho:"",toolType:w.toolType,description:(F=w.description)!=null?F:`Execute ${(Er=w.toolName)!=null?Er:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(ot==="step_await"&&w.awaitReason==="approval_required"){let z=(is=w.approvalId)!=null?is:`approval-${p()}`,q={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:"pending",agentId:(cr=pe==null?void 0:pe.agentId)!=null?cr:"virtual",executionId:(qr=(Mr=w.executionId)!=null?Mr:pe==null?void 0:pe.executionId)!=null?qr:"",toolName:(kr=w.toolName)!=null?kr:"",toolType:w.toolType,description:(ls=w.description)!=null?ls:`Execute ${(dr=w.toolName)!=null?dr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(ot==="approval_complete"){let z=w.approvalId;if(z){let G={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:(Ma=w.decision)!=null?Ma:"approved",agentId:(hn=pe==null?void 0:pe.agentId)!=null?hn:"virtual",executionId:(pr=(Cn=w.executionId)!=null?Cn:pe==null?void 0:pe.executionId)!=null?pr:"",toolName:(An=w.toolName)!=null?An:"",description:(Bo=w.description)!=null?Bo:"",resolvedAt:Date.now()}};g(G)}}else if(ot==="artifact_start"||ot==="artifact_delta"||ot==="artifact_update"||ot==="artifact_complete"){if(ot==="artifact_start"){let z=w.artifactType,q=String(w.id),G=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:q,artifactType:z,title:G,component:typeof w.component=="string"?w.component:void 0}),fe.set(q,{markdown:"",title:G}),!ae.has(q)){ae.add(q);let K={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:G,artifactType:z,status:"streaming"}})};se.set(q,K),g(K)}}else if(ot==="artifact_delta"){let z=String(w.id),q=typeof w.delta=="string"?w.delta:String((ur=w.delta)!=null?ur:"");n({type:"artifact_delta",id:z,artDelta:q});let G=fe.get(z);G&&(G.markdown+=q)}else if(ot==="artifact_update"){let z=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:z,component:typeof w.component=="string"?w.component:void 0})}else if(ot==="artifact_complete"){let z=String(w.id);n({type:"artifact_complete",id:z});let q=se.get(z);if(q){q.streaming=!1;try{let G=JSON.parse((yn=q.rawContent)!=null?yn:"{}");if(G.props){G.props.status="complete";let K=fe.get(z);K!=null&&K.markdown&&(G.props.markdown=K.markdown)}q.rawContent=JSON.stringify(G)}catch{}fe.delete(z),g(q),se.delete(z)}}}else if(ot==="transcript_insert"){let z=w.message;if(!z||typeof z!="object")continue;let q=String((Lr=z.id)!=null?Lr:`msg-${p()}`),G=z.role,Ne={id:q,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:p()};if(g(Ne),Ne.rawContent)try{let rt=JSON.parse(Ne.rawContent),ct=(cs=rt==null?void 0:rt.props)==null?void 0:cs.artifactId;typeof ct=="string"&&ae.add(ct)}catch{}b=null,S.current=null,le.delete(q),Ie.delete(q)}else if(ot==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let z=typeof w.error=="string"?w.error:((Do=w.error)==null?void 0:Do.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(z)});let q=b;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}else if(ot==="step_error"||ot==="dispatch_error"||ot==="flow_error"){let z=null;if(w.error instanceof Error)z=w.error;else if(ot==="dispatch_error"){let q=(ds=w.message)!=null?ds:w.error;q!=null&&q!==""&&(z=new Error(String(q)))}else{let q=w.error;typeof q=="string"&&q!==""?z=new Error(q):q!=null&&typeof q=="object"&&Reflect.has(q,"message")&&(z=new Error(String((so=q.message)!=null?so:q)))}if(z){n({type:"error",error:z});let q=b;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}}}}it.length=0};;){let{done:M,value:ue}=await s.read();if(M)break;i+=a.decode(ue,{stream:!0});let Te=i.split(`
12
12
 
13
- `);a=(fn=Me.pop())!=null?fn:"";for(let Ne of Me){let Ie=Ne.split(`
14
- `),Oe="message",Ge="";for(let ce of Ie)ce.startsWith("event:")?Oe=ce.replace("event:","").trim():ce.startsWith("data:")&&(Ge+=ce.replace("data:","").trim());if(!Ge)continue;let at;try{at=JSON.parse(Ge)}catch(ce){n({type:"error",error:ce instanceof Error?ce:new Error("Failed to parse chat stream payload")});continue}let Pt=Oe!=="message"?Oe:(xr=at.type)!=null?xr:"message";if((vr=this.onSSEEvent)==null||vr.call(this,Pt,at),this.parseSSEEvent){x.current=f;let ce=await this.handleCustomSSEEvent(at,n,x,g,l,E);if(x.current&&x.current!==f&&(f=x.current),ce)continue}J.push({payloadType:Pt,payload:at}),dt()}}dt()}};function ty(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function sa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Cs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Va="[Image]";function ny(e){return typeof e=="string"?[{type:"text",text:e}]:e}function ry(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function oy(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function sy(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ka(e){return{type:"text",text:e}}function ay(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function iy(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function ly(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Sm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],cy=["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"],Zr=[...Sm,...cy];function dy(e){return Sm.includes(e)||e.startsWith("image/")}function Ga(e){return dy(e.type)}async function Tm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ga(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Em(e,t=Zr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function py(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Mm(e,t){let n=py(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}ll();var km=16e3,uy=24e3,my=4096,gy=1380533830;function fy(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===gy?new Uint8Array(e,44):new Uint8Array(e)}function hy(e){var r;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var aa=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let t=(s=this.config)==null?void 0:s.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let l=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:km,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){l.getTracks().forEach(x=>x.stop());return}this.mediaStream=l;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:km});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new As(uy);if(o!==this.callGeneration){g.destroy(),l.getTracks().forEach(x=>x.stop()),u.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=`${hy(r)}/ws/agents/${encodeURIComponent(t)}/voice`,v=new WebSocket(f,["runtype.bearer",n]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,l,v,o))},v.onmessage=x=>this.handleMessage(x,o),v.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},v.onclose=x=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(x.code!==1e3){let E=x.code?` (code ${x.code})`:"";this.emitError(new Error(`Voice connection closed${E}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(l){throw this.cleanup(),this.emitError(l),this.emitStatus("error"),l}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,r,o){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(my,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),l=new Int16Array(d.length);for(let p=0;p<d.length;p++){let u=Math.max(-1,Math.min(1,d[p]));l[p]=u<0?u*32768:u*32767}r.send(l.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){var o,s;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let r;try{r=JSON.parse(t.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let r=fy(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,r){this.transcriptCallbacks.forEach(o=>o(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Xo=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Qo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new aa(e.runtype);case"browser":if(!Xo.isSupported())throw new Error("Browser speech recognition not supported");return new Xo(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function cl(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Qo({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Qo({type:"runtype",runtype:e.runtype});if(Xo.isSupported())return Qo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ja(e){try{return cl(e),!0}catch{return!1}}function ia(e){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of t){let o=e.find(s=>s.name===r);if(o)return o}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var Yo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t.text),s=r.getVoices();if(t.voice){let i=s.find(d=>d.name===t.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):ia(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var l,p;let d=i.error;d==="canceled"||d==="interrupted"?(l=n.onEnd)==null||l.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Ss=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){var r,o;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(t,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function dl(e){if(!e)return"";let t=yy(e);return Lm(t!==null?t:e)}function yy(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Lm(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
13
+ `);i=(yr=Te.pop())!=null?yr:"";for(let ke of Te){let He=ke.split(`
14
+ `),nt="message",Qe="",ht=null;for(let ce of He)ce.startsWith("event:")?nt=ce.replace("event:","").trim():ce.startsWith("data:")?Qe+=ce.replace("data:","").trim():ce.startsWith("id:")&&(ht=ce.slice(3).trim());let me=()=>{ht!==null&&ht!==""&&n({type:"cursor",id:ht})};if(!Qe){me();continue}let B;try{B=JSON.parse(Qe)}catch(ce){n({type:"error",error:ce instanceof Error?ce:new Error("Failed to parse chat stream payload")});continue}let xe=nt!=="message"?nt:(br=B.type)!=null?br:"message";if((Ue=this.onSSEEvent)==null||Ue.call(this,xe,B),this.parseSSEEvent){S.current=b;let ce=await this.handleCustomSSEEvent(B,n,S,g,p,T);if(S.current&&S.current!==b&&(b=S.current),ce){me();continue}}it.push({payloadType:xe,payload:B}),Ve(),me()}}Ve()}};function uy(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function aa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Xo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Va="[Image]";function my(e){return typeof e=="string"?[{type:"text",text:e}]:e}function gy(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function fy(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function hy(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ka(e){return{type:"text",text:e}}function yy(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function by(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function xy(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Hm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],vy=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Gr=[...Hm,...vy];function wy(e){return Hm.includes(e)||e.startsWith("image/")}function Ga(e){return wy(e.type)}async function Bm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ga(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Dm(e,t=Gr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Cy(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Nm(e,t){let n=Cy(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}dl();var Om=16e3,Ay=24e3,Sy=4096,Ty=1380533830;function Ey(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Ty?new Uint8Array(e,44):new Uint8Array(e)}function My(e){var r;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var ia=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let t=(s=this.config)==null?void 0:s.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Om,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(v=>v.stop());return}this.mediaStream=c;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:Om});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let f=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new Ss(Ay);if(o!==this.callGeneration){f.destroy(),c.getTracks().forEach(v=>v.stop()),u.close().catch(()=>{});return}this.playback=f,f.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let g=`${My(r)}/ws/agents/${encodeURIComponent(t)}/voice`,b=new WebSocket(g,["runtype.bearer",n]);b.binaryType="arraybuffer",this.ws=b,b.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,c,b,o))},b.onmessage=v=>this.handleMessage(v,o),b.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},b.onclose=v=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(v.code!==1e3){let S=v.code?` (code ${v.code})`:"";this.emitError(new Error(`Voice connection closed${S}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,r,o){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Sy,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let p=0;p<d.length;p++){let u=Math.max(-1,Math.min(1,d[p]));c[p]=u<0?u*32768:u*32767}r.send(c.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){var o,s;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let r;try{r=JSON.parse(t.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let r=Ey(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,r){this.transcriptCallbacks.forEach(o=>o(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var Qo=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Yo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ia(e.runtype);case"browser":if(!Qo.isSupported())throw new Error("Browser speech recognition not supported");return new Qo(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function pl(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Yo({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Yo({type:"runtype",runtype:e.runtype});if(Qo.isSupported())return Yo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ja(e){try{return pl(e),!0}catch{return!1}}function la(e){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of t){let o=e.find(s=>s.name===r);if(o)return o}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var Zo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t.text),s=r.getVoices();if(t.voice){let i=s.find(d=>d.name===t.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):la(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var c,p;let d=i.error;d==="canceled"||d==="interrupted"?(c=n.onEnd)==null||c.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Ts=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){var r,o;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(t,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function ul(e){if(!e)return"";let t=ky(e);return Fm(t!==null?t:e)}function ky(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Fm(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
15
15
  `),t=t.replace(/\n{2,}/g,`
16
- `),t.trim()}var Hm=null;var pl=()=>Hm?Hm():Promise.resolve().then(()=>(Wm(),Rm));var vy=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function wy(e,t){return vy.some(n=>e[n]!==t[n])}function Bm(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
16
+ `),t.trim()}var qm=null;var ml=()=>qm?qm():Promise.resolve().then(()=>(Um(),jm));var Wy=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Hy(e,t){return Wy.some(n=>e[n]!==t[n])}function gl(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
17
17
 
18
- _Details: ${n.message}_`:r}var la=e=>({isError:!0,content:[{type:"text",text:e}]}),Dm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Nm=e=>Ko(e)||e===Or,ca=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.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 Ss(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,o,s,a,i,d,l,p,u;if(t.type==="message"){this.upsertMessage(t.message);let g=t.message.toolCall,f=!!(g!=null&&g.name)&&(Ko(g.name)||g.name===Or&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&f&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.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"&&(t.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((l=this.agentExecution)==null?void 0:l.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,o;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new ws(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d,l;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(o=t.host)!=null?o:this.config.apiUrl,r=(l=(d=t.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId)!=null?l:this.config.agentId;!n||!r||!this.config.clientToken||pl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ja((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=Yo.isSupported()?new Yo({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let l=(r=t.host)!=null?r:this.config.apiUrl,p=(d=(i=t.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId)!=null?d:this.config.agentId,u=this.config.clientToken,g=t.browserFallback!==!1;if(l&&p&&u)return pl().then(({RuntypeSpeechEngine:f,FallbackSpeechEngine:v})=>{let x=new f({host:l,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return g&&n?new v(x,n,{onFallback:E=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${E.message}`)}):x});if(g&&n)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){var n,r;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Qo(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,l)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,l;(l=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||l.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,l;this.voiceStatus=i,this.voiceActive=i==="listening",(l=(d=this.callbacks).onVoiceStatusChanged)==null||l.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,o,s,a,i,d,l,p,u,g,f;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=t.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=t.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(l=(d=t.runtype)==null?void 0:d.host)!=null?l:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(u=t.runtype)==null?void 0:u.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((g=t.browser)==null?void 0:g.language)||"en-US",continuous:(f=t.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!wy(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 ws(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:u}=t,f={id:a!=null?a:n==="user"?sa():n==="assistant"?Cs():`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:l,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:u=!1,voiceProcessing:g,rawContent:f}=r,x={id:d!=null?d:o==="user"?sa():o==="assistant"?Cs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,p,u,g,f;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let o=sa(),s=Cs(),a={id:o,role:"user",content:r||Va,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let E=Bm(v,this.config.errorMessage);if(E){let T={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,v):(f=(g=this.callbacks).onError)==null||f.call(g,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=Cs();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let u=Bm(l,this.config.errorMessage);if(u){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,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(t,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 t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,g,f,v;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(l?x=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):x=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),x){let E=null;if(x instanceof Response){if(!x.ok){let T=await x.json().catch(()=>null);throw new Error((g=T==null?void 0:T.error)!=null?g:`Approval request failed: ${x.status}`)}E=x.body}else x instanceof ReadableStream&&(E=x);E?await this.connectStream(E,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(x){let E=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(v=(f=this.callbacks).onError)==null||v.call(f,x instanceof Error?x:new Error(String(x)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,g,f,v,x,E,T,L,k,M,P;let r=this.messages.find(C=>C.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(g=t.toolCall)==null?void 0:g.name;if(!o||!s){(v=(f=this.callbacks).onError)==null||v.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 C=(x=t.toolCall)==null?void 0:x.args,R=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(R.length===1){let F=typeof((E=R[0])==null?void 0:E.question)=="string"?R[0].question:"";F&&(a={[F]:n})}}this.markAskUserQuestionResolved(t,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(L=t.toolCall)==null?void 0:L.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let C=typeof n=="string"?n:Object.entries(n).map(([R,F])=>`${R}: ${Array.isArray(F)?F.join(", "):F}`).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:{};l.forEach((R,F)=>{let j=typeof(R==null?void 0:R.question)=="string"?R.question:"";if(!j)return;let H=C[j],O=Array.isArray(H)?H.join(", "):typeof H=="string"?H:"";this.appendMessage({id:`ask-user-q-${i}-${F}`,role:"assistant",content:j,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${F}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:n});if(!C.ok){let R=await C.json().catch(()=>null);throw new Error((k=R==null?void 0:R.error)!=null?k:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let R=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,R||(P=(M=this.callbacks).onError)==null||P.call(M,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var o,s;let n=this.messages.find(a=>a.id===t.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,o;if(((r=t.toolCall)==null?void 0:r.name)!==Or)return!1;let n=this.messages.find(s=>s.id===t.id);return((o=(n!=null?n:t).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,o=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,p,u;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async g=>{var P,C,R,F,j,H,O;let f=(P=g.toolCall)==null?void 0:P.name,v=(C=g.toolCall)==null?void 0:C.id;if(!f||!v)return null;let x=`${t}:${v}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(x),r.push(x);let E=this.markWebMcpToolRunning(g),T=(F=(R=g.agentMetadata)==null?void 0:R.webMcpToolCallId)!=null?F:f;if(f===Or)return{dedupeKey:x,resumeKey:T,output:el(),toolMessage:g,startedAt:E,completedAt:Date.now()};let L=new AbortController;this.webMcpResolveControllers.add(L),o.push(L);let k=this.client.executeWebMcpToolCall(f,(j=g.toolCall)==null?void 0:j.args,L.signal),M;if(!k)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await k}catch(N){let Y=N instanceof Error&&(N.name==="AbortError"||N.message.includes("aborted")||N.message.includes("abort"));return Y||(O=(H=this.callbacks).onError)==null||O.call(H,N instanceof Error?N:new Error(String(N))),this.markWebMcpToolComplete(g,la(Y?"Aborted by cancel()":Dm(N)),E),this.webMcpInflightKeys.delete(x),null}return L.signal.aborted?(this.markWebMcpToolComplete(g,la("Aborted by cancel()"),E),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:T,output:M,toolMessage:g,startedAt:E,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let g={};for(let v of i)g[v.resumeKey]=v.output;let f=await this.client.resumeFlow(t,g,{signal:s.signal});if(!f.ok){let v=await f.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${f.status}`)}for(let v of i)this.webMcpResolvedKeys.add(v.dedupeKey),this.markWebMcpToolComplete(v.toolMessage,v.output,v.startedAt,v.completedAt,((l=v.toolMessage.toolCall)==null?void 0:l.name)===Or?{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"))))(u=(p=this.callbacks).onError)==null||u.call(p,g instanceof Error?g:new Error(String(g)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,la("Aborted by cancel()"),v.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(t){var v,x,E,T,L,k,M,P,C,R,F,j;let n=(v=t.agentMetadata)==null?void 0:v.executionId,r=(x=t.toolCall)==null?void 0:x.name,o=(E=t.toolCall)==null?void 0:E.id;if(!n){(L=(T=this.callbacks).onError)==null||L.call(T,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let 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(O){(M=(k=this.callbacks).onError)==null||M.call(k,O instanceof Error?O:new Error(String(O)))}finally{this.webMcpInflightKeys.delete(H)}return}let s=`${n}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=r===Or,p=(P=t.toolCall)==null?void 0:P.args,u=l?null:this.client.executeWebMcpToolCall(r,p,d),g="execute",f=a;try{let H;if(l?H=el():u?H=await u:H={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,la("Aborted by cancel()"),a);return}let O=(R=(C=t.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?R:r;g="resume",await this.resumeWithToolOutput(n,O,H,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,H,a,f,l?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(H){let O=H instanceof Error&&(H.name==="AbortError"||H.message.includes("aborted")||H.message.includes("abort"));(g==="execute"||O||d.aborted)&&this.markWebMcpToolComplete(t,la(O||d.aborted?"Aborted by cancel()":Dm(H)),a),O||(j=(F=this.callbacks).onError)==null||j.call(F,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(t,n,r,o){var a,i;let s=await this.client.resumeFlow(t,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var o;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=dl(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return ia(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let r=dl(n.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var p,u,g,f,v,x,E,T,L,k,M,P,C,R,F;if(s!==r)return o;let a={...o,...n};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=o.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(g=a.agentMetadata)!=null?g:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let j=o.approval,H=n.approval;a.approval={...j,...H,executionId:H.executionId||j.executionId,toolName:H.toolName||j.toolName,description:H.description||j.description,toolType:(f=H.toolType)!=null?f:j.toolType,reason:(v=H.reason)!=null?v:j.reason,parameters:(x=H.parameters)!=null?x:j.parameters}}let i=(E=n.toolCall)==null?void 0:E.name,d=(T=n.agentMetadata)==null?void 0:T.executionId,l=(L=n.toolCall)==null?void 0:L.id;if(i&&Nm(i)&&d&&l&&((k=n.agentMetadata)==null?void 0:k.awaitingLocalTool)===!0){let j=`${d}:${l}`,H=this.webMcpInflightKeys.has(j),O=this.webMcpResolvedKeys.has(j),N=(M=o.toolCall)==null?void 0:M.name,Y=((P=o.agentMetadata)==null?void 0:P.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===l&&N!==void 0&&Nm(N)&&((R=o.toolCall)==null?void 0:R.status)==="complete";(H||O||Y)&&(a.agentMetadata={...(F=a.agentMetadata)!=null?F:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,l;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=(l=r.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};import{Activity as Cy,ArrowDown as Ay,ArrowUp as Sy,ArrowUpRight as Ty,Bot as Ey,ChevronDown as My,ChevronUp as ky,ChevronRight as Ly,ChevronLeft as Py,Check as Iy,Clipboard as Ry,ClipboardCopy as Wy,Copy as Hy,File as By,FileCode as Dy,FileSpreadsheet as Ny,FileText as Oy,ImagePlus as Fy,Loader as _y,LoaderCircle as $y,Mic as jy,Paperclip as Uy,RefreshCw as qy,Search as zy,Send as Vy,ShieldAlert as Ky,ShieldCheck as Gy,ShieldX as Jy,Square as Xy,ThumbsDown as Qy,ThumbsUp as Yy,Upload as Zy,Volume2 as eb,X as tb,User as nb,Mail as rb,Phone as ob,Calendar as sb,Clock as ab,Building as ib,MapPin as lb,Lock as cb,Key as db,CreditCard as pb,AtSign as ub,Hash as mb,Globe as gb,Link as fb,CircleCheck as hb,CircleX as yb,TriangleAlert as bb,Info as xb,Ban as vb,Shield as wb,ArrowLeft as Cb,ArrowRight as Ab,ExternalLink as Sb,Ellipsis as Tb,EllipsisVertical as Eb,Menu as Mb,House as kb,Plus as Lb,Minus as Pb,Pencil as Ib,Trash as Rb,Trash2 as Wb,Save as Hb,Download as Bb,Share as Db,Funnel as Nb,Settings as Ob,RotateCw as Fb,Maximize as _b,Minimize as $b,ShoppingCart as jb,ShoppingBag as Ub,Package as qb,Truck as zb,Tag as Vb,Gift as Kb,Receipt as Gb,Wallet as Jb,Store as Xb,DollarSign as Qb,Percent as Yb,Play as Zb,Pause as ex,VolumeX as tx,Camera as nx,Image as rx,Film as ox,Headphones as sx,MessageCircle as ax,MessageSquare as ix,Bell as lx,Heart as cx,Star as dx,Eye as px,EyeOff as ux,Bookmark as mx,CalendarDays as gx,History as fx,Timer as hx,Folder as yx,FolderOpen as bx,Files as xx,Sparkles as vx,Zap as wx,Sun as Cx,Moon as Ax,Flag as Sx,Monitor as Tx,Smartphone as Ex}from"lucide";var Mx={activity:Cy,"arrow-down":Ay,"arrow-up":Sy,"arrow-up-right":Ty,bot:Ey,"chevron-down":My,"chevron-up":ky,"chevron-right":Ly,"chevron-left":Py,check:Iy,clipboard:Ry,"clipboard-copy":Wy,copy:Hy,file:By,"file-code":Dy,"file-spreadsheet":Ny,"file-text":Oy,"image-plus":Fy,loader:_y,"loader-circle":$y,mic:jy,paperclip:Uy,"refresh-cw":qy,search:zy,send:Vy,"shield-alert":Ky,"shield-check":Gy,"shield-x":Jy,square:Xy,"thumbs-down":Qy,"thumbs-up":Yy,upload:Zy,"volume-2":eb,x:tb,user:nb,mail:rb,phone:ob,calendar:sb,clock:ab,building:ib,"map-pin":lb,lock:cb,key:db,"credit-card":pb,"at-sign":ub,hash:mb,globe:gb,link:fb,"circle-check":hb,"circle-x":yb,"triangle-alert":bb,info:xb,ban:vb,shield:wb,"arrow-left":Cb,"arrow-right":Ab,"external-link":Sb,ellipsis:Tb,"ellipsis-vertical":Eb,menu:Mb,house:kb,plus:Lb,minus:Pb,pencil:Ib,trash:Rb,"trash-2":Wb,save:Hb,download:Bb,share:Db,funnel:Nb,settings:Ob,"rotate-cw":Fb,maximize:_b,minimize:$b,"shopping-cart":jb,"shopping-bag":Ub,package:qb,truck:zb,tag:Vb,gift:Kb,receipt:Gb,wallet:Jb,store:Xb,"dollar-sign":Qb,percent:Yb,play:Zb,pause:ex,"volume-x":tx,camera:nx,image:rx,film:ox,headphones:sx,"message-circle":ax,"message-square":ix,bell:lx,heart:cx,star:dx,eye:px,"eye-off":ux,bookmark:mx,"calendar-days":gx,history:fx,timer:hx,folder:yx,"folder-open":bx,files:xx,sparkles:vx,zap:wx,sun:Cx,moon:Ax,flag:Sx,monitor:Tx,smartphone:Ex},ge=(e,t=24,n="currentColor",r=2)=>{let o=Mx[e];return o?kx(o,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function kx(e,t,n,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),o.appendChild(d)}),o}var Ya={allowedTypes:Zr,maxFileSize:10*1024*1024,maxFiles:4};function Lx(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Px(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Ts=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ya.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Ya.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Ya.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ya.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,o,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,l,"count");continue}let p=Em(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,u);continue}try{let u=await Tm(l),g=Ga(l)?URL.createObjectURL(l):null,f={id:Lx(),file:l,previewUrl:g,contentPart:u};this.attachments.push(f),this.renderPreview(f)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ga(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=y("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Px(t.file.type),d=ge(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=y("span");l.textContent=Mm(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.appendChild(a)}let o=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ge("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var Om=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function da(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];Om(s)&&Om(o)?n[r]=da(s,o):n[r]=o}return n}var nr="min(440px, calc(100vw - 24px))",ul="440px",Ix={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:nr,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:Ix,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(e,t){if(!(!e&&!t))return e?t?da(e,t):e:t}function ml(e){var t,n,r,o,s,a,i,d,l,p,u,g,f,v,x,E,T,L,k,M,P;return e?{...Dt,...e,theme:Fm(Dt.theme,e.theme),darkTheme:Fm(Dt.darkTheme,e.darkTheme),launcher:{...Dt.launcher,...e.launcher,dock:{...(t=Dt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Dt.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Dt.copy,...e.copy},sendButton:{...Dt.sendButton,...e.sendButton},statusIndicator:{...Dt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Dt.voiceRecognition,...e.voiceRecognition},features:(()=>{var se,ie,ae,xe,Be,V,X,He,K,ue;let C=(se=Dt.features)==null?void 0:se.artifacts,R=(ie=e.features)==null?void 0:ie.artifacts,F=(ae=Dt.features)==null?void 0:ae.scrollToBottom,j=(xe=e.features)==null?void 0:xe.scrollToBottom,H=(Be=Dt.features)==null?void 0:Be.scrollBehavior,O=(V=e.features)==null?void 0:V.scrollBehavior,N=(X=Dt.features)==null?void 0:X.streamAnimation,Y=(He=e.features)==null?void 0:He.streamAnimation,ke=(K=Dt.features)==null?void 0:K.askUserQuestion,pe=(ue=e.features)==null?void 0:ue.askUserQuestion,Z=C===void 0&&R===void 0?void 0:{...C,...R,layout:{...C==null?void 0:C.layout,...R==null?void 0:R.layout}},Te=F===void 0&&j===void 0?void 0:{...F,...j},Le=H===void 0&&O===void 0?void 0:{...H,...O},oe=N===void 0&&Y===void 0?void 0:{...N,...Y},Ae=ke===void 0&&pe===void 0?void 0:{...ke,...pe,styles:{...ke==null?void 0:ke.styles,...pe==null?void 0:pe.styles}};return{...Dt.features,...e.features,...Te!==void 0?{scrollToBottom:Te}:{},...Le!==void 0?{scrollBehavior:Le}:{},...Z!==void 0?{artifacts:Z}:{},...oe!==void 0?{streamAnimation:oe}:{},...Ae!==void 0?{askUserQuestion:Ae}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Dt.suggestionChips,suggestionChipsConfig:{...Dt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Dt.layout,...e.layout,header:{...(a=Dt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Dt.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(p=Dt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(f=(g=e.layout)==null?void 0:g.messages)==null?void 0:f.avatar},timestamp:{...(x=(v=Dt.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(T=(E=e.layout)==null?void 0:E.messages)==null?void 0:T.timestamp}},slots:{...(L=Dt.layout)==null?void 0:L.slots,...(k=e.layout)==null?void 0:k.slots}},markdown:{...Dt.markdown,...e.markdown,options:{...(M=Dt.markdown)==null?void 0:M.options,...(P=e.markdown)==null?void 0:P.options}},messageActions:{...Dt.messageActions,...e.messageActions}}:Dt}var _m={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"}},$m={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"}},jm={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:nr,maxWidth:ul,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 Es(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Es(e,r):r}function gl(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Es(e,a);d!==void 0&&(t[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function Um(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function qm(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=qm(s,o):n[r]=o}return n}function Rx(e,t){return t?qm(e,t):e}function pa(e,t={}){var o,s,a,i,d,l,p,u,g,f,v,x,E;let n={palette:_m,semantic:$m,components:jm},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(g=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(v=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:v.feedback}},spacing:{...n.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...n.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:Rx(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=Um(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(L=>L.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)r=T.transform(r);return r}function fl(e){var x,E,T,L,k,M,P,C,R,F,j,H,O,N,Y,ke,pe,Z,Te,Le,oe,Ae,se,ie,ae,xe,Be,V,X,He,K,ue,$e,fe,Ve,et,Ot,Xe,ye,J,dt,qe,Se,ve,nt,Lt,ee,je,wn,bt,fn,xr,vr,A,te,Me,Ne,Ie,Oe,Ge,at,Pt,ce,B,be,_e,xt,Ye,Rt,St,ht,kt,Xt,Ft,en,wr,$r,sr,ar,to,qt,ir,jr,In,kn,Rn,lr,Cr,no,qn,ro,vt,Ar,Sr,Ur,cr,ut,Io,Tr,Ro,Ln,os,oo,qr,so,ao,Wo,Ho,io,yt,Wn,Hn,Cn,wt,zn,Vn,Bn,lo;let t=gl(e),n={};for(let[Ce,zr]of Object.entries(t)){let Kn=Ce.replace(/\./g,"-");n[`--persona-${Kn}`]=zr.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(E=n["--persona-semantic-colors-secondary"])!=null?E:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(T=n["--persona-semantic-colors-accent"])!=null?T:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(L=n["--persona-semantic-colors-surface"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(k=n["--persona-semantic-colors-background"])!=null?k: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"]=(P=n["--persona-semantic-colors-text"])!=null?P:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(C=n["--persona-semantic-colors-text-muted"])!=null?C:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(R=n["--persona-semantic-colors-text-inverse"])!=null?R:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(F=n["--persona-semantic-colors-border"])!=null?F:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(j=n["--persona-semantic-colors-divider"])!=null?j:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(H=n["--persona-components-voice-recording-indicator"])!=null?H:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(O=n["--persona-components-voice-recording-background"])!=null?O:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(N=n["--persona-components-voice-processing-icon"])!=null?N:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(Y=n["--persona-components-voice-speaking-icon"])!=null?Y:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(ke=n["--persona-components-approval-requested-background"])!=null?ke:n["--persona-surface"],n["--persona-approval-border"]=(pe=n["--persona-components-approval-requested-border"])!=null?pe:n["--persona-border"],n["--persona-approval-text"]=(Z=n["--persona-components-approval-requested-text"])!=null?Z:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Te=n["--persona-components-approval-requested-shadow"])!=null?Te:"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"]=(Le=n["--persona-components-approval-approve-background"])!=null?Le:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(oe=n["--persona-components-approval-deny-background"])!=null?oe:n["--persona-container"],n["--persona-attachment-image-bg"]=(Ae=n["--persona-components-attachment-image-background"])!=null?Ae:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(se=n["--persona-components-attachment-image-border"])!=null?se:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(ie=n["--persona-semantic-typography-fontFamily"])!=null?ie:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(ae=n["--persona-semantic-typography-fontSize"])!=null?ae:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(xe=n["--persona-semantic-typography-fontWeight"])!=null?xe:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(Be=n["--persona-semantic-typography-lineHeight"])!=null?Be:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(V=n["--persona-palette-radius-sm"])!=null?V:"0.125rem",n["--persona-radius-md"]=(X=n["--persona-palette-radius-md"])!=null?X:"0.375rem",n["--persona-radius-lg"]=(He=n["--persona-palette-radius-lg"])!=null?He:"0.5rem",n["--persona-radius-xl"]=(K=n["--persona-palette-radius-xl"])!=null?K:"0.75rem",n["--persona-radius-full"]=(ue=n["--persona-palette-radius-full"])!=null?ue:"9999px",n["--persona-launcher-radius"]=(fe=($e=n["--persona-components-launcher-borderRadius"])!=null?$e:n["--persona-palette-radius-full"])!=null?fe:"9999px",n["--persona-launcher-bg"]=(Ve=n["--persona-components-launcher-background"])!=null?Ve:n["--persona-primary"],n["--persona-launcher-fg"]=(et=n["--persona-components-launcher-foreground"])!=null?et:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Ot=n["--persona-components-launcher-border"])!=null?Ot:n["--persona-border"],n["--persona-button-primary-bg"]=(Xe=n["--persona-components-button-primary-background"])!=null?Xe:n["--persona-primary"],n["--persona-button-primary-fg"]=(ye=n["--persona-components-button-primary-foreground"])!=null?ye:n["--persona-text-inverse"],n["--persona-button-radius"]=(dt=(J=n["--persona-components-button-primary-borderRadius"])!=null?J:n["--persona-palette-radius-full"])!=null?dt:"9999px",n["--persona-panel-radius"]=(Se=(qe=n["--persona-components-panel-borderRadius"])!=null?qe:n["--persona-radius-xl"])!=null?Se:"0.75rem",n["--persona-panel-border"]=(ve=n["--persona-components-panel-border"])!=null?ve:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Lt=(nt=n["--persona-components-panel-shadow"])!=null?nt:n["--persona-palette-shadows-xl"])!=null?Lt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(ee=n["--persona-components-launcher-shadow"])!=null?ee:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(wn=(je=n["--persona-components-input-borderRadius"])!=null?je:n["--persona-radius-lg"])!=null?wn:"0.5rem",n["--persona-message-user-radius"]=(fn=(bt=n["--persona-components-message-user-borderRadius"])!=null?bt:n["--persona-radius-lg"])!=null?fn:"0.5rem",n["--persona-message-assistant-radius"]=(vr=(xr=n["--persona-components-message-assistant-borderRadius"])!=null?xr:n["--persona-radius-lg"])!=null?vr:"0.5rem",n["--persona-header-bg"]=(A=n["--persona-components-header-background"])!=null?A:n["--persona-surface"],n["--persona-header-border"]=(te=n["--persona-components-header-border"])!=null?te:n["--persona-divider"],n["--persona-header-icon-bg"]=(Me=n["--persona-components-header-iconBackground"])!=null?Me: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"]=(Ie=n["--persona-components-header-titleForeground"])!=null?Ie:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Oe=n["--persona-components-header-subtitleForeground"])!=null?Oe:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Ge=n["--persona-components-header-actionIconForeground"])!=null?Ge:n["--persona-muted"];let r=(at=e.components)==null?void 0:at.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(Pt=e.components)==null?void 0:Pt.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"]=(be=n["--persona-components-introCard-padding"])!=null?be:"1.5rem",n["--persona-intro-card-shadow"]=(xt=(_e=o==null?void 0:o.shadow)!=null?_e:n["--persona-components-introCard-shadow"])!=null?xt:"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"]=(Rt=n["--persona-components-input-placeholder"])!=null?Rt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(St=n["--persona-components-message-user-background"])!=null?St: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"]=(kt=n["--persona-components-message-user-shadow"])!=null?kt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Xt=n["--persona-components-message-assistant-background"])!=null?Xt:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ft=n["--persona-components-message-assistant-text"])!=null?Ft:n["--persona-text"],n["--persona-message-assistant-border"]=(en=n["--persona-components-message-assistant-border"])!=null?en:n["--persona-border"],n["--persona-message-assistant-shadow"]=(wr=n["--persona-components-message-assistant-shadow"])!=null?wr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(sr=($r=n["--persona-components-scrollToBottom-background"])!=null?$r:n["--persona-button-primary-bg"])!=null?sr:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(to=(ar=n["--persona-components-scrollToBottom-foreground"])!=null?ar:n["--persona-button-primary-fg"])!=null?to:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(qt=n["--persona-components-scrollToBottom-border"])!=null?qt:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ir=n["--persona-components-scrollToBottom-size"])!=null?ir:"40px",n["--persona-scroll-to-bottom-radius"]=(kn=(In=(jr=n["--persona-components-scrollToBottom-borderRadius"])!=null?jr:n["--persona-button-radius"])!=null?In:n["--persona-radius-full"])!=null?kn:"9999px",n["--persona-scroll-to-bottom-shadow"]=(lr=(Rn=n["--persona-components-scrollToBottom-shadow"])!=null?Rn:n["--persona-palette-shadows-sm"])!=null?lr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Cr=n["--persona-components-scrollToBottom-padding"])!=null?Cr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(no=n["--persona-components-scrollToBottom-gap"])!=null?no:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(ro=(qn=n["--persona-components-scrollToBottom-fontSize"])!=null?qn:n["--persona-palette-typography-fontSize-sm"])!=null?ro:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(vt=n["--persona-components-scrollToBottom-iconSize"])!=null?vt:"14px",n["--persona-tool-bubble-shadow"]=(Ar=n["--persona-components-toolBubble-shadow"])!=null?Ar:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Sr=n["--persona-components-reasoningBubble-shadow"])!=null?Sr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Ur=n["--persona-components-composer-shadow"])!=null?Ur:"none",n["--persona-md-inline-code-bg"]=(cr=n["--persona-components-markdown-inlineCode-background"])!=null?cr:n["--persona-container"],n["--persona-md-inline-code-color"]=(ut=n["--persona-components-markdown-inlineCode-foreground"])!=null?ut:n["--persona-text"],n["--persona-md-link-color"]=(Tr=(Io=n["--persona-components-markdown-link-foreground"])!=null?Io:n["--persona-accent"])!=null?Tr:"#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 l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(Ro=n["--persona-components-markdown-codeBlock-background"])!=null?Ro:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Ln=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Ln:n["--persona-border"],n["--persona-md-code-block-text-color"]=(os=n["--persona-components-markdown-codeBlock-textColor"])!=null?os:"inherit",n["--persona-md-table-header-bg"]=(oo=n["--persona-components-markdown-table-headerBackground"])!=null?oo:n["--persona-container"],n["--persona-md-table-border-color"]=(qr=n["--persona-components-markdown-table-borderColor"])!=null?qr:n["--persona-border"],n["--persona-md-hr-color"]=(so=n["--persona-components-markdown-hr-color"])!=null?so:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(ao=n["--persona-components-markdown-blockquote-borderColor"])!=null?ao:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Wo=n["--persona-components-markdown-blockquote-background"])!=null?Wo:"transparent",n["--persona-md-blockquote-text-color"]=(Ho=n["--persona-components-markdown-blockquote-textColor"])!=null?Ho:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(io=n["--persona-components-collapsibleWidget-container"])!=null?io:n["--persona-surface"],n["--cw-surface"]=(yt=n["--persona-components-collapsibleWidget-surface"])!=null?yt:n["--persona-surface"],n["--cw-border"]=(Wn=n["--persona-components-collapsibleWidget-border"])!=null?Wn:n["--persona-border"],n["--persona-message-border"]=(Hn=n["--persona-components-message-border"])!=null?Hn:n["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let g=p==null?void 0:p.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=p==null?void 0:p.toggleGroup;f&&(f.gap&&(n["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(n["--persona-toggle-group-radius"]=f.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let Ce=v.toolbar;Ce.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=Ce.iconHoverColor),Ce.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=Ce.iconHoverBackground),Ce.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=Ce.iconPadding),Ce.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=Ce.iconBorderRadius),Ce.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=Ce.iconBorder),Ce.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Ce.toggleGroupGap),Ce.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=Ce.toggleBorderRadius),Ce.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=Ce.copyBackground),Ce.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=Ce.copyBorder),Ce.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=Ce.copyColor),Ce.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Ce.copyBorderRadius),Ce.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=Ce.copyPadding),Ce.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=Ce.copyMenuBackground,n["--persona-dropdown-bg"]=(Cn=n["--persona-dropdown-bg"])!=null?Cn:Ce.copyMenuBackground),Ce.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=Ce.copyMenuBorder,n["--persona-dropdown-border"]=(wt=n["--persona-dropdown-border"])!=null?wt:Ce.copyMenuBorder),Ce.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=Ce.copyMenuShadow,n["--persona-dropdown-shadow"]=(zn=n["--persona-dropdown-shadow"])!=null?zn:Ce.copyMenuShadow),Ce.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=Ce.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Vn=n["--persona-dropdown-radius"])!=null?Vn:Ce.copyMenuBorderRadius),Ce.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Ce.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Bn=n["--persona-dropdown-item-hover-bg"])!=null?Bn:Ce.copyMenuItemHoverBackground),Ce.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=Ce.iconBackground),Ce.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=Ce.toolbarBorder)}if(v!=null&&v.tab){let Ce=v.tab;Ce.background&&(n["--persona-artifact-tab-bg"]=Ce.background),Ce.activeBackground&&(n["--persona-artifact-tab-active-bg"]=Ce.activeBackground),Ce.activeBorder&&(n["--persona-artifact-tab-active-border"]=Ce.activeBorder),Ce.borderRadius&&(n["--persona-artifact-tab-radius"]=Ce.borderRadius),Ce.textColor&&(n["--persona-artifact-tab-color"]=Ce.textColor),Ce.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=Ce.hoverBackground),Ce.listBackground&&(n["--persona-artifact-tab-list-bg"]=Ce.listBackground),Ce.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=Ce.listBorderColor),Ce.listPadding&&(n["--persona-artifact-tab-list-padding"]=Ce.listPadding)}if(v!=null&&v.pane){let Ce=v.pane;if(Ce.toolbarBackground){let zr=(lo=Es(e,Ce.toolbarBackground))!=null?lo:Ce.toolbarBackground;n["--persona-artifact-toolbar-bg"]=zr}}return n}var Wx={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Hx={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"}}},zm=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Za=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Bx=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Za()},Vm=e=>Bx(e),Dx=e=>pa(e),Nx=e=>{var n;let t=pa(void 0,{validate:!1});return pa({...e,palette:{...t.palette,colors:{...Hx.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ua=e=>{let t=Vm(e),n=zm(e==null?void 0:e.theme),r=zm(e==null?void 0:e.darkTheme);return t==="dark"?Nx(da(n!=null?n:{},r!=null?r:{})):Dx(n)},Ox=e=>fl(e),Zo=(e,t)=>{let n=ua(t),r=Ox(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},hl=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Za())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Za());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};import{Idiomorph as Fx}from"idiomorph";var ei=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Fx.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Km=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var ti={index:-1,draft:""};function Gm(e){let{direction:t,history:n,currentValue:r,atStart:o,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...ti}}}function Jm(e,t){var n,r,o,s,a,i,d,l,p,u,g,f,v,x,E,T,L,k,M,P,C,R,F,j,H,O,N,Y,ke,pe,Z,Te,Le,oe,Ae,se,ie,ae;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(g=(u=e.approval)==null?void 0:u.status)!=null?g:"",(v=(f=e.toolCall)==null?void 0:f.status)!=null?v:"",(E=(x=e.toolCall)==null?void 0:x.name)!=null?E:"",(k=(L=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:L.length)!=null?k:0,(R=(C=(P=(M=e.toolCall)==null?void 0:M.chunks)==null?void 0:P[e.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?R:"",typeof((F=e.toolCall)==null?void 0:F.args)=="string"?e.toolCall.args.length:(j=e.toolCall)!=null&&j.args?JSON.stringify(e.toolCall.args).length:0,(N=(O=(H=e.reasoning)==null?void 0:H.chunks)==null?void 0:O.length)!=null?N:0,(Z=(pe=(ke=(Y=e.reasoning)==null?void 0:Y.chunks)==null?void 0:ke[e.reasoning.chunks.length-1])==null?void 0:pe.length)!=null?Z:0,(Ae=(oe=(Le=(Te=e.reasoning)==null?void 0:Te.chunks)==null?void 0:Le[e.reasoning.chunks.length-1])==null?void 0:oe.slice(-32))!=null?Ae:"",(ie=(se=e.contentParts)==null?void 0:se.length)!=null?ie:0,(ae=e.stopReason)!=null?ae:"",t].join("\0")}function Xm(){return new Map}function Qm(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Ym(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Zm(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ni(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Fr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function So(e,t){return Fr(e)-e.scrollTop<=t}function ri(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function oi(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return t&&n<0?"pause":!t&&o&&n>0&&r?"resume":"none"}function eg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function tg(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function ng(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var xn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},vn=1e5,To=vn+1;var ma={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},_x=["pre","code","a","script","style"],si=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:ma.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ma.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:ma.speed,duration:(o=e==null?void 0:e.duration)!=null?o:ma.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ma.buffer}},og=[{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"}],ga=new Map;for(let e of og)ga.set(e.name,e);var $x=e=>{ga.set(e.name,e)},jx=e=>{og.some(t=>t.name===e)||ga.delete(e)},Ux=()=>Array.from(ga.keys()),fa=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=ga.get(e))!=null?r:null},ai=(e,t,n,r,o)=>{if(!o)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
19
- `);return s<0?"":e.slice(0,s)}return e},qx=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},zx=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},yl=/\s/,Vx=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},Kx=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(yl.test(s[i])){let l=i;for(;l<s.length&&yl.test(s[l]);)l+=1;a.appendChild(r.createTextNode(s.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<s.length&&!yl.test(s[p]);)l.appendChild(qx(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,e)},Gx=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(zx(r,l,t,n.value)),n.value+=1));o.replaceChild(a,e)},ha=(e,t,n,r)=>{var u,g;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((u=r==null?void 0:r.skipTags)!=null?u:_x).map(f=>f.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Vx(d,s)||i.push(d),d=a.nextNode();let l={value:(g=r==null?void 0:r.startIndex)!=null?g:0},p=t==="char"?Kx:Gx;for(let f of i)p(f,n,l);return o.innerHTML},ii=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},ya=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},rg=new WeakMap,Jx=(e,t)=>{var s;if(!e.styles)return;let n=rg.get(t);if(n||(n=new Set,rg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},bl=new WeakMap,Xx=(e,t)=>{if(!e.onAttach)return;let n=bl.get(t);if(n||(n=new Map,bl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},sg=e=>{let t=bl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},xl=(e,t)=>{Jx(e,t),Xx(e,t)};function vl(e,t=vn){let n=e.style.position,r=e.style.zIndex,o=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=o}}var ba=0,Eo=null;function wl(e=document){var n;if(ba++,ba===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;Eo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,ba=Math.max(0,ba-1),ba===0&&Eo)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=Eo.originalOverflow,o.style.position=Eo.originalPosition,o.style.top=Eo.originalTop,o.style.width=Eo.originalWidth,s.scrollTo(0,Eo.scrollY),Eo=null}}}var xa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},dn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},Mo=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},rr=e=>{var n,r,o,s,a,i;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:xa.side,width:(o=t==null?void 0:t.width)!=null?o:xa.width,animate:(s=t==null?void 0:t.animate)!=null?s:xa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:xa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:xa.maxHeight}};var br={"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 Qx="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",li=(e,t={})=>{var E,T,L,k,M,P;let{showClose:n=!0,wrapperClassName:r=Qx,buttonSize:o,iconSize:s="28px"}=t,a=(E=e==null?void 0:e.launcher)!=null?E:{},i=(T=o!=null?o:a.closeButtonSize)!=null?T:"32px",d=y("div",r),l=(L=a.closeButtonTooltipText)!=null?L:"Close chat",p=(k=a.closeButtonShowTooltip)!=null?k:!0,u=(M=a.closeButtonIconName)!=null?M:"x",g=(P=a.closeButtonIconText)!=null?P:"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=At("button",{className:Ys("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":l},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Mn.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}}),x=ge(u,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=g,d.appendChild(v),p&&l){let C=null,R=()=>{if(C)return;let j=v.ownerDocument,H=j.body;if(!H)return;C=Nr(j,"div","persona-clear-chat-tooltip"),C.textContent=l;let O=Nr(j,"div");O.className="persona-clear-chat-tooltip-arrow",C.appendChild(O);let N=v.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(To),C.style.left=`${N.left+N.width/2}px`,C.style.top=`${N.top-8}px`,C.style.transform="translate(-50%, -100%)",H.appendChild(C)},F=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",R),d.addEventListener("mouseleave",F),v.addEventListener("focus",R),v.addEventListener("blur",F),d._cleanupTooltip=()=>{F(),d.removeEventListener("mouseenter",R),d.removeEventListener("mouseleave",F),v.removeEventListener("focus",R),v.removeEventListener("blur",F)}}return{button:v,wrapper:d}},Yx="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ci=(e,t={})=>{var C,R,F,j,H,O,N,Y,ke,pe,Z,Te,Le;let{wrapperClassName:n=Yx,buttonSize:r,iconSize:o="20px"}=t,a=(R=((C=e==null?void 0:e.launcher)!=null?C:{}).clearChat)!=null?R:{},i=(F=r!=null?r:a.size)!=null?F:"32px",d=(j=a.iconName)!=null?j:"refresh-cw",l=(H=a.iconColor)!=null?H:"",p=(O=a.backgroundColor)!=null?O:"",u=(N=a.borderWidth)!=null?N:"",g=(Y=a.borderColor)!=null?Y:"",f=(ke=a.borderRadius)!=null?ke:"",v=(pe=a.paddingX)!=null?pe:"",x=(Z=a.paddingY)!=null?Z:"",E=(Te=a.tooltipText)!=null?Te:"Clear chat",T=(Le=a.showTooltip)!=null?Le:!0,L=y("div",n),k=!!(u||g),M=At("button",{className:Ys("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!k&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:i,width:i,color:l||Mn.actionIconColor,backgroundColor:p||void 0,border:k?`${u||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),P=ge(d,o,"currentColor",1);if(P&&(P.style.display="block",M.appendChild(P)),L.appendChild(M),T&&E){let oe=null,Ae=()=>{if(oe)return;let ie=M.ownerDocument,ae=ie.body;if(!ae)return;oe=Nr(ie,"div","persona-clear-chat-tooltip"),oe.textContent=E;let xe=Nr(ie,"div");xe.className="persona-clear-chat-tooltip-arrow",oe.appendChild(xe);let Be=M.getBoundingClientRect();oe.style.position="fixed",oe.style.zIndex=String(To),oe.style.left=`${Be.left+Be.width/2}px`,oe.style.top=`${Be.top-8}px`,oe.style.transform="translate(-50%, -100%)",ae.appendChild(oe)},se=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};L.addEventListener("mouseenter",Ae),L.addEventListener("mouseleave",se),M.addEventListener("focus",Ae),M.addEventListener("blur",se),L._cleanupTooltip=()=>{se(),L.removeEventListener("mouseenter",Ae),L.removeEventListener("mouseleave",se),M.removeEventListener("focus",Ae),M.removeEventListener("blur",se)}}return{button:M,wrapper:L}};var Mn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},ko=e=>{var P,C,R,F,j,H,O,N,Y,ke,pe,Z,Te,Le,oe,Ae;let{config:t,showClose:n=!0}=e,r=At("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),o=(P=t==null?void 0:t.launcher)!=null?P:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(R=o.closeButtonPlacement)!=null?R:"inline",i=(F=o.headerIconHidden)!=null?F:!1,d=o.headerIconName,l=At("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 se=parseFloat(s)||24,ie=ge(d,se*.6,"currentColor",1);ie?l.replaceChildren(ie):l.textContent=(H=(j=t==null?void 0:t.launcher)==null?void 0:j.agentIconText)!=null?H:"\u{1F4AC}"}else if((O=t==null?void 0:t.launcher)!=null&&O.iconUrl){let se=y("img");se.src=t.launcher.iconUrl,se.alt="",se.className="persona-rounded-xl persona-object-cover",se.style.height=s,se.style.width=s,l.replaceChildren(se)}else l.textContent=(Y=(N=t==null?void 0:t.launcher)==null?void 0:N.agentIconText)!=null?Y:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=At("span",{className:"persona-text-base persona-font-semibold",text:(pe=(ke=t==null?void 0:t.launcher)==null?void 0:ke.title)!=null?pe:"Chat Assistant",style:{color:Mn.titleColor}}),g=At("span",{className:"persona-text-xs",text:(Te=(Z=t==null?void 0:t.launcher)==null?void 0:Z.subtitle)!=null?Te:"Here to help you get answers fast",style:{color:Mn.subtitleColor}});p.append(u,g),i?r.append(p):r.append(l,p);let f=(Le=o.clearChat)!=null?Le:{},v=(oe=f.enabled)!=null?oe:!0,x=(Ae=f.placement)!=null?Ae:"inline",E=null,T=null;if(v){let ie=ci(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=ie.button,T=ie.wrapper,x==="top-right"&&(T.style.right="48px"),x==="inline"&&r.appendChild(T)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="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:k,wrapper:M}=li(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&r.appendChild(M),{header:r,iconHolder:l,headerTitle:u,headerSubtitle:g,closeButton:k,closeButtonWrapper:M,clearChatButton:E,clearChatButtonWrapper:T}},Ms=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function es(e){let{items:t,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=e,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(To)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of t){if(f.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",f.id),f.destructive&&v.setAttribute("data-destructive",""),f.icon){let E=ge(f.icon,16,"currentColor",1.5);E&&v.appendChild(E)}let x=document.createElement("span");x.textContent=f.label,v.appendChild(x),v.addEventListener("click",E=>{E.stopPropagation(),p(),n(f.id)}),a.appendChild(v)}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 l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=v=>{!a.contains(v.target)&&!r.contains(v.target)&&p()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():p()}function g(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:u,destroy:g}}function Kt(e){let{icon:t,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=ge(t,r!=null?r:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function di(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let p=y("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let g=ge(t,s!=null?s:14,"currentColor",2);g&&p.appendChild(g)}let u=y("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[g,f]of Object.entries(d))p.setAttribute(g,f);return p}function pi(e){let{items:t,selectedId:n,onSelect:r,className:o}=e,s=y("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let u;p.icon?u=Kt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(u=y("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),s.appendChild(u)}function l(p){a=p,d()}return{element:s,setSelected:l}}function Cl(e){var f,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=y("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=y("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let u=ge(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,E;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(E=d.border)!=null?E:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=es({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),o(x)},anchor:l,position:s,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",x=>{x.stopPropagation();let E=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",E?"false":"true"),g.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{p.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var ag=e=>{var r;let t=ko({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function Zx(e,t,n){var r,o,s;if(t!=null&&t.length)for(let a of t){let i=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=ge(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=y("div","persona-relative");d.appendChild(i);let l=es({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var ig=e=>{var L,k,M,P,C,R,F,j,H;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(L=t==null?void 0:t.launcher)!=null?L:{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,l,p;if(d)l=Cl({label:(k=a.title)!=null?k:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=Mn.titleColor,p=(M=l.querySelector(".persona-combo-btn-label"))!=null?M:l;else{if(l=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=y("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Mn.titleColor,p.textContent=(P=a.title)!=null?P:"Chat Assistant",l.appendChild(p),Zx(l,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let N=o.onTitleClick;l.addEventListener("click",Y=>{Y.target.closest("button")||N()}),l.addEventListener("keydown",Y=>{(Y.key==="Enter"||Y.key===" ")&&(Y.preventDefault(),N())})}let O=o==null?void 0:o.titleRowHover;O&&(l.style.borderRadius=(R=O.borderRadius)!=null?R:"10px",l.style.padding=(F=O.padding)!=null?F:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var N,Y;l.style.backgroundColor=(N=O.background)!=null?N:"",l.style.borderColor=(Y=O.border)!=null?Y:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(j=a.closeButtonSize)!=null?j:"32px",g=y("div",""),f=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||Mn.actionIconColor;let v=(H=a.closeButtonIconName)!=null?H:"x",x=ge(v,"28px","currentColor",1);x?f.appendChild(x):f.textContent="\xD7",r&&f.addEventListener("click",r),g.appendChild(f),i.appendChild(g);let E=y("div");E.style.display="none";let T=y("span");return T.style.display="none",{header:i,iconHolder:E,headerTitle:p,headerSubtitle:T,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Al={default:ag,minimal:ig},lg=e=>{var t;return(t=Al[e])!=null?t:Al.default},va=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=y("div");p.style.display="none";let u=y("span"),g=y("span"),f=y("button");f.style.display="none";let v=y("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:u,headerSubtitle:g,closeButton:f,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=lg(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var ui=e=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},mi=e=>{var P,C,R,F,j,H,O,N,Y,ke,pe,Z;let t=(P=e==null?void 0:e.sendButton)!=null?P:{},n=(C=t.useIcon)!=null?C:!1,r=(R=t.iconText)!=null?R:"\u2191",o=t.iconName,s=(F=t.stopIconName)!=null?F:"square",a=(j=t.tooltipText)!=null?j:"Send message",i=(H=t.stopTooltipText)!=null?H:"Stop generating",d=(N=(O=e==null?void 0:e.copy)==null?void 0:O.sendButtonLabel)!=null?N:"Send",l=(ke=(Y=e==null?void 0:e.copy)==null?void 0:Y.stopButtonLabel)!=null?ke:"Stop",p=(pe=t.showTooltip)!=null?pe:!1,u=(Z=t.size)!=null?Z:"40px",g=t.backgroundColor,f=t.textColor,v=y("div","persona-send-button-wrapper"),x=At("button",{className:Ys("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?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&g||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),E=null,T=null;if(n){let Te=parseFloat(u)||24,Le=(f==null?void 0:f.trim())||"currentColor";o?(E=ge(o,Te,Le,2),E?x.appendChild(E):x.textContent=r):x.textContent=r,T=ge(s,Te,Le,2)}else x.textContent=d;let L=null;p&&a&&(L=y("div","persona-send-button-tooltip"),L.textContent=a,v.appendChild(L)),x.setAttribute("aria-label",a),v.appendChild(x);let k="send";return{button:x,wrapper:v,setMode:Te=>{if(Te===k)return;k=Te;let Le=Te==="stop"?i:a;if(x.setAttribute("aria-label",Le),L&&(L.textContent=Le),n){if(E&&T){let oe=Te==="stop"?T:E;x.replaceChildren(oe)}}else x.textContent=Te==="stop"?l:d}}},gi=e=>{var L,k,M,P,C,R,F,j,H,O,N,Y;let t=(L=e==null?void 0:e.voiceRecognition)!=null?L:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((k=t.provider)==null?void 0:k.type)==="runtype";if(!(r||o))return null;let a=(P=(M=e==null?void 0:e.sendButton)==null?void 0:M.size)!=null?P:"40px",i=(C=t.iconName)!=null?C:"mic",d=(R=t.iconSize)!=null?R:a,l=parseFloat(d)||24,p=(j=t.backgroundColor)!=null?j:(F=e==null?void 0:e.sendButton)==null?void 0:F.backgroundColor,u=(O=t.iconColor)!=null?O:(H=e==null?void 0:e.sendButton)==null?void 0:H.textColor,g=y("div","persona-send-button-wrapper"),f=At("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),x=ge(i,l,u||"currentColor",1.5);x?f.appendChild(x):f.textContent="\u{1F3A4}",g.appendChild(f);let E=(N=t.tooltipText)!=null?N:"Start voice recognition";if(((Y=t.showTooltip)!=null?Y:!1)&&E){let ke=y("div","persona-send-button-tooltip");ke.textContent=E,g.appendChild(ke)}return{button:f,wrapper:g}},fi=e=>{var v,x,E,T,L,k,M,P;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(E=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?E:"40px",r=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=y("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((T=t.allowedTypes)!=null?T:Zr).join(","),o.multiple=((L=t.maxFiles)!=null?L:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(k=t.buttonIconName)!=null?k:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),l=y("div","persona-send-button-wrapper"),p=At("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=t.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 u=ge(s,d,"currentColor",1.5);u?p.appendChild(u):p.textContent="\u{1F4CE}",p.addEventListener("click",C=>{C.preventDefault(),o.click()}),l.appendChild(p);let g=(P=t.buttonTooltipText)!=null?P:"Attach file",f=y("div","persona-send-button-tooltip");return f.textContent=g,l.appendChild(f),{button:p,wrapper:l,input:o,previewsContainer:r}},hi=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=y("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=s;return r},yi=()=>At("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var wa=e=>{var v,x,E,T,L,k;let{config:t}=e,n=At("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=yi(),o=At("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}=ui(t);a();let i=mi(t),d=gi(t),l=fi(t),p=hi(t);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let u=At("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),u.append(g,f),o.append(u),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!==(l==null?void 0:l.button)&&M.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(r,o,p),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:p,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:u,leftActions:g,rightActions:f,setSendButtonMode:i.setMode}};var cg=()=>{let e=At("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),n=ge("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=ge("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},dg=e=>{var v,x,E,T,L,k;let{config:t}=e,n=At("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=yi();r.style.display="none";let o=hi(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=ui(t);s.style.maxHeight="100px",a();let i=mi(t),d=gi(t),l=fi(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=At("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let g=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.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!==(l==null?void 0:l.button)&&M.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&p.append(l.input),p.append(u,s,g),l&&n.append(l.previewsContainer),n.append(p,r,o);let f=p;return{footer:n,suggestions:r,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:o,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:f,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var pg=e=>{var p,u,g,f,v,x,E,T,L,k,M,P,C,R,F,j,H;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=dn(e);if(Mo(e)){let O=(f=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?f:{},N=y("div","persona-widget-wrapper persona-fixed persona-transition");N.setAttribute("data-persona-composer-bar",""),N.dataset.state="collapsed",N.dataset.expandedSize=(v=O.expandedSize)!=null?v:"anchored",N.style.zIndex=String((E=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?E:vn);let Y=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Y.style.width="100%",N.appendChild(Y);let ke=y("div","persona-widget-pill-root");return ke.setAttribute("data-persona-composer-bar",""),ke.dataset.state="collapsed",ke.dataset.expandedSize=(T=O.expandedSize)!=null?T:"anchored",ke.style.zIndex=String((k=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?k:vn),{wrapper:N,panel:Y,pillRoot:ke}}if(n){let O=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),N=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild(N),{wrapper:O,panel:N}}if(!t){let O=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),N=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Y=(P=(M=e==null?void 0:e.launcher)==null?void 0:M.width)!=null?P:"100%";return O.style.width=Y,N.style.width="100%",O.appendChild(N),{wrapper:O,panel:N}}let o=(C=e==null?void 0:e.launcher)!=null?C:{},s=o.position&&br[o.position]?br[o.position]:br["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((F=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?F:vn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(H=(j=e==null?void 0:e.launcher)==null?void 0:j.width)!=null?H:e==null?void 0:e.launcherWidth,l=d!=null?d:nr;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},ev=(e,t)=>{var M,P,C,R,F,j,H,O,N;let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=li(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(C=(P=(M=e==null?void 0:e.launcher)==null?void 0:M.clearChat)==null?void 0:P.enabled)!=null?C:!0,a=null,i=null;if(s){let Y=ci(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Y.button,i=Y.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=At("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=At("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"}});l.style.setProperty("scrollbar-gutter","stable");let p=At("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(F=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?F:"Hello \u{1F44B}"}),u=At("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(H=(j=e==null?void 0:e.copy)==null?void 0:j.welcomeSubtitle)!=null?H:"Ask anything about your account or products."}),g=At("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,u),f=y("div","persona-flex persona-flex-col persona-gap-3"),v=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;v&&(f.style.maxWidth=v,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((N=e==null?void 0:e.copy)==null?void 0:N.showWelcomeCard)!==!1||(g.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(g,f);let E=At("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),T=dg({config:e}),{root:L,textNode:k}=cg();return n.append(d,o,l,E),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:f,composerOverlay:E,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:p,introSubtitle:u,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:L,peekTextNode:k}},ug=(e,t=!0)=>{var E,T,L,k,M,P,C,R,F;if(Mo(e))return ev(e,t);let n=At("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=e==null?void 0:e.layout)==null?void 0:E.header,o=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,s=r?va(e,r,{showClose:t}):ko({config:e,showClose:t}),a=At("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=At("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(k=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?k:"Hello \u{1F44B}"}),d=At("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(P=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeSubtitle)!=null?P:"Ask anything about your account or products."}),l=At("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:dn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),p=y("div","persona-flex persona-flex-col persona-gap-3"),u=(C=e==null?void 0:e.layout)==null?void 0:C.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((R=e==null?void 0:e.copy)==null?void 0:R.showWelcomeCard)!==!1||(l.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(l,p);let f=wa({config:e}),v=((F=e==null?void 0:e.layout)==null?void 0:F.showFooter)!==!1;o?Ms(n,s,e):(s.header.style.display="none",Ms(n,s,e)),n.append(a);let x=At("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 v||(f.footer.style.display="none"),n.append(f.footer),n.append(x),{container:n,body:a,messagesWrapper:p,composerOverlay:x,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 Sl=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
18
+ _Details: ${n.message}_`:r}var ca=e=>({isError:!0,content:[{type:"text",text:e}]}),Km=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Gm=e=>Ko(e)||e===Hr,da=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Ts(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,o,s,a,i,d,c,p,u;if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let f=t.message.toolCall,g=!!(f!=null&&f.name)&&(Ko(f.name)||f.name===Hr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&g&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,o;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new As(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d,c;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(o=t.host)!=null?o:this.config.apiUrl,r=(c=(d=t.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId)!=null?c:this.config.agentId;!n||!r||!this.config.clientToken||ml().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ja((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=Zo.isSupported()?new Zo({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let c=(r=t.host)!=null?r:this.config.apiUrl,p=(d=(i=t.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId)!=null?d:this.config.agentId,u=this.config.clientToken,f=t.browserFallback!==!1;if(c&&p&&u)return ml().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:b})=>{let v=new g({host:c,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return f&&n?new b(v,n,{onFallback:S=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${S.message}`)}):v});if(f&&n)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){var n,r;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Yo(o);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,o,s,a,i,d,c,p,u,f,g;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=t.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=t.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=t.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(u=t.runtype)==null?void 0:u.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((f=t.browser)==null?void 0:f.language)||"en-US",continuous:(g=t.browser)==null?void 0:g.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!Hy(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new As(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:u}=t,g={id:a!=null?a:n==="user"?aa():n==="assistant"?Xo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:u=!1,voiceProcessing:f,rawContent:g}=r,v={id:d!=null?d:o==="user"?aa():o==="assistant"?Xo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,c={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var c,p,u,f,g;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let o=aa(),s=Xo();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||Va,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(b){if(this.status==="resuming"||this.reconnecting)return;let v=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));if(!v){let S=gl(b,this.config.errorMessage);if(S){let T={id:s,role:"assistant",createdAt:new Date().toISOString(),content:S,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(b instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,b):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(b))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort(),this.teardownReconnect();let t=Xo();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let p=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!p){let u=gl(c,this.config.errorMessage);if(u){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(f)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(t,n){var s,a,i;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort(),n!=null&&n.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let r=n!=null&&n.preserveAssistantId?n.assistantMessageId:void 0,o=!1;for(let d of this.messages)d.streaming&&d.id!==r&&(d.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId,n==null?void 0:n.seedContent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(i=(a=this.callbacks).onError)==null||i.call(a,d instanceof Error?d:new Error(String(d)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,f,g,b;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(c?v=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let S=null;if(v instanceof Response){if(!v.ok){let T=await v.json().catch(()=>null);throw new Error((f=T==null?void 0:T.error)!=null?f:`Approval request failed: ${v.status}`)}S=v.body}else v instanceof ReadableStream&&(S=v);S?await this.connectStream(S,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let S=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,S||(b=(g=this.callbacks).onError)==null||b.call(g,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,f,g,b,v,S,T,L,P,E,k;let r=this.messages.find(C=>C.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!o||!s){(b=(g=this.callbacks).onError)==null||b.call(g,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let C=(v=t.toolCall)==null?void 0:v.args,I=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(I.length===1){let j=typeof((S=I[0])==null?void 0:S.question)=="string"?I[0].question:"";j&&(a={[j]:n})}}this.markAskUserQuestionResolved(t,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(L=t.toolCall)==null?void 0:L.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let C=typeof n=="string"?n:Object.entries(n).map(([I,j])=>`${I}: ${Array.isArray(j)?j.join(", "):j}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let C=a!=null?a:{};c.forEach((I,j)=>{let $=typeof(I==null?void 0:I.question)=="string"?I.question:"";if(!$)return;let R=C[$],N=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${j}`,role:"assistant",content:$,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${j}`,role:"user",content:N||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:n});if(!C.ok){let I=await C.json().catch(()=>null);throw new Error((P=I==null?void 0:I.error)!=null?P:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let I=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,I||(k=(E=this.callbacks).onError)==null||k.call(E,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var o,s;let n=this.messages.find(a=>a.id===t.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,o;if(((r=t.toolCall)==null?void 0:r.name)!==Hr)return!1;let n=this.messages.find(s=>s.id===t.id);return((o=(n!=null?n:t).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,o=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,c,p,u;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async f=>{var k,C,I,j,$,R,N;let g=(k=f.toolCall)==null?void 0:k.name,b=(C=f.toolCall)==null?void 0:C.id;if(!g||!b)return null;let v=`${t}:${b}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(f))return null;this.webMcpInflightKeys.add(v),r.push(v);let S=this.markWebMcpToolRunning(f),T=(j=(I=f.agentMetadata)==null?void 0:I.webMcpToolCallId)!=null?j:g;if(g===Hr)return{dedupeKey:v,resumeKey:T,output:nl(),toolMessage:f,startedAt:S,completedAt:Date.now()};let L=new AbortController;this.webMcpResolveControllers.add(L),o.push(L);let P=this.client.executeWebMcpToolCall(g,($=f.toolCall)==null?void 0:$.args,L.signal),E;if(!P)E={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{E=await P}catch(O){let Z=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return Z||(N=(R=this.callbacks).onError)==null||N.call(R,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(f,ca(Z?"Aborted by cancel()":Km(O)),S),this.webMcpInflightKeys.delete(v),null}return L.signal.aborted?(this.markWebMcpToolComplete(f,ca("Aborted by cancel()"),S),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:T,output:E,toolMessage:f,startedAt:S,completedAt:Date.now()}})),i=[];try{if(i=a.filter(b=>b!==null),i.length===0)return;let f={};for(let b of i)f[b.resumeKey]=b.output;let g=await this.client.resumeFlow(t,f,{signal:s.signal});if(!g.ok){let b=await g.json().catch(()=>null);throw new Error((d=b==null?void 0:b.error)!=null?d:`Resume failed: ${g.status}`)}for(let b of i)this.webMcpResolvedKeys.add(b.dedupeKey),this.markWebMcpToolComplete(b.toolMessage,b.output,b.startedAt,b.completedAt,((c=b.toolMessage.toolCall)==null?void 0:c.name)===Hr?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,f instanceof Error?f:new Error(String(f)));else for(let b of i)this.markWebMcpToolComplete(b.toolMessage,ca("Aborted by cancel()"),b.startedAt)}finally{for(let f of r)this.webMcpInflightKeys.delete(f);for(let f of o)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var b,v,S,T,L,P,E,k,C,I,j,$;let n=(b=t.agentMetadata)==null?void 0:b.executionId,r=(v=t.toolCall)==null?void 0:v.name,o=(S=t.toolCall)==null?void 0:S.id;if(!n){(L=(T=this.callbacks).onError)==null||L.call(T,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let R=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(R)||this.webMcpResolvedKeys.has(R))return;this.webMcpInflightKeys.add(R);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(R)}catch(N){(E=(P=this.callbacks).onError)==null||E.call(P,N instanceof Error?N:new Error(String(N)))}finally{this.webMcpInflightKeys.delete(R)}return}let s=`${n}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===Hr,p=(k=t.toolCall)==null?void 0:k.args,u=c?null:this.client.executeWebMcpToolCall(r,p,d),f="execute",g=a;try{let R;if(c?R=nl():u?R=await u:R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ca("Aborted by cancel()"),a);return}let N=(I=(C=t.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?I:r;f="resume",await this.resumeWithToolOutput(n,N,R,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,R,a,g,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(R){let N=R instanceof Error&&(R.name==="AbortError"||R.message.includes("aborted")||R.message.includes("abort"));(f==="execute"||N||d.aborted)&&this.markWebMcpToolComplete(t,ca(N||d.aborted?"Aborted by cancel()":Km(R)),a),N||($=(j=this.callbacks).onError)==null||$.call(j,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,o){var a,i;let s=await this.client.resumeFlow(t,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var o;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){var o,s;let n=(o=this.agentExecution)==null?void 0:o.executionId;if(!n||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var t;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((t=this.abortController)==null?void 0:t.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>{var n,r,o;return((n=t.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&((r=t.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||t.variant==="approval"&&((o=t.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var t,n;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(n=(t=this.callbacks).onReconnect)==null||n.call(t,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(r=>{this.reconnecting&&this.resumable&&r.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(Vm(),zm)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,r,o)=>t.connectStream(n,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>{var r,o;return(o=(r=t.callbacks).onReconnect)==null?void 0:o.call(r,n)},buildErrorContent:n=>gl(new Error(n),t.config.errorMessage),onError:n=>{var r,o;return(o=(r=t.callbacks).onError)==null?void 0:o.call(r,n)}}}reconnectNow(){var t;if(this.reconnecting){(t=this.reconnectController)==null||t.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Xo(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){var t;this.reconnecting=!1,(t=this.reconnectController)==null||t.teardown(),this.clearResumable()}clearResumable(){var n,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&((r=(n=this.config).onExecutionState)==null||r.call(n,null))}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{var r,o;this.executionStateTimer=null,(o=(r=this.config).onExecutionState)==null||o.call(r,this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=ul(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return la(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let r=ul(n.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var p,u,f,g,b,v,S,T,L,P,E,k,C,I,j;if(s!==r)return o;let a={...o,...n};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=o.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(f=a.agentMetadata)!=null?f:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let $=o.approval,R=n.approval;a.approval={...$,...R,executionId:R.executionId||$.executionId,toolName:R.toolName||$.toolName,description:R.description||$.description,toolType:(g=R.toolType)!=null?g:$.toolType,reason:(b=R.reason)!=null?b:$.reason,parameters:(v=R.parameters)!=null?v:$.parameters}}let i=(S=n.toolCall)==null?void 0:S.name,d=(T=n.agentMetadata)==null?void 0:T.executionId,c=(L=n.toolCall)==null?void 0:L.id;if(i&&Gm(i)&&d&&c&&((P=n.agentMetadata)==null?void 0:P.awaitingLocalTool)===!0){let $=`${d}:${c}`,R=this.webMcpInflightKeys.has($),N=this.webMcpResolvedKeys.has($),O=(E=o.toolCall)==null?void 0:E.name,Z=((k=o.agentMetadata)==null?void 0:k.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&O!==void 0&&Gm(O)&&((I=o.toolCall)==null?void 0:I.status)==="complete";(R||N||Z)&&(a.agentMetadata={...(j=a.agentMetadata)!=null?j:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,c;let o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};import{Activity as By,ArrowDown as Dy,ArrowUp as Ny,ArrowUpRight as Oy,Bot as Fy,ChevronDown as _y,ChevronUp as $y,ChevronRight as jy,ChevronLeft as Uy,Check as qy,Clipboard as zy,ClipboardCopy as Vy,Copy as Ky,File as Gy,FileCode as Jy,FileSpreadsheet as Xy,FileText as Qy,ImagePlus as Yy,Loader as Zy,LoaderCircle as eb,Mic as tb,Paperclip as nb,RefreshCw as rb,Search as ob,Send as sb,ShieldAlert as ab,ShieldCheck as ib,ShieldX as lb,Square as cb,ThumbsDown as db,ThumbsUp as pb,Upload as ub,Volume2 as mb,X as gb,User as fb,Mail as hb,Phone as yb,Calendar as bb,Clock as xb,Building as vb,MapPin as wb,Lock as Cb,Key as Ab,CreditCard as Sb,AtSign as Tb,Hash as Eb,Globe as Mb,Link as kb,CircleCheck as Lb,CircleX as Pb,TriangleAlert as Ib,Info as Rb,Ban as Wb,Shield as Hb,ArrowLeft as Bb,ArrowRight as Db,ExternalLink as Nb,Ellipsis as Ob,EllipsisVertical as Fb,Menu as _b,House as $b,Plus as jb,Minus as Ub,Pencil as qb,Trash as zb,Trash2 as Vb,Save as Kb,Download as Gb,Share as Jb,Funnel as Xb,Settings as Qb,RotateCw as Yb,Maximize as Zb,Minimize as ex,ShoppingCart as tx,ShoppingBag as nx,Package as rx,Truck as ox,Tag as sx,Gift as ax,Receipt as ix,Wallet as lx,Store as cx,DollarSign as dx,Percent as px,Play as ux,Pause as mx,VolumeX as gx,Camera as fx,Image as hx,Film as yx,Headphones as bx,MessageCircle as xx,MessageSquare as vx,Bell as wx,Heart as Cx,Star as Ax,Eye as Sx,EyeOff as Tx,Bookmark as Ex,CalendarDays as Mx,History as kx,Timer as Lx,Folder as Px,FolderOpen as Ix,Files as Rx,Sparkles as Wx,Zap as Hx,Sun as Bx,Moon as Dx,Flag as Nx,Monitor as Ox,Smartphone as Fx}from"lucide";var _x={activity:By,"arrow-down":Dy,"arrow-up":Ny,"arrow-up-right":Oy,bot:Fy,"chevron-down":_y,"chevron-up":$y,"chevron-right":jy,"chevron-left":Uy,check:qy,clipboard:zy,"clipboard-copy":Vy,copy:Ky,file:Gy,"file-code":Jy,"file-spreadsheet":Xy,"file-text":Qy,"image-plus":Yy,loader:Zy,"loader-circle":eb,mic:tb,paperclip:nb,"refresh-cw":rb,search:ob,send:sb,"shield-alert":ab,"shield-check":ib,"shield-x":lb,square:cb,"thumbs-down":db,"thumbs-up":pb,upload:ub,"volume-2":mb,x:gb,user:fb,mail:hb,phone:yb,calendar:bb,clock:xb,building:vb,"map-pin":wb,lock:Cb,key:Ab,"credit-card":Sb,"at-sign":Tb,hash:Eb,globe:Mb,link:kb,"circle-check":Lb,"circle-x":Pb,"triangle-alert":Ib,info:Rb,ban:Wb,shield:Hb,"arrow-left":Bb,"arrow-right":Db,"external-link":Nb,ellipsis:Ob,"ellipsis-vertical":Fb,menu:_b,house:$b,plus:jb,minus:Ub,pencil:qb,trash:zb,"trash-2":Vb,save:Kb,download:Gb,share:Jb,funnel:Xb,settings:Qb,"rotate-cw":Yb,maximize:Zb,minimize:ex,"shopping-cart":tx,"shopping-bag":nx,package:rx,truck:ox,tag:sx,gift:ax,receipt:ix,wallet:lx,store:cx,"dollar-sign":dx,percent:px,play:ux,pause:mx,"volume-x":gx,camera:fx,image:hx,film:yx,headphones:bx,"message-circle":xx,"message-square":vx,bell:wx,heart:Cx,star:Ax,eye:Sx,"eye-off":Tx,bookmark:Ex,"calendar-days":Mx,history:kx,timer:Lx,folder:Px,"folder-open":Ix,files:Rx,sparkles:Wx,zap:Hx,sun:Bx,moon:Dx,flag:Nx,monitor:Ox,smartphone:Fx},ye=(e,t=24,n="currentColor",r=2)=>{let o=_x[e];return o?$x(o,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function $x(e,t,n,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),o.appendChild(d)}),o}var Ya={allowedTypes:Gr,maxFileSize:10*1024*1024,maxFiles:4};function jx(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ux(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var Es=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ya.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Ya.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Ya.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ya.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,o,s,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let p=Dm(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,u);continue}try{let u=await Bm(c),f=Ga(c)?URL.createObjectURL(c):null,g={id:jx(),file:c,previewUrl:f,contentPart:u};this.attachments.push(g),this.renderPreview(g)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ga(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=y("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Ux(t.file.type),d=ye(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=Nm(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ye("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var Jm=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function pa(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];Jm(s)&&Jm(o)?n[r]=pa(s,o):n[r]=o}return n}var tr="min(440px, calc(100vw - 24px))",fl="440px",qx={enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:tr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},Dt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:qx,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Xm(e,t){if(!(!e&&!t))return e?t?pa(e,t):e:t}function hl(e){var t,n,r,o,s,a,i,d,c,p,u,f,g,b,v,S,T,L,P,E,k;return e?{...Dt,...e,theme:Xm(Dt.theme,e.theme),darkTheme:Xm(Dt.darkTheme,e.darkTheme),launcher:{...Dt.launcher,...e.launcher,dock:{...(t=Dt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Dt.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Dt.copy,...e.copy},sendButton:{...Dt.sendButton,...e.sendButton},statusIndicator:{...Dt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Dt.voiceRecognition,...e.voiceRecognition},features:(()=>{var re,se,ae,fe,$e,V,Q,Me,J,le;let C=(re=Dt.features)==null?void 0:re.artifacts,I=(se=e.features)==null?void 0:se.artifacts,j=(ae=Dt.features)==null?void 0:ae.scrollToBottom,$=(fe=e.features)==null?void 0:fe.scrollToBottom,R=($e=Dt.features)==null?void 0:$e.scrollBehavior,N=(V=e.features)==null?void 0:V.scrollBehavior,O=(Q=Dt.features)==null?void 0:Q.streamAnimation,Z=(Me=e.features)==null?void 0:Me.streamAnimation,Ee=(J=Dt.features)==null?void 0:J.askUserQuestion,de=(le=e.features)==null?void 0:le.askUserQuestion,ee=C===void 0&&I===void 0?void 0:{...C,...I,layout:{...C==null?void 0:C.layout,...I==null?void 0:I.layout}},Le=j===void 0&&$===void 0?void 0:{...j,...$},Pe=R===void 0&&N===void 0?void 0:{...R,...N},ne=O===void 0&&Z===void 0?void 0:{...O,...Z},Ae=Ee===void 0&&de===void 0?void 0:{...Ee,...de,styles:{...Ee==null?void 0:Ee.styles,...de==null?void 0:de.styles}};return{...Dt.features,...e.features,...Le!==void 0?{scrollToBottom:Le}:{},...Pe!==void 0?{scrollBehavior:Pe}:{},...ee!==void 0?{artifacts:ee}:{},...ne!==void 0?{streamAnimation:ne}:{},...Ae!==void 0?{askUserQuestion:Ae}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Dt.suggestionChips,suggestionChipsConfig:{...Dt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Dt.layout,...e.layout,header:{...(a=Dt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Dt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(u=(p=Dt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(v=(b=Dt.layout)==null?void 0:b.messages)==null?void 0:v.timestamp,...(T=(S=e.layout)==null?void 0:S.messages)==null?void 0:T.timestamp}},slots:{...(L=Dt.layout)==null?void 0:L.slots,...(P=e.layout)==null?void 0:P.slots}},markdown:{...Dt.markdown,...e.markdown,options:{...(E=Dt.markdown)==null?void 0:E.options,...(k=e.markdown)==null?void 0:k.options}},messageActions:{...Dt.messageActions,...e.messageActions}}:Dt}var Qm={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Ym={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Zm={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:tr,maxWidth:fl,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Ms(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Ms(e,r):r}function yl(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Ms(e,a);d!==void 0&&(t[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function eg(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function tg(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=tg(s,o):n[r]=o}return n}function zx(e,t){return t?tg(e,t):e}function ua(e,t={}){var o,s,a,i,d,c,p,u,f,g,b,v,S;let n={palette:Qm,semantic:Ym,components:Zm},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(b=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:b.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(S=e==null?void 0:e.semantic)==null?void 0:S.typography}},components:zx(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=eg(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(L=>L.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)r=T.transform(r);return r}function bl(e){var v,S,T,L,P,E,k,C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe,ne,Ae,re,se,ae,fe,$e,V,Q,Me,J,le,Ie,he,Ke,gt,Wt,tt,ge,X,it,Ve,Se,we,Ze,qt,be,pe,vn,Ct,fn,yr,br,Ue,M,ue,Te,ke,He,nt,Qe,ht,me,B,xe,ce,ft,Je,Lt,Mt,xt,Rt,Xt,Ot,en,xr,Nr,or,sr,Xr,zt,ar,Or,Hn,kn,Bn,ir,vr,Qr,zn,Yr,At,wr,Cr,Fr,lr,yt,Lo,Ar,Po,Ln,ss,Zr,_r,eo,to,Io,Ro,no,vt,Dn,Nn,wn,St,Vn,Kn,On,ro;let t=yl(e),n={};for(let[Ce,$r]of Object.entries(t)){let Gn=Ce.replace(/\./g,"-");n[`--persona-${Gn}`]=$r.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(S=n["--persona-semantic-colors-secondary"])!=null?S:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(T=n["--persona-semantic-colors-accent"])!=null?T:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(L=n["--persona-semantic-colors-surface"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(P=n["--persona-semantic-colors-background"])!=null?P:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(E=n["--persona-semantic-colors-container"])!=null?E:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(k=n["--persona-semantic-colors-text"])!=null?k:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(C=n["--persona-semantic-colors-text-muted"])!=null?C:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(I=n["--persona-semantic-colors-text-inverse"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(j=n["--persona-semantic-colors-border"])!=null?j:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=($=n["--persona-semantic-colors-divider"])!=null?$:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(R=n["--persona-components-voice-recording-indicator"])!=null?R:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(N=n["--persona-components-voice-recording-background"])!=null?N:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(O=n["--persona-components-voice-processing-icon"])!=null?O:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(Z=n["--persona-components-voice-speaking-icon"])!=null?Z:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Ee=n["--persona-components-approval-requested-background"])!=null?Ee:n["--persona-surface"],n["--persona-approval-border"]=(de=n["--persona-components-approval-requested-border"])!=null?de:n["--persona-border"],n["--persona-approval-text"]=(ee=n["--persona-components-approval-requested-text"])!=null?ee:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Le=n["--persona-components-approval-requested-shadow"])!=null?Le:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=(Pe=n["--persona-components-approval-approve-background"])!=null?Pe:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(ne=n["--persona-components-approval-deny-background"])!=null?ne:n["--persona-container"],n["--persona-attachment-image-bg"]=(Ae=n["--persona-components-attachment-image-background"])!=null?Ae:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(re=n["--persona-components-attachment-image-border"])!=null?re:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(se=n["--persona-semantic-typography-fontFamily"])!=null?se:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(ae=n["--persona-semantic-typography-fontSize"])!=null?ae:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(fe=n["--persona-semantic-typography-fontWeight"])!=null?fe:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=($e=n["--persona-semantic-typography-lineHeight"])!=null?$e:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(V=n["--persona-palette-radius-sm"])!=null?V:"0.125rem",n["--persona-radius-md"]=(Q=n["--persona-palette-radius-md"])!=null?Q:"0.375rem",n["--persona-radius-lg"]=(Me=n["--persona-palette-radius-lg"])!=null?Me:"0.5rem",n["--persona-radius-xl"]=(J=n["--persona-palette-radius-xl"])!=null?J:"0.75rem",n["--persona-radius-full"]=(le=n["--persona-palette-radius-full"])!=null?le:"9999px",n["--persona-launcher-radius"]=(he=(Ie=n["--persona-components-launcher-borderRadius"])!=null?Ie:n["--persona-palette-radius-full"])!=null?he:"9999px",n["--persona-launcher-bg"]=(Ke=n["--persona-components-launcher-background"])!=null?Ke:n["--persona-primary"],n["--persona-launcher-fg"]=(gt=n["--persona-components-launcher-foreground"])!=null?gt:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Wt=n["--persona-components-launcher-border"])!=null?Wt:n["--persona-border"],n["--persona-button-primary-bg"]=(tt=n["--persona-components-button-primary-background"])!=null?tt:n["--persona-primary"],n["--persona-button-primary-fg"]=(ge=n["--persona-components-button-primary-foreground"])!=null?ge:n["--persona-text-inverse"],n["--persona-button-radius"]=(it=(X=n["--persona-components-button-primary-borderRadius"])!=null?X:n["--persona-palette-radius-full"])!=null?it:"9999px",n["--persona-panel-radius"]=(Se=(Ve=n["--persona-components-panel-borderRadius"])!=null?Ve:n["--persona-radius-xl"])!=null?Se:"0.75rem",n["--persona-panel-border"]=(we=n["--persona-components-panel-border"])!=null?we:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(qt=(Ze=n["--persona-components-panel-shadow"])!=null?Ze:n["--persona-palette-shadows-xl"])!=null?qt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(be=n["--persona-components-launcher-shadow"])!=null?be:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(vn=(pe=n["--persona-components-input-borderRadius"])!=null?pe:n["--persona-radius-lg"])!=null?vn:"0.5rem",n["--persona-message-user-radius"]=(fn=(Ct=n["--persona-components-message-user-borderRadius"])!=null?Ct:n["--persona-radius-lg"])!=null?fn:"0.5rem",n["--persona-message-assistant-radius"]=(br=(yr=n["--persona-components-message-assistant-borderRadius"])!=null?yr:n["--persona-radius-lg"])!=null?br:"0.5rem",n["--persona-header-bg"]=(Ue=n["--persona-components-header-background"])!=null?Ue:n["--persona-surface"],n["--persona-header-border"]=(M=n["--persona-components-header-border"])!=null?M:n["--persona-divider"],n["--persona-header-icon-bg"]=(ue=n["--persona-components-header-iconBackground"])!=null?ue:n["--persona-primary"],n["--persona-header-icon-fg"]=(Te=n["--persona-components-header-iconForeground"])!=null?Te:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(ke=n["--persona-components-header-titleForeground"])!=null?ke:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(He=n["--persona-components-header-subtitleForeground"])!=null?He:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(nt=n["--persona-components-header-actionIconForeground"])!=null?nt:n["--persona-muted"];let r=(Qe=e.components)==null?void 0:Qe.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(ht=e.components)==null?void 0:ht.introCard;n["--persona-intro-card-bg"]=(me=n["--persona-components-introCard-background"])!=null?me:n["--persona-surface"],n["--persona-intro-card-radius"]=(B=n["--persona-components-introCard-borderRadius"])!=null?B:"1rem",n["--persona-intro-card-padding"]=(xe=n["--persona-components-introCard-padding"])!=null?xe:"1.5rem",n["--persona-intro-card-shadow"]=(ft=(ce=o==null?void 0:o.shadow)!=null?ce:n["--persona-components-introCard-shadow"])!=null?ft:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Je=n["--persona-components-input-background"])!=null?Je:n["--persona-surface"],n["--persona-input-placeholder"]=(Lt=n["--persona-components-input-placeholder"])!=null?Lt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Mt=n["--persona-components-message-user-background"])!=null?Mt:n["--persona-accent"],n["--persona-message-user-text"]=(xt=n["--persona-components-message-user-text"])!=null?xt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Rt=n["--persona-components-message-user-shadow"])!=null?Rt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Xt=n["--persona-components-message-assistant-background"])!=null?Xt:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ot=n["--persona-components-message-assistant-text"])!=null?Ot:n["--persona-text"],n["--persona-message-assistant-border"]=(en=n["--persona-components-message-assistant-border"])!=null?en:n["--persona-border"],n["--persona-message-assistant-shadow"]=(xr=n["--persona-components-message-assistant-shadow"])!=null?xr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(or=(Nr=n["--persona-components-scrollToBottom-background"])!=null?Nr:n["--persona-button-primary-bg"])!=null?or:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(Xr=(sr=n["--persona-components-scrollToBottom-foreground"])!=null?sr:n["--persona-button-primary-fg"])!=null?Xr:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(zt=n["--persona-components-scrollToBottom-border"])!=null?zt:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(ar=n["--persona-components-scrollToBottom-size"])!=null?ar:"40px",n["--persona-scroll-to-bottom-radius"]=(kn=(Hn=(Or=n["--persona-components-scrollToBottom-borderRadius"])!=null?Or:n["--persona-button-radius"])!=null?Hn:n["--persona-radius-full"])!=null?kn:"9999px",n["--persona-scroll-to-bottom-shadow"]=(ir=(Bn=n["--persona-components-scrollToBottom-shadow"])!=null?Bn:n["--persona-palette-shadows-sm"])!=null?ir:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(vr=n["--persona-components-scrollToBottom-padding"])!=null?vr:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Qr=n["--persona-components-scrollToBottom-gap"])!=null?Qr:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Yr=(zn=n["--persona-components-scrollToBottom-fontSize"])!=null?zn:n["--persona-palette-typography-fontSize-sm"])!=null?Yr:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(At=n["--persona-components-scrollToBottom-iconSize"])!=null?At:"14px",n["--persona-tool-bubble-shadow"]=(wr=n["--persona-components-toolBubble-shadow"])!=null?wr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Cr=n["--persona-components-reasoningBubble-shadow"])!=null?Cr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Fr=n["--persona-components-composer-shadow"])!=null?Fr:"none",n["--persona-md-inline-code-bg"]=(lr=n["--persona-components-markdown-inlineCode-background"])!=null?lr:n["--persona-container"],n["--persona-md-inline-code-color"]=(yt=n["--persona-components-markdown-inlineCode-foreground"])!=null?yt:n["--persona-text"],n["--persona-md-link-color"]=(Ar=(Lo=n["--persona-components-markdown-link-foreground"])!=null?Lo:n["--persona-accent"])!=null?Ar:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let c=n["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(n["--persona-md-prose-font-family"]=c),n["--persona-md-code-block-bg"]=(Po=n["--persona-components-markdown-codeBlock-background"])!=null?Po:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Ln=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Ln:n["--persona-border"],n["--persona-md-code-block-text-color"]=(ss=n["--persona-components-markdown-codeBlock-textColor"])!=null?ss:"inherit",n["--persona-md-table-header-bg"]=(Zr=n["--persona-components-markdown-table-headerBackground"])!=null?Zr:n["--persona-container"],n["--persona-md-table-border-color"]=(_r=n["--persona-components-markdown-table-borderColor"])!=null?_r:n["--persona-border"],n["--persona-md-hr-color"]=(eo=n["--persona-components-markdown-hr-color"])!=null?eo:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(to=n["--persona-components-markdown-blockquote-borderColor"])!=null?to:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Io=n["--persona-components-markdown-blockquote-background"])!=null?Io:"transparent",n["--persona-md-blockquote-text-color"]=(Ro=n["--persona-components-markdown-blockquote-textColor"])!=null?Ro:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(no=n["--persona-components-collapsibleWidget-container"])!=null?no:n["--persona-surface"],n["--cw-surface"]=(vt=n["--persona-components-collapsibleWidget-surface"])!=null?vt:n["--persona-surface"],n["--cw-border"]=(Dn=n["--persona-components-collapsibleWidget-border"])!=null?Dn:n["--persona-border"],n["--persona-message-border"]=(Nn=n["--persona-components-message-border"])!=null?Nn:n["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let g=p==null?void 0:p.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let b=p==null?void 0:p.artifact;if(b!=null&&b.toolbar){let Ce=b.toolbar;Ce.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=Ce.iconHoverColor),Ce.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=Ce.iconHoverBackground),Ce.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=Ce.iconPadding),Ce.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=Ce.iconBorderRadius),Ce.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=Ce.iconBorder),Ce.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Ce.toggleGroupGap),Ce.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=Ce.toggleBorderRadius),Ce.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=Ce.copyBackground),Ce.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=Ce.copyBorder),Ce.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=Ce.copyColor),Ce.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Ce.copyBorderRadius),Ce.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=Ce.copyPadding),Ce.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=Ce.copyMenuBackground,n["--persona-dropdown-bg"]=(wn=n["--persona-dropdown-bg"])!=null?wn:Ce.copyMenuBackground),Ce.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=Ce.copyMenuBorder,n["--persona-dropdown-border"]=(St=n["--persona-dropdown-border"])!=null?St:Ce.copyMenuBorder),Ce.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=Ce.copyMenuShadow,n["--persona-dropdown-shadow"]=(Vn=n["--persona-dropdown-shadow"])!=null?Vn:Ce.copyMenuShadow),Ce.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=Ce.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Kn=n["--persona-dropdown-radius"])!=null?Kn:Ce.copyMenuBorderRadius),Ce.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Ce.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(On=n["--persona-dropdown-item-hover-bg"])!=null?On:Ce.copyMenuItemHoverBackground),Ce.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=Ce.iconBackground),Ce.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=Ce.toolbarBorder)}if(b!=null&&b.tab){let Ce=b.tab;Ce.background&&(n["--persona-artifact-tab-bg"]=Ce.background),Ce.activeBackground&&(n["--persona-artifact-tab-active-bg"]=Ce.activeBackground),Ce.activeBorder&&(n["--persona-artifact-tab-active-border"]=Ce.activeBorder),Ce.borderRadius&&(n["--persona-artifact-tab-radius"]=Ce.borderRadius),Ce.textColor&&(n["--persona-artifact-tab-color"]=Ce.textColor),Ce.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=Ce.hoverBackground),Ce.listBackground&&(n["--persona-artifact-tab-list-bg"]=Ce.listBackground),Ce.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=Ce.listBorderColor),Ce.listPadding&&(n["--persona-artifact-tab-list-padding"]=Ce.listPadding)}if(b!=null&&b.pane){let Ce=b.pane;if(Ce.toolbarBackground){let $r=(ro=Ms(e,Ce.toolbarBackground))!=null?ro:Ce.toolbarBackground;n["--persona-artifact-toolbar-bg"]=$r}}return n}var Vx={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var Kx={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},ng=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Za=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Gx=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Za()},rg=e=>Gx(e),Jx=e=>ua(e),Xx=e=>{var n;let t=ua(void 0,{validate:!1});return ua({...e,palette:{...t.palette,colors:{...Kx.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ma=e=>{let t=rg(e),n=ng(e==null?void 0:e.theme),r=ng(e==null?void 0:e.darkTheme);return t==="dark"?Xx(pa(n!=null?n:{},r!=null?r:{})):Jx(n)},Qx=e=>bl(e),es=(e,t)=>{let n=ma(t),r=Qx(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},xl=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Za())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Za());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};import{Idiomorph as Yx}from"idiomorph";var ei=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Yx.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===o.getAttribute("data-tool-elapsed")?!1:void 0;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var og=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var ti={index:-1,draft:""};function sg(e){let{direction:t,history:n,currentValue:r,atStart:o,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...ti}}}function ag(e,t){var n,r,o,s,a,i,d,c,p,u,f,g,b,v,S,T,L,P,E,k,C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe,ne,Ae,re,se,ae;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(b=(g=e.toolCall)==null?void 0:g.status)!=null?b:"",(S=(v=e.toolCall)==null?void 0:v.name)!=null?S:"",(P=(L=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:L.length)!=null?P:0,(I=(C=(k=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:k[e.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?I:"",typeof((j=e.toolCall)==null?void 0:j.args)=="string"?e.toolCall.args.length:($=e.toolCall)!=null&&$.args?JSON.stringify(e.toolCall.args).length:0,(O=(N=(R=e.reasoning)==null?void 0:R.chunks)==null?void 0:N.length)!=null?O:0,(ee=(de=(Ee=(Z=e.reasoning)==null?void 0:Z.chunks)==null?void 0:Ee[e.reasoning.chunks.length-1])==null?void 0:de.length)!=null?ee:0,(Ae=(ne=(Pe=(Le=e.reasoning)==null?void 0:Le.chunks)==null?void 0:Pe[e.reasoning.chunks.length-1])==null?void 0:ne.slice(-32))!=null?Ae:"",(se=(re=e.contentParts)==null?void 0:re.length)!=null?se:0,(ae=e.stopReason)!=null?ae:"",t].join("\0")}function ig(){return new Map}function lg(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function cg(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function dg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function ni(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Br(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Co(e,t){return Br(e)-e.scrollTop<=t}function ri(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function oi(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return t&&n<0?"pause":!t&&o&&n>0&&r?"resume":"none"}function pg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function ug(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function mg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var nn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},xn=1e5,Ao=xn+1;var ga={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Zx=["pre","code","a","script","style"],si=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:ga.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ga.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:ga.speed,duration:(o=e==null?void 0:e.duration)!=null?o:ga.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ga.buffer}},fg=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],fa=new Map;for(let e of fg)fa.set(e.name,e);var ev=e=>{fa.set(e.name,e)},tv=e=>{fg.some(t=>t.name===e)||fa.delete(e)},nv=()=>Array.from(fa.keys()),ks=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=fa.get(e))!=null?r:null},ai=(e,t,n,r,o)=>{if(!o)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
19
+ `);return s<0?"":e.slice(0,s)}return e},rv=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},ov=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},vl=/\s/,sv=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},av=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(vl.test(s[i])){let c=i;for(;c<s.length&&vl.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let p=i;for(;p<s.length&&!vl.test(s[p]);)c.appendChild(rv(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(c),i=p}o.replaceChild(a,e)},iv=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(ov(r,c,t,n.value)),n.value+=1));o.replaceChild(a,e)},ha=(e,t,n,r)=>{var u,f;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((u=r==null?void 0:r.skipTags)!=null?u:Zx).map(g=>g.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)sv(d,s)||i.push(d),d=a.nextNode();let c={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?av:iv;for(let g of i)p(g,n,c);return o.innerHTML},ii=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},ya=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},gg=new WeakMap,lv=(e,t)=>{var s;if(!e.styles)return;let n=gg.get(t);if(n||(n=new Set,gg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},wl=new WeakMap,cv=(e,t)=>{if(!e.onAttach)return;let n=wl.get(t);if(n||(n=new Map,wl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},hg=e=>{let t=wl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},li=(e,t)=>{lv(e,t),cv(e,t)};function Cl(e,t=xn){let n=e.style.position,r=e.style.zIndex,o=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=o}}var ba=0,So=null;function Al(e=document){var n;if(ba++,ba===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;So={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,ba=Math.max(0,ba-1),ba===0&&So)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=So.originalOverflow,o.style.position=So.originalPosition,o.style.top=So.originalTop,o.style.width=So.originalWidth,s.scrollTo(0,So.scrollY),So=null}}}var xa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},dn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},To=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},nr=e=>{var n,r,o,s,a,i;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:xa.side,width:(o=t==null?void 0:t.width)!=null?o:xa.width,animate:(s=t==null?void 0:t.animate)!=null?s:xa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:xa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:xa.maxHeight}};var hr={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var dv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ci=(e,t={})=>{var S,T,L,P,E,k;let{showClose:n=!0,wrapperClassName:r=dv,buttonSize:o,iconSize:s="28px"}=t,a=(S=e==null?void 0:e.launcher)!=null?S:{},i=(T=o!=null?o:a.closeButtonSize)!=null?T:"32px",d=y("div",r),c=(L=a.closeButtonTooltipText)!=null?L:"Close chat",p=(P=a.closeButtonShowTooltip)!=null?P:!0,u=(E=a.closeButtonIconName)!=null?E:"x",f=(k=a.closeButtonIconText)!=null?k:"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),b=Et("button",{className:Zs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||Mn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),v=ye(u,s,"currentColor",1);if(v?(v.style.display="block",b.appendChild(v)):b.textContent=f,d.appendChild(b),p&&c){let C=null,I=()=>{if(C)return;let $=b.ownerDocument,R=$.body;if(!R)return;C=Wr($,"div","persona-clear-chat-tooltip"),C.textContent=c;let N=Wr($,"div");N.className="persona-clear-chat-tooltip-arrow",C.appendChild(N);let O=b.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(Ao),C.style.left=`${O.left+O.width/2}px`,C.style.top=`${O.top-8}px`,C.style.transform="translate(-50%, -100%)",R.appendChild(C)},j=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",I),d.addEventListener("mouseleave",j),b.addEventListener("focus",I),b.addEventListener("blur",j),d._cleanupTooltip=()=>{j(),d.removeEventListener("mouseenter",I),d.removeEventListener("mouseleave",j),b.removeEventListener("focus",I),b.removeEventListener("blur",j)}}return{button:b,wrapper:d}},pv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",di=(e,t={})=>{var C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe;let{wrapperClassName:n=pv,buttonSize:r,iconSize:o="20px"}=t,a=(I=((C=e==null?void 0:e.launcher)!=null?C:{}).clearChat)!=null?I:{},i=(j=r!=null?r:a.size)!=null?j:"32px",d=($=a.iconName)!=null?$:"refresh-cw",c=(R=a.iconColor)!=null?R:"",p=(N=a.backgroundColor)!=null?N:"",u=(O=a.borderWidth)!=null?O:"",f=(Z=a.borderColor)!=null?Z:"",g=(Ee=a.borderRadius)!=null?Ee:"",b=(de=a.paddingX)!=null?de:"",v=(ee=a.paddingY)!=null?ee:"",S=(Le=a.tooltipText)!=null?Le:"Clear chat",T=(Pe=a.showTooltip)!=null?Pe:!0,L=y("div",n),P=!!(u||f),E=Et("button",{className:Zs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!P&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":S},style:{height:i,width:i,color:c||Mn.actionIconColor,backgroundColor:p||void 0,border:P?`${u||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:b||void 0,paddingRight:b||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),k=ye(d,o,"currentColor",1);if(k&&(k.style.display="block",E.appendChild(k)),L.appendChild(E),T&&S){let ne=null,Ae=()=>{if(ne)return;let se=E.ownerDocument,ae=se.body;if(!ae)return;ne=Wr(se,"div","persona-clear-chat-tooltip"),ne.textContent=S;let fe=Wr(se,"div");fe.className="persona-clear-chat-tooltip-arrow",ne.appendChild(fe);let $e=E.getBoundingClientRect();ne.style.position="fixed",ne.style.zIndex=String(Ao),ne.style.left=`${$e.left+$e.width/2}px`,ne.style.top=`${$e.top-8}px`,ne.style.transform="translate(-50%, -100%)",ae.appendChild(ne)},re=()=>{ne&&ne.parentNode&&(ne.parentNode.removeChild(ne),ne=null)};L.addEventListener("mouseenter",Ae),L.addEventListener("mouseleave",re),E.addEventListener("focus",Ae),E.addEventListener("blur",re),L._cleanupTooltip=()=>{re(),L.removeEventListener("mouseenter",Ae),L.removeEventListener("mouseleave",re),E.removeEventListener("focus",Ae),E.removeEventListener("blur",re)}}return{button:E,wrapper:L}};var Mn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Eo=e=>{var k,C,I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe,ne,Ae;let{config:t,showClose:n=!0}=e,r=Et("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),o=(k=t==null?void 0:t.launcher)!=null?k:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(I=o.closeButtonPlacement)!=null?I:"inline",i=(j=o.headerIconHidden)!=null?j:!1,d=o.headerIconName,c=Et("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let re=parseFloat(s)||24,se=ye(d,re*.6,"currentColor",1);se?c.replaceChildren(se):c.textContent=(R=($=t==null?void 0:t.launcher)==null?void 0:$.agentIconText)!=null?R:"\u{1F4AC}"}else if((N=t==null?void 0:t.launcher)!=null&&N.iconUrl){let re=y("img");re.src=t.launcher.iconUrl,re.alt="",re.className="persona-rounded-xl persona-object-cover",re.style.height=s,re.style.width=s,c.replaceChildren(re)}else c.textContent=(Z=(O=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?Z:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Et("span",{className:"persona-text-base persona-font-semibold",text:(de=(Ee=t==null?void 0:t.launcher)==null?void 0:Ee.title)!=null?de:"Chat Assistant",style:{color:Mn.titleColor}}),f=Et("span",{className:"persona-text-xs",text:(Le=(ee=t==null?void 0:t.launcher)==null?void 0:ee.subtitle)!=null?Le:"Here to help you get answers fast",style:{color:Mn.subtitleColor}});p.append(u,f),i?r.append(p):r.append(c,p);let g=(Pe=o.clearChat)!=null?Pe:{},b=(ne=g.enabled)!=null?ne:!0,v=(Ae=g.placement)!=null?Ae:"inline",S=null,T=null;if(b){let se=di(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});S=se.button,T=se.wrapper,v==="top-right"&&(T.style.right="48px"),v==="inline"&&r.appendChild(T)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:P,wrapper:E}=ci(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&r.appendChild(E),{header:r,iconHolder:c,headerTitle:u,headerSubtitle:f,closeButton:P,closeButtonWrapper:E,clearChatButton:S,clearChatButtonWrapper:T}},Ls=(e,t,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function ts(e){let{items:t,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=e,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Ao)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let S=document.createElement("hr");a.appendChild(S)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",g.id),g.destructive&&b.setAttribute("data-destructive",""),g.icon){let S=ye(g.icon,16,"currentColor",1.5);S&&b.appendChild(S)}let v=document.createElement("span");v.textContent=g.label,b.appendChild(v),b.addEventListener("click",S=>{S.stopPropagation(),p(),n(g.id)}),a.appendChild(b)}let i=null;function d(){if(!s)return;let g=r.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=b=>{!a.contains(b.target)&&!r.contains(b.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:p,toggle:u,destroy:f}}function Gt(e){let{icon:t,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=ye(t,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function pi(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let p=y("button",c);if(p.type="button",p.setAttribute("aria-label",n),t){let f=ye(t,s!=null?s:14,"currentColor",2);f&&p.appendChild(f)}let u=y("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))p.setAttribute(f,g);return p}function ui(e){let{items:t,selectedId:n,onSelect:r,className:o}=e,s=y("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let u;p.icon?u=Gt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(u=y("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),s.appendChild(u)}function c(p){a=p,d()}return{element:s,setSelected:c}}function Sl(e){var g,b;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,c=y("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",t);let p=y("span","persona-combo-btn-label");p.textContent=t,c.appendChild(p);let u=ye(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),d&&(c.style.borderRadius=(g=d.borderRadius)!=null?g:"10px",c.style.padding=(b=d.padding)!=null?b:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var v,S;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(S=d.border)!=null?S:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=ts({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),o(v)},anchor:c,position:s,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",v=>{v.stopPropagation();let S=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",S?"false":"true"),f.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{p.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var yg=e=>{var r;let t=Eo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function uv(e,t,n){var r,o,s;if(t!=null&&t.length)for(let a of t){let i=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=ye(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=y("div","persona-relative");d.appendChild(i);let c=ts({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var bg=e=>{var L,P,E,k,C,I,j,$,R;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(L=t==null?void 0:t.launcher)!=null?L:{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,p;if(d)c=Sl({label:(P=a.title)!=null?P:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=Mn.titleColor,p=(E=c.querySelector(".persona-combo-btn-label"))!=null?E:c;else{if(c=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=y("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Mn.titleColor,p.textContent=(k=a.title)!=null?k:"Chat Assistant",c.appendChild(p),uv(c,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let O=o.onTitleClick;c.addEventListener("click",Z=>{Z.target.closest("button")||O()}),c.addEventListener("keydown",Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),O())})}let N=o==null?void 0:o.titleRowHover;N&&(c.style.borderRadius=(I=N.borderRadius)!=null?I:"10px",c.style.padding=(j=N.padding)!=null?j:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var O,Z;c.style.backgroundColor=(O=N.background)!=null?O:"",c.style.borderColor=(Z=N.border)!=null?Z:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let u=($=a.closeButtonSize)!=null?$:"32px",f=y("div",""),g=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=u,g.style.width=u,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||Mn.actionIconColor;let b=(R=a.closeButtonIconName)!=null?R:"x",v=ye(b,"28px","currentColor",1);v?g.appendChild(v):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let S=y("div");S.style.display="none";let T=y("span");return T.style.display="none",{header:i,iconHolder:S,headerTitle:p,headerSubtitle:T,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Tl={default:yg,minimal:bg},xg=e=>{var t;return(t=Tl[e])!=null?t:Tl.default},va=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let c=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=y("div");p.style.display="none";let u=y("span"),f=y("span"),g=y("button");g.style.display="none";let b=y("div");return b.style.display="none",{header:c,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:g,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=xg(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var mi=e=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},gi=e=>{var k,C,I,j,$,R,N,O,Z,Ee,de,ee;let t=(k=e==null?void 0:e.sendButton)!=null?k:{},n=(C=t.useIcon)!=null?C:!1,r=(I=t.iconText)!=null?I:"\u2191",o=t.iconName,s=(j=t.stopIconName)!=null?j:"square",a=($=t.tooltipText)!=null?$:"Send message",i=(R=t.stopTooltipText)!=null?R:"Stop generating",d=(O=(N=e==null?void 0:e.copy)==null?void 0:N.sendButtonLabel)!=null?O:"Send",c=(Ee=(Z=e==null?void 0:e.copy)==null?void 0:Z.stopButtonLabel)!=null?Ee:"Stop",p=(de=t.showTooltip)!=null?de:!1,u=(ee=t.size)!=null?ee:"40px",f=t.backgroundColor,g=t.textColor,b=y("div","persona-send-button-wrapper"),v=Et("button",{className:Zs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!f&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&f||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),S=null,T=null;if(n){let Le=parseFloat(u)||24,Pe=(g==null?void 0:g.trim())||"currentColor";o?(S=ye(o,Le,Pe,2),S?v.appendChild(S):v.textContent=r):v.textContent=r,T=ye(s,Le,Pe,2)}else v.textContent=d;let L=null;p&&a&&(L=y("div","persona-send-button-tooltip"),L.textContent=a,b.appendChild(L)),v.setAttribute("aria-label",a),b.appendChild(v);let P="send";return{button:v,wrapper:b,setMode:Le=>{if(Le===P)return;P=Le;let Pe=Le==="stop"?i:a;if(v.setAttribute("aria-label",Pe),L&&(L.textContent=Pe),n){if(S&&T){let ne=Le==="stop"?T:S;v.replaceChildren(ne)}}else v.textContent=Le==="stop"?c:d}}},fi=e=>{var L,P,E,k,C,I,j,$,R,N,O,Z;let t=(L=e==null?void 0:e.voiceRecognition)!=null?L:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((P=t.provider)==null?void 0:P.type)==="runtype";if(!(r||o))return null;let a=(k=(E=e==null?void 0:e.sendButton)==null?void 0:E.size)!=null?k:"40px",i=(C=t.iconName)!=null?C:"mic",d=(I=t.iconSize)!=null?I:a,c=parseFloat(d)||24,p=($=t.backgroundColor)!=null?$:(j=e==null?void 0:e.sendButton)==null?void 0:j.backgroundColor,u=(N=t.iconColor)!=null?N:(R=e==null?void 0:e.sendButton)==null?void 0:R.textColor,f=y("div","persona-send-button-wrapper"),g=Et("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),v=ye(i,c,u||"currentColor",1.5);v?g.appendChild(v):g.textContent="\u{1F3A4}",f.appendChild(g);let S=(O=t.tooltipText)!=null?O:"Start voice recognition";if(((Z=t.showTooltip)!=null?Z:!1)&&S){let Ee=y("div","persona-send-button-tooltip");Ee.textContent=S,f.appendChild(Ee)}return{button:g,wrapper:f}},hi=e=>{var b,v,S,T,L,P,E,k;let t=(b=e==null?void 0:e.attachments)!=null?b:{};if(t.enabled!==!0)return null;let n=(S=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?S:"40px",r=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=y("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((T=t.allowedTypes)!=null?T:Gr).join(","),o.multiple=((L=t.maxFiles)!=null?L:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(P=t.buttonIconName)!=null?P:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=y("div","persona-send-button-wrapper"),p=Et("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(E=t.buttonTooltipText)!=null?E:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let u=ye(s,d,"currentColor",1.5);u?p.appendChild(u):p.textContent="\u{1F4CE}",p.addEventListener("click",C=>{C.preventDefault(),o.click()}),c.appendChild(p);let f=(k=t.buttonTooltipText)!=null?k:"Attach file",g=y("div","persona-send-button-tooltip");return g.textContent=f,c.appendChild(g),{button:p,wrapper:c,input:o,previewsContainer:r}},yi=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let c=y("a");c.href=t.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},bi=()=>Et("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var wa=e=>{var b,v,S,T,L,P;let{config:t}=e,n=Et("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=bi(),o=Et("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=mi(t);a();let i=gi(t),d=fi(t),c=hi(t),p=yi(t);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let u=Et("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),f=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&f.append(c.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),u.append(f,g),o.append(u),o.addEventListener("click",E=>{E.target!==i.button&&E.target!==i.wrapper&&E.target!==(d==null?void 0:d.button)&&E.target!==(d==null?void 0:d.wrapper)&&E.target!==(c==null?void 0:c.button)&&E.target!==(c==null?void 0:c.wrapper)&&s.focus()}),n.append(r,o,p),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(b=d==null?void 0:d.button)!=null?b:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:p,attachmentButton:(S=c==null?void 0:c.button)!=null?S:null,attachmentButtonWrapper:(T=c==null?void 0:c.wrapper)!=null?T:null,attachmentInput:(L=c==null?void 0:c.input)!=null?L:null,attachmentPreviewsContainer:(P=c==null?void 0:c.previewsContainer)!=null?P:null,actionsRow:u,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var vg=()=>{let e=Et("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),n=ye("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=ye("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},wg=e=>{var b,v,S,T,L,P;let{config:t}=e,n=Et("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=bi();r.style.display="none";let o=yi(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=mi(t);s.style.maxHeight="100px",a();let i=gi(t),d=fi(t),c=hi(t);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let p=Et("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&u.append(c.wrapper);let f=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.append(i.wrapper),p.addEventListener("click",E=>{E.target!==i.button&&E.target!==i.wrapper&&E.target!==(d==null?void 0:d.button)&&E.target!==(d==null?void 0:d.wrapper)&&E.target!==(c==null?void 0:c.button)&&E.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&p.append(c.input),p.append(u,s,f),c&&n.append(c.previewsContainer),n.append(p,r,o);let g=p;return{footer:n,suggestions:r,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(b=d==null?void 0:d.button)!=null?b:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:o,attachmentButton:(S=c==null?void 0:c.button)!=null?S:null,attachmentButtonWrapper:(T=c==null?void 0:c.wrapper)!=null?T:null,attachmentInput:(L=c==null?void 0:c.input)!=null?L:null,attachmentPreviewsContainer:(P=c==null?void 0:c.previewsContainer)!=null?P:null,actionsRow:g,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var Cg=e=>{var p,u,f,g,b,v,S,T,L,P,E,k,C,I,j,$,R;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=dn(e);if(To(e)){let N=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},O=y("div","persona-widget-wrapper persona-fixed persona-transition");O.setAttribute("data-persona-composer-bar",""),O.dataset.state="collapsed",O.dataset.expandedSize=(b=N.expandedSize)!=null?b:"anchored",O.style.zIndex=String((S=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?S:xn);let Z=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Z.style.width="100%",O.appendChild(Z);let Ee=y("div","persona-widget-pill-root");return Ee.setAttribute("data-persona-composer-bar",""),Ee.dataset.state="collapsed",Ee.dataset.expandedSize=(T=N.expandedSize)!=null?T:"anchored",Ee.style.zIndex=String((P=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?P:xn),{wrapper:O,panel:Z,pillRoot:Ee}}if(n){let N=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),O=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return N.appendChild(O),{wrapper:N,panel:O}}if(!t){let N=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),O=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(k=(E=e==null?void 0:e.launcher)==null?void 0:E.width)!=null?k:"100%";return N.style.width=Z,O.style.width="100%",N.appendChild(O),{wrapper:N,panel:O}}let o=(C=e==null?void 0:e.launcher)!=null?C:{},s=o.position&&hr[o.position]?hr[o.position]:hr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((j=(I=e==null?void 0:e.launcher)==null?void 0:I.zIndex)!=null?j:xn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=($=e==null?void 0:e.launcher)==null?void 0:$.width)!=null?R:e==null?void 0:e.launcherWidth,c=d!=null?d:tr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},mv=(e,t)=>{var E,k,C,I,j,$,R,N,O;let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=ci(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(C=(k=(E=e==null?void 0:e.launcher)==null?void 0:E.clearChat)==null?void 0:k.enabled)!=null?C:!0,a=null,i=null;if(s){let Z=di(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Z.button,i=Z.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Et("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Et("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let p=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(j=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?j:"Hello \u{1F44B}"}),u=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=($=e==null?void 0:e.copy)==null?void 0:$.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),f=Et("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,u),g=y("div","persona-flex persona-flex-col persona-gap-3"),b=(N=e==null?void 0:e.layout)==null?void 0:N.contentMaxWidth;b&&(g.style.maxWidth=b,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(f.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(f,g);let S=Et("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),T=wg({config:e}),{root:L,textNode:P}=vg();return n.append(d,o,c,S),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:g,composerOverlay:S,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:p,introSubtitle:u,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:L,peekTextNode:P}},Ag=(e,t=!0)=>{var S,T,L,P,E,k,C,I,j;if(To(e))return mv(e,t);let n=Et("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(S=e==null?void 0:e.layout)==null?void 0:S.header,o=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,s=r?va(e,r,{showClose:t}):Eo({config:e,showClose:t}),a=Et("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=Et("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(P=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?P:"Hello \u{1F44B}"}),d=Et("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(E=e==null?void 0:e.copy)==null?void 0:E.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),c=Et("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:dn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),p=y("div","persona-flex persona-flex-col persona-gap-3"),u=(C=e==null?void 0:e.layout)==null?void 0:C.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((I=e==null?void 0:e.copy)==null?void 0:I.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,p);let g=wa({config:e}),b=((j=e==null?void 0:e.layout)==null?void 0:j.showFooter)!==!1;o?Ls(n,s,e):(s.header.style.display="none",Ls(n,s,e)),n.append(a);let v=Et("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return b||(g.footer.style.display="none"),n.append(g.footer),n.append(v),{container:n,body:a,messagesWrapper:p,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var El=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
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 la=e=>({isError:!0,content:[{type:"text",text:e}]
24
24
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
25
25
  </span>
26
26
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
27
- `,n.addEventListener("click",t);let r=s=>{var k,M,P,C,R,F,j,H,O,N,Y,ke,pe;let a=(k=s.launcher)!=null?k:{},i=dn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let Z=(M=a.title)!=null?M:"Chat Assistant";d.textContent=Z,d.setAttribute("title",Z)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let Z=(P=a.subtitle)!=null?P:"Here to help you get answers fast";l.textContent=Z,l.setAttribute("title",Z)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let Z=(C=a.agentIconSize)!=null?C:"40px";if(u.style.height=Z,u.style.width=Z,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let Te=parseFloat(Z)||24,Le=ge(a.agentIconName,Te*.6,"var(--persona-text-inverse, #ffffff)",2);Le?(u.appendChild(Le),u.style.display=""):(u.textContent=(R=a.agentIconText)!=null?R:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(F=a.agentIconText)!=null?F:"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let Z=(j=a.agentIconSize)!=null?j:"40px";g.style.height=Z,g.style.width=Z,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 Z=(H=a.callToActionIconSize)!=null?H:"32px";f.style.height=Z,f.style.width=Z,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 Te=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,Te=(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 Le=parseFloat(Z)||24,oe=Math.max(Le-Te,8),Ae=ge(a.callToActionIconName,oe,"currentColor",2);Ae?f.appendChild(Ae):f.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else f.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}let v=a.position&&br[a.position]?br[a.position]:br["bottom-right"],x="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";n.className=i?E:`${x} ${v}`,i||(n.style.zIndex=String((Y=a.zIndex)!=null?Y:vn));let T="1px solid var(--persona-border, #e5e7eb)",L="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(ke=a.border)!=null?ke:T,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:L,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(pe=a.collapsedMaxWidth)!=null?pe:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:o}};var mg=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:o}=pg(e),s=ug(e,t),a={wrapper:n,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},l={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:l,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=>{l.footer.replaceWith(g),l.footer=g}}},Tl=({config:e,plugins:t,onToggle:n})=>{let r=t.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:e,defaultRenderer:()=>Sl(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=Sl(e,n);return{instance:o,element:o.element}};var tv=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},nv=(e,t)=>{if(!e)return null;let n=tv(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},rv=(e,t)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},ov=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},El=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Ml=320,fg=320,sv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),av=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),iv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),lv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),cv=(e,t,n)=>{if(e.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var u;let l=y("img");l.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${Ml}px`,l.style.maxHeight=`${fg}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,l.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{p=!0}),ov(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,o=Math.max(0,o-1),l.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},dv=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!El(r.audio))return;let o=y("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ml}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},pv=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!El(r.video))return;let o=y("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ml}px`,o.style.maxHeight=`${fg}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},uv=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!El(r.data))return;let o=y("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},ks=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(o),e},hg=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:ks};if(t){let o=t(r);if(o!==null)return o}return ks()},mv=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=y("img");o.src=r,o.alt=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},gg=(e,t,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?r.textContent=t.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},gv=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},yg=(e,t,n)=>{var v,x,E,T,L,k,M;let r=(v=t.showCopy)!=null?v:!0,o=(x=t.showUpvote)!=null?x:!0,s=(E=t.showDownvote)!=null?E:!0,a=(T=t.showReadAloud)!=null?T:!1;if(!r&&!o&&!s&&!a){let P=y("div");return P.style.display="none",P.id=`actions-${e.id}`,P.setAttribute("data-actions-for",e.id),P}let i=(L=t.visibility)!=null?L:"hover",d=(k=t.align)!=null?k:"right",l=(M=t.layout)!=null?M:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[l],g=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(P,C,R)=>{let F=Kt({icon:P,label:C,size:14,className:"persona-message-action-btn"});return F.setAttribute("data-action",R),F};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},Ca=(e,t,n,r,o,s)=>{var se,ie,ae,xe,Be,V,X,He,K,ue,$e,fe,Ve,et,Ot,Xe,ye;let a=n!=null?n:{},i=(se=a.layout)!=null?se:"bubble",d=a.avatar,l=a.timestamp,p=(ie=d==null?void 0:d.show)!=null?ie:!1,u=(ae=l==null?void 0:l.show)!=null?ae:!1,g=(xe=d==null?void 0:d.position)!=null?xe:"left",f=(Be=l==null?void 0:l.position)!=null?Be:"below",v=gv(e.role,i),x=y("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=sv(e),T=(X=(V=e.content)==null?void 0:V.trim())!=null?X:"",k=E.length>0&&T===Va,M=si((K=(He=s==null?void 0:s.widgetConfig)==null?void 0:He.features)==null?void 0:K.streamAnimation),P=(fe=($e=(ue=s==null?void 0:s.widgetConfig)==null?void 0:ue.features)==null?void 0:$e.streamAnimation)==null?void 0:fe.plugins,C=e.role==="assistant"&&M.type!=="none"?fa(M.type,P):null,R=e.role==="assistant"&&((Ve=C==null?void 0:C.isAnimating)==null?void 0:Ve.call(C,e))===!0,F=e.role==="assistant"&&C!==null&&(!!e.streaming||R);F&&(C!=null&&C.bubbleClass)&&x.classList.add(C.bubbleClass);let j=document.createElement("div");j.classList.add("persona-message-content"),e.streaming&&j.classList.add("persona-content-streaming"),F&&C&&(C.containerClass&&j.classList.add(C.containerClass),j.style.setProperty("--persona-stream-step",`${M.speed}ms`),j.style.setProperty("--persona-stream-duration",`${M.duration}ms`));let H=F?ai((et=e.content)!=null?et:"",M.buffer,C,e,!!e.streaming):(Ot=e.content)!=null?Ot:"",O=t({text:H,message:e,streaming:!!e.streaming,raw:e.rawContent}),N=O;F&&(C==null?void 0:C.wrap)==="char"?N=ha(O,"char",e.id,{skipTags:C.skipTags}):F&&(C==null?void 0:C.wrap)==="word"&&(N=ha(O,"word",e.id,{skipTags:C.skipTags}));let Y=null;if(k?(Y=document.createElement("div"),Y.innerHTML=N,Y.style.display="none",j.appendChild(Y)):j.innerHTML=N,F&&(C!=null&&C.useCaret)&&!k&&T){let J=ii(),dt=j.querySelectorAll(".persona-stream-char, .persona-stream-word"),qe=dt[dt.length-1];if(qe!=null&&qe.parentNode)qe.parentNode.insertBefore(J,qe.nextSibling);else{let Se=j.lastElementChild;Se?Se.appendChild(J):j.appendChild(J)}}if(u&&f==="inline"&&e.createdAt){let J=gg(e,l,"span");J.classList.add("persona-timestamp-inline");let dt=j.lastElementChild;dt?dt.appendChild(J):j.appendChild(J)}if(E.length>0){let J=cv(E,!k&&!!T,()=>{k&&Y&&(Y.style.display="")});J?x.appendChild(J):k&&Y&&(Y.style.display="")}let ke=av(e);if(ke.length>0){let J=dv(ke);J&&x.appendChild(J)}let pe=iv(e);if(pe.length>0){let J=pv(pe);J&&x.appendChild(J)}let Z=lv(e);if(Z.length>0){let J=uv(Z);J&&x.appendChild(J)}if(x.appendChild(j),u&&f==="below"&&e.createdAt){let J=gg(e,l);J.classList.add("persona-mt-1"),x.appendChild(J)}let Te=e.role==="assistant"?nv(e.stopReason,(ye=(Xe=s==null?void 0:s.widgetConfig)==null?void 0:Xe.copy)==null?void 0:ye.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let J=!!(H&&H.trim()),dt=M.placeholder==="skeleton",qe=dt&&M.buffer==="line"&&J;if(J)qe&&x.appendChild(ya());else if(dt)x.appendChild(ya());else{let Se=hg("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Se&&x.appendChild(Se)}}if(Te&&e.stopReason&&!e.streaming&&(T||(j.style.display="none"),x.appendChild(rv(e.stopReason,Te))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let J=yg(e,r,o);x.appendChild(J)}if(!p||e.role==="system")return x;let oe=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ae=mv(d,e.role);return g==="right"||g==="left"&&e.role==="user"?oe.append(x,Ae):oe.append(Ae,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),oe},fv=(e,t,n,r,o,s)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ca(e,t,n,r,o,s)};var Ls=new Set,hv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),yv=(e,t)=>{var r,o;let n=(o=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
28
- `):""},bg=(e,t)=>{let n=Ls.has(e),r=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=ge(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}o.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},kl=(e,t)=>{var pe,Z,Te,Le,oe,Ae,se,ie,ae,xe,Be;let n=e.reasoning,r=y("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let o=(Z=(pe=t==null?void 0:t.features)==null?void 0:pe.reasoningDisplay)!=null?Z:{},s=o.expandable!==!1,a=s&&Ls.has(e.id),i=n.status!=="complete",d=yv(e,(Te=o.previewMaxLines)!=null?Te:3),l=y("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");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=y("div","persona-flex persona-flex-col persona-text-left"),u=y("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",f=(Le=t==null?void 0:t.reasoning)!=null?Le:{},v=String((oe=n.startedAt)!=null?oe:Date.now()),x=()=>{let V=y("span","");return V.setAttribute("data-tool-elapsed",v),V.textContent=Ua(n),V},E=(Ae=f.renderCollapsedSummary)==null?void 0:Ae.call(f,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ua(n),createElapsedElement:x});typeof E=="string"&&E.trim()?(u.textContent=E,p.appendChild(u)):E instanceof HTMLElement?p.appendChild(E):(u.textContent=g,p.appendChild(u));let T=y("span","persona-text-xs persona-text-persona-primary");T.textContent=vm(n),p.appendChild(T);let L=(se=o.loadingAnimation)!=null?se:"none",k=f.activeTextTemplate,M=f.completeTextTemplate,P=i?k:M,C=E instanceof HTMLElement,R=(V,X,He)=>{let K=He;for(let ue of X){let $e=y("span","persona-tool-char");$e.style.setProperty("--char-index",String(K)),$e.textContent=ue===" "?"\xA0":ue,V.appendChild($e),K++}return K},F=(V,X)=>{u.textContent="";let He=qa(V,""),K=0;for(let ue of He){let $e=ue.styles.length>0?(()=>{let fe=y("span",ue.styles.map(Ve=>`persona-tool-text-${Ve}`).join(" "));return u.appendChild(fe),fe})():u;if(ue.isDuration&&i)$e.appendChild(x());else{let fe=ue.isDuration?Ua(n):ue.text;X?K=R($e,fe,K):$e.appendChild(document.createTextNode(fe))}}};if(!C&&P)if(T.style.display="none",u.style.display="",i&&L!=="none"){let V=(ie=f.loadingAnimationDuration)!=null?ie:2e3;u.setAttribute("data-preserve-animation","true"),L==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),F(P,!1)):(u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),L==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),F(P,!0))}else F(P,!1);else if(!C&&i&&L!=="none"){u.style.display="";let V=(ae=f.loadingAnimationDuration)!=null?ae:2e3;if(u.setAttribute("data-preserve-animation","true"),L==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`);else{u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),L==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let X=u.textContent||g;u.textContent="",R(u,X,0)}n.status==="complete"&&(u.style.display="none")}else C||(n.status==="complete"?u.style.display="none":u.style.display="");let j=null;if(s){j=y("div","persona-flex persona-items-center");let X=ge(a?"chevron-up":"chevron-down",16,"currentColor",2);X?j.appendChild(X):j.textContent=a?"Hide":"Show";let He=y("div","persona-flex persona-items-center persona-ml-auto");He.append(j),l.append(p,He)}else l.append(p);let H=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(H.setAttribute("data-persona-collapsed-preview","reasoning"),H.style.display="none",H.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let V=(Be=(xe=t==null?void 0:t.reasoning)==null?void 0:xe.renderCollapsedPreview)==null?void 0:Be.call(xe,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});hv(H,V)||(H.textContent=d),H.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(l,H),r;let O=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");O.style.display=a?"":"none";let N=n.chunks.join(""),Y=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Y.textContent=N||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(Y),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),j){j.innerHTML="";let X=ge(a?"chevron-up":"chevron-down",16,"currentColor",2);X?j.appendChild(X):j.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",H.style.display=a?"none":H.textContent||H.childNodes.length?"":"none"})(),r.append(l,H,O),r};var Ps=new Set,bv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),xv=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let r=((s=n.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
29
- `);let o=Ao(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
30
- `):""},Ll=(e,t)=>{var n,r,o;e.style.backgroundColor=(n=t.codeBlockBackgroundColor)!=null?n:"var(--persona-container, #f3f4f6)",e.style.borderColor=(r=t.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",e.style.color=(o=t.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},vv=(e,t)=>{var p,u,g,f,v;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,o=(u=r==null?void 0:r.collapsedMode)!=null?u:"tool-call",s=xv(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?wm(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(f=t==null?void 0:t.toolCall)!=null?f:{},l=a;return o==="tool-name"?l=((v=n.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=nl(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=nl(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},xg=(e,t,n)=>{var p;let r=Ps.has(e),o=(p=n==null?void 0:n.toolCall)!=null?p:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",g=ge(r?"chevron-up":"chevron-down",16,u,2);g?l.appendChild(g):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Pl=(e,t)=>{var N,Y,ke,pe,Z,Te,Le,oe,Ae;let n=e.toolCall,r=(N=t==null?void 0:t.toolCall)!=null?N:{},o=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let s=(ke=(Y=t==null?void 0:t.features)==null?void 0:Y.toolCallDisplay)!=null?ke:{},a=s.expandable!==!1,i=a&&Ps.has(e.id),{summary:d,previewText:l,isActive:p}=vv(e,t),u=y("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(u.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(u.style.paddingLeft=r.headerPaddingX,u.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(u.style.paddingTop=r.headerPaddingY,u.style.paddingBottom=r.headerPaddingY);let g=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(f.style.color=r.headerTextColor);let v=String((pe=n.startedAt)!=null?pe:Date.now()),x=()=>{let se=y("span","");return se.setAttribute("data-tool-elapsed",v),se.textContent=ra(n),se},E=(Te=r.renderCollapsedSummary)==null?void 0:Te.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(Z=s.collapsedMode)!=null?Z:"tool-call",isActive:p,config:t!=null?t:{},elapsed:ra(n),createElapsedElement:x});typeof E=="string"&&E.trim()?(f.textContent=E,g.appendChild(f)):E instanceof HTMLElement?g.appendChild(E):(f.textContent=d,g.appendChild(f));let T=(Le=s.loadingAnimation)!=null?Le:"none",L=r.activeTextTemplate,k=r.completeTextTemplate,M=p?L:k,P=E instanceof HTMLElement,C=(se,ie,ae)=>{let xe=ae;for(let Be of ie){let V=y("span","persona-tool-char");V.style.setProperty("--char-index",String(xe)),V.textContent=Be===" "?"\xA0":Be,se.appendChild(V),xe++}return xe},R=(se,ie)=>{var V;f.textContent="";let ae=((V=n.name)==null?void 0:V.trim())||"tool",xe=qa(se,ae),Be=0;for(let X of xe){let He=X.styles.length>0?(()=>{let K=y("span",X.styles.map(ue=>`persona-tool-text-${ue}`).join(" "));return f.appendChild(K),K})():f;if(X.isDuration&&p)He.appendChild(x());else{let K=X.isDuration?ra(n):X.text;ie?Be=C(He,K,Be):He.appendChild(document.createTextNode(K))}}};if(!P)if(p&&T!=="none"){let se=(oe=r.loadingAnimationDuration)!=null?oe:2e3;if(f.setAttribute("data-preserve-animation","true"),T==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${se}ms`),M&&R(M,!1);else if(f.classList.add(`persona-tool-loading-${T}`),f.style.setProperty("--persona-tool-anim-duration",`${se}ms`),T==="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)R(M,!0);else{let ie=f.textContent||d;f.textContent="",C(f,ie,0)}}else M&&R(M,!1);let F=null;if(a){F=y("div","persona-flex persona-items-center");let se=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",ie=ge(i?"chevron-up":"chevron-down",16,se,2);ie?F.appendChild(ie):F.textContent=i?"Hide":"Show";let ae=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ae.append(F),u.append(g,ae)}else u.append(g);let j=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(j.setAttribute("data-persona-collapsed-preview","tool"),j.style.display="none",j.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&l){let se=(Ae=r.renderCollapsedPreview)==null?void 0:Ae.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});bv(j,se)||(j.textContent=l),j.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,j),o;let H=y("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 se=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?se.style.color=r.contentTextColor:r.headerTextColor&&(se.style.color=r.headerTextColor),se.textContent=n.name,H.appendChild(se)}if(n.args!==void 0){let se=y("div","persona-space-y-1"),ie=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ie.style.color=r.labelTextColor),ie.textContent="Arguments";let ae=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Ll(ae,r),ae.textContent=Ao(n.args),se.append(ie,ae),H.appendChild(se)}if(n.chunks&&n.chunks.length){let se=y("div","persona-space-y-1"),ie=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ie.style.color=r.labelTextColor),ie.textContent="Activity";let ae=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Ll(ae,r),ae.textContent=n.chunks.join(""),se.append(ie,ae),H.appendChild(se)}if(n.status==="complete"&&n.result!==void 0){let se=y("div","persona-space-y-1"),ie=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ie.style.color=r.labelTextColor),ie.textContent="Result";let ae=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Ll(ae,r),ae.textContent=Ao(n.result),se.append(ie,ae),H.appendChild(se)}if(n.status==="complete"&&typeof n.duration=="number"){let se=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(se.style.color=r.contentTextColor),se.textContent=`Duration: ${n.duration}ms`,H.appendChild(se)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),F){F.innerHTML="";let se=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",ie=ge(i?"chevron-up":"chevron-down",16,se,2);ie?F.appendChild(ie):F.textContent=i?"Hide":"Show"}H.style.display=i?"":"none",j.style.display=i?"none":j.textContent||j.childNodes.length?"":"none"})(),o.append(u,j,H),o};var ts=new Map,bi=e=>{let n=(e.startsWith(Dr)?e.slice(Dr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},vg=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,wg=(e,t)=>{var r,o,s;let n=(o=(r=vg(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=ts.get(e))!=null?s:n==="expanded"},Cg=(e,t,n)=>{var a,i;let r=vg(n);e.setAttribute("aria-expanded",t?"true":"false");let o=e.querySelector("[data-approval-details-label]");o&&(o.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=ge(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},Ag=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=wg(e,n);Cg(r,s,n),o.style.display=s?"":"none"};var xi=(e,t)=>{var R,F,j,H,O,N,Y,ke,pe,Z,Te,Le,oe,Ae,se;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(n==null?void 0:n.status)==="pending",s=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(R=r==null?void 0:r.backgroundColor)!=null?R:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(F=r==null?void 0:r.borderColor)!=null?F:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(j=r==null?void 0:r.titleColor)!=null?j:"currentColor",p=ge(d,20,l,2);p&&i.appendChild(p);let u=y("div","persona-flex-1 persona-min-w-0"),g=y("div","persona-flex persona-items-center persona-gap-2"),f=y("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 ie=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");ie.setAttribute("data-approval-status",n.status),n.status==="approved"?(ie.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",ie.style.color="var(--persona-palette-colors-success-700, #15803d)",ie.textContent="Approved"):n.status==="denied"?(ie.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",ie.style.color="var(--persona-palette-colors-error-700, #b91c1c)",ie.textContent="Denied"):n.status==="timeout"&&(ie.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",ie.style.color="var(--persona-palette-colors-warning-700, #b45309)",ie.textContent="Timeout"),g.appendChild(ie)}u.appendChild(g);let x=n.toolType==="webmcp"||n.toolName.startsWith(Dr)?Qs(n.toolName):void 0,E=(O=r==null?void 0:r.formatDescription)==null?void 0:O.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...x?{displayTitle:x}:{},...n.reason?{reason:n.reason}:{}}),T=!n.toolName,L=E||(T?n.description:`The assistant wants to use \u201C${x!=null?x:bi(n.toolName)}\u201D.`),k=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(k.style.color=r.descriptionColor),k.textContent=L,u.appendChild(k),n.reason){let ie=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");ie.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?ie.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(ie.style.color=r.descriptionColor);let ae=y("span","persona-font-medium");ae.textContent=`${(N=r==null?void 0:r.reasonLabel)!=null?N:"Agent's stated reason:"} `,ie.appendChild(ae),ie.appendChild(document.createTextNode(n.reason)),u.appendChild(ie)}let M=(Y=r==null?void 0:r.detailsDisplay)!=null?Y:"collapsed",P=!!n.description&&!T,C=P||!!n.parameters;if(M!=="hidden"&&C){let ie=wg(e.id,t),ae=y("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");ae.type="button",ae.setAttribute("data-expand-header","true"),ae.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor);let xe=y("span");xe.setAttribute("data-approval-details-label","true");let Be=y("span","persona-inline-flex persona-items-center");Be.setAttribute("data-approval-details-chevron","true"),ae.append(xe,Be),Cg(ae,ie,t),u.appendChild(ae);let V=y("div");if(V.setAttribute("data-approval-details","true"),V.style.display=ie?"":"none",P){let X=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(X.style.color=r.descriptionColor),X.textContent=n.description,V.appendChild(X)}if(n.parameters){let X=y("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(X.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(X.style.color=r.parameterTextColor),X.style.fontSize="0.75rem",X.style.lineHeight="1rem",X.textContent=Ao(n.parameters),V.appendChild(X)}u.appendChild(V)}if(o){let ie=y("div","persona-flex persona-gap-2 persona-mt-2");ie.setAttribute("data-approval-buttons","true");let ae=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");ae.type="button",ae.style.backgroundColor=(ke=r==null?void 0:r.approveButtonColor)!=null?ke:"var(--persona-approval-approve-bg, #22c55e)",ae.style.color=(pe=r==null?void 0:r.approveButtonTextColor)!=null?pe:"#ffffff",ae.setAttribute("data-approval-action","approve");let xe=ge("shield-check",14,(Z=r==null?void 0:r.approveButtonTextColor)!=null?Z:"#ffffff",2);xe&&(xe.style.marginRight="4px",ae.appendChild(xe));let Be=document.createTextNode((Te=r==null?void 0:r.approveLabel)!=null?Te:"Approve");ae.appendChild(Be);let V=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");V.type="button",V.style.backgroundColor=(Le=r==null?void 0:r.denyButtonColor)!=null?Le:"transparent",V.style.color=(oe=r==null?void 0:r.denyButtonTextColor)!=null?oe:"var(--persona-feedback-error, #dc2626)",V.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,V.setAttribute("data-approval-action","deny");let X=ge("shield-x",14,(Ae=r==null?void 0:r.denyButtonTextColor)!=null?Ae:"var(--persona-feedback-error, #dc2626)",2);X&&(X.style.marginRight="4px",V.appendChild(X));let He=document.createTextNode((se=r==null?void 0:r.denyLabel)!=null?se:"Deny");V.appendChild(He),ie.append(ae,V),u.appendChild(ie)}return a.append(i,u),s.appendChild(a),s};function wv(e){var n,r;let t=(n=e.getRootNode)==null?void 0:n.call(e);return t instanceof ShadowRoot?t:((r=e.ownerDocument)!=null?r:document).body}function Sg(e){var x;let{anchor:t,content:n,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=e,l=(x=e.container)!=null?x:wv(t),p=!1,u=null,g=()=>{if(!p)return;let E=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${E.width}px`);let T=r==="top-start"||r==="top-end"?E.top-o-n.getBoundingClientRect().height:E.bottom+o,L=r==="bottom-end"||r==="top-end"?E.right-n.getBoundingClientRect().width:E.left;n.style.top=`${T}px`,n.style.left=`${L}px`},f=()=>{p&&(p=!1,u&&(u(),u=null),n.remove())},v=()=>{var P,C,R;if(p)return;p=!0,a!=null&&(n.style.zIndex=String(a)),l.appendChild(n),g();let E=(C=((P=t.ownerDocument)!=null?P:document).defaultView)!=null?C:window,T=(R=t.ownerDocument)!=null?R:document,L=()=>{if(!t.isConnected){f(),d==null||d("anchor-removed");return}g()},k=F=>{let j=typeof F.composedPath=="function"?F.composedPath():[];j.includes(n)||j.includes(t)||(f(),d==null||d("outside"))},M=E.setTimeout(()=>{T.addEventListener("pointerdown",k,!0)},0);E.addEventListener("scroll",L,!0),E.addEventListener("resize",L),u=()=>{E.clearTimeout(M),T.removeEventListener("pointerdown",k,!0),E.removeEventListener("scroll",L,!0),E.removeEventListener("resize",L)},i==null||i()};return{get isOpen(){return p},open:v,close:f,toggle:()=>p?f():v(),reposition:g,destroy:f}}function Tg(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Cv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Eg=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},ns=(e,t)=>{Eg(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},Av=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Sv=(e,t)=>{var r,o;let n=(r=t==null?void 0:t.detailsDisplay)!=null?r:"collapsed";return(o=ts.get(e))!=null?o:n==="expanded"},Il=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},Tv=(e,t)=>{var l,p;let n=y("span","persona-approval-title");t!=null&&t.titleColor&&(n.style.color=t.titleColor);let o=e.toolType==="webmcp"||e.toolName.startsWith(Dr)?Qs(e.toolName):void 0,s=(p=t==null?void 0:t.formatDescription)==null?void 0:p.call(t,{toolName:e.toolName,toolType:e.toolType,description:(l=e.description)!=null?l:"",parameters:e.parameters,...o?{displayTitle:o}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=o!=null?o:bi(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),i){n.append(" from ");let u=document.createElement("strong");u.textContent=i,n.appendChild(u)}return n},Ev=e=>{let t=y("div","persona-approval-resolved"),n=ge("ban",15,"currentColor",2);n&&t.appendChild(n);let r=y("span","persona-approval-resolved-name");return r.textContent=e.toolName?bi(e.toolName):"Tool",t.append(r,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},Mv=(e,t,n,r,o,s,a)=>{var F,j,H,O,N,Y,ke;let i=y("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),r!=null&&r.backgroundColor&&(i.style.background=r.backgroundColor),r!=null&&r.borderColor&&(i.style.borderColor=r.borderColor),(r==null?void 0:r.shadow)!==void 0&&(i.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let d=(F=r==null?void 0:r.detailsDisplay)!=null?F:"collapsed",l=!!n.description&&d!=="hidden",p=n.parameters!=null&&d!=="hidden",u=l||p,g=u&&Sv(t.id,r),f=(j=r==null?void 0:r.showDetailsLabel)!=null?j:"Show details",v=(H=r==null?void 0:r.hideDetailsLabel)!=null?H:"Hide details",x=y("button","persona-approval-head");x.type="button",u?(x.setAttribute("data-action","toggle-params"),x.setAttribute("aria-expanded",g?"true":"false"),x.setAttribute("aria-label",g?v:f)):x.setAttribute("data-static","true");let E=y("span","persona-approval-logo"),T=ge("shield-check",16,"currentColor",2);T&&E.appendChild(T),x.appendChild(E);let L=Tv(n,r);if(u){let pe=y("span","persona-approval-toggle");pe.setAttribute("aria-hidden","true");let Z=ge("chevron-down",14,"currentColor",2);Z&&pe.appendChild(Z),L.append(" "),L.appendChild(pe)}x.appendChild(L),i.appendChild(x);let k=y("div","persona-approval-body");if(u){let pe=y("div","persona-approval-details");if(pe.setAttribute("data-role","params"),pe.hidden=!g,l){let Z=y("p","persona-approval-desc");r!=null&&r.descriptionColor&&(Z.style.color=r.descriptionColor),Z.textContent=n.description,pe.appendChild(Z)}if(p){let Z=y("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(Z.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(Z.style.color=r.parameterTextColor),Z.textContent=Ao(n.parameters),pe.appendChild(Z)}k.appendChild(pe)}if(n.reason){let pe=y("p","persona-approval-reason");r!=null&&r.reasonColor?pe.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(pe.style.color=r.descriptionColor);let Z=y("span","persona-approval-reason-label");Z.textContent=`${(O=r==null?void 0:r.reasonLabel)!=null?O:"Agent's stated reason:"} `,pe.append(Z,document.createTextNode(n.reason)),k.appendChild(pe)}let M=y("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)},R=y("button","persona-approval-deny");if(R.type="button",R.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(R.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(R.style.color=r.denyButtonTextColor),R.append((N=r==null?void 0:r.denyLabel)!=null?N:"Deny"),a){let pe=y("div","persona-approval-split"),Z=y("button","persona-approval-primary");Z.type="button",Z.setAttribute("data-action","always"),C(Z),Z.append((Y=r==null?void 0:r.approveLabel)!=null?Y:"Always allow",Il("\u23CE"));let Te=y("button","persona-approval-caret");Te.type="button",Te.setAttribute("data-action","toggle-menu"),Te.setAttribute("aria-label","More options"),C(Te);let Le=ge("chevron-down",15,"currentColor",2);Le&&Te.appendChild(Le),pe.append(Z,Te),M.append(pe,R),R.append(Il("Esc"));let oe=y("div","persona-approval-menu"),Ae=y("button","persona-approval-menu-item");Ae.type="button",Ae.append("Allow once",Il("\u2318\u23CE")),oe.appendChild(Ae),P=Sg({anchor:pe,content:oe,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,P),Ae.addEventListener("click",()=>{ns(e,t.id),o()})}else{let pe=y("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,R)}return k.appendChild(M),i.appendChild(k),i.addEventListener("click",pe=>{let Z=pe.target instanceof Element?pe.target.closest("[data-action]"):null;if(!Z)return;let Te=Z.getAttribute("data-action");if(Te==="toggle-params"){let Le=i.querySelector('[data-role="params"]');if(Le){let oe=Le.hidden;Le.hidden=!oe,x.setAttribute("aria-expanded",oe?"true":"false"),x.setAttribute("aria-label",oe?v:f),ts.set(t.id,oe)}return}if(Te==="toggle-menu"){P==null||P.toggle();return}if(Te==="always"){ns(e,t.id),o({remember:!0});return}if(Te==="allow"){ns(e,t.id),o();return}if(Te==="deny"){ns(e,t.id),s();return}}),i},Mg=()=>{let e=Cv();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=Av(a);if(i.status!=="pending"){if(ns(e,r.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Ev(i)}Eg(e,r.id);let l=(d==null?void 0:d.enableAlwaysAllow)===!0,p=Mv(e,r,i,d,o,s,l);if(l){e.pendingOrder.includes(r.id)||e.pendingOrder.push(r.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=g=>{Tg(g)||r.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),ns(e,r.id),g.key==="Escape"?s():g.metaKey||g.ctrlKey?o():o({remember:!0})))};e.keyHandlers.set(r.id,u),document.addEventListener("keydown",u)}return p}},teardown:()=>{for(let r of[...e.keyHandlers.keys(),...e.popovers.keys()])ns(e,r);e.latestPendingApprovalId=null}}};var kg=e=>{let t=[],n=null;return{buttons:t,render:(o,s,a,i,d,l)=>{e.innerHTML="",t.length=0;let p=(l==null?void 0:l.agentPushed)===!0;if(p||(n=null),!o||!o.length||!p&&(i!=null?i:s?s.getMessages():[]).some(E=>E.role==="user"))return;let u=document.createDocumentFragment(),g=s?s.isStreaming():!1,f=v=>{switch(v){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(v=>{let x=y("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");x.type="button",x.textContent=v,x.disabled=g,d!=null&&d.fontFamily&&(x.style.fontFamily=f(d.fontFamily)),d!=null&&d.fontWeight&&(x.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(x.style.paddingLeft=d.paddingX,x.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(x.style.paddingTop=d.paddingY,x.style.paddingBottom=d.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),u.appendChild(x),t.push(x)}),e.appendChild(u),p){let v=JSON.stringify(o);v!==n&&(n=v,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var Aa=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Sa=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}};var kv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),Lv=new Set(["step_start","execution_start"]),Pv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Iv=new Set(["step_complete","agent_turn_complete"]),Rv=new Set(["flow_complete","agent_complete"]),Lg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),Ig=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Un=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,rs=(e,t)=>{let n=e[t];return Ig(n)?n:void 0};function Rl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function vi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Wv(e,t){return typeof t.type=="string"?t.type:e}function Hv(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Bv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function Pg(e){var r,o,s,a,i;let t=rs(e,"result"),n=[rs(e,"tokens"),rs(e,"totalTokens"),t?rs(t,"tokens"):void 0,rs(e,"usage"),t?rs(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(o=(r=Un(d.output))!=null?r:Un(d.outputTokens))!=null?o:Un(d.completionTokens);if(l!==void 0)return l}return(i=(s=Un(e.outputTokens))!=null?s:Un(e.completionTokens))!=null?i:t?(a=Un(t.outputTokens))!=null?a:Un(t.completionTokens):void 0}function Dv(e){var n,r,o,s,a;let t=rs(e,"result");return(a=(o=(r=(n=Un(e.executionTime))!=null?n:Un(e.executionTimeMs))!=null?r:Un(e.execution_time))!=null?o:Un(e.duration))!=null?a:t?(s=Un(t.executionTime))!=null?s:Un(t.executionTimeMs):void 0}function Nv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Ta=class{constructor(t=Nv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:vi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!Ig(n)){Lg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Wv(t,n),o=this.now();if(kv.has(r)){this.startRun(o);return}if(Lv.has(r)){this.run||this.startRun(o);return}if(Pv.has(r)){if(!Bv(r,n))return;let a=Hv(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+Rl(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:vi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Iv.has(r)){if(!this.run)return;let a=this.run,i=Pg(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Rl(a.visibleCharCount),p=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:vi(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(Rv.has(r)){if(!this.run)return;let a=this.run,i=Pg(n),d=i!=null?i:a.exactOutputTokens+Rl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:vi(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(Lg.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let o=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=Dv(n);return s!=null?s:r-t.startedAt}};function Is(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Ov={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)"}},Fv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},_v=["flowName","stepName","reasoningText","text","name","tool","toolName"],$v=100;function jv(e,t){let n={...Ov,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return Fv}function Uv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function qv(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${o}.${s}`}function zv(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let o=r.split("."),s=n;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Vv(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function Kv(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Gv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Jv(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Xv(e,t,n){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Wl(e,t,n,r,o,s,a,i){var g;let d=o.has(e.id),l=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Is(l,(g=r.classNames)==null?void 0:g.eventRow);let p=a.find(f=>f.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let f=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(f)return l.appendChild(f),l}return l.appendChild(u()),l;function u(){var N,Y;let f=y("div",""),v=y("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",e.id);let x=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=ge(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&x.appendChild(E);let T=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=(N=r.timestampFormat)!=null?N:"relative";T.textContent=L==="relative"?Uv(e.timestamp,n):qv(e.timestamp);let k=null;r.showSequenceNumbers!==!1&&(k=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(t+1));let M=jv(e.type,r.badgeColors),P=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");P.style.backgroundColor=M.bg,P.style.color=M.text,P.style.borderColor=M.text+"50",P.textContent=e.type;let C=(Y=r.descriptionFields)!=null?Y:_v,R=zv(e.payload,C),F=null;R&&(F=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),F.textContent=R);let j=y("div","persona-flex-1 persona-min-w-0"),H=y("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),O=ge("clipboard","12px","currentColor",1.5);return O&&H.appendChild(O),H.addEventListener("click",async ke=>{ke.stopPropagation(),await Vv(Kv(e)),H.innerHTML="";let pe=ge("check","12px","currentColor",1.5);pe&&H.appendChild(pe),setTimeout(()=>{H.innerHTML="";let Z=ge("clipboard","12px","currentColor",1.5);Z&&H.appendChild(Z)},1500)}),v.appendChild(x),v.appendChild(T),k&&v.appendChild(k),v.appendChild(P),F&&v.appendChild(F),v.appendChild(j),v.appendChild(H),f.appendChild(v),d&&f.appendChild(Xv(e,a,i)),f}}function Rg(e){var v,x,E,T,L;let{buffer:t,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=e,i=(v=o==null?void 0:o.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",p=(E=i==null?void 0:i.label)!=null?E:"",u=(L=(T=o==null?void 0:o.features)==null?void 0:T.eventStream)!=null?L:{},g=s.find(k=>k.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&o){let k=g.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>f().element,onClose:r});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return f();function f(){let k=u.classNames,M=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Is(M,k==null?void 0:k.panel);let P=[],C="",R="",F=null,j=[],H={},O=0,N=ni(),Y=0,ke=0,pe=!1,Z=null,Te=!1,Le=0,oe=new Set,Ae=new Map,se="",ie="",ae=null,xe,Be,V,X,He=null,K=null,ue=null;function $e(){let ce=y("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),B=y("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Is(B,k==null?void 0:k.headerBar),a){K=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),K.style.cursor="help",He=y("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),He.textContent="-- tok/s",ue=y("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),ue.style.display="none",ue.style.pointerEvents="none";let Ft=K,en=ue,wr=()=>{if(!en.textContent)return;let sr=Ft.getBoundingClientRect(),ar=ce.getBoundingClientRect();en.style.left=`${sr.left-ar.left}px`,en.style.top=`${sr.bottom-ar.top+4}px`,en.style.display="block"},$r=()=>{en.style.display="none"};K.addEventListener("mouseenter",wr),K.addEventListener("mouseleave",$r),K.appendChild(He)}let be=y("div","persona-flex-1");xe=y("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let _e=y("option","");_e.value="",_e.textContent="All events (0)",xe.appendChild(_e),Be=y("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),Be.type="button",Be.title="Copy All";let Ye=ge("clipboard-copy","12px","currentColor",1.5);Ye&&Be.appendChild(Ye);let Rt=y("span","persona-event-copy-all persona-text-xs");Rt.textContent="Copy All",Be.appendChild(Rt),K&&B.appendChild(K),B.appendChild(be),B.appendChild(xe),B.appendChild(Be);let St=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Is(St,k==null?void 0:k.searchBar);let ht=ge("search","14px","var(--persona-muted, #9ca3af)",1.5),kt=y("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");ht&&kt.appendChild(ht),V=y("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Is(V,k==null?void 0:k.searchInput),V.type="text",V.placeholder="Search event payloads...",X=y("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),X.type="button",X.style.display="none";let Xt=ge("x","12px","currentColor",2);return Xt&&X.appendChild(Xt),St.appendChild(kt),St.appendChild(V),St.appendChild(X),ce.appendChild(B),ce.appendChild(St),ue&&ce.appendChild(ue),ce}let fe,Ve=s.find(ce=>ce.renderEventStreamToolbar);if(Ve!=null&&Ve.renderEventStreamToolbar&&o){let ce=Ve.renderEventStreamToolbar({config:o,defaultRenderer:()=>$e(),eventCount:t.getSize(),filteredCount:0,onFilterChange:B=>{C=B,ee(),bt()},onSearchChange:B=>{R=B,ee(),bt()}});fe=ce!=null?ce:$e()}else fe=$e();let et=y("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");et.style.display="none";function Ot(){if(!a||!He||!K)return;let ce=a(),B=Gv(ce);He.textContent=B;let be=Jv(ce);ue&&(ue.textContent=be,be||(ue.style.display="none")),K.setAttribute("aria-label",be?`Throughput: ${B}, ${be}`:`Throughput: ${B}`)}let Xe=y("div","persona-flex-1 persona-min-h-0 persona-relative"),ye=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ye.style.height="100%";let J=y("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Is(J,k==null?void 0:k.scrollIndicator),J.style.display="none",J.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let dt=ge(l,"14px","currentColor",2);dt&&J.appendChild(dt);let qe=y("span","");qe.textContent=p,J.appendChild(qe);let Se=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Se.style.display="none",Xe.appendChild(ye),Xe.appendChild(Se),Xe.appendChild(J),M.setAttribute("tabindex","0"),M.appendChild(fe),M.appendChild(et),M.appendChild(Xe);function ve(){let ce=t.getAll(),B={};for(let St of ce)B[St.type]=(B[St.type]||0)+1;let be=Object.keys(B).sort(),_e=be.length!==j.length||!be.every((St,ht)=>St===j[ht]),xt=!_e&&be.some(St=>B[St]!==H[St]),Ye=ce.length!==Object.values(H).reduce((St,ht)=>St+ht,0);if(!_e&&!xt&&!Ye||(j=be,H=B,!xe))return;let Rt=xe.value;if(xe.options[0].textContent=`All events (${ce.length})`,_e){for(;xe.options.length>1;)xe.remove(1);for(let St of be){let ht=y("option","");ht.value=St,ht.textContent=`${St} (${B[St]||0})`,xe.appendChild(ht)}Rt&&be.includes(Rt)?xe.value=Rt:Rt&&(xe.value="",C="")}else for(let St=1;St<xe.options.length;St++){let ht=xe.options[St];ht.textContent=`${ht.value} (${B[ht.value]||0})`}}function nt(){let ce=t.getAll();if(C&&(ce=ce.filter(B=>B.type===C)),R){let B=R.toLowerCase();ce=ce.filter(be=>be.type.toLowerCase().includes(B)||be.payload.toLowerCase().includes(B))}return ce}function Lt(){return C!==""||R!==""}function ee(){O=0,Y=0,N.resume(),J.style.display="none"}function je(ce){oe.has(ce)?oe.delete(ce):oe.add(ce),ae=ce;let B=ye.scrollTop,be=N.isFollowing();Te=!0,N.pause(),bt(),ye.scrollTop=B,be&&N.resume(),Te=!1}function wn(){return So(ye,50)}function bt(){ke=Date.now(),pe=!1,Ot(),ve();let ce=t.getEvictedCount();ce>0?(et.textContent=`${ce.toLocaleString()} older events truncated`,et.style.display=""):et.style.display="none",P=nt();let B=P.length,be=t.getSize()>0;B===0&&be&&Lt()?(Se.textContent=R?`No events matching '${R}'`:"No events matching filter",Se.style.display="",ye.style.display="none"):(Se.style.display="none",ye.style.display=""),Be&&(Be.title=Lt()?`Copy Filtered (${B})`:"Copy All"),d&&!N.isFollowing()&&B>O&&(Y+=B-O,qe.textContent=p?`${p}${Y>0?` (${Y})`:""}`:"",J.style.display=""),O=B;let _e=t.getAll(),xt=_e.length>0?_e[0].timestamp:0,Ye=new Set(P.map(ht=>ht.id));for(let ht of oe)Ye.has(ht)||oe.delete(ht);let Rt=C!==se||R!==ie,St=Ae.size===0&&P.length>0;if(Rt||St||P.length===0){ye.innerHTML="",Ae.clear();let ht=document.createDocumentFragment();for(let kt=0;kt<P.length;kt++){let Xt=Wl(P[kt],kt,xt,u,oe,je,s,o);Ae.set(P[kt].id,Xt),ht.appendChild(Xt)}ye.appendChild(ht),se=C,ie=R,ae=null}else{if(ae!==null){let kt=Ae.get(ae);if(kt&&kt.parentNode===ye){let Xt=P.findIndex(Ft=>Ft.id===ae);if(Xt>=0){let Ft=Wl(P[Xt],Xt,xt,u,oe,je,s,o);ye.insertBefore(Ft,kt),kt.remove(),Ae.set(ae,Ft)}}ae=null}let ht=new Set(P.map(kt=>kt.id));for(let[kt,Xt]of Ae)ht.has(kt)||(Xt.remove(),Ae.delete(kt));for(let kt=0;kt<P.length;kt++){let Xt=P[kt];if(!Ae.has(Xt.id)){let Ft=Wl(Xt,kt,xt,u,oe,je,s,o);Ae.set(Xt.id,Ft),ye.appendChild(Ft)}}}N.isFollowing()&&(ye.scrollTop=ye.scrollHeight)}function fn(){if(Date.now()-ke>=$v){Z!==null&&(cancelAnimationFrame(Z),Z=null),bt();return}pe||(pe=!0,Z=requestAnimationFrame(()=>{Z=null,bt()}))}let xr=(ce,B)=>{if(!Be)return;Be.innerHTML="";let be=ge(ce,"12px","currentColor",1.5);be&&Be.appendChild(be);let _e=y("span","persona-text-xs");_e.textContent="Copy All",Be.appendChild(_e),setTimeout(()=>{Be.innerHTML="";let xt=ge("clipboard-copy","12px","currentColor",1.5);xt&&Be.appendChild(xt);let Ye=y("span","persona-text-xs");Ye.textContent="Copy All",Be.appendChild(Ye),Be.disabled=!1},B)},vr=async()=>{if(Be){Be.disabled=!0;try{let ce;Lt()?ce=P:n?(ce=await n(),ce.length===0&&(ce=t.getAll())):ce=t.getAll();let B=ce.map(be=>{try{return JSON.parse(be.payload)}catch{return be.payload}});await navigator.clipboard.writeText(JSON.stringify(B,null,2)),xr("check",1500)}catch{xr("x",1500)}}},A=()=>{xe&&(C=xe.value,ee(),bt())},te=()=>{!V||!X||(X.style.display=V.value?"":"none",F&&clearTimeout(F),F=setTimeout(()=>{R=V.value,ee(),bt()},150))},Me=()=>{!V||!X||(V.value="",R="",X.style.display="none",F&&clearTimeout(F),ee(),bt())},Ne=()=>{if(Te)return;let ce=ye.scrollTop,{action:B,nextLastScrollTop:be}=ri({following:N.isFollowing(),currentScrollTop:ce,lastScrollTop:Le,nearBottom:wn(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Le=be,B==="resume"?(N.resume(),Y=0,J.style.display="none"):B==="pause"&&(N.pause(),d&&(qe.textContent=p,J.style.display=""))},Ie=ce=>{let B=oi({following:N.isFollowing(),deltaY:ce.deltaY,nearBottom:wn(),resumeWhenNearBottom:!0});B==="pause"?(N.pause(),d&&(qe.textContent=p,J.style.display="")):B==="resume"&&(N.resume(),Y=0,J.style.display="none")},Oe=()=>{d&&(ye.scrollTop=ye.scrollHeight,N.resume(),Y=0,J.style.display="none")},Ge=ce=>{let B=ce.target;if(!B||B.closest("button"))return;let be=B.closest("[data-event-id]");if(!be)return;let _e=be.getAttribute("data-event-id");_e&&je(_e)},at=ce=>{if((ce.metaKey||ce.ctrlKey)&&ce.key==="f"){ce.preventDefault(),V==null||V.focus(),V==null||V.select();return}ce.key==="Escape"&&(V&&document.activeElement===V?(Me(),V.blur(),M.focus()):r&&r())};Be&&Be.addEventListener("click",vr),xe&&xe.addEventListener("change",A),V&&V.addEventListener("input",te),X&&X.addEventListener("click",Me),ye.addEventListener("scroll",Ne),ye.addEventListener("wheel",Ie,{passive:!0}),ye.addEventListener("click",Ge),J.addEventListener("click",Oe),M.addEventListener("keydown",at);function Pt(){F&&clearTimeout(F),Z!==null&&(cancelAnimationFrame(Z),Z=null),pe=!1,Ae.clear(),Be&&Be.removeEventListener("click",vr),xe&&xe.removeEventListener("change",A),V&&V.removeEventListener("input",te),X&&X.removeEventListener("click",Me),ye.removeEventListener("scroll",Ne),ye.removeEventListener("wheel",Ie),ye.removeEventListener("click",Ge),J.removeEventListener("click",Oe),M.removeEventListener("keydown",at)}return{element:M,update:fn,destroy:Pt}}}function Wg(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",o=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let 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",u.appendChild(g);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(f)}else u.textContent=a;if(l.append(p,u),i.append(d,l),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 Hg=(e,t)=>{var r,o,s;let n=(s=(o=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>Wg(e,t)});if(p)return p}return Wg(e,t)};var Hl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},Lo=new Hl;Lo.register("PersonaArtifactCard",Hg);function Qv(e){var o;let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=e.props)!=null?o:{},null,2),t.appendChild(n),t.appendChild(r),t}function Bg(e,t){var Be,V,X,He;let n=(V=(Be=e.features)==null?void 0:Be.artifacts)==null?void 0:V.layout,o=((X=n==null?void 0:n.toolbarPreset)!=null?X:"default")==="document",s=(He=n==null?void 0:n.panePadding)==null?void 0:He.trim(),a=e.markdown?bs(e.markdown):null,i=Js(e.sanitize),d=K=>{let ue=a?a(K):Yr(K);return i?i(ue):ue},l=typeof document!="undefined"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};l&&l.addEventListener("click",()=>{var K;p(),(K=t.onDismiss)==null||K.call(t)});let u=y("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");u.setAttribute("data-persona-theme-zone","artifact-pane"),o&&u.classList.add("persona-artifact-pane-document");let g=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&g.classList.add("persona-artifact-toolbar-document");let f=y("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let v=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var K;p(),(K=t.onDismiss)==null||K.call(t)});let x="rendered",E=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?Kt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Kt({icon:"eye",label:"Rendered view"}),L=o?Kt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Kt({icon:"code-2",label:"Source"}),k=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),M=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,P=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,C=n==null?void 0:n.documentToolbarCopyMenuItems,R=!!(P&&C&&C.length>0),F=null,j,H=null,O=null;if(o&&(M||P)&&!R){if(j=M?di({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let K=ge("chevron-down",14,"currentColor",2);K&&j.appendChild(K)}}else o&&R?(F=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),j=M?di({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),H=Kt({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"}}),F.append(j,H)):o?j=Kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):j=Kt({icon:"copy",label:"Copy"});let N=o?Kt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Kt({icon:"refresh-cw",label:"Refresh"}),Y=o?Kt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Kt({icon:"x",label:"Close"}),ke=()=>{var Ve,et,Ot;let K=(Ve=Ae.find(Xe=>Xe.id===se))!=null?Ve:Ae[Ae.length-1],ue=(et=K==null?void 0:K.id)!=null?et:null,$e=(K==null?void 0:K.artifactType)==="markdown"&&(Ot=K.markdown)!=null?Ot:"",fe=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:$e,jsonPayload:fe,id:ue}},pe=async()=>{var Ve;let{markdown:K,jsonPayload:ue}=ke(),$e=(Ve=Ae.find(et=>et.id===se))!=null?Ve:Ae[Ae.length-1],fe=($e==null?void 0:$e.artifactType)==="markdown"?K:$e?ue:"";try{await navigator.clipboard.writeText(fe)}catch{}};if(j.addEventListener("click",async()=>{let K=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(K&&R){let{markdown:ue,jsonPayload:$e,id:fe}=ke();try{await K({actionId:"primary",artifactId:fe,markdown:ue,jsonPayload:$e})}catch{}return}await pe()}),H&&(C!=null&&C.length)){let K=()=>{var $e;return($e=u.closest("[data-persona-root]"))!=null?$e:document.body},ue=()=>{O=es({items:C.map($e=>({id:$e.id,label:$e.label})),onSelect:async $e=>{let{markdown:fe,jsonPayload:Ve,id:et}=ke(),Ot=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Ot?await Ot({actionId:$e,artifactId:et,markdown:fe,jsonPayload:Ve}):$e==="markdown"||$e==="md"?await navigator.clipboard.writeText(fe):$e==="json"||$e==="source"?await navigator.clipboard.writeText(Ve):await navigator.clipboard.writeText(fe||Ve)}catch{}},anchor:F!=null?F:H,position:"bottom-right",portal:K()})};u.isConnected?ue():requestAnimationFrame(ue),H.addEventListener("click",$e=>{$e.stopPropagation(),O==null||O.toggle()})}N.addEventListener("click",async()=>{var K;try{await((K=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:K.call(n))}catch{}ae()}),Y.addEventListener("click",()=>{var K;p(),(K=t.onDismiss)==null||K.call(t)});let Z=()=>{o&&(T.setAttribute("aria-pressed",x==="rendered"?"true":"false"),L.setAttribute("aria-pressed",x==="source"?"true":"false"))};T.addEventListener("click",()=>{x="rendered",Z(),ae()}),L.addEventListener("click",()=>{x="source",Z(),ae()});let Te=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(g.replaceChildren(),E.append(T,L),F?k.append(F,N,Y):k.append(j,N,Y),g.append(E,Te,k),Z()):(g.appendChild(f),g.appendChild(v)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let Le=y("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),oe=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Le.style.paddingLeft=s,Le.style.paddingRight=s,oe.style.padding=s),u.appendChild(g),u.appendChild(Le),u.appendChild(oe);let Ae=[],se=null,ie=!1,ae=()=>{var fe,Ve,et,Ot;let K=o&&Ae.length<=1;Le.classList.toggle("persona-hidden",K),Le.replaceChildren();for(let Xe of Ae){let ye=y("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ye.type="button",ye.textContent=Xe.title||Xe.id.slice(0,8),Xe.id===se&&ye.classList.add("persona-bg-persona-container","persona-border-persona-border"),ye.addEventListener("click",()=>t.onSelect(Xe.id)),Le.appendChild(ye)}oe.replaceChildren();let ue=se&&Ae.find(Xe=>Xe.id===se)||Ae[Ae.length-1];if(!ue)return;if(o){let Xe=ue.artifactType==="markdown"?"MD":(fe=ue.component)!=null?fe:"Component",J=(ue.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Te.textContent=`${J} \xB7 ${Xe}`}else f.textContent="Artifacts";if(ue.artifactType==="markdown"){if(o&&x==="source"){let ye=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ye.textContent=(Ve=ue.markdown)!=null?Ve:"",oe.appendChild(ye);return}let Xe=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Xe.innerHTML=d((et=ue.markdown)!=null?et:""),oe.appendChild(Xe);return}let $e=ue.component?Lo.get(ue.component):void 0;if($e){let ye={message:{id:ue.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let J=$e((Ot=ue.props)!=null?Ot:{},ye);if(J){oe.appendChild(J);return}}catch{}}oe.appendChild(Qv(ue))},xe=()=>{var ue;let K=Ae.length>0;if(u.classList.toggle("persona-hidden",!K),l){let $e=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ve=((ue=$e==null?void 0:$e.classList.contains("persona-artifact-narrow-host"))!=null?ue:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&Ve&&ie?(l.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:l,update(K){var ue,$e,fe;Ae=K.artifacts,se=(fe=($e=K.selectedId)!=null?$e:(ue=K.artifacts[K.artifacts.length-1])==null?void 0:ue.id)!=null?fe:null,Ae.length>0&&(ie=!0),ae(),xe()},setMobileOpen(K){ie=K,!K&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):xe()}}}function or(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Dg(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!or(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function Yv(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function wi(e,t){var d,l,p,u,g,f,v,x,E,T;if(!or(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Yv(e),Dg(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(f=n==null?void 0:n.paneBackground)==null?void 0:f.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let o=(v=n==null?void 0:n.panePadding)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Dg(e,t)}var Ng=["panel","seamless"];function Ci(e,t){var i,d,l,p,u,g;for(let f of Ng)e.classList.remove(`persona-artifact-appearance-${f}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!or(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",o=Ng.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let f=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Og(e,t){var n,r,o;return!t||!or(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Zv(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function ew(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function tw(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function nw(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function Fg(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function _g(e,t,n,r,o,s){let a=Zv(o,200),i=nw(t,n,r,200);i=Math.max(a,i);let d=ew(s);return d!==null&&(i=Math.min(i,d)),tw(e,a,i)}var $g={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"}},Bl=(e,t,n,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,E;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=$g[a])!=null?x:$g.init;s.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),l=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let T=y("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var C,R;let L=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${t.id}-${a}-${T.name}`;let k=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=T.label,L.appendChild(k);let M=(C=T.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=`${t.id}-${a}-${T.name}`,P.name=T.name,P.placeholder=(R=T.placeholder)!=null?R:"",T.required&&(P.required=!0),L.appendChild(P),p.appendChild(L)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=y("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");f.type="submit",f.textContent=(E=i.submitLabel)!=null?E:"Submit",u.appendChild(g),u.appendChild(f),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async T=>{var P,C;T.preventDefault();let L=(P=n.formEndpoint)!=null?P:"/form",k=new FormData(p),M={};k.forEach((R,F)=>{M[F]=R}),M.type=a,f.disabled=!0,g.textContent="Submitting\u2026";try{let R=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!R.ok)throw new Error(`Form submission failed (${R.status})`);let F=await R.json();g.textContent=(C=F.message)!=null?C:"Thanks! We'll be in touch soon.",F.success&&F.nextPrompt&&await r.sendMessage(String(F.nextPrompt))}catch(R){g.textContent=R instanceof Error?R.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Dl=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,o;return((r=n.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(s=>s.id));return[...n.filter(s=>!r.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Ai=new Dl;var jg=()=>{let e=new Map,t=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:t,off:n,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var rw=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},ow=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(n,o+1)}return null},Si=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=rw(e),n=ow(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},Nl=e=>typeof e=="string"?e:e==null?"":String(e),Rs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Nl(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=Nl(n.element);if(r&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Nl(n.text)}}},Ug=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ti=e=>{let t=new Set(Ug(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Ug(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),r();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},u=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let g=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:g,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var sw=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},aw=e=>e.map(t=>({...t,streaming:!1})),iw=e=>e.map(t=>({...t,status:"complete"})),Ol=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?sw(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?aw(n.messages):void 0,artifacts:n.artifacts?iw(n.artifacts):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as lw,STR as cw,OBJ as dw}from"partial-json";function pw(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function uw(e,t){if(!pw(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function Fl(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let o=lw(n,cw|dw),s=uw(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function mw(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function _l(e,t){let{config:n,message:r,onPropsUpdate:o}=t,s=Lo.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function gw(){let e=Fl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function qg(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function $l(e){let t=qg(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function jl(e){let t=qg(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var fw=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ul(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=fw}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,f.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,f.appendChild(x),g.appendChild(f);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 T=[];for(let C=1;C<=5;C++){let R=document.createElement("button");R.type="button",R.className="persona-feedback-rating-btn persona-feedback-star-btn",R.setAttribute("role","radio"),R.setAttribute("aria-checked","false"),R.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${l[C-1]}`),R.title=l[C-1],R.dataset.rating=String(C),R.innerHTML=`
27
+ `,n.addEventListener("click",t);let r=s=>{var P,E,k,C,I,j,$,R,N,O,Z,Ee,de;let a=(P=s.launcher)!=null?P:{},i=dn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ee=(E=a.title)!=null?E:"Chat Assistant";d.textContent=ee,d.setAttribute("title",ee)}let c=n.querySelector("[data-role='launcher-subtitle']");if(c){let ee=(k=a.subtitle)!=null?k:"Here to help you get answers fast";c.textContent=ee,c.setAttribute("title",ee)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let ee=(C=a.agentIconSize)!=null?C:"40px";if(u.style.height=ee,u.style.width=ee,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let Le=parseFloat(ee)||24,Pe=ye(a.agentIconName,Le*.6,"var(--persona-text-inverse, #ffffff)",2);Pe?(u.appendChild(Pe),u.style.display=""):(u.textContent=(I=a.agentIconText)!=null?I:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(j=a.agentIconText)!=null?j:"\u{1F4AC}",u.style.display="")}let f=n.querySelector("[data-role='launcher-image']");if(f){let ee=($=a.agentIconSize)!=null?$:"40px";f.style.height=ee,f.style.width=ee,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=n.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let ee=(R=a.callToActionIconSize)!=null?R:"32px";g.style.height=ee,g.style.width=ee,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let Le=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,Le=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let Pe=parseFloat(ee)||24,ne=Math.max(Pe-Le,8),Ae=ye(a.callToActionIconName,ne,"currentColor",2);Ae?g.appendChild(Ae):g.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}else g.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}let b=a.position&&hr[a.position]?hr[a.position]:hr["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",S="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?S:`${v} ${b}`,i||(n.style.zIndex=String((Z=a.zIndex)!=null?Z:xn));let T="1px solid var(--persona-border, #e5e7eb)",L="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(Ee=a.border)!=null?Ee:T,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:L,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(de=a.collapsedMaxWidth)!=null?de:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:o}};var Sg=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:o}=Cg(e),s=Ag(e,t),a={wrapper:n,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},c={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:c,replaceHeader:f=>(d.element.replaceWith(f.header),d.element=f.header,d.iconHolder=f.iconHolder,d.headerTitle=f.headerTitle,d.headerSubtitle=f.headerSubtitle,d.closeButton=f.closeButton,d.closeButtonWrapper=f.closeButtonWrapper,d.clearChatButton=f.clearChatButton,d.clearChatButtonWrapper=f.clearChatButtonWrapper,f),replaceComposer:f=>{c.footer.replaceWith(f),c.footer=f}}},Ml=({config:e,plugins:t,onToggle:n})=>{let r=t.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:e,defaultRenderer:()=>El(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=El(e,n);return{instance:o,element:o.element}};var gv=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},fv=(e,t)=>{if(!e)return null;let n=gv(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},hv=(e,t)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},yv=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},kl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},Ll=320,Eg=320,bv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),xv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),vv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),wv=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),Cv=(e,t,n)=>{if(e.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var u;let c=y("img");c.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Ll}px`,c.style.maxHeight=`${Eg}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,c.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{p=!0}),yv(i.image)?(c.src=i.image,r.appendChild(c)):(p=!0,o=Math.max(0,o-1),c.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},Av=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!kl(r.audio))return;let o=y("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ll}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Sv=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!kl(r.video))return;let o=y("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${Ll}px`,o.style.maxHeight=`${Eg}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Tv=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!kl(r.data))return;let o=y("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Ps=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(o),e},Mg=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Ps};if(t){let o=t(r);if(o!==null)return o}return Ps()},Ev=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=y("img");o.src=r,o.alt=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Tg=(e,t,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?r.textContent=t.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Mv=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},kg=(e,t,n)=>{var b,v,S,T,L,P,E;let r=(b=t.showCopy)!=null?b:!0,o=(v=t.showUpvote)!=null?v:!0,s=(S=t.showDownvote)!=null?S:!0,a=(T=t.showReadAloud)!=null?T:!1;if(!r&&!o&&!s&&!a){let k=y("div");return k.style.display="none",k.id=`actions-${e.id}`,k.setAttribute("data-actions-for",e.id),k}let i=(L=t.visibility)!=null?L:"hover",d=(P=t.align)!=null?P:"right",c=(E=t.layout)!=null?E:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[c],f=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);f.id=`actions-${e.id}`,f.setAttribute("data-actions-for",e.id);let g=(k,C,I)=>{let j=Gt({icon:k,label:C,size:14,className:"persona-message-action-btn"});return j.setAttribute("data-action",I),j};return r&&f.appendChild(g("copy","Copy message","copy")),a&&f.appendChild(g("volume-2","Read aloud","read-aloud")),o&&f.appendChild(g("thumbs-up","Upvote","upvote")),s&&f.appendChild(g("thumbs-down","Downvote","downvote")),f},Ca=(e,t,n,r,o,s)=>{var re,se,ae,fe,$e,V,Q,Me,J,le,Ie,he,Ke,gt,Wt,tt,ge;let a=n!=null?n:{},i=(re=a.layout)!=null?re:"bubble",d=a.avatar,c=a.timestamp,p=(se=d==null?void 0:d.show)!=null?se:!1,u=(ae=c==null?void 0:c.show)!=null?ae:!1,f=(fe=d==null?void 0:d.position)!=null?fe:"left",g=($e=c==null?void 0:c.position)!=null?$e:"below",b=Mv(e.role,i),v=y("div",b.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let S=bv(e),T=(Q=(V=e.content)==null?void 0:V.trim())!=null?Q:"",P=S.length>0&&T===Va,E=si((J=(Me=s==null?void 0:s.widgetConfig)==null?void 0:Me.features)==null?void 0:J.streamAnimation),k=(he=(Ie=(le=s==null?void 0:s.widgetConfig)==null?void 0:le.features)==null?void 0:Ie.streamAnimation)==null?void 0:he.plugins,C=e.role==="assistant"&&E.type!=="none"?ks(E.type,k):null,I=e.role==="assistant"&&((Ke=C==null?void 0:C.isAnimating)==null?void 0:Ke.call(C,e))===!0,j=e.role==="assistant"&&C!==null&&(!!e.streaming||I);j&&(C!=null&&C.bubbleClass)&&v.classList.add(C.bubbleClass);let $=document.createElement("div");$.classList.add("persona-message-content"),e.streaming&&$.classList.add("persona-content-streaming"),j&&C&&(C.containerClass&&$.classList.add(C.containerClass),$.style.setProperty("--persona-stream-step",`${E.speed}ms`),$.style.setProperty("--persona-stream-duration",`${E.duration}ms`));let R=j?ai((gt=e.content)!=null?gt:"",E.buffer,C,e,!!e.streaming):(Wt=e.content)!=null?Wt:"",N=t({text:R,message:e,streaming:!!e.streaming,raw:e.rawContent}),O=N;j&&(C==null?void 0:C.wrap)==="char"?O=ha(N,"char",e.id,{skipTags:C.skipTags}):j&&(C==null?void 0:C.wrap)==="word"&&(O=ha(N,"word",e.id,{skipTags:C.skipTags}));let Z=null;if(P?(Z=document.createElement("div"),Z.innerHTML=O,Z.style.display="none",$.appendChild(Z)):$.innerHTML=O,j&&(C!=null&&C.useCaret)&&!P&&T){let X=ii(),it=$.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ve=it[it.length-1];if(Ve!=null&&Ve.parentNode)Ve.parentNode.insertBefore(X,Ve.nextSibling);else{let Se=$.lastElementChild;Se?Se.appendChild(X):$.appendChild(X)}}if(u&&g==="inline"&&e.createdAt){let X=Tg(e,c,"span");X.classList.add("persona-timestamp-inline");let it=$.lastElementChild;it?it.appendChild(X):$.appendChild(X)}if(S.length>0){let X=Cv(S,!P&&!!T,()=>{P&&Z&&(Z.style.display="")});X?v.appendChild(X):P&&Z&&(Z.style.display="")}let Ee=xv(e);if(Ee.length>0){let X=Av(Ee);X&&v.appendChild(X)}let de=vv(e);if(de.length>0){let X=Sv(de);X&&v.appendChild(X)}let ee=wv(e);if(ee.length>0){let X=Tv(ee);X&&v.appendChild(X)}if(v.appendChild($),u&&g==="below"&&e.createdAt){let X=Tg(e,c);X.classList.add("persona-mt-1"),v.appendChild(X)}let Le=e.role==="assistant"?fv(e.stopReason,(ge=(tt=s==null?void 0:s.widgetConfig)==null?void 0:tt.copy)==null?void 0:ge.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let X=!!(R&&R.trim()),it=E.placeholder==="skeleton",Ve=it&&E.buffer==="line"&&X;if(X)Ve&&v.appendChild(ya());else if(it)v.appendChild(ya());else{let Se=Mg("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Se&&v.appendChild(Se)}}if(Le&&e.stopReason&&!e.streaming&&(T||($.style.display="none"),v.appendChild(hv(e.stopReason,Le))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let X=kg(e,r,o);v.appendChild(X)}if(!p||e.role==="system")return v;let ne=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Ae=Ev(d,e.role);return f==="right"||f==="left"&&e.role==="user"?ne.append(v,Ae):ne.append(Ae,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),ne},kv=(e,t,n,r,o,s)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Ca(e,t,n,r,o,s)};var Is=new Set,Lv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Pv=(e,t)=>{var r,o;let n=(o=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
28
+ `):""},Lg=(e,t)=>{let n=Is.has(e),r=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=ye(n?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=n?"Hide":"Show"}o.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},Pl=(e,t)=>{var de,ee,Le,Pe,ne,Ae,re,se,ae,fe,$e;let n=e.reasoning,r=y("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let o=(ee=(de=t==null?void 0:t.features)==null?void 0:de.reasoningDisplay)!=null?ee:{},s=o.expandable!==!1,a=s&&Is.has(e.id),i=n.status!=="complete",d=Pv(e,(Le=o.previewMaxLines)!=null?Le:3),c=y("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=y("div","persona-flex persona-flex-col persona-text-left"),u=y("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(Pe=t==null?void 0:t.reasoning)!=null?Pe:{},b=String((ne=n.startedAt)!=null?ne:Date.now()),v=()=>{let V=y("span","");return V.setAttribute("data-tool-elapsed",b),V.textContent=Ua(n),V},S=(Ae=g.renderCollapsedSummary)==null?void 0:Ae.call(g,{message:e,reasoning:n,defaultSummary:f,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Ua(n),createElapsedElement:v});typeof S=="string"&&S.trim()?(u.textContent=S,p.appendChild(u)):S instanceof HTMLElement?p.appendChild(S):(u.textContent=f,p.appendChild(u));let T=y("span","persona-text-xs persona-text-persona-primary");T.textContent=Pm(n),p.appendChild(T);let L=(re=o.loadingAnimation)!=null?re:"none",P=g.activeTextTemplate,E=g.completeTextTemplate,k=i?P:E,C=S instanceof HTMLElement,I=(V,Q,Me)=>{let J=Me;for(let le of Q){let Ie=y("span","persona-tool-char");Ie.style.setProperty("--char-index",String(J)),Ie.textContent=le===" "?"\xA0":le,V.appendChild(Ie),J++}return J},j=(V,Q)=>{u.textContent="";let Me=qa(V,""),J=0;for(let le of Me){let Ie=le.styles.length>0?(()=>{let he=y("span",le.styles.map(Ke=>`persona-tool-text-${Ke}`).join(" "));return u.appendChild(he),he})():u;if(le.isDuration&&i)Ie.appendChild(v());else{let he=le.isDuration?Ua(n):le.text;Q?J=I(Ie,he,J):Ie.appendChild(document.createTextNode(he))}}};if(!C&&k)if(T.style.display="none",u.style.display="",i&&L!=="none"){let V=(se=g.loadingAnimationDuration)!=null?se:2e3;u.setAttribute("data-preserve-animation","true"),L==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),j(k,!1)):(u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),L==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),j(k,!0))}else j(k,!1);else if(!C&&i&&L!=="none"){u.style.display="";let V=(ae=g.loadingAnimationDuration)!=null?ae:2e3;if(u.setAttribute("data-preserve-animation","true"),L==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`);else{u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),L==="shimmer-color"&&(g.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let Q=u.textContent||f;u.textContent="",I(u,Q,0)}n.status==="complete"&&(u.style.display="none")}else C||(n.status==="complete"?u.style.display="none":u.style.display="");let $=null;if(s){$=y("div","persona-flex persona-items-center");let Q=ye(a?"chevron-up":"chevron-down",16,"currentColor",2);Q?$.appendChild(Q):$.textContent=a?"Hide":"Show";let Me=y("div","persona-flex persona-items-center persona-ml-auto");Me.append($),c.append(p,Me)}else c.append(p);let R=y("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 V=($e=(fe=t==null?void 0:t.reasoning)==null?void 0:fe.renderCollapsedPreview)==null?void 0:$e.call(fe,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Lv(R,V)||(R.textContent=d),R.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(c,R),r;let N=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");N.style.display=a?"":"none";let O=n.chunks.join(""),Z=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Z.textContent=O||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),N.appendChild(Z),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),$){$.innerHTML="";let Q=ye(a?"chevron-up":"chevron-down",16,"currentColor",2);Q?$.appendChild(Q):$.textContent=a?"Hide":"Show"}N.style.display=a?"":"none",R.style.display=a?"none":R.textContent||R.childNodes.length?"":"none"})(),r.append(c,R,N),r};var Rs=new Set,Iv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Rv=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let r=((s=n.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
29
+ `);let o=wo(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
30
+ `):""},Il=(e,t)=>{var n,r,o;e.style.backgroundColor=(n=t.codeBlockBackgroundColor)!=null?n:"var(--persona-container, #f3f4f6)",e.style.borderColor=(r=t.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",e.style.color=(o=t.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},Wv=(e,t)=>{var p,u,f,g,b;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,o=(u=r==null?void 0:r.collapsedMode)!=null?u:"tool-call",s=Rv(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=n?Im(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(g=t==null?void 0:t.toolCall)!=null?g:{},c=a;return o==="tool-name"?c=((b=n.name)==null?void 0:b.trim())||a:o==="tool-preview"&&s&&(c=s),i&&d.activeTextTemplate?c=ol(n,d.activeTextTemplate,c):!i&&d.completeTextTemplate&&(c=ol(n,d.completeTextTemplate,c)),{summary:c,previewText:s,isActive:i}},Pg=(e,t,n)=>{var p;let r=Rs.has(e),o=(p=n==null?void 0:n.toolCall)!=null?p:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),c=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let u=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",f=ye(r?"chevron-up":"chevron-down",16,u,2);f?c.appendChild(f):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Rl=(e,t)=>{var O,Z,Ee,de,ee,Le,Pe,ne,Ae;let n=e.toolCall,r=(O=t==null?void 0:t.toolCall)!=null?O:{},o=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let s=(Ee=(Z=t==null?void 0:t.features)==null?void 0:Z.toolCallDisplay)!=null?Ee:{},a=s.expandable!==!1,i=a&&Rs.has(e.id),{summary:d,previewText:c,isActive:p}=Wv(e,t),u=y("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(u.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(u.style.paddingLeft=r.headerPaddingX,u.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(u.style.paddingTop=r.headerPaddingY,u.style.paddingBottom=r.headerPaddingY);let f=y("div","persona-flex persona-flex-col persona-text-left"),g=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(g.style.color=r.headerTextColor);let b=String((de=n.startedAt)!=null?de:Date.now()),v=()=>{let re=y("span","");return re.setAttribute("data-tool-elapsed",b),re.textContent=oa(n),re},S=(Le=r.renderCollapsedSummary)==null?void 0:Le.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:c,collapsedMode:(ee=s.collapsedMode)!=null?ee:"tool-call",isActive:p,config:t!=null?t:{},elapsed:oa(n),createElapsedElement:v});typeof S=="string"&&S.trim()?(g.textContent=S,f.appendChild(g)):S instanceof HTMLElement?f.appendChild(S):(g.textContent=d,f.appendChild(g));let T=(Pe=s.loadingAnimation)!=null?Pe:"none",L=r.activeTextTemplate,P=r.completeTextTemplate,E=p?L:P,k=S instanceof HTMLElement,C=(re,se,ae)=>{let fe=ae;for(let $e of se){let V=y("span","persona-tool-char");V.style.setProperty("--char-index",String(fe)),V.textContent=$e===" "?"\xA0":$e,re.appendChild(V),fe++}return fe},I=(re,se)=>{var V;g.textContent="";let ae=((V=n.name)==null?void 0:V.trim())||"tool",fe=qa(re,ae),$e=0;for(let Q of fe){let Me=Q.styles.length>0?(()=>{let J=y("span",Q.styles.map(le=>`persona-tool-text-${le}`).join(" "));return g.appendChild(J),J})():g;if(Q.isDuration&&p)Me.appendChild(v());else{let J=Q.isDuration?oa(n):Q.text;se?$e=C(Me,J,$e):Me.appendChild(document.createTextNode(J))}}};if(!k)if(p&&T!=="none"){let re=(ne=r.loadingAnimationDuration)!=null?ne:2e3;if(g.setAttribute("data-preserve-animation","true"),T==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${re}ms`),E&&I(E,!1);else if(g.classList.add(`persona-tool-loading-${T}`),g.style.setProperty("--persona-tool-anim-duration",`${re}ms`),T==="shimmer-color"&&(r.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),E)I(E,!0);else{let se=g.textContent||d;g.textContent="",C(g,se,0)}}else E&&I(E,!1);let j=null;if(a){j=y("div","persona-flex persona-items-center");let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=ye(i?"chevron-up":"chevron-down",16,re,2);se?j.appendChild(se):j.textContent=i?"Hide":"Show";let ae=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");ae.append(j),u.append(f,ae)}else u.append(f);let $=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if($.setAttribute("data-persona-collapsed-preview","tool"),$.style.display="none",$.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&c){let re=(Ae=r.renderCollapsedPreview)==null?void 0:Ae.call(r,{message:e,toolCall:n,defaultPreview:c,isActive:p,config:t!=null?t:{}});Iv($,re)||($.textContent=c),$.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,$),o;let R=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(R.style.display=i?"":"none",r.contentBackgroundColor&&(R.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(R.style.color=r.contentTextColor),r.contentPaddingX&&(R.style.paddingLeft=r.contentPaddingX,R.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(R.style.paddingTop=r.contentPaddingY,R.style.paddingBottom=r.contentPaddingY),n.name){let re=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?re.style.color=r.contentTextColor:r.headerTextColor&&(re.style.color=r.headerTextColor),re.textContent=n.name,R.appendChild(re)}if(n.args!==void 0){let re=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Arguments";let ae=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Il(ae,r),ae.textContent=wo(n.args),re.append(se,ae),R.appendChild(re)}if(n.chunks&&n.chunks.length){let re=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Activity";let ae=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Il(ae,r),ae.textContent=n.chunks.join(""),re.append(se,ae),R.appendChild(re)}if(n.status==="complete"&&n.result!==void 0){let re=y("div","persona-space-y-1"),se=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(se.style.color=r.labelTextColor),se.textContent="Result";let ae=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");ae.style.fontSize="0.75rem",ae.style.lineHeight="1rem",Il(ae,r),ae.textContent=wo(n.result),re.append(se,ae),R.appendChild(re)}if(n.status==="complete"&&typeof n.duration=="number"){let re=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(re.style.color=r.contentTextColor),re.textContent=`Duration: ${n.duration}ms`,R.appendChild(re)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),j){j.innerHTML="";let re=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=ye(i?"chevron-up":"chevron-down",16,re,2);se?j.appendChild(se):j.textContent=i?"Hide":"Show"}R.style.display=i?"":"none",$.style.display=i?"none":$.textContent||$.childNodes.length?"":"none"})(),o.append(u,$,R),o};var ns=new Map,xi=e=>{let n=(e.startsWith(Rr)?e.slice(Rr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},Ig=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Rg=(e,t)=>{var r,o,s;let n=(o=(r=Ig(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=ns.get(e))!=null?s:n==="expanded"},Wg=(e,t,n)=>{var a,i;let r=Ig(n);e.setAttribute("aria-expanded",t?"true":"false");let o=e.querySelector("[data-approval-details-label]");o&&(o.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=ye(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},Hg=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=Rg(e,n);Wg(r,s,n),o.style.display=s?"":"none"};var vi=(e,t)=>{var I,j,$,R,N,O,Z,Ee,de,ee,Le,Pe,ne,Ae,re;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(n==null?void 0:n.status)==="pending",s=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(I=r==null?void 0:r.backgroundColor)!=null?I:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(j=r==null?void 0:r.borderColor)!=null?j:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":($=r==null?void 0:r.titleColor)!=null?$:"currentColor",p=ye(d,20,c,2);p&&i.appendChild(p);let u=y("div","persona-flex-1 persona-min-w-0"),f=y("div","persona-flex persona-items-center persona-gap-2"),g=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(g.style.color=r.titleColor),g.textContent=(R=r==null?void 0:r.title)!=null?R:"Approval Required",f.appendChild(g),!o){let se=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");se.setAttribute("data-approval-status",n.status),n.status==="approved"?(se.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",se.style.color="var(--persona-palette-colors-success-700, #15803d)",se.textContent="Approved"):n.status==="denied"?(se.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",se.style.color="var(--persona-palette-colors-error-700, #b91c1c)",se.textContent="Denied"):n.status==="timeout"&&(se.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",se.style.color="var(--persona-palette-colors-warning-700, #b45309)",se.textContent="Timeout"),f.appendChild(se)}u.appendChild(f);let v=n.toolType==="webmcp"||n.toolName.startsWith(Rr)?Ys(n.toolName):void 0,S=(N=r==null?void 0:r.formatDescription)==null?void 0:N.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...v?{displayTitle:v}:{},...n.reason?{reason:n.reason}:{}}),T=!n.toolName,L=S||(T?n.description:`The assistant wants to use \u201C${v!=null?v:xi(n.toolName)}\u201D.`),P=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(P.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(P.style.color=r.descriptionColor),P.textContent=L,u.appendChild(P),n.reason){let se=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");se.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?se.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(se.style.color=r.descriptionColor);let ae=y("span","persona-font-medium");ae.textContent=`${(O=r==null?void 0:r.reasonLabel)!=null?O:"Agent's stated reason:"} `,se.appendChild(ae),se.appendChild(document.createTextNode(n.reason)),u.appendChild(se)}let E=(Z=r==null?void 0:r.detailsDisplay)!=null?Z:"collapsed",k=!!n.description&&!T,C=k||!!n.parameters;if(E!=="hidden"&&C){let se=Rg(e.id,t),ae=y("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");ae.type="button",ae.setAttribute("data-expand-header","true"),ae.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor);let fe=y("span");fe.setAttribute("data-approval-details-label","true");let $e=y("span","persona-inline-flex persona-items-center");$e.setAttribute("data-approval-details-chevron","true"),ae.append(fe,$e),Wg(ae,se,t),u.appendChild(ae);let V=y("div");if(V.setAttribute("data-approval-details","true"),V.style.display=se?"":"none",k){let Q=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(Q.style.color=r.descriptionColor),Q.textContent=n.description,V.appendChild(Q)}if(n.parameters){let Q=y("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(Q.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(Q.style.color=r.parameterTextColor),Q.style.fontSize="0.75rem",Q.style.lineHeight="1rem",Q.textContent=wo(n.parameters),V.appendChild(Q)}u.appendChild(V)}if(o){let se=y("div","persona-flex persona-gap-2 persona-mt-2");se.setAttribute("data-approval-buttons","true");let ae=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");ae.type="button",ae.style.backgroundColor=(Ee=r==null?void 0:r.approveButtonColor)!=null?Ee:"var(--persona-approval-approve-bg, #22c55e)",ae.style.color=(de=r==null?void 0:r.approveButtonTextColor)!=null?de:"#ffffff",ae.setAttribute("data-approval-action","approve");let fe=ye("shield-check",14,(ee=r==null?void 0:r.approveButtonTextColor)!=null?ee:"#ffffff",2);fe&&(fe.style.marginRight="4px",ae.appendChild(fe));let $e=document.createTextNode((Le=r==null?void 0:r.approveLabel)!=null?Le:"Approve");ae.appendChild($e);let V=y("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");V.type="button",V.style.backgroundColor=(Pe=r==null?void 0:r.denyButtonColor)!=null?Pe:"transparent",V.style.color=(ne=r==null?void 0:r.denyButtonTextColor)!=null?ne:"var(--persona-feedback-error, #dc2626)",V.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,V.setAttribute("data-approval-action","deny");let Q=ye("shield-x",14,(Ae=r==null?void 0:r.denyButtonTextColor)!=null?Ae:"var(--persona-feedback-error, #dc2626)",2);Q&&(Q.style.marginRight="4px",V.appendChild(Q));let Me=document.createTextNode((re=r==null?void 0:r.denyLabel)!=null?re:"Deny");V.appendChild(Me),se.append(ae,V),u.appendChild(se)}return a.append(i,u),s.appendChild(a),s};function Hv(e){var n,r;let t=(n=e.getRootNode)==null?void 0:n.call(e);return t instanceof ShadowRoot?t:((r=e.ownerDocument)!=null?r:document).body}function Bg(e){var v;let{anchor:t,content:n,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=e,c=(v=e.container)!=null?v:Hv(t),p=!1,u=null,f=()=>{if(!p)return;let S=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${S.width}px`);let T=r==="top-start"||r==="top-end"?S.top-o-n.getBoundingClientRect().height:S.bottom+o,L=r==="bottom-end"||r==="top-end"?S.right-n.getBoundingClientRect().width:S.left;n.style.top=`${T}px`,n.style.left=`${L}px`},g=()=>{p&&(p=!1,u&&(u(),u=null),n.remove())},b=()=>{var k,C,I;if(p)return;p=!0,a!=null&&(n.style.zIndex=String(a)),c.appendChild(n),f();let S=(C=((k=t.ownerDocument)!=null?k:document).defaultView)!=null?C:window,T=(I=t.ownerDocument)!=null?I:document,L=()=>{if(!t.isConnected){g(),d==null||d("anchor-removed");return}f()},P=j=>{let $=typeof j.composedPath=="function"?j.composedPath():[];$.includes(n)||$.includes(t)||(g(),d==null||d("outside"))},E=S.setTimeout(()=>{T.addEventListener("pointerdown",P,!0)},0);S.addEventListener("scroll",L,!0),S.addEventListener("resize",L),u=()=>{S.clearTimeout(E),T.removeEventListener("pointerdown",P,!0),S.removeEventListener("scroll",L,!0),S.removeEventListener("resize",L)},i==null||i()};return{get isOpen(){return p},open:b,close:g,toggle:()=>p?g():b(),reposition:f,destroy:g}}function Dg(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var Bv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),Ng=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},rs=(e,t)=>{Ng(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},Dv=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Nv=(e,t)=>{var r,o;let n=(r=t==null?void 0:t.detailsDisplay)!=null?r:"collapsed";return(o=ns.get(e))!=null?o:n==="expanded"},Wl=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},Ov=(e,t)=>{var c,p;let n=y("span","persona-approval-title");t!=null&&t.titleColor&&(n.style.color=t.titleColor);let o=e.toolType==="webmcp"||e.toolName.startsWith(Rr)?Ys(e.toolName):void 0,s=(p=t==null?void 0:t.formatDescription)==null?void 0:p.call(t,{toolName:e.toolName,toolType:e.toolType,description:(c=e.description)!=null?c:"",parameters:e.parameters,...o?{displayTitle:o}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=o!=null?o:xi(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),i){n.append(" from ");let u=document.createElement("strong");u.textContent=i,n.appendChild(u)}return n},Fv=e=>{let t=y("div","persona-approval-resolved"),n=ye("ban",15,"currentColor",2);n&&t.appendChild(n);let r=y("span","persona-approval-resolved-name");return r.textContent=e.toolName?xi(e.toolName):"Tool",t.append(r,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},_v=(e,t,n,r,o,s,a)=>{var j,$,R,N,O,Z,Ee;let i=y("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),r!=null&&r.backgroundColor&&(i.style.background=r.backgroundColor),r!=null&&r.borderColor&&(i.style.borderColor=r.borderColor),(r==null?void 0:r.shadow)!==void 0&&(i.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let d=(j=r==null?void 0:r.detailsDisplay)!=null?j:"collapsed",c=!!n.description&&d!=="hidden",p=n.parameters!=null&&d!=="hidden",u=c||p,f=u&&Nv(t.id,r),g=($=r==null?void 0:r.showDetailsLabel)!=null?$:"Show details",b=(R=r==null?void 0:r.hideDetailsLabel)!=null?R:"Hide details",v=y("button","persona-approval-head");v.type="button",u?(v.setAttribute("data-action","toggle-params"),v.setAttribute("aria-expanded",f?"true":"false"),v.setAttribute("aria-label",f?b:g)):v.setAttribute("data-static","true");let S=y("span","persona-approval-logo"),T=ye("shield-check",16,"currentColor",2);T&&S.appendChild(T),v.appendChild(S);let L=Ov(n,r);if(u){let de=y("span","persona-approval-toggle");de.setAttribute("aria-hidden","true");let ee=ye("chevron-down",14,"currentColor",2);ee&&de.appendChild(ee),L.append(" "),L.appendChild(de)}v.appendChild(L),i.appendChild(v);let P=y("div","persona-approval-body");if(u){let de=y("div","persona-approval-details");if(de.setAttribute("data-role","params"),de.hidden=!f,c){let ee=y("p","persona-approval-desc");r!=null&&r.descriptionColor&&(ee.style.color=r.descriptionColor),ee.textContent=n.description,de.appendChild(ee)}if(p){let ee=y("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(ee.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ee.style.color=r.parameterTextColor),ee.textContent=wo(n.parameters),de.appendChild(ee)}P.appendChild(de)}if(n.reason){let de=y("p","persona-approval-reason");r!=null&&r.reasonColor?de.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(de.style.color=r.descriptionColor);let ee=y("span","persona-approval-reason-label");ee.textContent=`${(N=r==null?void 0:r.reasonLabel)!=null?N:"Agent's stated reason:"} `,de.append(ee,document.createTextNode(n.reason)),P.appendChild(de)}let E=y("div","persona-approval-actions"),k=null,C=de=>{r!=null&&r.approveButtonColor&&(de.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(de.style.color=r.approveButtonTextColor)},I=y("button","persona-approval-deny");if(I.type="button",I.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(I.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(I.style.color=r.denyButtonTextColor),I.append((O=r==null?void 0:r.denyLabel)!=null?O:"Deny"),a){let de=y("div","persona-approval-split"),ee=y("button","persona-approval-primary");ee.type="button",ee.setAttribute("data-action","always"),C(ee),ee.append((Z=r==null?void 0:r.approveLabel)!=null?Z:"Always allow",Wl("\u23CE"));let Le=y("button","persona-approval-caret");Le.type="button",Le.setAttribute("data-action","toggle-menu"),Le.setAttribute("aria-label","More options"),C(Le);let Pe=ye("chevron-down",15,"currentColor",2);Pe&&Le.appendChild(Pe),de.append(ee,Le),E.append(de,I),I.append(Wl("Esc"));let ne=y("div","persona-approval-menu"),Ae=y("button","persona-approval-menu-item");Ae.type="button",Ae.append("Allow once",Wl("\u2318\u23CE")),ne.appendChild(Ae),k=Bg({anchor:de,content:ne,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,k),Ae.addEventListener("click",()=>{rs(e,t.id),o()})}else{let de=y("button","persona-approval-primary persona-approval-primary--solo");de.type="button",de.setAttribute("data-action","allow"),C(de),de.append((Ee=r==null?void 0:r.approveLabel)!=null?Ee:"Allow"),E.append(de,I)}return P.appendChild(E),i.appendChild(P),i.addEventListener("click",de=>{let ee=de.target instanceof Element?de.target.closest("[data-action]"):null;if(!ee)return;let Le=ee.getAttribute("data-action");if(Le==="toggle-params"){let Pe=i.querySelector('[data-role="params"]');if(Pe){let ne=Pe.hidden;Pe.hidden=!ne,v.setAttribute("aria-expanded",ne?"true":"false"),v.setAttribute("aria-label",ne?b:g),ns.set(t.id,ne)}return}if(Le==="toggle-menu"){k==null||k.toggle();return}if(Le==="always"){rs(e,t.id),o({remember:!0});return}if(Le==="allow"){rs(e,t.id),o();return}if(Le==="deny"){rs(e,t.id),s();return}}),i},Og=()=>{let e=Bv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:o,deny:s,config:a})=>{let i=r==null?void 0:r.approval;if(!i)return null;let d=Dv(a);if(i.status!=="pending"){if(rs(e,r.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return Fv(i)}Ng(e,r.id);let c=(d==null?void 0:d.enableAlwaysAllow)===!0,p=_v(e,r,i,d,o,s,c);if(c){e.pendingOrder.includes(r.id)||e.pendingOrder.push(r.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=f=>{Dg(f)||r.id===e.latestPendingApprovalId&&(f.key!=="Escape"&&f.key!=="Enter"||(f.preventDefault(),f.stopImmediatePropagation(),rs(e,r.id),f.key==="Escape"?s():f.metaKey||f.ctrlKey?o():o({remember:!0})))};e.keyHandlers.set(r.id,u),document.addEventListener("keydown",u)}return p}},teardown:()=>{for(let r of[...e.keyHandlers.keys(),...e.popovers.keys()])rs(e,r);e.latestPendingApprovalId=null}}};var Fg=e=>{let t=[],n=null;return{buttons:t,render:(o,s,a,i,d,c)=>{e.innerHTML="",t.length=0;let p=(c==null?void 0:c.agentPushed)===!0;if(p||(n=null),!o||!o.length||!p&&(i!=null?i:s?s.getMessages():[]).some(S=>S.role==="user"))return;let u=document.createDocumentFragment(),f=s?s.isStreaming():!1,g=b=>{switch(b){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(o.forEach(b=>{let v=y("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=b,v.disabled=f,d!=null&&d.fontFamily&&(v.style.fontFamily=g(d.fontFamily)),d!=null&&d.fontWeight&&(v.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(v.style.paddingLeft=d.paddingX,v.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(v.style.paddingTop=d.paddingY,v.style.paddingBottom=d.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:b},bubbles:!0,composed:!0})),s.sendMessage(b))}),u.appendChild(v),t.push(v)}),e.appendChild(u),p){let b=JSON.stringify(o);b!==n&&(n=b,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var Aa=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Sa=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}};var $v=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),jv=new Set(["step_start","execution_start"]),Uv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),qv=new Set(["step_complete","agent_turn_complete"]),zv=new Set(["flow_complete","agent_complete"]),_g=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),jg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),qn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,os=(e,t)=>{let n=e[t];return jg(n)?n:void 0};function Hl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function wi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Vv(e,t){return typeof t.type=="string"?t.type:e}function Kv(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Gv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function $g(e){var r,o,s,a,i;let t=os(e,"result"),n=[os(e,"tokens"),os(e,"totalTokens"),t?os(t,"tokens"):void 0,os(e,"usage"),t?os(t,"usage"):void 0];for(let d of n){if(!d)continue;let c=(o=(r=qn(d.output))!=null?r:qn(d.outputTokens))!=null?o:qn(d.completionTokens);if(c!==void 0)return c}return(i=(s=qn(e.outputTokens))!=null?s:qn(e.completionTokens))!=null?i:t?(a=qn(t.outputTokens))!=null?a:qn(t.completionTokens):void 0}function Jv(e){var n,r,o,s,a;let t=os(e,"result");return(a=(o=(r=(n=qn(e.executionTime))!=null?n:qn(e.executionTimeMs))!=null?r:qn(e.execution_time))!=null?o:qn(e.duration))!=null?a:t?(s=qn(t.executionTime))!=null?s:qn(t.executionTimeMs):void 0}function Xv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Ta=class{constructor(t=Xv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:wi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!jg(n)){_g.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=Vv(t,n),o=this.now();if($v.has(r)){this.startRun(o);return}if(jv.has(r)){this.run||this.startRun(o);return}if(Uv.has(r)){if(!Gv(r,n))return;let a=Kv(n);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Hl(i.visibleCharCount),c=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:wi(d,c),outputTokens:d,durationMs:c,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(qv.has(r)){if(!this.run)return;let a=this.run,i=$g(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,c=a.exactOutputTokens+Hl(a.visibleCharCount),p=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:wi(c,p),outputTokens:c,durationMs:p,source:d?"usage":"estimate"};return}if(zv.has(r)){if(!this.run)return;let a=this.run,i=$g(n),d=i!=null?i:a.exactOutputTokens+Hl(a.visibleCharCount),c=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:wi(d,p),outputTokens:d,durationMs:p,source:c},this.run=null;return}if(_g.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let o=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=Jv(n);return s!=null?s:r-t.startedAt}};function Ws(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var Qv={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Yv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Zv=["flowName","stepName","reasoningText","text","name","tool","toolName"],ew=100;function tw(e,t){let n={...Qv,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return Yv}function nw(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function rw(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${o}.${s}`}function ow(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let o=r.split("."),s=n;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function sw(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function aw(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function iw(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function lw(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function cw(e,t,n){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function Bl(e,t,n,r,o,s,a,i){var f;let d=o.has(e.id),c=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Ws(c,(f=r.classNames)==null?void 0:f.eventRow);let p=a.find(g=>g.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let g=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(u()),c;function u(){var O,Z;let g=y("div",""),b=y("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");b.setAttribute("data-event-id",e.id);let v=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),S=ye(d?"chevron-down":"chevron-right","14px","currentColor",2);S&&v.appendChild(S);let T=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=(O=r.timestampFormat)!=null?O:"relative";T.textContent=L==="relative"?nw(e.timestamp,n):rw(e.timestamp);let P=null;r.showSequenceNumbers!==!1&&(P=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),P.textContent=String(t+1));let E=tw(e.type,r.badgeColors),k=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");k.style.backgroundColor=E.bg,k.style.color=E.text,k.style.borderColor=E.text+"50",k.textContent=e.type;let C=(Z=r.descriptionFields)!=null?Z:Zv,I=ow(e.payload,C),j=null;I&&(j=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),j.textContent=I);let $=y("div","persona-flex-1 persona-min-w-0"),R=y("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),N=ye("clipboard","12px","currentColor",1.5);return N&&R.appendChild(N),R.addEventListener("click",async Ee=>{Ee.stopPropagation(),await sw(aw(e)),R.innerHTML="";let de=ye("check","12px","currentColor",1.5);de&&R.appendChild(de),setTimeout(()=>{R.innerHTML="";let ee=ye("clipboard","12px","currentColor",1.5);ee&&R.appendChild(ee)},1500)}),b.appendChild(v),b.appendChild(T),P&&b.appendChild(P),b.appendChild(k),j&&b.appendChild(j),b.appendChild($),b.appendChild(R),g.appendChild(b),d&&g.appendChild(cw(e,a,i)),g}}function Ug(e){var b,v,S,T,L;let{buffer:t,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=e,i=(b=o==null?void 0:o.features)==null?void 0:b.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,c=(v=i==null?void 0:i.iconName)!=null?v:"arrow-down",p=(S=i==null?void 0:i.label)!=null?S:"",u=(L=(T=o==null?void 0:o.features)==null?void 0:T.eventStream)!=null?L:{},f=s.find(P=>P.renderEventStreamView);if(f!=null&&f.renderEventStreamView&&o){let P=f.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>g().element,onClose:r});if(P)return{element:P,update:()=>{},destroy:()=>{}}}return g();function g(){let P=u.classNames,E=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ws(E,P==null?void 0:P.panel);let k=[],C="",I="",j=null,$=[],R={},N=0,O=ni(),Z=0,Ee=0,de=!1,ee=null,Le=!1,Pe=0,ne=new Set,Ae=new Map,re="",se="",ae=null,fe,$e,V,Q,Me=null,J=null,le=null;function Ie(){let me=y("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),B=y("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");if(Ws(B,P==null?void 0:P.headerBar),a){J=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap"),J.style.cursor="help",Me=y("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Me.textContent="-- tok/s",le=y("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),le.style.display="none",le.style.pointerEvents="none";let Ot=J,en=le,xr=()=>{if(!en.textContent)return;let or=Ot.getBoundingClientRect(),sr=me.getBoundingClientRect();en.style.left=`${or.left-sr.left}px`,en.style.top=`${or.bottom-sr.top+4}px`,en.style.display="block"},Nr=()=>{en.style.display="none"};J.addEventListener("mouseenter",xr),J.addEventListener("mouseleave",Nr),J.appendChild(Me)}let xe=y("div","persona-flex-1");fe=y("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let ce=y("option","");ce.value="",ce.textContent="All events (0)",fe.appendChild(ce),$e=y("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),$e.type="button",$e.title="Copy All";let Je=ye("clipboard-copy","12px","currentColor",1.5);Je&&$e.appendChild(Je);let Lt=y("span","persona-event-copy-all persona-text-xs");Lt.textContent="Copy All",$e.appendChild(Lt),J&&B.appendChild(J),B.appendChild(xe),B.appendChild(fe),B.appendChild($e);let Mt=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ws(Mt,P==null?void 0:P.searchBar);let xt=ye("search","14px","var(--persona-muted, #9ca3af)",1.5),Rt=y("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");xt&&Rt.appendChild(xt),V=y("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Ws(V,P==null?void 0:P.searchInput),V.type="text",V.placeholder="Search event payloads...",Q=y("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Q.type="button",Q.style.display="none";let Xt=ye("x","12px","currentColor",2);return Xt&&Q.appendChild(Xt),Mt.appendChild(Rt),Mt.appendChild(V),Mt.appendChild(Q),me.appendChild(B),me.appendChild(Mt),le&&me.appendChild(le),me}let he,Ke=s.find(me=>me.renderEventStreamToolbar);if(Ke!=null&&Ke.renderEventStreamToolbar&&o){let me=Ke.renderEventStreamToolbar({config:o,defaultRenderer:()=>Ie(),eventCount:t.getSize(),filteredCount:0,onFilterChange:B=>{C=B,be(),Ct()},onSearchChange:B=>{I=B,be(),Ct()}});he=me!=null?me:Ie()}else he=Ie();let gt=y("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");gt.style.display="none";function Wt(){if(!a||!Me||!J)return;let me=a(),B=iw(me);Me.textContent=B;let xe=lw(me);le&&(le.textContent=xe,xe||(le.style.display="none")),J.setAttribute("aria-label",xe?`Throughput: ${B}, ${xe}`:`Throughput: ${B}`)}let tt=y("div","persona-flex-1 persona-min-h-0 persona-relative"),ge=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");ge.style.height="100%";let X=y("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Ws(X,P==null?void 0:P.scrollIndicator),X.style.display="none",X.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let it=ye(c,"14px","currentColor",2);it&&X.appendChild(it);let Ve=y("span","");Ve.textContent=p,X.appendChild(Ve);let Se=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Se.style.display="none",tt.appendChild(ge),tt.appendChild(Se),tt.appendChild(X),E.setAttribute("tabindex","0"),E.appendChild(he),E.appendChild(gt),E.appendChild(tt);function we(){let me=t.getAll(),B={};for(let Mt of me)B[Mt.type]=(B[Mt.type]||0)+1;let xe=Object.keys(B).sort(),ce=xe.length!==$.length||!xe.every((Mt,xt)=>Mt===$[xt]),ft=!ce&&xe.some(Mt=>B[Mt]!==R[Mt]),Je=me.length!==Object.values(R).reduce((Mt,xt)=>Mt+xt,0);if(!ce&&!ft&&!Je||($=xe,R=B,!fe))return;let Lt=fe.value;if(fe.options[0].textContent=`All events (${me.length})`,ce){for(;fe.options.length>1;)fe.remove(1);for(let Mt of xe){let xt=y("option","");xt.value=Mt,xt.textContent=`${Mt} (${B[Mt]||0})`,fe.appendChild(xt)}Lt&&xe.includes(Lt)?fe.value=Lt:Lt&&(fe.value="",C="")}else for(let Mt=1;Mt<fe.options.length;Mt++){let xt=fe.options[Mt];xt.textContent=`${xt.value} (${B[xt.value]||0})`}}function Ze(){let me=t.getAll();if(C&&(me=me.filter(B=>B.type===C)),I){let B=I.toLowerCase();me=me.filter(xe=>xe.type.toLowerCase().includes(B)||xe.payload.toLowerCase().includes(B))}return me}function qt(){return C!==""||I!==""}function be(){N=0,Z=0,O.resume(),X.style.display="none"}function pe(me){ne.has(me)?ne.delete(me):ne.add(me),ae=me;let B=ge.scrollTop,xe=O.isFollowing();Le=!0,O.pause(),Ct(),ge.scrollTop=B,xe&&O.resume(),Le=!1}function vn(){return Co(ge,50)}function Ct(){Ee=Date.now(),de=!1,Wt(),we();let me=t.getEvictedCount();me>0?(gt.textContent=`${me.toLocaleString()} older events truncated`,gt.style.display=""):gt.style.display="none",k=Ze();let B=k.length,xe=t.getSize()>0;B===0&&xe&&qt()?(Se.textContent=I?`No events matching '${I}'`:"No events matching filter",Se.style.display="",ge.style.display="none"):(Se.style.display="none",ge.style.display=""),$e&&($e.title=qt()?`Copy Filtered (${B})`:"Copy All"),d&&!O.isFollowing()&&B>N&&(Z+=B-N,Ve.textContent=p?`${p}${Z>0?` (${Z})`:""}`:"",X.style.display=""),N=B;let ce=t.getAll(),ft=ce.length>0?ce[0].timestamp:0,Je=new Set(k.map(xt=>xt.id));for(let xt of ne)Je.has(xt)||ne.delete(xt);let Lt=C!==re||I!==se,Mt=Ae.size===0&&k.length>0;if(Lt||Mt||k.length===0){ge.innerHTML="",Ae.clear();let xt=document.createDocumentFragment();for(let Rt=0;Rt<k.length;Rt++){let Xt=Bl(k[Rt],Rt,ft,u,ne,pe,s,o);Ae.set(k[Rt].id,Xt),xt.appendChild(Xt)}ge.appendChild(xt),re=C,se=I,ae=null}else{if(ae!==null){let Rt=Ae.get(ae);if(Rt&&Rt.parentNode===ge){let Xt=k.findIndex(Ot=>Ot.id===ae);if(Xt>=0){let Ot=Bl(k[Xt],Xt,ft,u,ne,pe,s,o);ge.insertBefore(Ot,Rt),Rt.remove(),Ae.set(ae,Ot)}}ae=null}let xt=new Set(k.map(Rt=>Rt.id));for(let[Rt,Xt]of Ae)xt.has(Rt)||(Xt.remove(),Ae.delete(Rt));for(let Rt=0;Rt<k.length;Rt++){let Xt=k[Rt];if(!Ae.has(Xt.id)){let Ot=Bl(Xt,Rt,ft,u,ne,pe,s,o);Ae.set(Xt.id,Ot),ge.appendChild(Ot)}}}O.isFollowing()&&(ge.scrollTop=ge.scrollHeight)}function fn(){if(Date.now()-Ee>=ew){ee!==null&&(cancelAnimationFrame(ee),ee=null),Ct();return}de||(de=!0,ee=requestAnimationFrame(()=>{ee=null,Ct()}))}let yr=(me,B)=>{if(!$e)return;$e.innerHTML="";let xe=ye(me,"12px","currentColor",1.5);xe&&$e.appendChild(xe);let ce=y("span","persona-text-xs");ce.textContent="Copy All",$e.appendChild(ce),setTimeout(()=>{$e.innerHTML="";let ft=ye("clipboard-copy","12px","currentColor",1.5);ft&&$e.appendChild(ft);let Je=y("span","persona-text-xs");Je.textContent="Copy All",$e.appendChild(Je),$e.disabled=!1},B)},br=async()=>{if($e){$e.disabled=!0;try{let me;qt()?me=k:n?(me=await n(),me.length===0&&(me=t.getAll())):me=t.getAll();let B=me.map(xe=>{try{return JSON.parse(xe.payload)}catch{return xe.payload}});await navigator.clipboard.writeText(JSON.stringify(B,null,2)),yr("check",1500)}catch{yr("x",1500)}}},Ue=()=>{fe&&(C=fe.value,be(),Ct())},M=()=>{!V||!Q||(Q.style.display=V.value?"":"none",j&&clearTimeout(j),j=setTimeout(()=>{I=V.value,be(),Ct()},150))},ue=()=>{!V||!Q||(V.value="",I="",Q.style.display="none",j&&clearTimeout(j),be(),Ct())},Te=()=>{if(Le)return;let me=ge.scrollTop,{action:B,nextLastScrollTop:xe}=ri({following:O.isFollowing(),currentScrollTop:me,lastScrollTop:Pe,nearBottom:vn(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Pe=xe,B==="resume"?(O.resume(),Z=0,X.style.display="none"):B==="pause"&&(O.pause(),d&&(Ve.textContent=p,X.style.display=""))},ke=me=>{let B=oi({following:O.isFollowing(),deltaY:me.deltaY,nearBottom:vn(),resumeWhenNearBottom:!0});B==="pause"?(O.pause(),d&&(Ve.textContent=p,X.style.display="")):B==="resume"&&(O.resume(),Z=0,X.style.display="none")},He=()=>{d&&(ge.scrollTop=ge.scrollHeight,O.resume(),Z=0,X.style.display="none")},nt=me=>{let B=me.target;if(!B||B.closest("button"))return;let xe=B.closest("[data-event-id]");if(!xe)return;let ce=xe.getAttribute("data-event-id");ce&&pe(ce)},Qe=me=>{if((me.metaKey||me.ctrlKey)&&me.key==="f"){me.preventDefault(),V==null||V.focus(),V==null||V.select();return}me.key==="Escape"&&(V&&document.activeElement===V?(ue(),V.blur(),E.focus()):r&&r())};$e&&$e.addEventListener("click",br),fe&&fe.addEventListener("change",Ue),V&&V.addEventListener("input",M),Q&&Q.addEventListener("click",ue),ge.addEventListener("scroll",Te),ge.addEventListener("wheel",ke,{passive:!0}),ge.addEventListener("click",nt),X.addEventListener("click",He),E.addEventListener("keydown",Qe);function ht(){j&&clearTimeout(j),ee!==null&&(cancelAnimationFrame(ee),ee=null),de=!1,Ae.clear(),$e&&$e.removeEventListener("click",br),fe&&fe.removeEventListener("change",Ue),V&&V.removeEventListener("input",M),Q&&Q.removeEventListener("click",ue),ge.removeEventListener("scroll",Te),ge.removeEventListener("wheel",ke),ge.removeEventListener("click",nt),X.removeEventListener("click",He),E.removeEventListener("keydown",Qe)}return{element:E,update:fn,destroy:ht}}}function qg(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",o=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(g)}else u.textContent=a;if(c.append(p,u),i.append(d,c),o==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${n}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",r),i.append(f)}return i}var zg=(e,t)=>{var r,o,s;let n=(s=(o=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:t.config,defaultRenderer:()=>qg(e,t)});if(p)return p}return qg(e,t)};var Dl=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},Mo=new Dl;Mo.register("PersonaArtifactCard",zg);function dw(e){var o;let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=e.props)!=null?o:{},null,2),t.appendChild(n),t.appendChild(r),t}function Vg(e,t){var $e,V,Q,Me;let n=(V=($e=e.features)==null?void 0:$e.artifacts)==null?void 0:V.layout,o=((Q=n==null?void 0:n.toolbarPreset)!=null?Q:"default")==="document",s=(Me=n==null?void 0:n.panePadding)==null?void 0:Me.trim(),a=e.markdown?vs(e.markdown):null,i=Xs(e.sanitize),d=J=>{let le=a?a(J):Kr(J);return i?i(le):le},c=typeof document!="undefined"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{c==null||c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),N==null||N.hide()};c&&c.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let u=y("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");u.setAttribute("data-persona-theme-zone","artifact-pane"),o&&u.classList.add("persona-artifact-pane-document");let f=y("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&f.classList.add("persona-artifact-toolbar-document");let g=y("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let b=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");b.type="button",b.textContent="Close",b.setAttribute("aria-label","Close artifacts panel"),b.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let v="rendered",S=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?Gt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Gt({icon:"eye",label:"Rendered view"}),L=o?Gt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Gt({icon:"code-2",label:"Source"}),P=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),E=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,k=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,C=n==null?void 0:n.documentToolbarCopyMenuItems,I=!!(k&&C&&C.length>0),j=null,$,R=null,N=null;if(o&&(E||k)&&!I){if($=E?pi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),k){let J=ye("chevron-down",14,"currentColor",2);J&&$.appendChild(J)}}else o&&I?(j=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),$=E?pi({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R=Gt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),j.append($,R)):o?$=Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):$=Gt({icon:"copy",label:"Copy"});let O=o?Gt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"refresh-cw",label:"Refresh"}),Z=o?Gt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"x",label:"Close"}),Ee=()=>{var Ke,gt,Wt;let J=(Ke=Ae.find(tt=>tt.id===re))!=null?Ke:Ae[Ae.length-1],le=(gt=J==null?void 0:J.id)!=null?gt:null,Ie=(J==null?void 0:J.artifactType)==="markdown"&&(Wt=J.markdown)!=null?Wt:"",he=J?JSON.stringify({component:J.component,props:J.props},null,2):"";return{markdown:Ie,jsonPayload:he,id:le}},de=async()=>{var Ke;let{markdown:J,jsonPayload:le}=Ee(),Ie=(Ke=Ae.find(gt=>gt.id===re))!=null?Ke:Ae[Ae.length-1],he=(Ie==null?void 0:Ie.artifactType)==="markdown"?J:Ie?le:"";try{await navigator.clipboard.writeText(he)}catch{}};if($.addEventListener("click",async()=>{let J=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(J&&I){let{markdown:le,jsonPayload:Ie,id:he}=Ee();try{await J({actionId:"primary",artifactId:he,markdown:le,jsonPayload:Ie})}catch{}return}await de()}),R&&(C!=null&&C.length)){let J=()=>{var Ie;return(Ie=u.closest("[data-persona-root]"))!=null?Ie:document.body},le=()=>{N=ts({items:C.map(Ie=>({id:Ie.id,label:Ie.label})),onSelect:async Ie=>{let{markdown:he,jsonPayload:Ke,id:gt}=Ee(),Wt=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Wt?await Wt({actionId:Ie,artifactId:gt,markdown:he,jsonPayload:Ke}):Ie==="markdown"||Ie==="md"?await navigator.clipboard.writeText(he):Ie==="json"||Ie==="source"?await navigator.clipboard.writeText(Ke):await navigator.clipboard.writeText(he||Ke)}catch{}},anchor:j!=null?j:R,position:"bottom-right",portal:J()})};u.isConnected?le():requestAnimationFrame(le),R.addEventListener("click",Ie=>{Ie.stopPropagation(),N==null||N.toggle()})}O.addEventListener("click",async()=>{var J;try{await((J=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:J.call(n))}catch{}ae()}),Z.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let ee=()=>{o&&(T.setAttribute("aria-pressed",v==="rendered"?"true":"false"),L.setAttribute("aria-pressed",v==="source"?"true":"false"))};T.addEventListener("click",()=>{v="rendered",ee(),ae()}),L.addEventListener("click",()=>{v="source",ee(),ae()});let Le=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(f.replaceChildren(),S.append(T,L),j?P.append(j,O,Z):P.append($,O,Z),f.append(S,Le,P),ee()):(f.appendChild(g),f.appendChild(b)),s&&(f.style.paddingLeft=s,f.style.paddingRight=s);let Pe=y("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),ne=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Pe.style.paddingLeft=s,Pe.style.paddingRight=s,ne.style.padding=s),u.appendChild(f),u.appendChild(Pe),u.appendChild(ne);let Ae=[],re=null,se=!1,ae=()=>{var he,Ke,gt,Wt;let J=o&&Ae.length<=1;Pe.classList.toggle("persona-hidden",J),Pe.replaceChildren();for(let tt of Ae){let ge=y("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");ge.type="button",ge.textContent=tt.title||tt.id.slice(0,8),tt.id===re&&ge.classList.add("persona-bg-persona-container","persona-border-persona-border"),ge.addEventListener("click",()=>t.onSelect(tt.id)),Pe.appendChild(ge)}ne.replaceChildren();let le=re&&Ae.find(tt=>tt.id===re)||Ae[Ae.length-1];if(!le)return;if(o){let tt=le.artifactType==="markdown"?"MD":(he=le.component)!=null?he:"Component",X=(le.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Le.textContent=`${X} \xB7 ${tt}`}else g.textContent="Artifacts";if(le.artifactType==="markdown"){if(o&&v==="source"){let ge=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ge.textContent=(Ke=le.markdown)!=null?Ke:"",ne.appendChild(ge);return}let tt=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");tt.innerHTML=d((gt=le.markdown)!=null?gt:""),ne.appendChild(tt);return}let Ie=le.component?Mo.get(le.component):void 0;if(Ie){let ge={message:{id:le.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let X=Ie((Wt=le.props)!=null?Wt:{},ge);if(X){ne.appendChild(X);return}}catch{}}ne.appendChild(dw(le))},fe=()=>{var le;let J=Ae.length>0;if(u.classList.toggle("persona-hidden",!J),c){let Ie=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ke=((le=Ie==null?void 0:Ie.classList.contains("persona-artifact-narrow-host"))!=null?le:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;J&&Ke&&se?(c.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:c,update(J){var le,Ie,he;Ae=J.artifacts,re=(he=(Ie=J.selectedId)!=null?Ie:(le=J.artifacts[J.artifacts.length-1])==null?void 0:le.id)!=null?he:null,Ae.length>0&&(se=!0),ae(),fe()},setMobileOpen(J){se=J,!J&&c?(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):fe()}}}function rr(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Kg(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!rr(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function pw(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ci(e,t){var d,c,p,u,f,g,b,v,S,T;if(!rr(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),pw(e),Kg(e,t);return}let n=(c=(d=t.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=n==null?void 0:n.paneMaxWidth)!=null?f:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(g=n==null?void 0:n.paneBackground)==null?void 0:g.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let o=(b=n==null?void 0:n.panePadding)==null?void 0:b.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(S=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:S.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Kg(e,t)}var Gg=["panel","seamless"];function Ai(e,t){var i,d,c,p,u,f;for(let g of Gg)e.classList.remove(`persona-artifact-appearance-${g}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!rr(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=n==null?void 0:n.paneAppearance)!=null?c:"panel",o=Gg.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let g=((f=n.unifiedSplitOuterRadius)==null?void 0:f.trim())||s;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function Jg(e,t){var n,r,o;return!t||!rr(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function uw(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function mw(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function gw(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function fw(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function Xg(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function Qg(e,t,n,r,o,s){let a=uw(o,200),i=fw(t,n,r,200);i=Math.max(a,i);let d=mw(s);return d!==null&&(i=Math.min(i,d)),gw(e,a,i)}var Yg={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Nl=(e,t,n,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var b,v,S;if(s.dataset.enhanced==="true")return;let a=(b=s.dataset.tvForm)!=null?b:"init";s.dataset.enhanced="true";let i=(v=Yg[a])!=null?v:Yg.init;s.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),c=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let T=y("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var C,I;let L=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${t.id}-${a}-${T.name}`;let P=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");P.textContent=T.label,L.appendChild(P);let E=(C=T.type)!=null?C:"text",k;E==="textarea"?(k=document.createElement("textarea"),k.rows=3):(k=document.createElement("input"),k.type=E),k.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",k.id=`${t.id}-${a}-${T.name}`,k.name=T.name,k.placeholder=(I=T.placeholder)!=null?I:"",T.required&&(k.required=!0),L.appendChild(k),p.appendChild(L)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=y("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");g.type="submit",g.textContent=(S=i.submitLabel)!=null?S:"Submit",u.appendChild(f),u.appendChild(g),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async T=>{var k,C;T.preventDefault();let L=(k=n.formEndpoint)!=null?k:"/form",P=new FormData(p),E={};P.forEach((I,j)=>{E[j]=I}),E.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let I=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});if(!I.ok)throw new Error(`Form submission failed (${I.status})`);let j=await I.json();f.textContent=(C=j.message)!=null?C:"Thanks! We'll be in touch soon.",j.success&&j.nextPrompt&&await r.sendMessage(String(j.nextPrompt))}catch(I){f.textContent=I instanceof Error?I.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Ol=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,o;return((r=n.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(s=>s.id));return[...n.filter(s=>!r.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Si=new Ol;var Zg=()=>{let e=new Map,t=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:t,off:n,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var hw=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},yw=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(n,o+1)}return null},Ti=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=hw(e),n=yw(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},Fl=e=>typeof e=="string"?e:e==null?"":String(e),Hs={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Fl(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=Fl(n.element);if(r&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Fl(n.text)}}},ef=e=>Array.isArray(e)?e.map(t=>String(t)):[],Ei=e=>{let t=new Set(ef(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(ef(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((c,p)=>c||(p==null?void 0:p({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),r();let d={action:i,message:s.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",d)},u=c(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var bw=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},xw=e=>e.map(t=>({...t,streaming:!1})),vw=e=>e.map(t=>({...t,status:"complete"})),_l=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?bw(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?xw(n.messages):void 0,artifacts:n.artifacts?vw(n.artifacts):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as ww,STR as Cw,OBJ as Aw}from"partial-json";function Sw(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Tw(e,t){if(!Sw(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function $l(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let o=ww(n,Cw|Aw),s=Tw(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Ew(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function jl(e,t){let{config:n,message:r,onPropsUpdate:o}=t,s=Mo.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Mw(){let e=$l();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function tf(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Ul(e){let t=tf(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function ql(e){let t=tf(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var kw=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function zl(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=kw}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=r,g.appendChild(b);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=o,g.appendChild(v),f.appendChild(g);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let C=1;C<=5;C++){let I=document.createElement("button");I.type="button",I.className="persona-feedback-rating-btn persona-feedback-star-btn",I.setAttribute("role","radio"),I.setAttribute("aria-checked","false"),I.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${c[C-1]}`),I.title=c[C-1],I.dataset.rating=String(C),I.innerHTML=`
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
- `,R.addEventListener("click",()=>{u=C,T.forEach((F,j)=>{let H=j<C;F.classList.toggle("selected",H),F.setAttribute("aria-checked",j===C-1?"true":"false")})}),T.push(R),E.appendChild(R)}g.appendChild(E);let L=null;if(d){let C=document.createElement("div");C.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),C.appendChild(L),g.appendChild(C)}let k=document.createElement("div");k.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(),p.remove()});let P=document.createElement("button");return P.type="button",P.className="persona-feedback-btn persona-feedback-btn-submit",P.textContent=a,P.addEventListener("click",async()=>{if(u===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let C=(L==null?void 0:L.value.trim())||void 0;await t(u,C),p.remove()}catch(C){P.disabled=!1,P.textContent=a,console.error("[CSAT Feedback] Failed to submit:",C)}}),k.appendChild(M),k.appendChild(P),g.appendChild(k),p.appendChild(g),p}function ql(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:l="Not likely",highLabel:p="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let g=null,f=document.createElement("div");f.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,v.appendChild(x);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=o,v.appendChild(E),f.appendChild(v);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let k=document.createElement("span");k.className="persona-feedback-label-low",k.textContent=l;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=p,L.appendChild(k),L.appendChild(M);let P=document.createElement("div");P.className="persona-feedback-numbers";let C=[];for(let O=0;O<=10;O++){let N=document.createElement("button");N.type="button",N.className="persona-feedback-rating-btn persona-feedback-number-btn",N.setAttribute("role","radio"),N.setAttribute("aria-checked","false"),N.setAttribute("aria-label",`Rating ${O} out of 10`),N.textContent=String(O),N.dataset.rating=String(O),O<=6?N.classList.add("persona-feedback-detractor"):O<=8?N.classList.add("persona-feedback-passive"):N.classList.add("persona-feedback-promoter"),N.addEventListener("click",()=>{g=O,C.forEach((Y,ke)=>{Y.classList.toggle("selected",ke===O),Y.setAttribute("aria-checked",ke===O?"true":"false")})}),C.push(N),P.appendChild(N)}T.appendChild(L),T.appendChild(P),f.appendChild(T);let R=null;if(d){let O=document.createElement("div");O.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=s,R.rows=3,R.setAttribute("aria-label","Additional comments"),O.appendChild(R),f.appendChild(O)}let F=document.createElement("div");F.className="persona-feedback-actions";let j=document.createElement("button");j.type="button",j.className="persona-feedback-btn persona-feedback-btn-skip",j.textContent=i,j.addEventListener("click",()=>{n==null||n(),u.remove()});let 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){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}H.disabled=!0,H.textContent="Submitting...";try{let O=(R==null?void 0:R.value.trim())||void 0;await t(g,O),u.remove()}catch(O){H.disabled=!1,H.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),F.appendChild(j),F.appendChild(H),f.appendChild(F),u.appendChild(f),u}var Ws="persona-chat-history",hw=30*1e3,yw={"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 bw(e){var r,o,s;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(o=yw[i.type])!=null?o:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Ei(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function xw(e){var t,n,r,o,s,a,i,d,l;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(l=e.clearOnChatClear)!=null?l:!0}:null}function vw(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var zl=e=>!e||typeof e!="object"?{}:{...e},zg=e=>e.map(t=>({...t,streaming:!1})),Vg=(e,t,n)=>{let r=e!=null&&e.markdown?bs(e.markdown):null,o=Js(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var p,u,g;let a=(p=s.text)!=null?p:"",i=(u=s.message.rawContent)!=null?u:null;if(t){let f=t.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=Vo()!==null,l;if(e!=null&&e.postprocessMessage){let f=e.postprocessMessage({...s,text:a,raw:(g=i!=null?i:s.text)!=null?g:""});l=o?o(f):f}else if(r){let f=s.streaming?Ku(a):a,v=r(f);l=o&&d?o(v):v}else l=Yr(a);return l}};function Kg(e){var i,d,l,p;let t=y("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",o=(l=e==null?void 0:e.iconColor)!=null?l:"rgba(59, 130, 246, 0.6)",s=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=ge(n,r,o,s);if(a&&t.appendChild(a),e!=null&&e.label){let u=y("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var Vl=(e,t,n)=>{var Oc,Fc,_c,$c,jc,Uc,qc,zc,Vc,Kc,Gc,Jc,Xc,Qc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Rd,Wd;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=ml(t),o=Ai.getForInstance(r.plugins),{plugin:s,teardown:a}=Mg();r.components&&Lo.registerAll(r.components);let i=jg(),l=r.persistState===!1?null:(Oc=r.storageAdapter)!=null?Oc:Ol(),p={},u=null,g=!1,f=c=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(c);if(m&&typeof m=="object"&&"state"in m){let{state:h,open:b}=m;return b&&(g=!0),h}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return c};if(l!=null&&l.load)try{let c=l.load();if(c&&typeof c.then=="function")u=c.then(m=>{let h=m!=null?m:{messages:[],metadata:{}};return f(h)});else{let m=c!=null?c:{messages:[],metadata:{}},h=f(m);h.metadata&&(p=zl(h.metadata)),(Fc=h.messages)!=null&&Fc.length&&(r={...r,initialMessages:h.messages}),(_c=h.artifacts)!=null&&_c.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:($c=h.selectedArtifactId)!=null?$c:null})}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",c)}else if(r.onStateLoaded)try{let c=f({messages:[],metadata:{}});(jc=c.messages)!=null&&jc.length&&(r={...r,initialMessages:c.messages})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",c)}let v=()=>p,x=c=>{var h;p=(h=c({...p}))!=null?h:{},sn()},E=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Si],T=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Rs.message,Rs.messageAndClick],L=Ti({parsers:E,handlers:T,getSessionMetadata:v,updateSessionMetadata:x,emit:i.emit,documentRef:typeof document!="undefined"?document:null});L.syncFromMetadata();let k=(qc=(Uc=r.launcher)==null?void 0:Uc.enabled)!=null?qc:!0,M=(Vc=(zc=r.launcher)==null?void 0:zc.autoExpand)!=null?Vc:!1,P=(Kc=r.autoFocusInput)!=null?Kc:!1,C=M,R=k,F=(Jc=(Gc=r.layout)==null?void 0:Gc.header)==null?void 0:Jc.layout,j=!1,H=()=>Mo(r),O=()=>k||H(),N=H()?!1:k?M:!0,Y=!1,ke=null,pe=()=>{Y=!0,ke&&clearTimeout(ke),ke=setTimeout(()=>{Y&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Y=!1)},1e4)},Z=Vg(r,L,pe),Te=(Qc=(Xc=r.features)==null?void 0:Xc.showReasoning)!=null?Qc:!0,Le=(Zc=(Yc=r.features)==null?void 0:Yc.showToolCalls)!=null?Zc:!0,oe=(td=(ed=r.features)==null?void 0:ed.showEventStreamToggle)!=null?td:!1,Ae=(rd=(nd=r.features)==null?void 0:nd.scrollToBottom)!=null?rd:{},se=(sd=(od=r.features)==null?void 0:od.scrollBehavior)!=null?sd:{},ae=`${(id=typeof r.persistState=="object"?(ad=r.persistState)==null?void 0:ad.keyPrefix:void 0)!=null?id:"persona-"}event-stream`,xe=oe?new Sa(ae):null,Be=(dd=(cd=(ld=r.features)==null?void 0:ld.eventStream)==null?void 0:cd.maxEvents)!=null?dd:2e3,V=oe?new Aa(Be,xe):null,X=oe?new Ta:null,He=null,K=!1,ue=null,$e=0;xe==null||xe.open().then(()=>V==null?void 0:V.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let fe={onCopy:c=>{var m,h;i.emit("message:copy",c),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(c.id,"copy").catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",b)}),(h=(m=r.messageActions)==null?void 0:m.onCopy)==null||h.call(m,c)},onFeedback:c=>{var m,h;i.emit("message:feedback",c),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(c.messageId,c.type).catch(b=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",b)}),(h=(m=r.messageActions)==null?void 0:m.onFeedback)==null||h.call(m,c)}},Ve=(pd=r.statusIndicator)!=null?pd:{},et=c=>{var m,h,b,S;return c==="idle"?(m=Ve.idleText)!=null?m:xn.idle:c==="connecting"?(h=Ve.connectingText)!=null?h:xn.connecting:c==="connected"?(b=Ve.connectedText)!=null?b:xn.connected:c==="error"?(S=Ve.errorText)!=null?S:xn.error:xn[c]};function Ot(c,m,h,b){if(b==="idle"&&h.idleLink){c.textContent="";let S=document.createElement("a");S.href=h.idleLink,S.target="_blank",S.rel="noopener noreferrer",S.textContent=m,S.style.color="inherit",S.style.textDecoration="none",c.appendChild(S)}else c.textContent=m}let Xe=mg({config:r,showClose:O()}),{wrapper:ye,panel:J,pillRoot:dt}=Xe.shell,qe=Xe.panelElements,{container:Se,body:ve,messagesWrapper:nt,suggestions:Lt,textarea:ee,sendButton:je,sendButtonWrapper:wn,composerForm:bt,statusText:fn,introTitle:xr,introSubtitle:vr,closeButton:A,iconHolder:te,headerTitle:Me,headerSubtitle:Ne,header:Ie,footer:Oe,actionsRow:Ge,leftActions:at,rightActions:Pt}=qe,ce=qe.setSendButtonMode,B=qe.micButton,be=qe.micButtonWrapper,_e=qe.attachmentButton,xt=qe.attachmentButtonWrapper,Ye=qe.attachmentInput,Rt=qe.attachmentPreviewsContainer;Se.classList.add("persona-relative"),ve.classList.add("persona-relative");let St=12,ht=()=>{var c;return(c=Ae.label)!=null?c:""},kt=()=>{var c;return(c=Ae.iconName)!=null?c:"arrow-down"},Xt=()=>Ae.enabled!==!1,Ft=()=>{var c;return(c=se.mode)!=null?c:"anchor-top"},en=()=>Ft()==="follow"||Ft()==="anchor-top"&&Rr,wr=()=>{var c;return(c=se.anchorTopOffset)!=null?c:16},$r=()=>{var c;return(c=se.restorePosition)!=null?c:"bottom"},sr=()=>se.pauseOnInteraction===!0,ar=()=>se.showActivityWhilePinned!==!1,to=()=>se.announce===!0,qt=y("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");qt.type="button",qt.style.display="none",qt.setAttribute("data-persona-scroll-to-bottom","true");let ir=y("span","persona-flex persona-items-center"),jr=y("span",""),In=y("span","");In.setAttribute("data-persona-scroll-to-bottom-count",""),In.style.display="none",qt.append(ir,jr,In),Se.appendChild(qt);let kn=y("div","persona-stream-anchor-spacer");kn.setAttribute("aria-hidden","true"),kn.setAttribute("data-persona-anchor-spacer",""),kn.style.flexShrink="0",kn.style.pointerEvents="none",kn.style.height="0px",ve.appendChild(kn);let Rn=y("div","persona-sr-only");Rn.setAttribute("aria-live","polite"),Rn.setAttribute("aria-atomic","true"),Rn.setAttribute("role","status"),Rn.setAttribute("data-persona-live-region",""),Object.assign(Rn.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),Se.appendChild(Rn);let lr=null,Cr=null,no=c=>{!to()||!c||(Cr=c,lr===null&&(lr=setTimeout(()=>{lr=null,Cr&&to()&&(Rn.textContent=Cr),Cr=null},400)))},qn=()=>{let m=Oe.style.display==="none"?0:Oe.offsetHeight;qt.style.bottom=`${m+St}px`};qn();let ro=()=>{let c=!!ht();qt.setAttribute("aria-label",ht()||"Jump to latest"),qt.title=ht(),qt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),ir.innerHTML="";let m=ge(kt(),"14px","currentColor",2);m?(ir.appendChild(m),ir.style.display=""):ir.style.display="none",jr.textContent=ht(),jr.style.display=c?"":"none"};ro();let vt=null,Ar=null,Sr=o.find(c=>c.renderHeader);if(Sr!=null&&Sr.renderHeader){let c=Sr.renderHeader({config:r,defaultRenderer:()=>{let m=ko({config:r,showClose:O()});return Ms(Se,m,r),m.header},onClose:()=>$t(!1,"user")});if(c){let m=Se.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(c),Ie=c,Xe.header.element=c)}}let Ur=()=>{var m,h,b,S;if(!V)return;if(K=!0,!He&&V&&(He=Rg({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>cr(),config:r,plugins:o,getThroughput:()=>{var W;return(W=X==null?void 0:X.getMetric())!=null?W:{status:"idle"}}})),He&&(ve.style.display="none",(m=Oe.parentNode)==null||m.insertBefore(He.element,Oe),He.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let W=(S=(b=(h=r.features)==null?void 0:h.eventStream)==null?void 0:b.classNames)==null?void 0:S.toggleButtonActive;W&&W.split(/\s+/).forEach(q=>q&&ut.classList.add(q))}let c=()=>{if(!K)return;let W=Date.now();W-$e>=200&&(He==null||He.update(),$e=W),ue=requestAnimationFrame(c)};$e=0,ue=requestAnimationFrame(c),On(),i.emit("eventStream:opened",{timestamp:Date.now()})},cr=()=>{var c,m,h;if(K){if(K=!1,He&&He.element.remove(),ve.style.display="",ut){ut.style.boxShadow="";let b=(h=(m=(c=r.features)==null?void 0:c.eventStream)==null?void 0:m.classNames)==null?void 0:h.toggleButtonActive;b&&b.split(/\s+/).forEach(S=>S&&ut.classList.remove(S))}ue!==null&&(cancelAnimationFrame(ue),ue=null),On(),i.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(oe){let c=(md=(ud=r.features)==null?void 0:ud.eventStream)==null?void 0:md.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(c!=null&&c.toggleButton?" "+c.toggleButton:"");ut=y("button",m),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let h=ge("activity","18px","currentColor",1.5);h&&ut.appendChild(h);let b=qe.clearChatButtonWrapper,S=qe.closeButtonWrapper,W=b||S;W&&W.parentNode===Ie?Ie.insertBefore(ut,W):Ie.appendChild(ut),ut.addEventListener("click",()=>{K?cr():Ur()})}let Io=c=>{var S,W,q,_,D;let m=r.attachments;if(!(m!=null&&m.enabled))return;let h=(S=c.querySelector("[data-persona-composer-attachment-previews]"))!=null?S:c.querySelector(".persona-attachment-previews");if(!h){h=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let de=c.querySelector("[data-persona-composer-form]");de!=null&&de.parentNode?de.parentNode.insertBefore(h,de):c.insertBefore(h,c.firstChild)}if(!((W=c.querySelector("[data-persona-composer-attachment-input]"))!=null?W:c.querySelector('input[type="file"]'))){let de=y("input");de.type="file",de.setAttribute("data-persona-composer-attachment-input",""),de.accept=((q=m.allowedTypes)!=null?q:Zr).join(","),de.multiple=((_=m.maxFiles)!=null?_:4)>1,de.style.display="none",de.setAttribute("aria-label",(D=m.buttonTooltipText)!=null?D:"Attach files"),c.appendChild(de)}},Tr=o.find(c=>c.renderComposer);if(Tr!=null&&Tr.renderComposer){let c=r.composer,m=Tr.renderComposer({config:r,defaultRenderer:()=>wa({config:r}).footer,onSubmit:h=>{var q;if(!$||$.isStreaming())return;let b=h.trim(),S=(q=vt==null?void 0:vt.hasAttachments())!=null?q:!1;if(!b&&!S)return;mc();let W;S&&(W=[],W.push(...vt.getContentParts()),b&&W.push(Ka(b))),$.sendMessage(b,{contentParts:W}),S&&vt.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ye==null||Ye.click()},models:c==null?void 0:c.models,selectedModelId:c==null?void 0:c.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((gd=r.voiceRecognition)==null?void 0:gd.enabled)===!0?()=>{Ar==null||Ar()}:void 0});m&&(Xe.replaceComposer(m),Oe=Xe.composer.footer)}let Ro=c=>{let m=(...le)=>{for(let Q of le){let we=c.querySelector(Q);if(we)return we}return null},h=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),S=c.querySelector("[data-persona-composer-submit]"),W=c.querySelector("[data-persona-composer-mic]"),q=c.querySelector("[data-persona-composer-status]");h&&(bt=h),b&&(ee=b),S&&(je=S),W&&(B=W,be=W.parentElement),q&&(fn=q);let _=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(Lt=_);let D=m("[data-persona-composer-attachment-button]",".persona-attachment-button");D&&(_e=D,xt=D.parentElement),Ye=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Rt=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let de=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");de&&(Ge=de)};Io(Oe),Ro(Oe);let Ln=(xd=(fd=r.layout)==null?void 0:fd.contentMaxWidth)!=null?xd:H()?(bd=(yd=(hd=r.launcher)==null?void 0:hd.composerBar)==null?void 0:yd.contentMaxWidth)!=null?bd:"720px":void 0;if(Ln&&(nt.style.maxWidth=Ln,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%"),Ln&&bt&&!H()&&(bt.style.maxWidth=Ln,bt.style.marginLeft="auto",bt.style.marginRight="auto"),Ln&&Lt&&!H()&&(Lt.style.maxWidth=Ln,Lt.style.marginLeft="auto",Lt.style.marginRight="auto"),Ln&&Rt&&!H()&&(Rt.style.maxWidth=Ln,Rt.style.marginLeft="auto",Rt.style.marginRight="auto"),(vd=r.attachments)!=null&&vd.enabled&&Ye&&Rt){vt=Ts.fromConfig(r.attachments),vt.setPreviewsContainer(Rt),Ye.addEventListener("change",h=>{let b=h.target;vt==null||vt.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,m=Kg(c);Se.appendChild(m)}(()=>{var b,S;let c=(S=(b=r.layout)==null?void 0:b.slots)!=null?S:{},m=W=>{switch(W){case"body-top":return Se.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return nt;case"footer-top":return Lt;case"composer":return bt;case"footer-bottom":return fn;default:return null}},h=(W,q)=>{var _;switch(W){case"header-left":case"header-center":case"header-right":if(W==="header-left")Ie.insertBefore(q,Ie.firstChild);else if(W==="header-right")Ie.appendChild(q);else{let D=Ie.querySelector(".persona-flex-col");D?(_=D.parentNode)==null||_.insertBefore(q,D.nextSibling):Ie.appendChild(q)}break;case"body-top":{let D=ve.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith(q):ve.insertBefore(q,ve.firstChild);break}case"body-bottom":ve.appendChild(q);break;case"footer-top":Lt.replaceWith(q);break;case"footer-bottom":fn.replaceWith(q);break;default:break}};for(let[W,q]of Object.entries(c))if(q)try{let _=q({config:r,defaultContent:()=>m(W)});_&&h(W,_)}catch(_){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${W}":`,_)}})();let oo=c=>{var q,_;let h=c.target.closest('button[data-expand-header="true"]');if(!h)return;let b=h.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=h.getAttribute("data-bubble-type");if(W==="reasoning")Ls.has(S)?Ls.delete(S):Ls.add(S),bg(S,b);else if(W==="tool")Ps.has(S)?Ps.delete(S):Ps.add(S),xg(S,b,r);else if(W==="approval"){let D=r.approval!==!1?r.approval:void 0,de=((q=D==null?void 0:D.detailsDisplay)!=null?q:"collapsed")==="expanded",le=(_=ts.get(S))!=null?_:de;ts.set(S,!le),Ag(S,b,r)}Lr.delete(S)};nt.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),oo(c))}),nt.addEventListener("keydown",c=>{let m=c.target;(c.key==="Enter"||c.key===" ")&&m.closest('button[data-expand-header="true"]')&&(c.preventDefault(),oo(c))}),nt.addEventListener("copy",c=>{let{clipboardData:m}=c;if(!m)return;let h=nt.getRootNode(),b=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!b||b.isCollapsed)return;let S=b.toString(),W=Km(S);!W||W===S||(m.setData("text/plain",W),c.preventDefault())});let qr=new Map,so=null,ao="idle",Wo={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Ho=(c,m)=>{let{icon:h,label:b}=Wo[m];c.setAttribute("aria-label",b),c.title=b,c.setAttribute("aria-pressed",m==="idle"?"false":"true"),c.classList.toggle("persona-message-action-active",m!=="idle"),c.classList.toggle("persona-message-action-loading",m==="loading");let S=ge(h,14,"currentColor",2);S&&(c.innerHTML="",c.appendChild(S))},io=()=>{nt.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{var W;let h=m.closest("[data-actions-for]"),b=(W=h==null?void 0:h.getAttribute("data-actions-for"))!=null?W:null;Ho(m,b&&b===so?ao:"idle")})};nt.addEventListener("click",c=>{var q;let h=c.target.closest(".persona-message-action-btn[data-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let b=h.closest("[data-actions-for]");if(!b)return;let S=b.getAttribute("data-actions-for");if(!S)return;let W=h.getAttribute("data-action");if(W==="copy"){let D=$.getMessages().find(de=>de.id===S);if(D&&fe.onCopy){let de=D.content||"";navigator.clipboard.writeText(de).then(()=>{h.classList.add("persona-message-action-success");let le=ge("check",14,"currentColor",2);le&&(h.innerHTML="",h.appendChild(le)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Q=ge("copy",14,"currentColor",2);Q&&(h.innerHTML="",h.appendChild(Q))},2e3)}).catch(le=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",le)}),fe.onCopy(D)}}else if(W==="read-aloud")$.toggleReadAloud(S);else if(W==="upvote"||W==="downvote"){let D=((q=qr.get(S))!=null?q:null)===W,de=W==="upvote"?"thumbs-up":"thumbs-down";if(D){qr.delete(S),h.classList.remove("persona-message-action-active");let le=ge(de,14,"currentColor",2);le&&(h.innerHTML="",h.appendChild(le))}else{let le=W==="upvote"?"downvote":"upvote",Q=b.querySelector(`[data-action="${le}"]`);if(Q){Q.classList.remove("persona-message-action-active");let Ue=ge(le==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ue&&(Q.innerHTML="",Q.appendChild(Ue))}qr.set(S,W),h.classList.add("persona-message-action-active");let we=ge(de,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 Ee=$.getMessages().find(Ze=>Ze.id===S);Ee&&fe.onFeedback&&fe.onFeedback({type:W,messageId:Ee.id,message:Ee})}}}),nt.addEventListener("click",c=>{let h=c.target.closest("button[data-approval-action]");if(!h)return;c.preventDefault(),c.stopPropagation();let b=h.closest(".persona-approval-bubble");if(!b)return;let S=b.getAttribute("data-message-id");if(!S)return;let W=h.getAttribute("data-approval-action");if(!W)return;let q=W==="approve"?"approved":"denied",D=$.getMessages().find(le=>le.id===S);if(!(D!=null&&D.approval))return;let de=b.querySelector("[data-approval-buttons]");de&&de.querySelectorAll("button").forEach(Q=>{Q.disabled=!0,Q.style.opacity="0.5",Q.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?$.resolveWebMcpApproval(S,q):$.resolveApproval(D.approval,q)});let yt=null,Wn=null,Hn={artifacts:[],selectedId:null},Cn=!1,wt={current:null};nt.addEventListener("click",c=>{var Q,we,Fe,Ee,Ze;let h=c.target.closest("[data-download-artifact]");if(!h)return;c.preventDefault(),c.stopPropagation();let b=h.getAttribute("data-download-artifact");if(!b||((Fe=(we=(Q=r.features)==null?void 0:Q.artifacts)==null?void 0:we.onArtifactAction)==null?void 0:Fe.call(we,{type:"download",artifactId:b}))===!0)return;let W=$.getArtifactById(b),q=W==null?void 0:W.markdown,_=(W==null?void 0:W.title)||"artifact";if(!q){let Ue=h.closest("[data-open-artifact]"),ct=Ue==null?void 0:Ue.closest("[data-message-id]"),rt=ct==null?void 0:ct.getAttribute("data-message-id");if(rt){let Pe=$.getMessages().find(ze=>ze.id===rt);if(Pe!=null&&Pe.rawContent)try{let ze=JSON.parse(Pe.rawContent);q=(Ee=ze==null?void 0:ze.props)==null?void 0:Ee.markdown,_=((Ze=ze==null?void 0:ze.props)==null?void 0:Ze.title)||_}catch{}}}if(!q)return;let D=new Blob([q],{type:"text/markdown"}),de=URL.createObjectURL(D),le=document.createElement("a");le.href=de,le.download=`${_}.md`,le.click(),URL.revokeObjectURL(de)}),nt.addEventListener("click",c=>{var W,q,_;let h=c.target.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||((_=(q=(W=r.features)==null?void 0:W.artifacts)==null?void 0:q.onArtifactAction)==null?void 0:_.call(q,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),Cn=!1,$.selectArtifact(b),Er())}),nt.addEventListener("keydown",c=>{if(c.key!=="Enter"&&c.key!==" ")return;let m=c.target;m.hasAttribute("data-open-artifact")&&(c.preventDefault(),m.click())});let zn=qe.composerOverlay,Vn=(c,m,h)=>{var _,D,de,le;let b=m.trim();if(!b||!wt.current)return;let S=(_=c.getAttribute("data-tool-call-id"))!=null?_:"",W=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:S,answer:b,answers:h.structured,values:(D=h.values)!=null?D:h.source==="multi"?b.split(", "):[b],isFreeText:W,source:h.source},bubbles:!0,composed:!0})),Jo(zn,S);let q=wt.current.getMessages().find(Q=>{var we;return((we=Q.toolCall)==null?void 0:we.id)===S});(de=q==null?void 0:q.agentMetadata)!=null&&de.awaitingLocalTool?wt.current.resolveAskUserQuestion(q,(le=h.structured)!=null?le:b):wt.current.sendMessage(b)},Bn=c=>{var S;let m=wt.current;if(!m)return;let h=(S=c.getAttribute("data-tool-call-id"))!=null?S:"",b=m.getMessages().find(W=>{var q;return((q=W.toolCall)==null?void 0:q.id)===h});b&&m.persistAskUserQuestionProgress(b,{answers:Na(c,b),currentIndex:tr(c)})},lo=c=>Object.entries(c).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Ce=c=>{var S,W,q;if(((W=(S=r.features)==null?void 0:S.askUserQuestion)==null?void 0:W.groupedAutoAdvance)===!1)return;let m=tr(c),h=vs(c);if(m>=h-1)return;let b=(q=wt.current)==null?void 0:q.getMessages().find(_=>{var D;return((D=_.toolCall)==null?void 0:D.id)===c.getAttribute("data-tool-call-id")});b&&(Oa(c,b,r,m+1),Bn(c))};zn.addEventListener("click",c=>{var W,q,_,D,de,le,Q,we,Fe,Ee,Ze,Ue,ct,rt;let h=c.target.closest("[data-ask-user-action]");if(!h)return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;let S=h.getAttribute("data-ask-user-action");if(c.preventDefault(),c.stopPropagation(),S==="dismiss"){let Re=(W=b.getAttribute("data-tool-call-id"))!=null?W:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),Jo(zn,Re);let Pe=(q=wt.current)==null?void 0:q.getMessages().find(ze=>{var Ke;return((Ke=ze.toolCall)==null?void 0:Ke.id)===Re});(_=Pe==null?void 0:Pe.agentMetadata)!=null&&_.awaitingLocalTool&&((D=wt.current)==null||D.markAskUserQuestionResolved(Pe),(de=wt.current)==null||de.resolveAskUserQuestion(Pe,"(dismissed)"));return}if(S==="pick"){let Re=h.getAttribute("data-option-label");if(!Re)return;let Pe=b.getAttribute("data-multi-select")==="true",ze=wo(b);if(ze&&Pe){let Ke=Go(b)[tr(b)],gt=new Set(Array.isArray(Ke)?Ke:[]);gt.has(Re)?gt.delete(Re):gt.add(Re),Co(b,Array.from(gt)),Bn(b);return}if(ze){Co(b,Re),Bn(b),Ce(b);return}if(Pe){let Ke=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ke?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ke);let gt=b.querySelector('[data-ask-user-action="submit-multi"]');gt&&(gt.disabled=Yi(b).length===0);return}Vn(b,Re,{source:"pick",values:[Re]});return}if(S==="submit-multi"){let Re=Yi(b);if(Re.length===0)return;Vn(b,Re.join(", "),{source:"multi",values:Re});return}if(S==="open-free-text"){let Re=b.querySelector('[data-ask-free-text-row="true"]');if(Re){Re.classList.remove("persona-hidden");let Pe=Re.querySelector('[data-ask-free-text-input="true"]');Pe==null||Pe.focus()}return}if(S==="focus-free-text"){let Re=b.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus();return}if(S==="submit-free-text"){let Re=b.querySelector('[data-ask-free-text-input="true"]'),Pe=(le=Re==null?void 0:Re.value)!=null?le:"";if(!Pe.trim())return;if(wo(b)){Co(b,Pe.trim()),Bn(b),Ce(b);return}Vn(b,Pe,{source:"free-text"});return}if(S==="next"||S==="back"){if(!wt.current)return;let Re=(Q=b.getAttribute("data-tool-call-id"))!=null?Q:"",Pe=wt.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Re});if(!Pe)return;let ze=b.querySelector('[data-ask-free-text-input="true"]'),Ke=(Fe=(we=ze==null?void 0:ze.value)==null?void 0:we.trim())!=null?Fe:"";if(Ke){let De=Go(b)[tr(b)];(typeof De!="string"||De!==Ke)&&Co(b,Ke)}let gt=S==="next"?1:-1,I=tr(b)+gt;Oa(b,Pe,r,I),Bn(b);return}if(S==="submit-all"){if(!wt.current)return;let Re=(Ee=b.getAttribute("data-tool-call-id"))!=null?Ee:"",Pe=wt.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Re});if(!Pe)return;let ze=b.querySelector('[data-ask-free-text-input="true"]'),Ke=(Ue=(Ze=ze==null?void 0:ze.value)==null?void 0:Ze.trim())!=null?Ue:"";Ke&&Co(b,Ke);let gt=Na(b,Pe);wt.current.persistAskUserQuestionProgress(Pe,{answers:gt,currentIndex:tr(b)});let I=lo(gt);Vn(b,I||"(submitted)",{source:"submit-all",structured:gt});return}if(S==="skip"){if(!wt.current)return;let Re=(ct=b.getAttribute("data-tool-call-id"))!=null?ct:"",Pe=wt.current.getMessages().find(We=>{var me;return((me=We.toolCall)==null?void 0:me.id)===Re});if(!Pe)return;let ze=wo(b),Ke=tr(b),gt=vs(b),I=Ke>=gt-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Re},bubbles:!0,composed:!0})),Jo(zn,Re),(rt=Pe.agentMetadata)!=null&&rt.awaitingLocalTool&&(wt.current.markAskUserQuestionResolved(Pe),wt.current.resolveAskUserQuestion(Pe,"(dismissed)"));return}Co(b,"");let De=b.querySelector('[data-ask-free-text-input="true"]');if(De&&(De.value=""),I){let We=Na(b,Pe),me=lo(We);Vn(b,me||"(skipped)",{source:"submit-all",structured:We});return}Oa(b,Pe,r,Ke+1),Bn(b);return}}),zn.addEventListener("keydown",c=>{var W;if(c.key!=="Enter")return;let h=c.target;if(!((W=h.matches)!=null&&W.call(h,'[data-ask-free-text-input="true"]')))return;let b=h.closest("[data-persona-ask-sheet-for]");if(!b)return;c.preventDefault();let S=h.value;if(S.trim()){if(wo(b)){Co(b,S.trim()),Bn(b),Ce(b);return}Vn(b,S,{source:"free-text"})}});let zr=c=>{if(!/^[1-9]$/.test(c.key)||c.metaKey||c.ctrlKey||c.altKey)return;let m=c.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let h=zn.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let b=Number(c.key),W=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[b-1];W&&(c.preventDefault(),W.click())};document.addEventListener("keydown",zr);let Kn=null,_t=null,Gn=null,Vr=null,Hs=()=>{};function ss(){Vr==null||Vr(),Vr=null}let Bs=()=>{var q;if(!Kn||!_t)return;let c=e.classList.contains("persona-artifact-appearance-seamless"),h=((q=e.ownerDocument.defaultView)!=null?q:window).innerWidth<=640;if(!c||e.classList.contains("persona-artifact-narrow-host")||h){_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=Kn.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`},Bo=()=>{},Er=()=>{var h,b,S,W,q;if(!yt||!or(r))return;wi(e,r),Ci(e,r),Bo();let c=(W=(S=(b=(h=r.features)==null?void 0:h.artifacts)==null?void 0:b.layout)==null?void 0:S.narrowHostMaxWidth)!=null?W:520,m=J.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=c),yt.update(Hn),Cn?(yt.setMobileOpen(!1),yt.element.classList.add("persona-hidden"),(q=yt.backdrop)==null||q.classList.add("persona-hidden")):Hn.artifacts.length>0&&(yt.element.classList.remove("persona-hidden"),yt.setMobileOpen(!0)),Hs()};if(or(r)){J.style.position="relative";let c=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");c.appendChild(Se),yt=Bg(r,{onSelect:h=>{var b;return(b=wt.current)==null?void 0:b.selectArtifact(h)},onDismiss:()=>{Cn=!0,Er()}}),yt.element.classList.add("persona-hidden"),Kn=m,m.appendChild(c),m.appendChild(yt.element),yt.backdrop&&J.appendChild(yt.backdrop),J.appendChild(m),Hs=()=>{var b,S,W,q;if(!Kn||!yt)return;if(!(((W=(S=(b=r.features)==null?void 0:b.artifacts)==null?void 0:S.layout)==null?void 0:W.resizable)===!0)){Gn==null||Gn(),Gn=null,ss(),_t&&(_t.remove(),_t=null),yt.element.style.removeProperty("width"),yt.element.style.removeProperty("maxWidth");return}if(!_t){let _=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");_.setAttribute("role","separator"),_.setAttribute("aria-orientation","vertical"),_.setAttribute("aria-label","Resize artifacts panel"),_.tabIndex=0;let D=e.ownerDocument,de=(q=D.defaultView)!=null?q:window,le=Q=>{var ct,rt;if(!yt||Q.button!==0||e.classList.contains("persona-artifact-narrow-host")||de.innerWidth<=640)return;Q.preventDefault(),ss();let we=Q.clientX,Fe=yt.element.getBoundingClientRect().width,Ee=(rt=(ct=r.features)==null?void 0:ct.artifacts)==null?void 0:rt.layout,Ze=Re=>{let Pe=Kn.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),Ke=ze?0:Fg(Kn,de),gt=ze?0:_.getBoundingClientRect().width||6,I=Fe-(Re.clientX-we),De=_g(I,Pe,Ke,gt,Ee==null?void 0:Ee.resizableMinWidth,Ee==null?void 0:Ee.resizableMaxWidth);yt.element.style.width=`${De}px`,yt.element.style.maxWidth="none",Bs()},Ue=()=>{D.removeEventListener("pointermove",Ze),D.removeEventListener("pointerup",Ue),D.removeEventListener("pointercancel",Ue),Vr=null;try{_.releasePointerCapture(Q.pointerId)}catch{}};Vr=Ue,D.addEventListener("pointermove",Ze),D.addEventListener("pointerup",Ue),D.addEventListener("pointercancel",Ue);try{_.setPointerCapture(Q.pointerId)}catch{}};_.addEventListener("pointerdown",le),_t=_,Kn.insertBefore(_,yt.element),Gn=()=>{_.removeEventListener("pointerdown",le)}}if(_t){let _=Hn.artifacts.length>0&&!Cn;_t.classList.toggle("persona-hidden",!_),Bs()}},Bo=()=>{var de,le,Q,we,Fe,Ee,Ze,Ue,ct,rt,Re,Pe,ze,Ke;if(!k||!yt||((le=(de=r.launcher)==null?void 0:de.sidebarMode)!=null?le:!1)||dn(r)&&rr(r).reveal==="emerge")return;let b=(Q=e.ownerDocument.defaultView)!=null?Q:window,S=(Fe=(we=r.launcher)==null?void 0:we.mobileFullscreen)!=null?Fe:!0,W=(Ze=(Ee=r.launcher)==null?void 0:Ee.mobileBreakpoint)!=null?Ze:640;if(S&&b.innerWidth<=W||!Og(r,k))return;let q=(rt=(ct=(Ue=r.launcher)==null?void 0:Ue.width)!=null?ct:r.launcherWidth)!=null?rt:nr,_=(Ke=(ze=(Pe=(Re=r.features)==null?void 0:Re.artifacts)==null?void 0:Pe.layout)==null?void 0:ze.expandedPanelWidth)!=null?Ke:"min(720px, calc(100vw - 24px))";Hn.artifacts.length>0&&!Cn?(J.style.width=_,J.style.maxWidth=_):(J.style.width=q,J.style.maxWidth=q)},typeof ResizeObserver!="undefined"&&(Wn=new ResizeObserver(()=>{Er()}),Wn.observe(J))}else J.appendChild(Se),H()&&dt&&(qe.peekBanner&&dt.appendChild(qe.peekBanner),dt.appendChild(Oe));e.appendChild(ye),dt&&e.appendChild(dt);let co=()=>{var De,We,me,Wt,It,Vt,ft,jt,Fn,Zt,Je,Tt,nn,Zn,_n,_o,$o,gs,fs,Gt,jo,ho,yo,Qr,Uo,gr,Hr,Qe;if(H()){J.style.width="100%",J.style.maxWidth="100%";let Ht=(We=(De=r.launcher)==null?void 0:De.composerBar)!=null?We:{},zt=ye.dataset.state==="expanded",Bt=(me=Ht.expandedSize)!=null?me:"anchored";if(!(zt&&Bt!=="fullscreen")){Se.style.background="",Se.style.border="",Se.style.borderRadius="",Se.style.overflow="",Se.style.boxShadow="";return}let Et=(It=(Wt=r.theme)==null?void 0:Wt.components)==null?void 0:It.panel,Nt=ua(r),un=(gn,er)=>{var bo;return gn==null||gn===""?er:(bo=Es(Nt,gn))!=null?bo:gn},$n="1px solid var(--persona-border)",Br="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",mn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Se.style.background="var(--persona-surface, #ffffff)",Se.style.border=un(Et==null?void 0:Et.border,$n),Se.style.borderRadius=un(Et==null?void 0:Et.borderRadius,mn),Se.style.boxShadow=un(Et==null?void 0:Et.shadow,Br),Se.style.overflow="hidden";return}let c=dn(r),m=(ft=(Vt=r.launcher)==null?void 0:Vt.sidebarMode)!=null?ft:!1,h=c||m||((Fn=(jt=r.launcher)==null?void 0:jt.fullHeight)!=null?Fn:!1),b=((Zt=r.launcher)==null?void 0:Zt.enabled)===!1,S=(Tt=(Je=r.theme)==null?void 0:Je.components)==null?void 0:Tt.panel,W=ua(r),q=(Ht,zt)=>{var Bt;return Ht==null||Ht===""?zt:(Bt=Es(W,Ht))!=null?Bt:Ht},_=(nn=e.ownerDocument.defaultView)!=null?nn:window,D=(_n=(Zn=r.launcher)==null?void 0:Zn.mobileFullscreen)!=null?_n:!0,de=($o=(_o=r.launcher)==null?void 0:_o.mobileBreakpoint)!=null?$o:640,le=_.innerWidth<=de,Q=D&&le&&k,we=(fs=(gs=r.launcher)==null?void 0:gs.position)!=null?fs:"bottom-left",Fe=we==="bottom-left"||we==="top-left",Ee=(jo=(Gt=r.launcher)==null?void 0:Gt.zIndex)!=null?jo:vn,Ze=m||Q?"none":"1px solid var(--persona-border)",Ue=Q?"none":m?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))";c&&!Q&&(Ue="none",Ze="none");let ct=m||Q?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",rt=q(S==null?void 0:S.border,Ze),Re=q(S==null?void 0:S.shadow,Ue),Pe=q(S==null?void 0:S.borderRadius,ct),ze=ve.scrollTop;e.style.cssText="",ye.style.cssText="",J.style.cssText="",Se.style.cssText="",ve.style.cssText="",Oe.style.cssText="",K&&(ve.style.display="none");let Ke=()=>{var zt;if(ze<=0)return;((zt=ve.ownerDocument.defaultView)!=null?zt:window).requestAnimationFrame(()=>{if(ve.scrollTop===ze)return;let Bt=ve.scrollHeight-ve.clientHeight;Bt<=0||(ve.scrollTop=Math.min(ze,Bt))})};if(Q){ye.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"),ye.style.cssText=`
34
+ `,I.addEventListener("click",()=>{u=C,T.forEach((j,$)=>{let R=$<C;j.classList.toggle("selected",R),j.setAttribute("aria-checked",$===C-1?"true":"false")})}),T.push(I),S.appendChild(I)}f.appendChild(S);let L=null;if(d){let C=document.createElement("div");C.className="persona-feedback-comment-container",L=document.createElement("textarea"),L.className="persona-feedback-comment",L.placeholder=s,L.rows=3,L.setAttribute("aria-label","Additional comments"),C.appendChild(L),f.appendChild(C)}let P=document.createElement("div");P.className="persona-feedback-actions";let E=document.createElement("button");E.type="button",E.className="persona-feedback-btn persona-feedback-btn-skip",E.textContent=i,E.addEventListener("click",()=>{n==null||n(),p.remove()});let k=document.createElement("button");return k.type="button",k.className="persona-feedback-btn persona-feedback-btn-submit",k.textContent=a,k.addEventListener("click",async()=>{if(u===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}k.disabled=!0,k.textContent="Submitting...";try{let C=(L==null?void 0:L.value.trim())||void 0;await t(u,C),p.remove()}catch(C){k.disabled=!1,k.textContent=a,console.error("[CSAT Feedback] Failed to submit:",C)}}),P.appendChild(E),P.appendChild(k),f.appendChild(P),p.appendChild(f),p}function Vl(e){let{onSubmit:t,onDismiss:n,title:r="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let b=document.createElement("div");b.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,b.appendChild(v);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=o,b.appendChild(S),g.appendChild(b);let T=document.createElement("div");T.className="persona-feedback-rating persona-feedback-rating-nps",T.setAttribute("role","radiogroup"),T.setAttribute("aria-label","Likelihood rating from 0 to 10");let L=document.createElement("div");L.className="persona-feedback-labels";let P=document.createElement("span");P.className="persona-feedback-label-low",P.textContent=c;let E=document.createElement("span");E.className="persona-feedback-label-high",E.textContent=p,L.appendChild(P),L.appendChild(E);let k=document.createElement("div");k.className="persona-feedback-numbers";let C=[];for(let N=0;N<=10;N++){let O=document.createElement("button");O.type="button",O.className="persona-feedback-rating-btn persona-feedback-number-btn",O.setAttribute("role","radio"),O.setAttribute("aria-checked","false"),O.setAttribute("aria-label",`Rating ${N} out of 10`),O.textContent=String(N),O.dataset.rating=String(N),N<=6?O.classList.add("persona-feedback-detractor"):N<=8?O.classList.add("persona-feedback-passive"):O.classList.add("persona-feedback-promoter"),O.addEventListener("click",()=>{f=N,C.forEach((Z,Ee)=>{Z.classList.toggle("selected",Ee===N),Z.setAttribute("aria-checked",Ee===N?"true":"false")})}),C.push(O),k.appendChild(O)}T.appendChild(L),T.appendChild(k),g.appendChild(T);let I=null;if(d){let N=document.createElement("div");N.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=s,I.rows=3,I.setAttribute("aria-label","Additional comments"),N.appendChild(I),g.appendChild(N)}let j=document.createElement("div");j.className="persona-feedback-actions";let $=document.createElement("button");$.type="button",$.className="persona-feedback-btn persona-feedback-btn-skip",$.textContent=i,$.addEventListener("click",()=>{n==null||n(),u.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(f===null){k.classList.add("persona-feedback-shake"),setTimeout(()=>k.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let N=(I==null?void 0:I.value.trim())||void 0;await t(f,N),u.remove()}catch(N){R.disabled=!1,R.textContent=a,console.error("[NPS Feedback] Failed to submit:",N)}}),j.appendChild($),j.appendChild(R),g.appendChild(j),u.appendChild(g),u}var Bs="persona-chat-history",Lw=30*1e3,Pw={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function Iw(e){var r,o,s;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(o=Pw[i.type])!=null?o:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Mi(e){if(!e)return!1;let t=e.types;return t?typeof t.contains=="function"?t.contains("Files"):Array.from(t).includes("Files"):!1}function Rw(e){var t,n,r,o,s,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function Ww(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Kl=e=>!e||typeof e!="object"?{}:{...e},nf=e=>e.map(t=>({...t,streaming:!1})),rf=(e,t,n)=>{let r=e!=null&&e.markdown?vs(e.markdown):null,o=Xs(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&o&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),s=>{var p,u,f;let a=(p=s.text)!=null?p:"",i=(u=s.message.rawContent)!=null?u:null;if(t){let g=t.process({text:a,raw:i!=null?i:a,message:s.message,streaming:s.streaming});g!==null&&(a=g.text,g.persist||(s.message.__skipPersist=!0),g.resubmit&&!s.streaming&&n&&n())}let d=Vo()!==null,c;if(e!=null&&e.postprocessMessage){let g=e.postprocessMessage({...s,text:a,raw:(f=i!=null?i:s.text)!=null?f:""});c=o?o(g):g}else if(r){let g=s.streaming?rm(a):a,b=r(g);c=o&&d?o(b):b}else c=Kr(a);return c}};function of(e){var i,d,c,p;let t=y("div","persona-attachment-drop-overlay");e!=null&&e.background&&t.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&t.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&t.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&t.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&t.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&t.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&t.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let n=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(d=e==null?void 0:e.iconSize)!=null?d:"48px",o=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",s=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=ye(n,r,o,s);if(a&&t.appendChild(a),e!=null&&e.label){let u=y("span","persona-drop-overlay-label");u.textContent=e.label,t.appendChild(u)}return t}var Gl=(e,t,n)=>{var $c,jc,Uc,qc,zc,Vc,Kc,Gc,Jc,Xc,Qc,Yc,Zc,ed,td,nd,rd,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,yd,bd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Rd,Wd,Hd,Bd,Dd;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=hl(t),o=Si.getForInstance(r.plugins),{plugin:s,teardown:a}=Og();r.components&&Mo.registerAll(r.components);let i=Zg(),c=r.persistState===!1?null:($c=r.storageAdapter)!=null?$c:_l(),p={},u=null,f=!1,g=l=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:h,open:x}=m;return x&&(f=!0),h}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return l};if(c!=null&&c.load)try{let l=c.load();if(l&&typeof l.then=="function")u=l.then(m=>{let h=m!=null?m:{messages:[],metadata:{}};return g(h)});else{let m=l!=null?l:{messages:[],metadata:{}},h=g(m);h.metadata&&(p=Kl(h.metadata)),(jc=h.messages)!=null&&jc.length&&(r={...r,initialMessages:h.messages}),(Uc=h.artifacts)!=null&&Uc.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(qc=h.selectedArtifactId)!=null?qc:null})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=g({messages:[],metadata:{}});(zc=l.messages)!=null&&zc.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let b=()=>p,v=l=>{var h;p=(h=l({...p}))!=null?h:{},Pn()},S=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ti],T=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Hs.message,Hs.messageAndClick],L=Ei({parsers:S,handlers:T,getSessionMetadata:b,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null});L.syncFromMetadata();let P=(Kc=(Vc=r.launcher)==null?void 0:Vc.enabled)!=null?Kc:!0,E=(Jc=(Gc=r.launcher)==null?void 0:Gc.autoExpand)!=null?Jc:!1,k=(Xc=r.autoFocusInput)!=null?Xc:!1,C=E,I=P,j=(Yc=(Qc=r.layout)==null?void 0:Qc.header)==null?void 0:Yc.layout,$=!1,R=()=>To(r),N=()=>P||R(),O=R()?!1:P?E:!0,Z=!1,Ee=null,de=()=>{Z=!0,Ee&&clearTimeout(Ee),Ee=setTimeout(()=>{Z&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Z=!1)},1e4)},ee=rf(r,L,de),Le=(ed=(Zc=r.features)==null?void 0:Zc.showReasoning)!=null?ed:!0,Pe=(nd=(td=r.features)==null?void 0:td.showToolCalls)!=null?nd:!0,ne=(od=(rd=r.features)==null?void 0:rd.showEventStreamToggle)!=null?od:!1,Ae=(ad=(sd=r.features)==null?void 0:sd.scrollToBottom)!=null?ad:{},re=(ld=(id=r.features)==null?void 0:id.scrollBehavior)!=null?ld:{},ae=`${(dd=typeof r.persistState=="object"?(cd=r.persistState)==null?void 0:cd.keyPrefix:void 0)!=null?dd:"persona-"}event-stream`,fe=ne?new Sa(ae):null,$e=(md=(ud=(pd=r.features)==null?void 0:pd.eventStream)==null?void 0:ud.maxEvents)!=null?md:2e3,V=ne?new Aa($e,fe):null,Q=ne?new Ta:null,Me=null,J=!1,le=null,Ie=0;fe==null||fe.open().then(()=>V==null?void 0:V.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let he={onCopy:l=>{var m,h;i.emit("message:copy",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.id,"copy").catch(x=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",x)}),(h=(m=r.messageActions)==null?void 0:m.onCopy)==null||h.call(m,l)},onFeedback:l=>{var m,h;i.emit("message:feedback",l),F!=null&&F.isClientTokenMode()&&F.submitMessageFeedback(l.messageId,l.type).catch(x=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",x)}),(h=(m=r.messageActions)==null?void 0:m.onFeedback)==null||h.call(m,l)}},Ke=(gd=r.statusIndicator)!=null?gd:{},gt=l=>{var m,h,x,A,W,U;return l==="idle"?(m=Ke.idleText)!=null?m:nn.idle:l==="connecting"?(h=Ke.connectingText)!=null?h:nn.connecting:l==="connected"?(x=Ke.connectedText)!=null?x:nn.connected:l==="error"?(A=Ke.errorText)!=null?A:nn.error:l==="paused"?(W=Ke.pausedText)!=null?W:nn.paused:l==="resuming"?(U=Ke.resumingText)!=null?U:nn.resuming:nn[l]};function Wt(l,m,h,x){if(x==="idle"&&h.idleLink){l.textContent="";let A=document.createElement("a");A.href=h.idleLink,A.target="_blank",A.rel="noopener noreferrer",A.textContent=m,A.style.color="inherit",A.style.textDecoration="none",l.appendChild(A)}else l.textContent=m}let tt=Sg({config:r,showClose:N()}),{wrapper:ge,panel:X,pillRoot:it}=tt.shell,Ve=tt.panelElements,{container:Se,body:we,messagesWrapper:Ze,suggestions:qt,textarea:be,sendButton:pe,sendButtonWrapper:vn,composerForm:Ct,statusText:fn,introTitle:yr,introSubtitle:br,closeButton:Ue,iconHolder:M,headerTitle:ue,headerSubtitle:Te,header:ke,footer:He,actionsRow:nt,leftActions:Qe,rightActions:ht}=Ve,me=Ve.setSendButtonMode,B=Ve.micButton,xe=Ve.micButtonWrapper,ce=Ve.attachmentButton,ft=Ve.attachmentButtonWrapper,Je=Ve.attachmentInput,Lt=Ve.attachmentPreviewsContainer;Se.classList.add("persona-relative"),we.classList.add("persona-relative");let Mt=12,xt=()=>{var l;return(l=Ae.label)!=null?l:""},Rt=()=>{var l;return(l=Ae.iconName)!=null?l:"arrow-down"},Xt=()=>Ae.enabled!==!1,Ot=()=>{var l;return(l=re.mode)!=null?l:"anchor-top"},en=()=>Ot()==="follow"||Ot()==="anchor-top"&&so,xr=()=>{var l;return(l=re.anchorTopOffset)!=null?l:16},Nr=()=>{var l;return(l=re.restorePosition)!=null?l:"bottom"},or=()=>re.pauseOnInteraction===!0,sr=()=>re.showActivityWhilePinned!==!1,Xr=()=>re.announce===!0,zt=y("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");zt.type="button",zt.style.display="none",zt.setAttribute("data-persona-scroll-to-bottom","true");let ar=y("span","persona-flex persona-items-center"),Or=y("span",""),Hn=y("span","");Hn.setAttribute("data-persona-scroll-to-bottom-count",""),Hn.style.display="none",zt.append(ar,Or,Hn),Se.appendChild(zt);let kn=y("div","persona-stream-anchor-spacer");kn.setAttribute("aria-hidden","true"),kn.setAttribute("data-persona-anchor-spacer",""),kn.style.flexShrink="0",kn.style.pointerEvents="none",kn.style.height="0px",we.appendChild(kn);let Bn=y("div","persona-sr-only");Bn.setAttribute("aria-live","polite"),Bn.setAttribute("aria-atomic","true"),Bn.setAttribute("role","status"),Bn.setAttribute("data-persona-live-region",""),Object.assign(Bn.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),Se.appendChild(Bn);let ir=null,vr=null,Qr=l=>{!Xr()||!l||(vr=l,ir===null&&(ir=setTimeout(()=>{ir=null,vr&&Xr()&&(Bn.textContent=vr),vr=null},400)))},zn=()=>{let m=He.style.display==="none"?0:He.offsetHeight;zt.style.bottom=`${m+Mt}px`};zn();let Yr=()=>{let l=!!xt();zt.setAttribute("aria-label",xt()||"Jump to latest"),zt.title=xt(),zt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),ar.innerHTML="";let m=ye(Rt(),"14px","currentColor",2);m?(ar.appendChild(m),ar.style.display=""):ar.style.display="none",Or.textContent=xt(),Or.style.display=l?"":"none"};Yr();let At=null,wr=null,Cr=o.find(l=>l.renderHeader);if(Cr!=null&&Cr.renderHeader){let l=Cr.renderHeader({config:r,defaultRenderer:()=>{let m=Eo({config:r,showClose:N()});return Ls(Se,m,r),m.header},onClose:()=>_t(!1,"user")});if(l){let m=Se.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),ke=l,tt.header.element=l)}}let Fr=()=>{var m,h,x,A;if(!V)return;if(J=!0,!Me&&V&&(Me=Ug({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>lr(),config:r,plugins:o,getThroughput:()=>{var W;return(W=Q==null?void 0:Q.getMetric())!=null?W:{status:"idle"}}})),Me&&(we.style.display="none",(m=He.parentNode)==null||m.insertBefore(Me.element,He),Me.update()),yt){yt.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let W=(A=(x=(h=r.features)==null?void 0:h.eventStream)==null?void 0:x.classNames)==null?void 0:A.toggleButtonActive;W&&W.split(/\s+/).forEach(U=>U&&yt.classList.add(U))}let l=()=>{if(!J)return;let W=Date.now();W-Ie>=200&&(Me==null||Me.update(),Ie=W),le=requestAnimationFrame(l)};Ie=0,le=requestAnimationFrame(l),Fn(),i.emit("eventStream:opened",{timestamp:Date.now()})},lr=()=>{var l,m,h;if(J){if(J=!1,Me&&Me.element.remove(),we.style.display="",yt){yt.style.boxShadow="";let x=(h=(m=(l=r.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:h.toggleButtonActive;x&&x.split(/\s+/).forEach(A=>A&&yt.classList.remove(A))}le!==null&&(cancelAnimationFrame(le),le=null),Fn(),i.emit("eventStream:closed",{timestamp:Date.now()})}},yt=null;if(ne){let l=(hd=(fd=r.features)==null?void 0:fd.eventStream)==null?void 0:hd.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");yt=y("button",m),yt.style.width="28px",yt.style.height="28px",yt.style.color=Mn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let h=ye("activity","18px","currentColor",1.5);h&&yt.appendChild(h);let x=Ve.clearChatButtonWrapper,A=Ve.closeButtonWrapper,W=x||A;W&&W.parentNode===ke?ke.insertBefore(yt,W):ke.appendChild(yt),yt.addEventListener("click",()=>{J?lr():Fr()})}let Lo=l=>{var A,W,U,_,D;let m=r.attachments;if(!(m!=null&&m.enabled))return;let h=(A=l.querySelector("[data-persona-composer-attachment-previews]"))!=null?A:l.querySelector(".persona-attachment-previews");if(!h){h=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.setAttribute("data-persona-composer-attachment-previews",""),h.style.display="none";let ie=l.querySelector("[data-persona-composer-form]");ie!=null&&ie.parentNode?ie.parentNode.insertBefore(h,ie):l.insertBefore(h,l.firstChild)}if(!((W=l.querySelector("[data-persona-composer-attachment-input]"))!=null?W:l.querySelector('input[type="file"]'))){let ie=y("input");ie.type="file",ie.setAttribute("data-persona-composer-attachment-input",""),ie.accept=((U=m.allowedTypes)!=null?U:Gr).join(","),ie.multiple=((_=m.maxFiles)!=null?_:4)>1,ie.style.display="none",ie.setAttribute("aria-label",(D=m.buttonTooltipText)!=null?D:"Attach files"),l.appendChild(ie)}},Ar=o.find(l=>l.renderComposer);if(Ar!=null&&Ar.renderComposer){let l=r.composer,m=Ar.renderComposer({config:r,defaultRenderer:()=>wa({config:r}).footer,onSubmit:h=>{var U;if(!F||F.isStreaming())return;let x=h.trim(),A=(U=At==null?void 0:At.hasAttachments())!=null?U:!1;if(!x&&!A)return;hc();let W;A&&(W=[],W.push(...At.getContentParts()),x&&W.push(Ka(x))),F.sendMessage(x,{contentParts:W}),A&&At.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Je==null||Je.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h},r.agent&&(r.agent={...r.agent,model:h})},onVoiceToggle:((yd=r.voiceRecognition)==null?void 0:yd.enabled)===!0?()=>{wr==null||wr()}:void 0});m&&(tt.replaceComposer(m),He=tt.composer.footer)}let Po=l=>{let m=(...oe)=>{for(let Y of oe){let ve=l.querySelector(Y);if(ve)return ve}return null},h=l.querySelector("[data-persona-composer-form]"),x=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),W=l.querySelector("[data-persona-composer-mic]"),U=l.querySelector("[data-persona-composer-status]");h&&(Ct=h),x&&(be=x),A&&(pe=A),W&&(B=W,xe=W.parentElement),U&&(fn=U);let _=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(qt=_);let D=m("[data-persona-composer-attachment-button]",".persona-attachment-button");D&&(ce=D,ft=D.parentElement),Je=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Lt=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ie=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ie&&(nt=ie)};Lo(He),Po(He);let Ln=(Cd=(bd=r.layout)==null?void 0:bd.contentMaxWidth)!=null?Cd:R()?(wd=(vd=(xd=r.launcher)==null?void 0:xd.composerBar)==null?void 0:vd.contentMaxWidth)!=null?wd:"720px":void 0;if(Ln&&(Ze.style.maxWidth=Ln,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%"),Ln&&Ct&&!R()&&(Ct.style.maxWidth=Ln,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),Ln&&qt&&!R()&&(qt.style.maxWidth=Ln,qt.style.marginLeft="auto",qt.style.marginRight="auto"),Ln&&Lt&&!R()&&(Lt.style.maxWidth=Ln,Lt.style.marginLeft="auto",Lt.style.marginRight="auto"),(Ad=r.attachments)!=null&&Ad.enabled&&Je&&Lt){At=Es.fromConfig(r.attachments),At.setPreviewsContainer(Lt),Je.addEventListener("change",h=>{let x=h.target;At==null||At.handleFileSelect(x.files),x.value=""});let l=r.attachments.dropOverlay,m=of(l);Se.appendChild(m)}(()=>{var x,A;let l=(A=(x=r.layout)==null?void 0:x.slots)!=null?A:{},m=W=>{switch(W){case"body-top":return Se.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ze;case"footer-top":return qt;case"composer":return Ct;case"footer-bottom":return fn;default:return null}},h=(W,U)=>{var _;switch(W){case"header-left":case"header-center":case"header-right":if(W==="header-left")ke.insertBefore(U,ke.firstChild);else if(W==="header-right")ke.appendChild(U);else{let D=ke.querySelector(".persona-flex-col");D?(_=D.parentNode)==null||_.insertBefore(U,D.nextSibling):ke.appendChild(U)}break;case"body-top":{let D=we.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith(U):we.insertBefore(U,we.firstChild);break}case"body-bottom":we.appendChild(U);break;case"footer-top":qt.replaceWith(U);break;case"footer-bottom":fn.replaceWith(U);break;default:break}};for(let[W,U]of Object.entries(l))if(U)try{let _=U({config:r,defaultContent:()=>m(W)});_&&h(W,_)}catch(_){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${W}":`,_)}})();let Zr=l=>{var U,_;let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let x=h.closest(".persona-reasoning-bubble, .persona-tool-bubble, .persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let W=h.getAttribute("data-bubble-type");if(W==="reasoning")Is.has(A)?Is.delete(A):Is.add(A),Lg(A,x);else if(W==="tool")Rs.has(A)?Rs.delete(A):Rs.add(A),Pg(A,x,r);else if(W==="approval"){let D=r.approval!==!1?r.approval:void 0,ie=((U=D==null?void 0:D.detailsDisplay)!=null?U:"collapsed")==="expanded",oe=(_=ns.get(A))!=null?_:ie;ns.set(A,!oe),Hg(A,x,r)}Mr.delete(A)};Ze.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Zr(l))}),Ze.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Zr(l))}),Ze.addEventListener("copy",l=>{let{clipboardData:m}=l;if(!m)return;let h=Ze.getRootNode(),x=typeof h.getSelection=="function"?h.getSelection():window.getSelection();if(!x||x.isCollapsed)return;let A=x.toString(),W=og(A);!W||W===A||(m.setData("text/plain",W),l.preventDefault())});let _r=new Map,eo=null,to="idle",Io={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},Ro=(l,m)=>{let{icon:h,label:x}=Io[m];l.setAttribute("aria-label",x),l.title=x,l.setAttribute("aria-pressed",m==="idle"?"false":"true"),l.classList.toggle("persona-message-action-active",m!=="idle"),l.classList.toggle("persona-message-action-loading",m==="loading");let A=ye(h,14,"currentColor",2);A&&(l.innerHTML="",l.appendChild(A))},no=()=>{Ze.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{var W;let h=m.closest("[data-actions-for]"),x=(W=h==null?void 0:h.getAttribute("data-actions-for"))!=null?W:null;Ro(m,x&&x===eo?to:"idle")})};Ze.addEventListener("click",l=>{var U;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest("[data-actions-for]");if(!x)return;let A=x.getAttribute("data-actions-for");if(!A)return;let W=h.getAttribute("data-action");if(W==="copy"){let D=F.getMessages().find(ie=>ie.id===A);if(D&&he.onCopy){let ie=D.content||"";navigator.clipboard.writeText(ie).then(()=>{h.classList.add("persona-message-action-success");let oe=ye("check",14,"currentColor",2);oe&&(h.innerHTML="",h.appendChild(oe)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Y=ye("copy",14,"currentColor",2);Y&&(h.innerHTML="",h.appendChild(Y))},2e3)}).catch(oe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",oe)}),he.onCopy(D)}}else if(W==="read-aloud")F.toggleReadAloud(A);else if(W==="upvote"||W==="downvote"){let D=((U=_r.get(A))!=null?U:null)===W,ie=W==="upvote"?"thumbs-up":"thumbs-down";if(D){_r.delete(A),h.classList.remove("persona-message-action-active");let oe=ye(ie,14,"currentColor",2);oe&&(h.innerHTML="",h.appendChild(oe))}else{let oe=W==="upvote"?"downvote":"upvote",Y=x.querySelector(`[data-action="${oe}"]`);if(Y){Y.classList.remove("persona-message-action-active");let qe=ye(oe==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);qe&&(Y.innerHTML="",Y.appendChild(qe))}_r.set(A,W),h.classList.add("persona-message-action-active");let ve=ye(ie,14,"currentColor",2);ve&&(ve.setAttribute("fill","currentColor"),h.innerHTML="",h.appendChild(ve)),h.classList.remove("persona-message-action-pop"),h.offsetWidth,h.classList.add("persona-message-action-pop");let Fe=F.getMessages().find(je=>je.id===A);Fe&&he.onFeedback&&he.onFeedback({type:W,messageId:Fe.id,message:Fe})}}}),Ze.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.closest(".persona-approval-bubble");if(!x)return;let A=x.getAttribute("data-message-id");if(!A)return;let W=h.getAttribute("data-approval-action");if(!W)return;let U=W==="approve"?"approved":"denied",D=F.getMessages().find(oe=>oe.id===A);if(!(D!=null&&D.approval))return;let ie=x.querySelector("[data-approval-buttons]");ie&&ie.querySelectorAll("button").forEach(Y=>{Y.disabled=!0,Y.style.opacity="0.5",Y.style.cursor="not-allowed"}),D.approval.toolType==="webmcp"?F.resolveWebMcpApproval(A,U):F.resolveApproval(D.approval,U)});let vt=null,Dn=null,Nn={artifacts:[],selectedId:null},wn=!1,St={current:null};Ze.addEventListener("click",l=>{var Y,ve,Oe,Fe,je;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let x=h.getAttribute("data-download-artifact");if(!x||((Oe=(ve=(Y=r.features)==null?void 0:Y.artifacts)==null?void 0:ve.onArtifactAction)==null?void 0:Oe.call(ve,{type:"download",artifactId:x}))===!0)return;let W=F.getArtifactById(x),U=W==null?void 0:W.markdown,_=(W==null?void 0:W.title)||"artifact";if(!U){let qe=h.closest("[data-open-artifact]"),ut=qe==null?void 0:qe.closest("[data-message-id]"),st=ut==null?void 0:ut.getAttribute("data-message-id");if(st){let Re=F.getMessages().find(ze=>ze.id===st);if(Re!=null&&Re.rawContent)try{let ze=JSON.parse(Re.rawContent);U=(Fe=ze==null?void 0:ze.props)==null?void 0:Fe.markdown,_=((je=ze==null?void 0:ze.props)==null?void 0:je.title)||_}catch{}}}if(!U)return;let D=new Blob([U],{type:"text/markdown"}),ie=URL.createObjectURL(D),oe=document.createElement("a");oe.href=ie,oe.download=`${_}.md`,oe.click(),URL.revokeObjectURL(ie)}),Ze.addEventListener("click",l=>{var W,U,_;let h=l.target.closest("[data-open-artifact]");if(!h)return;let x=h.getAttribute("data-open-artifact");!x||((_=(U=(W=r.features)==null?void 0:W.artifacts)==null?void 0:U.onArtifactAction)==null?void 0:_.call(U,{type:"open",artifactId:x}))===!0||(l.preventDefault(),l.stopPropagation(),wn=!1,F.selectArtifact(x),Sr())}),Ze.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let Vn=Ve.composerOverlay,Kn=(l,m,h)=>{var _,D,ie,oe;let x=m.trim();if(!x||!St.current)return;let A=(_=l.getAttribute("data-tool-call-id"))!=null?_:"",W=h.source==="free-text";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:answered",{detail:{toolUseId:A,answer:x,answers:h.structured,values:(D=h.values)!=null?D:h.source==="multi"?x.split(", "):[x],isFreeText:W,source:h.source},bubbles:!0,composed:!0})),Jo(Vn,A);let U=St.current.getMessages().find(Y=>{var ve;return((ve=Y.toolCall)==null?void 0:ve.id)===A});(ie=U==null?void 0:U.agentMetadata)!=null&&ie.awaitingLocalTool?St.current.resolveAskUserQuestion(U,(oe=h.structured)!=null?oe:x):St.current.sendMessage(x)},On=l=>{var A;let m=St.current;if(!m)return;let h=(A=l.getAttribute("data-tool-call-id"))!=null?A:"",x=m.getMessages().find(W=>{var U;return((U=W.toolCall)==null?void 0:U.id)===h});x&&m.persistAskUserQuestionProgress(x,{answers:Na(l,x),currentIndex:er(l)})},ro=l=>Object.entries(l).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Ce=l=>{var A,W,U;if(((W=(A=r.features)==null?void 0:A.askUserQuestion)==null?void 0:W.groupedAutoAdvance)===!1)return;let m=er(l),h=Cs(l);if(m>=h-1)return;let x=(U=St.current)==null?void 0:U.getMessages().find(_=>{var D;return((D=_.toolCall)==null?void 0:D.id)===l.getAttribute("data-tool-call-id")});x&&(Oa(l,x,r,m+1),On(l))};Vn.addEventListener("click",l=>{var W,U,_,D,ie,oe,Y,ve,Oe,Fe,je,qe,ut,st;let h=l.target.closest("[data-ask-user-action]");if(!h)return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;let A=h.getAttribute("data-ask-user-action");if(l.preventDefault(),l.stopPropagation(),A==="dismiss"){let Be=(W=x.getAttribute("data-tool-call-id"))!=null?W:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),Jo(Vn,Be);let Re=(U=St.current)==null?void 0:U.getMessages().find(ze=>{var Xe;return((Xe=ze.toolCall)==null?void 0:Xe.id)===Be});(_=Re==null?void 0:Re.agentMetadata)!=null&&_.awaitingLocalTool&&((D=St.current)==null||D.markAskUserQuestionResolved(Re),(ie=St.current)==null||ie.resolveAskUserQuestion(Re,"(dismissed)"));return}if(A==="pick"){let Be=h.getAttribute("data-option-label");if(!Be)return;let Re=x.getAttribute("data-multi-select")==="true",ze=xo(x);if(ze&&Re){let Xe=Go(x)[er(x)],bt=new Set(Array.isArray(Xe)?Xe:[]);bt.has(Be)?bt.delete(Be):bt.add(Be),vo(x,Array.from(bt)),On(x);return}if(ze){vo(x,Be),On(x),Ce(x);return}if(Re){let Xe=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Xe?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Xe);let bt=x.querySelector('[data-ask-user-action="submit-multi"]');bt&&(bt.disabled=el(x).length===0);return}Kn(x,Be,{source:"pick",values:[Be]});return}if(A==="submit-multi"){let Be=el(x);if(Be.length===0)return;Kn(x,Be.join(", "),{source:"multi",values:Be});return}if(A==="open-free-text"){let Be=x.querySelector('[data-ask-free-text-row="true"]');if(Be){Be.classList.remove("persona-hidden");let Re=Be.querySelector('[data-ask-free-text-input="true"]');Re==null||Re.focus()}return}if(A==="focus-free-text"){let Be=x.querySelector('[data-ask-free-text-input="true"]');Be==null||Be.focus();return}if(A==="submit-free-text"){let Be=x.querySelector('[data-ask-free-text-input="true"]'),Re=(oe=Be==null?void 0:Be.value)!=null?oe:"";if(!Re.trim())return;if(xo(x)){vo(x,Re.trim()),On(x),Ce(x);return}Kn(x,Re,{source:"free-text"});return}if(A==="next"||A==="back"){if(!St.current)return;let Be=(Y=x.getAttribute("data-tool-call-id"))!=null?Y:"",Re=St.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Be});if(!Re)return;let ze=x.querySelector('[data-ask-free-text-input="true"]'),Xe=(Oe=(ve=ze==null?void 0:ze.value)==null?void 0:ve.trim())!=null?Oe:"";if(Xe){let De=Go(x)[er(x)];(typeof De!="string"||De!==Xe)&&vo(x,Xe)}let bt=A==="next"?1:-1,H=er(x)+bt;Oa(x,Re,r,H),On(x);return}if(A==="submit-all"){if(!St.current)return;let Be=(Fe=x.getAttribute("data-tool-call-id"))!=null?Fe:"",Re=St.current.getMessages().find(De=>{var We;return((We=De.toolCall)==null?void 0:We.id)===Be});if(!Re)return;let ze=x.querySelector('[data-ask-free-text-input="true"]'),Xe=(qe=(je=ze==null?void 0:ze.value)==null?void 0:je.trim())!=null?qe:"";Xe&&vo(x,Xe);let bt=Na(x,Re);St.current.persistAskUserQuestionProgress(Re,{answers:bt,currentIndex:er(x)});let H=ro(bt);Kn(x,H||"(submitted)",{source:"submit-all",structured:bt});return}if(A==="skip"){if(!St.current)return;let Be=(ut=x.getAttribute("data-tool-call-id"))!=null?ut:"",Re=St.current.getMessages().find(We=>{var Ye;return((Ye=We.toolCall)==null?void 0:Ye.id)===Be});if(!Re)return;let ze=xo(x),Xe=er(x),bt=Cs(x),H=Xe>=bt-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Be},bubbles:!0,composed:!0})),Jo(Vn,Be),(st=Re.agentMetadata)!=null&&st.awaitingLocalTool&&(St.current.markAskUserQuestionResolved(Re),St.current.resolveAskUserQuestion(Re,"(dismissed)"));return}vo(x,"");let De=x.querySelector('[data-ask-free-text-input="true"]');if(De&&(De.value=""),H){let We=Na(x,Re),Ye=ro(We);Kn(x,Ye||"(skipped)",{source:"submit-all",structured:We});return}Oa(x,Re,r,Xe+1),On(x);return}}),Vn.addEventListener("keydown",l=>{var W;if(l.key!=="Enter")return;let h=l.target;if(!((W=h.matches)!=null&&W.call(h,'[data-ask-free-text-input="true"]')))return;let x=h.closest("[data-persona-ask-sheet-for]");if(!x)return;l.preventDefault();let A=h.value;if(A.trim()){if(xo(x)){vo(x,A.trim()),On(x),Ce(x);return}Kn(x,A,{source:"free-text"})}});let $r=l=>{if(!/^[1-9]$/.test(l.key)||l.metaKey||l.ctrlKey||l.altKey)return;let m=l.target;if((m==null?void 0:m.tagName)==="INPUT"||(m==null?void 0:m.tagName)==="TEXTAREA"||m!=null&&m.isContentEditable)return;let h=Vn.querySelector("[data-persona-ask-sheet-for]");if(!h||h.getAttribute("data-ask-layout")!=="rows"||h.getAttribute("data-multi-select")==="true")return;let x=Number(l.key),W=h.querySelectorAll('[data-ask-pill-list="true"] [data-ask-user-action="pick"], [data-ask-pill-list="true"] [data-ask-user-action="focus-free-text"]')[x-1];W&&(l.preventDefault(),W.click())};document.addEventListener("keydown",$r);let Gn=null,Ft=null,Jn=null,jr=null,Ds=()=>{};function as(){jr==null||jr(),jr=null}let Ns=()=>{var U;if(!Gn||!Ft)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=((U=e.ownerDocument.defaultView)!=null?U:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){Ft.style.removeProperty("position"),Ft.style.removeProperty("left"),Ft.style.removeProperty("top"),Ft.style.removeProperty("bottom"),Ft.style.removeProperty("width"),Ft.style.removeProperty("z-index");return}let x=Gn.firstElementChild;if(!x||x===Ft)return;let A=10;Ft.style.position="absolute",Ft.style.top="0",Ft.style.bottom="0",Ft.style.width=`${A}px`,Ft.style.zIndex="5";let W=x.offsetWidth-A/2;Ft.style.left=`${Math.max(0,W)}px`},Wo=()=>{},Sr=()=>{var h,x,A,W,U;if(!vt||!rr(r))return;Ci(e,r),Ai(e,r),Wo();let l=(W=(A=(x=(h=r.features)==null?void 0:h.artifacts)==null?void 0:x.layout)==null?void 0:A.narrowHostMaxWidth)!=null?W:520,m=X.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),vt.update(Nn),wn?(vt.setMobileOpen(!1),vt.element.classList.add("persona-hidden"),(U=vt.backdrop)==null||U.classList.add("persona-hidden")):Nn.artifacts.length>0&&(vt.element.classList.remove("persona-hidden"),vt.setMobileOpen(!0)),Ds()};if(rr(r)){X.style.position="relative";let l=y("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=y("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(Se),vt=Vg(r,{onSelect:h=>{var x;return(x=St.current)==null?void 0:x.selectArtifact(h)},onDismiss:()=>{wn=!0,Sr()}}),vt.element.classList.add("persona-hidden"),Gn=m,m.appendChild(l),m.appendChild(vt.element),vt.backdrop&&X.appendChild(vt.backdrop),X.appendChild(m),Ds=()=>{var x,A,W,U;if(!Gn||!vt)return;if(!(((W=(A=(x=r.features)==null?void 0:x.artifacts)==null?void 0:A.layout)==null?void 0:W.resizable)===!0)){Jn==null||Jn(),Jn=null,as(),Ft&&(Ft.remove(),Ft=null),vt.element.style.removeProperty("width"),vt.element.style.removeProperty("maxWidth");return}if(!Ft){let _=y("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");_.setAttribute("role","separator"),_.setAttribute("aria-orientation","vertical"),_.setAttribute("aria-label","Resize artifacts panel"),_.tabIndex=0;let D=e.ownerDocument,ie=(U=D.defaultView)!=null?U:window,oe=Y=>{var ut,st;if(!vt||Y.button!==0||e.classList.contains("persona-artifact-narrow-host")||ie.innerWidth<=640)return;Y.preventDefault(),as();let ve=Y.clientX,Oe=vt.element.getBoundingClientRect().width,Fe=(st=(ut=r.features)==null?void 0:ut.artifacts)==null?void 0:st.layout,je=Be=>{let Re=Gn.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),Xe=ze?0:Xg(Gn,ie),bt=ze?0:_.getBoundingClientRect().width||6,H=Oe-(Be.clientX-ve),De=Qg(H,Re,Xe,bt,Fe==null?void 0:Fe.resizableMinWidth,Fe==null?void 0:Fe.resizableMaxWidth);vt.element.style.width=`${De}px`,vt.element.style.maxWidth="none",Ns()},qe=()=>{D.removeEventListener("pointermove",je),D.removeEventListener("pointerup",qe),D.removeEventListener("pointercancel",qe),jr=null;try{_.releasePointerCapture(Y.pointerId)}catch{}};jr=qe,D.addEventListener("pointermove",je),D.addEventListener("pointerup",qe),D.addEventListener("pointercancel",qe);try{_.setPointerCapture(Y.pointerId)}catch{}};_.addEventListener("pointerdown",oe),Ft=_,Gn.insertBefore(_,vt.element),Jn=()=>{_.removeEventListener("pointerdown",oe)}}if(Ft){let _=Nn.artifacts.length>0&&!wn;Ft.classList.toggle("persona-hidden",!_),Ns()}},Wo=()=>{var ie,oe,Y,ve,Oe,Fe,je,qe,ut,st,Be,Re,ze,Xe;if(!P||!vt||((oe=(ie=r.launcher)==null?void 0:ie.sidebarMode)!=null?oe:!1)||dn(r)&&nr(r).reveal==="emerge")return;let x=(Y=e.ownerDocument.defaultView)!=null?Y:window,A=(Oe=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?Oe:!0,W=(je=(Fe=r.launcher)==null?void 0:Fe.mobileBreakpoint)!=null?je:640;if(A&&x.innerWidth<=W||!Jg(r,P))return;let U=(st=(ut=(qe=r.launcher)==null?void 0:qe.width)!=null?ut:r.launcherWidth)!=null?st:tr,_=(Xe=(ze=(Re=(Be=r.features)==null?void 0:Be.artifacts)==null?void 0:Re.layout)==null?void 0:ze.expandedPanelWidth)!=null?Xe:"min(720px, calc(100vw - 24px))";Nn.artifacts.length>0&&!wn?(X.style.width=_,X.style.maxWidth=_):(X.style.width=U,X.style.maxWidth=U)},typeof ResizeObserver!="undefined"&&(Dn=new ResizeObserver(()=>{Sr()}),Dn.observe(X))}else X.appendChild(Se),R()&&it&&(Ve.peekBanner&&it.appendChild(Ve.peekBanner),it.appendChild(He));e.appendChild(ge),it&&e.appendChild(it);let oo=()=>{var De,We,Ye,Pt,_e,Kt,wt,an,Rn,Ht,mn,_n,Ge,It,$n,Oo,Fo,_o,$o,fs,hs,Jt,jo,go,fo,Vr,Uo,et;if(R()){X.style.width="100%",X.style.maxWidth="100%";let Nt=(We=(De=r.launcher)==null?void 0:De.composerBar)!=null?We:{},Bt=ge.dataset.state==="expanded",Vt=(Ye=Nt.expandedSize)!=null?Ye:"anchored";if(!(Bt&&Vt!=="fullscreen")){Se.style.background="",Se.style.border="",Se.style.borderRadius="",Se.style.overflow="",Se.style.boxShadow="";return}let mt=(_e=(Pt=r.theme)==null?void 0:Pt.components)==null?void 0:_e.panel,jt=ma(r),gn=(un,Zn)=>{var ho;return un==null||un===""?Zn:(ho=Ms(jt,un))!=null?ho:un},jn="1px solid var(--persona-border)",Ir="var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",pn="var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))";Se.style.background="var(--persona-surface, #ffffff)",Se.style.border=gn(mt==null?void 0:mt.border,jn),Se.style.borderRadius=gn(mt==null?void 0:mt.borderRadius,pn),Se.style.boxShadow=gn(mt==null?void 0:mt.shadow,Ir),Se.style.overflow="hidden";return}let l=dn(r),m=(wt=(Kt=r.launcher)==null?void 0:Kt.sidebarMode)!=null?wt:!1,h=l||m||((Rn=(an=r.launcher)==null?void 0:an.fullHeight)!=null?Rn:!1),x=((Ht=r.launcher)==null?void 0:Ht.enabled)===!1,A=(_n=(mn=r.theme)==null?void 0:mn.components)==null?void 0:_n.panel,W=ma(r),U=(Nt,Bt)=>{var Vt;return Nt==null||Nt===""?Bt:(Vt=Ms(W,Nt))!=null?Vt:Nt},_=(Ge=e.ownerDocument.defaultView)!=null?Ge:window,D=($n=(It=r.launcher)==null?void 0:It.mobileFullscreen)!=null?$n:!0,ie=(Fo=(Oo=r.launcher)==null?void 0:Oo.mobileBreakpoint)!=null?Fo:640,oe=_.innerWidth<=ie,Y=D&&oe&&P,ve=($o=(_o=r.launcher)==null?void 0:_o.position)!=null?$o:"bottom-left",Oe=ve==="bottom-left"||ve==="top-left",Fe=(hs=(fs=r.launcher)==null?void 0:fs.zIndex)!=null?hs:xn,je=m||Y?"none":"1px solid var(--persona-border)",qe=Y?"none":m?Oe?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Y&&(qe="none",je="none");let ut=m||Y?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",st=U(A==null?void 0:A.border,je),Be=U(A==null?void 0:A.shadow,qe),Re=U(A==null?void 0:A.borderRadius,ut),ze=we.scrollTop;e.style.cssText="",ge.style.cssText="",X.style.cssText="",Se.style.cssText="",we.style.cssText="",He.style.cssText="",J&&(we.style.display="none");let Xe=()=>{var Bt;if(ze<=0)return;((Bt=we.ownerDocument.defaultView)!=null?Bt:window).requestAnimationFrame(()=>{if(we.scrollTop===ze)return;let Vt=we.scrollHeight-we.clientHeight;Vt<=0||(we.scrollTop=Math.min(ze,Vt))})};if(Y){ge.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),ge.style.cssText=`
35
35
  position: fixed !important;
36
36
  inset: 0 !important;
37
37
  width: 100% !important;
@@ -41,9 +41,9 @@ _Details: ${n.message}_`:r}var la=e=>({isError:!0,content:[{type:"text",text:e}]
41
41
  padding: 0 !important;
42
42
  display: flex !important;
43
43
  flex-direction: column !important;
44
- z-index: ${Ee} !important;
44
+ z-index: ${Fe} !important;
45
45
  background-color: var(--persona-surface, #ffffff) !important;
46
- `,J.style.cssText=`
46
+ `,X.style.cssText=`
47
47
  position: relative !important;
48
48
  display: flex !important;
49
49
  flex-direction: column !important;
@@ -67,20 +67,20 @@ _Details: ${n.message}_`:r}var la=e=>({isError:!0,content:[{type:"text",text:e}]
67
67
  overflow: hidden !important;
68
68
  border-radius: 0 !important;
69
69
  border: none !important;
70
- `,ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.overflowY="auto",Oe.style.flexShrink="0",j=!0,Ke();return}let gt=(yo=(ho=r==null?void 0:r.launcher)==null?void 0:ho.width)!=null?yo:r==null?void 0:r.launcherWidth,I=gt!=null?gt:nr;if(!m&&!c)b&&h?(J.style.width="100%",J.style.maxWidth="100%"):(J.style.width=I,J.style.maxWidth=I);else if(c)if(rr(r).reveal==="emerge"){let zt=rr(r).width;J.style.width=zt,J.style.maxWidth=zt}else J.style.width="100%",J.style.maxWidth="100%";if(Bo(),J.style.boxShadow=Re,J.style.borderRadius=Pe,Se.style.border=rt,Se.style.borderRadius=Pe,c&&!Q&&(S==null?void 0:S.border)===void 0&&(Se.style.border="none",rr(r).side==="right"?Se.style.borderLeft="1px solid var(--persona-border)":Se.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",b&&(e.style.width="100%"),ye.style.display="flex",ye.style.flexDirection="column",ye.style.flex="1 1 0%",ye.style.minHeight="0",ye.style.maxHeight="100%",ye.style.height="100%",b&&(ye.style.overflow="hidden"),J.style.display="flex",J.style.flexDirection="column",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.maxHeight="100%",J.style.height="100%",J.style.overflow="hidden",Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.maxHeight="100%",Se.style.overflow="hidden",ve.style.flex="1 1 0%",ve.style.minHeight="0",ve.style.overflowY="auto",Oe.style.flexShrink="0"),ye.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!m&&!b&&!c&&((Qr=br[we])!=null?Qr:br["bottom-right"]).split(" ").forEach(zt=>ye.classList.add(zt)),m){let Ht=(gr=(Uo=r.launcher)==null?void 0:Uo.sidebarWidth)!=null?gr:"420px";ye.style.cssText=`
70
+ `,we.style.flex="1 1 0%",we.style.minHeight="0",we.style.overflowY="auto",He.style.flexShrink="0",$=!0,Xe();return}let bt=(jo=(Jt=r==null?void 0:r.launcher)==null?void 0:Jt.width)!=null?jo:r==null?void 0:r.launcherWidth,H=bt!=null?bt:tr;if(!m&&!l)x&&h?(X.style.width="100%",X.style.maxWidth="100%"):(X.style.width=H,X.style.maxWidth=H);else if(l)if(nr(r).reveal==="emerge"){let Bt=nr(r).width;X.style.width=Bt,X.style.maxWidth=Bt}else X.style.width="100%",X.style.maxWidth="100%";if(Wo(),X.style.boxShadow=Be,X.style.borderRadius=Re,Se.style.border=st,Se.style.borderRadius=Re,l&&!Y&&(A==null?void 0:A.border)===void 0&&(Se.style.border="none",nr(r).side==="right"?Se.style.borderLeft="1px solid var(--persona-border)":Se.style.borderRight="1px solid var(--persona-border)"),h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",x&&(e.style.width="100%"),ge.style.display="flex",ge.style.flexDirection="column",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.maxHeight="100%",ge.style.height="100%",x&&(ge.style.overflow="hidden"),X.style.display="flex",X.style.flexDirection="column",X.style.flex="1 1 0%",X.style.minHeight="0",X.style.maxHeight="100%",X.style.height="100%",X.style.overflow="hidden",Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.maxHeight="100%",Se.style.overflow="hidden",we.style.flex="1 1 0%",we.style.minHeight="0",we.style.overflowY="auto",He.style.flexShrink="0"),ge.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!m&&!x&&!l&&((go=hr[ve])!=null?go:hr["bottom-right"]).split(" ").forEach(Bt=>ge.classList.add(Bt)),m){let Nt=(Vr=(fo=r.launcher)==null?void 0:fo.sidebarWidth)!=null?Vr:"420px";ge.style.cssText=`
71
71
  position: fixed !important;
72
72
  top: 0 !important;
73
73
  bottom: 0 !important;
74
- width: ${Ht} !important;
74
+ width: ${Nt} !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: ${Ee} !important;
82
- ${Fe?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
83
- `,J.style.cssText=`
81
+ z-index: ${Fe} !important;
82
+ ${Oe?"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 la=e=>({isError:!0,content:[{type:"text",text:e}]
91
91
  min-height: 0 !important;
92
92
  margin: 0 !important;
93
93
  padding: 0 !important;
94
- box-shadow: ${Re} !important;
95
- border-radius: ${Pe} !important;
96
- `,J.style.setProperty("width","100%","important"),J.style.setProperty("max-width","100%","important"),Se.style.cssText=`
94
+ box-shadow: ${Be} !important;
95
+ border-radius: ${Re} !important;
96
+ `,X.style.setProperty("width","100%","important"),X.style.setProperty("max-width","100%","important"),Se.style.cssText=`
97
97
  display: flex !important;
98
98
  flex-direction: column !important;
99
99
  flex: 1 1 0% !important;
@@ -102,29 +102,29 @@ _Details: ${n.message}_`:r}var la=e=>({isError:!0,content:[{type:"text",text:e}]
102
102
  min-height: 0 !important;
103
103
  max-height: 100% !important;
104
104
  overflow: hidden !important;
105
- border-radius: ${Pe} !important;
106
- border: ${rt} !important;
107
- `,Oe.style.cssText=`
105
+ border-radius: ${Re} !important;
106
+ border: ${st} !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(!b&&!c){let Ht="max-height: -moz-available !important; max-height: stretch !important;",zt=m?"":"padding-top: 1.25em !important;",Bt=m?"":`z-index: ${(Qe=(Hr=r.launcher)==null?void 0:Hr.zIndex)!=null?Qe:vn} !important;`;ye.style.cssText+=Ht+zt+Bt}Ke()};co(),Zo(e,r),wi(e,r),Ci(e,r);let it=[];it.push(()=>{document.removeEventListener("keydown",zr)}),it.push(()=>{lr!==null&&clearTimeout(lr)});let rn=null,on=null;it.push(()=>{rn==null||rn(),rn=null,on==null||on(),on=null}),Wn&&it.push(()=>{Wn==null||Wn.disconnect(),Wn=null}),it.push(()=>{Gn==null||Gn(),Gn=null,ss(),_t&&(_t.remove(),_t=null),yt==null||yt.element.style.removeProperty("width"),yt==null||yt.element.style.removeProperty("maxWidth")}),oe&&it.push(()=>{ue!==null&&(cancelAnimationFrame(ue),ue=null),He==null||He.destroy(),He=null,V==null||V.destroy(),V=null,xe=null});let Mr=null,Ds=()=>{Mr&&(Mr(),Mr=null),r.colorScheme==="auto"&&(Mr=hl(()=>{Zo(e,r)}))};Ds(),it.push(()=>{Mr&&(Mr(),Mr=null)}),it.push(a);let Kr=(wd=r.features)==null?void 0:wd.streamAnimation;if(Kr!=null&&Kr.type&&Kr.type!=="none"){let c=fa(Kr.type,Kr.plugins);c&&(xl(c,e),it.push(()=>sg(e)))}let Do=kg(Lt),kr=null,$,as=c=>{var b,S;if(!$)return;let m=c!=null?c:$.getMessages(),h=((S=(b=r.features)==null?void 0:b.suggestReplies)==null?void 0:S.enabled)!==!1?tl(m):null;h?Do.render(h,$,ee,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(W=>W.role==="user")?Do.render([],$,ee,m):Do.render(r.suggestionChips,$,ee,m,r.suggestionChipsConfig)},dr=!1,Lr=Xm(),Gr=new Map,Pr=new Map,pr=new Map,is=0,Ma=Vo()!==null,hn=ni(),An=0,ur=null,Sn=!1,No=!1,mr=0,yn=null,Ir=null,ls=!1,Oo=!1,cs=null,Rr=!0,tt=!1,w=null,z=4,U=24,G=80,he=new Map,re={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},mt=(Ad=(Cd=r.voiceRecognition)==null?void 0:Cd.autoResume)!=null?Ad:!1,pt=c=>{i.emit("voice:state",{active:re.active,source:c,timestamp:Date.now()})},Dn=()=>{x(c=>({...c,voiceState:{active:re.active,timestamp:Date.now(),manuallyDeactivated:re.manuallyDeactivated}}))},po=()=>{var b,S;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=zl(p.voiceState),m=!!c.active,h=Number((S=c.timestamp)!=null?S:0);re.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-h<hw&&setTimeout(()=>{var W,q;re.active||(re.manuallyDeactivated=!1,((q=(W=r.voiceRecognition)==null?void 0:W.provider)==null?void 0:q.type)==="runtype"?$.toggleVoice().then(()=>{re.active=$.isVoiceActive(),pt("restore"),$.isVoiceActive()&&us()}):La("restore"))},1e3)},Jn=()=>$?zg($.getMessages()).filter(c=>!c.__skipPersist):[];function sn(c){if(!(l!=null&&l.save))return;let h={messages:c?zg(c):$?Jn():[],metadata:p,artifacts:Hn.artifacts,selectedArtifactId:Hn.selectedId};try{let b=l.save(h);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 Xn=null,Jr=()=>ye.querySelector("#persona-scroll-container")||ve,pn=()=>{Xn!==null&&(cancelAnimationFrame(Xn),Xn=null),Sn=!1},Tn=()=>{ur!==null&&(cancelAnimationFrame(ur),ur=null),No=!1,pn()},Nn=()=>dr&&Di()&&(Ft()!=="anchor-top"||ar()),Bi=()=>{let c=ht()||"Jump to latest",m=Nn();qt.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),mr>0?(In.textContent=String(mr),In.style.display="",qt.setAttribute("aria-label",`${c} (${mr} new)`)):(In.textContent="",In.style.display="none",qt.setAttribute("aria-label",m?`${c} (response streaming below)`:c))},rc=()=>{mr!==0&&(mr=0,Bi())},Di=()=>en()?!hn.isFollowing():!So(ve,U),On=()=>{if(!Xt()||K){qt.parentNode&&qt.remove(),qt.style.display="none";return}qt.parentNode!==Se&&Se.appendChild(qt),qn();let m=Fr(ve)>0&&Di();m?Bi():rc(),qt.style.display=m?"":"none"},Ns=()=>{hn.pause()&&(Tn(),On())},uo=()=>{hn.resume(),rc(),On()},mo=(c=!1)=>{en()&&hn.isFollowing()&&(!c&&!dr||(ur!==null&&(cancelAnimationFrame(ur),ur=null),No=!0,ur=requestAnimationFrame(()=>{ur=null,No=!1,hn.isFollowing()&&kf(Jr(),c?220:140)})))},oc=(c,m,h,b=()=>!0)=>{let S=c.scrollTop,W=m(),q=W-S;if(pn(),Math.abs(q)<1){Sn=!0,c.scrollTop=W,An=c.scrollTop,Sn=!1;return}let _=performance.now();Sn=!0;let D=le=>1-Math.pow(1-le,3),de=le=>{if(!b()){pn();return}let Q=m();Q!==W&&(W=Q,q=W-S);let we=le-_,Fe=Math.min(we/h,1),Ee=D(Fe),Ze=S+q*Ee;c.scrollTop=Ze,An=c.scrollTop,Fe<1?Xn=requestAnimationFrame(de):(c.scrollTop=W,An=c.scrollTop,Xn=null,Sn=!1)};Xn=requestAnimationFrame(de)},kf=(c,m=500)=>{let h=Fr(c)-c.scrollTop;if(Math.abs(h)<1){An=c.scrollTop;return}if(Math.abs(h)>=G){pn(),Sn=!0,c.scrollTop=Fr(c),An=c.scrollTop,Sn=!1;return}oc(c,()=>Fr(c),m,()=>hn.isFollowing())},sc=()=>{let c=Jr();Sn=!0,c.scrollTop=Fr(c),An=c.scrollTop,Sn=!1,On()},ac=c=>{let m=0,h=c;for(;h&&h!==ve;)m+=h.offsetTop,h=h.offsetParent;return m},ic=()=>{var W;if($r()!=="last-user-turn")return!1;let c=(W=$==null?void 0:$.getMessages())!=null?W:[];if(c.length<2)return!1;let m=[...c].reverse().find(q=>q.role==="user");if(!m)return!1;let h=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(m.id):m.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),b=ve.querySelector(`[data-message-id="${h}"]`);if(!b)return!1;let S=Math.min(Math.max(0,ac(b)-wr()),Fr(ve));return Sn=!0,ve.scrollTop=S,An=ve.scrollTop,Sn=!1,Ft()==="follow"&&!So(ve,U)&&hn.pause(),On(),!0},lc=c=>{kn.style.height=`${Math.max(0,Math.round(c))}px`,yn&&(yn.spacerHeight=Math.max(0,c))},Os=()=>{Ir!==null&&(cancelAnimationFrame(Ir),Ir=null),pn(),yn=null,kn.style.height="0px"},Lf=c=>{Ir!==null&&cancelAnimationFrame(Ir),Ir=requestAnimationFrame(()=>{var D;Ir=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=ve.querySelector(`[data-message-id="${m}"]`);if(!h)return;let b=ac(h),S=(D=yn==null?void 0:yn.spacerHeight)!=null?D:0,W=ve.scrollHeight-S,{targetScrollTop:q,spacerHeight:_}=tg({anchorOffsetTop:b,topOffset:wr(),viewportHeight:ve.clientHeight,contentHeight:W});yn={initialSpacerHeight:_,contentHeightAtAnchor:W,spacerHeight:_},lc(_),oc(ve,()=>q,220)})},Pf=()=>{if(en()){if(!hn.isFollowing()||So(ve,1))return;mo(!dr);return}if(yn&&yn.initialSpacerHeight>0){let c=ve.scrollHeight-yn.spacerHeight,m=ng({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:c});m!==yn.spacerHeight&&lc(m)}On()},If=c=>{let m=Ft();m==="follow"?(uo(),mo(!0)):m==="anchor-top"&&(Rr=!1,tt=!0,Lf(c))},Rf=()=>{if(Ft()==="anchor-top"){if(tt){Rr=!1;return}Rr=!0,Os(),uo(),mo(!0)}},Wf=c=>{let m=new Map;c.forEach(h=>{let b=he.get(h.id);m.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(i.emit("assistant:message",h),!Oo&&(Ft()!=="anchor-top"||ar())&&Di()&&(mr+=1,Bi(),On(),no(mr===1?"1 new message below.":`${mr} new messages below.`))),h.role==="assistant"&&(b!=null&&b.streaming)&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(b?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),he.clear(),m.forEach((h,b)=>{he.set(b,h)})},Hf=(c,m,h)=>{var rt,Re,Pe,ze,Ke,gt;let b=document.createElement("div"),W=(()=>{var De;let I=o.find(We=>We.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((De=r.loadingIndicator)!=null&&De.render)return r.loadingIndicator.render})(),q=(I,De)=>De==null?!1:typeof De=="string"?(I.textContent=De,!0):(I.appendChild(De),!0),_=new Set,D=new Set,de=o.some(I=>I.renderAskUserQuestion),le=[],Q=[],we=r.enableComponentStreaming!==!1,Fe=r.approval!==!1,Ee=[];if(m.forEach(I=>{var Je,Tt,nn,Zn,_n,_o,$o,gs,fs,Gt,jo,ho,yo,Qr,Uo,gr,Hr;_.add(I.id);let De=de&&xo(I),We=Fe&&I.variant==="approval"&&!!I.approval,me=!De&&I.role==="assistant"&&!I.variant&&we&&$l(I);if(!We&&pr.has(I.id)){let Qe=c.querySelector(`#wrapper-${I.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime"),pr.delete(I.id)}if(!me&&Pr.has(I.id)){let Qe=c.querySelector(`#wrapper-${I.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime"),Pr.delete(I.id)}let Wt=xo(I)?`:${(Je=I.agentMetadata)!=null&&Je.askUserQuestionAnswered?"a":"u"}:${(Tt=I.agentMetadata)!=null&&Tt.askUserQuestionAnswers?Object.keys(I.agentMetadata.askUserQuestionAnswers).length:0}`:"",It=Jm(I,is)+Wt,Vt=De||We||me?null:Qm(Lr,I.id,It);if(Vt){b.appendChild(Vt.cloneNode(!0)),xo(I)&&((nn=I.toolCall)!=null&&nn.id)&&((Zn=I.agentMetadata)==null?void 0:Zn.awaitingLocalTool)===!0&&!((_n=I.agentMetadata)!=null&&_n.askUserQuestionAnswered)&&(D.add(I.toolCall.id),ta(I,r,qe.composerOverlay));return}let ft=null,jt=o.find(Qe=>!!(I.variant==="reasoning"&&Qe.renderReasoning||I.variant==="tool"&&Qe.renderToolCall||!I.variant&&Qe.renderMessage)),Fn=(_o=r.layout)==null?void 0:_o.messages;if(xo(I)&&(($o=I.agentMetadata)==null?void 0:$o.askUserQuestionAnswered)===!0){Gr.delete(I.id);let Qe=c.querySelector(`#wrapper-${I.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime");return}if(Fa(I)&&((fs=(gs=r.features)==null?void 0:gs.suggestReplies)==null?void 0:fs.enabled)!==!1)return;if(xo(I)&&((jo=(Gt=r.features)==null?void 0:Gt.askUserQuestion)==null?void 0:jo.enabled)!==!1){let Qe=o.find(Ht=>typeof Ht.renderAskUserQuestion=="function");if(Qe&&wt.current){let Ht=Gr.get(I.id),zt=Ht!==It,Bt=null;if(zt){let{payload:Nt,complete:un}=vo(I),$n=I.id,Br=()=>{var mn;return(mn=wt.current)==null?void 0:mn.getMessages().find(gn=>gn.id===$n)};Bt=Qe.renderAskUserQuestion({message:I,payload:Nt,complete:un,resolve:mn=>{var er;let gn=Br();gn&&((er=wt.current)==null||er.resolveAskUserQuestion(gn,mn))},dismiss:()=>{var gn,er,bo;let mn=Br();(gn=mn==null?void 0:mn.agentMetadata)!=null&&gn.awaitingLocalTool&&((er=wt.current)==null||er.markAskUserQuestionResolved(mn),(bo=wt.current)==null||bo.resolveAskUserQuestion(mn,"(dismissed)"))},config:r})}let Jt=Ht!=null;if(zt&&Bt===null&&!Jt){((ho=I.agentMetadata)==null?void 0:ho.awaitingLocalTool)===!0&&!((yo=I.agentMetadata)!=null&&yo.askUserQuestionAnswered)&&(D.add(I.toolCall.id),ta(I,r,qe.composerOverlay));return}let Et=document.createElement("div");Et.className="persona-flex",Et.id=`wrapper-${I.id}`,Et.setAttribute("data-wrapper-id",I.id),Et.setAttribute("data-ask-plugin-stub","true"),Et.setAttribute("data-preserve-runtime","true"),b.appendChild(Et),le.push({messageId:I.id,fingerprint:It,bubble:Bt});return}else{((Qr=I.agentMetadata)==null?void 0:Qr.awaitingLocalTool)===!0&&!((Uo=I.agentMetadata)!=null&&Uo.askUserQuestionAnswered)&&(D.add(I.toolCall.id),ta(I,r,qe.composerOverlay));return}}else if(We){let Qe=(gr=o.find(Jt=>typeof Jt.renderApproval=="function"))!=null?gr:s,zt=pr.get(I.id)!==It,Bt=null;if(zt&&(Qe!=null&&Qe.renderApproval)){let Jt=I.id,Et=(Nt,un)=>{var Br,mn,gn;let $n=(Br=wt.current)==null?void 0:Br.getMessages().find(er=>er.id===Jt);$n!=null&&$n.approval&&($n.approval.toolType==="webmcp"?(mn=wt.current)==null||mn.resolveWebMcpApproval($n.id,Nt):(gn=wt.current)==null||gn.resolveApproval($n.approval,Nt,un))};Bt=Qe.renderApproval({message:I,defaultRenderer:()=>xi(I,r),config:r,approve:Nt=>Et("approved",Nt),deny:Nt=>Et("denied",Nt)})}if(zt&&Bt===null){let Jt=c.querySelector(`#wrapper-${I.id}`);Jt==null||Jt.removeAttribute("data-preserve-runtime"),pr.delete(I.id),ft=xi(I,r)}else{let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id=`wrapper-${I.id}`,Jt.setAttribute("data-wrapper-id",I.id),Jt.setAttribute("data-approval-plugin-stub","true"),Jt.setAttribute("data-preserve-runtime","true"),b.appendChild(Jt),Ee.push({messageId:I.id,fingerprint:It,bubble:Bt});return}}else if(jt)if(I.variant==="reasoning"&&I.reasoning&&jt.renderReasoning){if(!Te)return;ft=jt.renderReasoning({message:I,defaultRenderer:()=>kl(I,r),config:r})}else if(I.variant==="tool"&&I.toolCall&&jt.renderToolCall){if(!Le)return;ft=jt.renderToolCall({message:I,defaultRenderer:()=>Pl(I,r),config:r})}else jt.renderMessage&&(ft=jt.renderMessage({message:I,defaultRenderer:()=>{let Qe=Ca(I,h,Fn,r.messageActions,fe,{loadingIndicatorRenderer:W,widgetConfig:r});return I.role!=="user"&&Bl(Qe,I,r,$),Qe},config:r}));if(!ft&&me){let Qe=jl(I);if(Qe){let Ht=Pr.get(I.id),zt=Ht!==It,Bt=r.wrapComponentDirectiveInBubble!==!1,Jt=null;if(zt){let Et=_l(Qe,{config:r,message:I,transform:h});if(Et)if(Bt){let Nt=document.createElement("div");if(Nt.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(" "),Nt.id=`bubble-${I.id}`,Nt.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let un=document.createElement("div");un.className="persona-mb-3 persona-text-sm persona-leading-relaxed",un.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),Nt.appendChild(un)}Nt.appendChild(Et),Jt=Nt}else{let Nt=document.createElement("div");if(Nt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Nt.id=`bubble-${I.id}`,Nt.setAttribute("data-message-id",I.id),Nt.setAttribute("data-persona-component-directive","true"),I.content&&I.content.trim()){let un=document.createElement("div");un.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",un.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),Nt.appendChild(un)}Nt.appendChild(Et),Jt=Nt}}if(Jt||Ht!=null){let Et=document.createElement("div");Et.className="persona-flex",Et.id=`wrapper-${I.id}`,Et.setAttribute("data-wrapper-id",I.id),Et.setAttribute("data-component-directive-stub","true"),Et.setAttribute("data-preserve-runtime","true"),Bt||Et.classList.add("persona-w-full"),b.appendChild(Et),Q.push({messageId:I.id,fingerprint:It,bubble:Jt});return}}}if(!ft)if(I.variant==="reasoning"&&I.reasoning){if(!Te)return;ft=kl(I,r)}else if(I.variant==="tool"&&I.toolCall){if(!Le)return;ft=Pl(I,r)}else if(I.variant==="approval"&&I.approval){if(r.approval===!1)return;ft=xi(I,r)}else{let Qe=(Hr=r.layout)==null?void 0:Hr.messages;Qe!=null&&Qe.renderUserMessage&&I.role==="user"?ft=Qe.renderUserMessage({message:I,config:r,streaming:!!I.streaming}):Qe!=null&&Qe.renderAssistantMessage&&I.role==="assistant"?ft=Qe.renderAssistantMessage({message:I,config:r,streaming:!!I.streaming}):ft=Ca(I,h,Qe,r.messageActions,fe,{loadingIndicatorRenderer:W,widgetConfig:r}),I.role!=="user"&&ft&&Bl(ft,I,r,$)}let Zt=document.createElement("div");Zt.className="persona-flex",Zt.id=`wrapper-${I.id}`,Zt.setAttribute("data-wrapper-id",I.id),I.role==="user"&&Zt.classList.add("persona-justify-end"),(ft==null?void 0:ft.getAttribute("data-persona-component-directive"))==="true"&&Zt.classList.add("persona-w-full"),Zt.appendChild(ft),Ym(Lr,I.id,It,Zt),b.appendChild(Zt)}),qe.composerOverlay&&qe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let We=De.getAttribute("data-persona-ask-sheet-for");We&&!D.has(We)&&Jo(qe.composerOverlay,We)}),(Re=(rt=r.features)==null?void 0:rt.toolCallDisplay)!=null&&Re.grouped){let I=[],De=[];m.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&Le){De.push(We);return}De.length>1&&I.push(De),De=[]}),De.length>1&&I.push(De),I.forEach((We,me)=>{var Je,Tt;let Wt=We.map(nn=>Array.from(b.children).find(Zn=>Zn instanceof HTMLElement&&Zn.getAttribute("data-wrapper-id")===nn.id)).filter(nn=>!!nn);if(Wt.length<2)return;let It=document.createElement("div");It.className="persona-flex",It.id=`wrapper-tool-group-${me}-${We[0].id}`,It.setAttribute("data-wrapper-id",`tool-group-${me}-${We[0].id}`);let Vt=document.createElement("div");Vt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Vt.setAttribute("data-persona-tool-group","true");let ft=document.createElement("div");ft.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let jt=`Called ${We.length} tools`,Fn=(Tt=(Je=r.toolCall)==null?void 0:Je.renderGroupedSummary)==null?void 0:Tt.call(Je,{messages:We,toolCalls:We.map(nn=>nn.toolCall).filter(nn=>!!nn),defaultSummary:jt,config:r});q(ft,Fn)||(ft.textContent=jt);let Zt=document.createElement("div");Zt.className="persona-tool-group-stack persona-flex persona-flex-col",Vt.append(ft,Zt),It.appendChild(Vt),Wt[0].before(It),Wt.forEach((nn,Zn)=>{let _n=document.createElement("div");_n.className="persona-tool-group-item persona-relative",_n.setAttribute("data-persona-tool-group-item","true"),Zn<Wt.length-1&&_n.setAttribute("data-persona-tool-group-connector","true"),_n.appendChild(nn),Zt.appendChild(_n)})})}Zm(Lr,_);let Ze=m.some(I=>I.role==="assistant"&&I.streaming),Ue=m[m.length-1],ct=(Ue==null?void 0:Ue.role)==="assistant"&&!Ue.streaming&&Ue.variant!=="approval";if(dr&&m.some(I=>I.role==="user")&&!Ze&&!ct){let I={config:r,streaming:!0,location:"standalone",defaultRenderer:ks},De=o.find(me=>me.renderLoadingIndicator),We=null;if(De!=null&&De.renderLoadingIndicator&&(We=De.renderLoadingIndicator(I)),We===null&&((Pe=r.loadingIndicator)!=null&&Pe.render)&&(We=r.loadingIndicator.render(I)),We===null&&(We=ks()),We){let me=document.createElement("div"),Wt=((ze=r.loadingIndicator)==null?void 0:ze.showBubble)!==!1;me.className=Wt?["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(" "),me.setAttribute("data-typing-indicator","true"),me.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",me.appendChild(We);let It=document.createElement("div");It.className="persona-flex",It.id="wrapper-typing-indicator",It.setAttribute("data-wrapper-id","typing-indicator"),It.appendChild(me),b.appendChild(It)}}if(!dr&&m.length>0){let I=m[m.length-1],De={config:r,lastMessage:I,messageCount:m.length},We=o.find(Wt=>Wt.renderIdleIndicator),me=null;if(We!=null&&We.renderIdleIndicator&&(me=We.renderIdleIndicator(De)),me===null&&((Ke=r.loadingIndicator)!=null&&Ke.renderIdle)&&(me=r.loadingIndicator.renderIdle(De)),me){let Wt=document.createElement("div"),It=((gt=r.loadingIndicator)==null?void 0:gt.showBubble)!==!1;Wt.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-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(" "),Wt.setAttribute("data-idle-indicator","true"),Wt.appendChild(me);let Vt=document.createElement("div");Vt.className="persona-flex",Vt.id="wrapper-idle-indicator",Vt.setAttribute("data-wrapper-id","idle-indicator"),Vt.appendChild(Wt),b.appendChild(Vt)}}if(ei(c,b),le.length>0)for(let{messageId:I,fingerprint:De,bubble:We}of le){let me=c.querySelector(`#wrapper-${I}`);me&&We!==null&&(me.replaceChildren(We),me.setAttribute("data-bubble-fp",De),Gr.set(I,De))}if(Gr.size>0)for(let I of Gr.keys())_.has(I)||Gr.delete(I);if(Q.length>0)for(let{messageId:I,fingerprint:De,bubble:We}of Q){let me=c.querySelector(`#wrapper-${I}`);me&&We!==null&&(me.replaceChildren(We),me.setAttribute("data-bubble-fp",De),Pr.set(I,De))}if(Pr.size>0)for(let I of Pr.keys())_.has(I)||Pr.delete(I);if(Ee.length>0)for(let{messageId:I,fingerprint:De,bubble:We}of Ee){let me=c.querySelector(`#wrapper-${I}`);me&&We!==null&&(me.replaceChildren(We),me.setAttribute("data-bubble-fp",De),pr.set(I,De))}if(pr.size>0)for(let I of pr.keys())_.has(I)||pr.delete(I)},Fs=(c,m,h)=>{Hf(c,m,h),io()},_s=null,Bf=()=>{var h;if(_s)return;let c=b=>{let S=b.composedPath();S.includes(ye)||dt&&S.includes(dt)||$t(!1,"user")};_s=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},cc=()=>{var m;if(!_s)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",_s,!0),_s=null};it.push(()=>cc());let $s=null,Df=()=>{var h;if($s)return;let c=b=>{b.key==="Escape"&&(b.isComposing||$t(!1,"user"))};$s=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},dc=()=>{var m;if(!$s)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",$s,!0),$s=null};it.push(()=>dc());let js=!1,pc=new Set,Nf=()=>{var m,h,b,S;let c=(b=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.peek)==null?void 0:b.streamAnimation;return c||((S=r.features)==null?void 0:S.streamAnimation)},ds=()=>{var ct,rt,Re,Pe;if(!H())return;let c=qe.peekBanner,m=qe.peekTextNode;if(!c||!m)return;if(N){c.classList.remove("persona-pill-peek--visible");return}let h=(ct=$==null?void 0:$.getMessages())!=null?ct:[],b;for(let ze=h.length-1;ze>=0;ze--){let Ke=h[ze];if(Ke.role==="assistant"&&Ke.content){b=Ke;break}}if(!b){c.classList.remove("persona-pill-peek--visible");return}let S=b.content,W=!!b.streaming,q=Nf(),_=si(q),D=_.type!=="none"?fa(_.type,q==null?void 0:q.plugins):null,de=((rt=D==null?void 0:D.isAnimating)==null?void 0:rt.call(D,b))===!0,le=D!==null&&(W||de);le&&D&&!pc.has(D.name)&&(xl(D,e),pc.add(D.name));let Q=le&&(D!=null&&D.containerClass)?D.containerClass:null,we=(Re=m.dataset.personaPeekStreamClass)!=null?Re:null;we&&we!==Q&&(m.classList.remove(we),delete m.dataset.personaPeekStreamClass),Q&&we!==Q&&(m.classList.add(Q),m.dataset.personaPeekStreamClass=Q),le?(m.style.setProperty("--persona-stream-step",`${_.speed}ms`),m.style.setProperty("--persona-stream-duration",`${_.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let Fe=le?ai(S,_.buffer,D,b,W):S;if(le&&_.placeholder==="skeleton"&&W&&(!Fe||!Fe.trim())){let ze=document.createElement("div"),Ke=ya();Ke.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Ke),ei(m,ze)}else{let ze=Math.max(0,Fe.length-100),Ke=Fe.length>100?Fe.slice(-100):Fe,gt=Yr(Ke);if(!le||!D){let I=Fe.length>100?`\u2026${Ke}`:Ke;m.textContent!==I&&(m.textContent=I)}else{let I=gt;(D.wrap==="char"||D.wrap==="word")&&(I=ha(gt,D.wrap,`peek-${b.id}`,{skipTags:D.skipTags,startIndex:ze}));let De=document.createElement("div");if(De.innerHTML=I,D.useCaret&&Ke.length>0){let We=ii(),me=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),Wt=me[me.length-1];Wt!=null&&Wt.parentNode?Wt.parentNode.insertBefore(We,Wt.nextSibling):De.appendChild(We)}ei(m,De),(Pe=D.onAfterRender)==null||Pe.call(D,{container:m,bubble:c,messageId:b.id,message:b,speed:_.speed,duration:_.duration})}}let Ue=dr||js;c.classList.toggle("persona-pill-peek--visible",Ue)};if(H()){let c=qe.peekBanner;if(c){let b=S=>{S.preventDefault(),S.stopPropagation(),$t(!0,"user")};c.addEventListener("pointerdown",b),it.push(()=>{c.removeEventListener("pointerdown",b)})}let m=()=>{js||(js=!0,ds())},h=()=>{js&&(js=!1,ds())};J.addEventListener("pointerenter",m),J.addEventListener("pointerleave",h),it.push(()=>{J.removeEventListener("pointerenter",m),J.removeEventListener("pointerleave",h)}),dt&&(dt.addEventListener("pointerenter",m),dt.addEventListener("pointerleave",h),it.push(()=>{dt.removeEventListener("pointerenter",m),dt.removeEventListener("pointerleave",h)}))}let Of=c=>{var we,Fe,Ee,Ze,Ue,ct,rt,Re;let m=(Fe=(we=r.launcher)==null?void 0:we.composerBar)!=null?Fe:{},h=(Ee=m.expandedSize)!=null?Ee:"anchored",b=(Ze=m.bottomOffset)!=null?Ze:"16px",S=m.collapsedMaxWidth,W=(Ue=m.expandedMaxWidth)!=null?Ue:"880px",q=(ct=m.expandedTopOffset)!=null?ct:"5vh",_=(rt=m.modalMaxWidth)!=null?rt:"880px",D=(Re=m.modalMaxHeight)!=null?Re:"min(90vh, 800px)",de="calc(100vw - 32px)",le="var(--persona-pill-area-height, 80px)",Q=ye.style;if(Q.left="",Q.right="",Q.top="",Q.bottom="",Q.transform="",Q.width="",Q.maxWidth="",Q.height="",Q.maxHeight="",dt){let Pe=dt.style;Pe.bottom=b,Pe.width=S!=null?S:""}if(c&&h!=="fullscreen"){if(h==="modal"){Q.top="50%",Q.left="50%",Q.transform="translate(-50%, -50%)",Q.bottom="auto",Q.right="auto",Q.width=_,Q.maxWidth=de,Q.maxHeight=D,Q.height=D;return}Q.left="50%",Q.transform="translateX(-50%)",Q.bottom=`calc(${b} + ${le})`,Q.top=q,Q.width=W,Q.maxWidth=de}},Us=()=>{var D,de,le,Q,we,Fe,Ee,Ze;if(!O())return;if(H()){let ct=(le=((de=(D=r.launcher)==null?void 0:D.composerBar)!=null?de:{}).expandedSize)!=null?le:"anchored",rt=N?"expanded":"collapsed";ye.dataset.state=rt,ye.dataset.expandedSize=ct,dt&&(dt.dataset.state=rt,dt.dataset.expandedSize=ct),ye.style.removeProperty("display"),ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Of(N),Se.style.display=N?"flex":"none",co(),N?(Bf(),Df()):(cc(),dc()),ds();return}let c=dn(r),m=(Q=e.ownerDocument.defaultView)!=null?Q:window,h=(Fe=(we=r.launcher)==null?void 0:we.mobileBreakpoint)!=null?Fe:640,b=(Ze=(Ee=r.launcher)==null?void 0:Ee.mobileFullscreen)!=null?Ze:!0,S=m.innerWidth<=h,W=b&&S&&k,q=rr(r).reveal;N?(ye.style.removeProperty("display"),ye.style.display=c?"flex":"",ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-95","persona-opacity-0"),J.classList.add("persona-scale-100","persona-opacity-100"),Yt?Yt.element.style.display="none":an&&(an.style.display="none")):(c?c&&(q==="overlay"||q==="push")&&!W?(ye.style.removeProperty("display"),ye.style.display="flex",ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ye.style.setProperty("display","none","important"),ye.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ye.style.display="",ye.classList.add("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-100","persona-opacity-100"),J.classList.add("persona-scale-95","persona-opacity-0")),Yt?Yt.element.style.display=c?"none":"":an&&(an.style.display=c?"none":""))},$t=(c,m="user")=>{var W,q;if(!O()||N===c)return;let h=N;N=c,Us();let b=(()=>{var Ee,Ze,Ue,ct,rt,Re,Pe,ze,Ke,gt;let _=(Ze=(Ee=r.launcher)==null?void 0:Ee.sidebarMode)!=null?Ze:!1,D=(Ue=e.ownerDocument.defaultView)!=null?Ue:window,de=(rt=(ct=r.launcher)==null?void 0:ct.mobileFullscreen)!=null?rt:!0,le=(Pe=(Re=r.launcher)==null?void 0:Re.mobileBreakpoint)!=null?Pe:640,Q=D.innerWidth<=le,we=dn(r)&&de&&Q,Fe=H()&&((gt=(Ke=(ze=r.launcher)==null?void 0:ze.composerBar)==null?void 0:Ke.expandedSize)!=null?gt:"fullscreen")==="fullscreen";return _||de&&Q&&k||we||Fe})();if(N&&b){if(!rn){let _=e.getRootNode(),D=_ instanceof ShadowRoot?_.host:e.closest(".persona-host");D&&(rn=vl(D,(q=(W=r.launcher)==null?void 0:W.zIndex)!=null?q:vn))}on||(on=wl(e.ownerDocument))}else N||(rn==null||rn(),rn=null,on==null||on(),on=null);N&&(qs(),ic()||(Ft()==="follow"?mo(!0):sc()));let S={open:N,source:m,timestamp:Date.now()};N&&!h?i.emit("widget:opened",S):!N&&h&&i.emit("widget:closed",S),i.emit("widget:state",{open:N,launcherEnabled:k,voiceActive:re.active,streaming:$.isStreaming()})},Ni=c=>{ce(c?"stop":"send"),B&&(B.disabled=c),Do.buttons.forEach(m=>{m.disabled=c}),Oe.dataset.personaComposerStreaming=c?"true":"false",Oe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},Oi=()=>{re.active||ee&&ee.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Oi(),200)});let uc=()=>{var h,b,S,W,q,_,D,de,le,Q,we;xr.textContent=(b=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?b:"Hello \u{1F44B}",vr.textContent=(W=(S=r.copy)==null?void 0:S.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",ee.placeholder=(_=(q=r.copy)==null?void 0:q.inputPlaceholder)!=null?_:"How can I help...";let c=ve.querySelector("[data-persona-intro-card]");if(c){let Fe=((D=r.copy)==null?void 0:D.showWelcomeCard)!==!1;c.style.display=Fe?"":"none",Fe?(ve.classList.remove("persona-gap-3"),ve.classList.add("persona-gap-6")):(ve.classList.remove("persona-gap-6"),ve.classList.add("persona-gap-3"))}!((le=(de=r.sendButton)==null?void 0:de.useIcon)!=null&&le)&&!($!=null&&$.isStreaming())&&(je.textContent=(we=(Q=r.copy)==null?void 0:Q.sendButtonLabel)!=null?we:"Send"),ee.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ee.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=p.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{x(m=>({...m,sessionId:c}))}});let Fo=null,Ff=()=>{Fo==null&&(Fo=setInterval(()=>{let c=nt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Fo),Fo=null;return}let m=Date.now();c.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=ja(m-b))})},100))};$=new ca(r,{onMessagesChanged(c){var S,W;Fs(nt,c,Z),Ff(),as(c),mo(!dr),Wf(c);let m=[...c].reverse().find(q=>q.role==="user"),h=[...c].reverse().find(q=>q.role==="assistant");c.length===0&&(Os(),Rr=!0,tt=!1),!ls||Oo?(ls=!0,cs=(S=m==null?void 0:m.id)!=null?S:null,w=(W=h==null?void 0:h.id)!=null?W:null):m&&m.id!==cs?(cs=m.id,If(m.id)):h&&h.id!==w&&Rf(),h&&(w=h.id);let b=re.lastUserMessageId;m&&m.id!==b&&(re.lastUserMessageId=m.id,i.emit("user:message",m)),re.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),sn(c),ds()},onStatusChanged(c){var b;let m=(b=r.statusIndicator)!=null?b:{};Ot(fn,(S=>{var W,q,_,D;return S==="idle"?(W=m.idleText)!=null?W:xn.idle:S==="connecting"?(q=m.connectingText)!=null?q:xn.connecting:S==="connected"?(_=m.connectedText)!=null?_:xn.connected:S==="error"?(D=m.errorText)!=null?D:xn.error:xn[S]})(c),m,c)},onStreamingChanged(c){dr=c,Ni(c),$&&Fs(nt,$.getMessages(),Z),c||mo(!0),On(),no(c?"Responding\u2026":"Response complete."),ds()},onVoiceStatusChanged(c){var m,h;if(i.emit("voice:status",{status:c,timestamp:Date.now()}),((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype")switch(c){case"listening":Xr(),us();break;case"processing":Xr(),qf();break;case"speaking":Xr(),zf();break;default:c==="idle"&&$.isBargeInActive()?(Xr(),us(),B==null||B.setAttribute("aria-label","End voice session")):(re.active=!1,Xr(),pt("system"),Dn());break}},onArtifactsState(c){Hn=c,Er(),sn()}}),wt.current=$;let Fi=null;if($.onReadAloudChange((c,m)=>{var S;so=c,ao=m,io();let h=c!=null?c:Fi;c&&(Fi=c);let b=h&&(S=$.getMessages().find(W=>W.id===h))!=null?S:null;i.emit("message:read-aloud",{messageId:h,message:b,state:m,timestamp:Date.now()}),m==="idle"&&(Fi=null)}),ls=!0,((Td=(Sd=r.voiceRecognition)==null?void 0:Sd.provider)==null?void 0:Td.type)==="runtype")try{$.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&$.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(V||r.onSSEEvent)&&$.setSSEEventCallback((c,m)=>{var h;(h=r.onSSEEvent)==null||h.call(r,c,m),X==null||X.processEvent(c,m),V==null||V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(m)})}),u&&u.then(c=>{var m,h,b;if(c){if(c.metadata&&(p=zl(c.metadata),L.syncFromMetadata()),(m=c.messages)!=null&&m.length){Oo=!0;try{$.hydrateMessages(c.messages)}finally{Oo=!1}}(h=c.artifacts)!=null&&h.length&&$.hydrateArtifacts(c.artifacts,(b=c.selectedArtifactId)!=null?b:null)}}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let mc=()=>{var m,h,b;!H()||N||!((b=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.expandOnSubmit)==null||b)||$t(!0,"auto")},gc=c=>{var S;if(c.preventDefault(),$.isStreaming()){$.cancel(),X==null||X.reset(),He==null||He.update();return}let m=ee.value.trim(),h=(S=vt==null?void 0:vt.hasAttachments())!=null?S:!1;if(!m&&!h)return;mc();let b;h&&(b=[],b.push(...vt.getContentParts()),m&&b.push(Ka(m))),ee.value="",ee.style.height="auto",ka(),$.sendMessage(m,{contentParts:b}),h&&vt.clearAttachments()},_f=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},_i={...ti},$i=!1,ka=()=>{_i={...ti}},$f=()=>$.getMessages().filter(c=>c.role==="user").map(c=>{var m;return(m=c.content)!=null?m:""}).filter(c=>c.length>0),jf=c=>{if(!ee)return;$i=!0,ee.value=c,ee.dispatchEvent(new Event("input",{bubbles:!0})),$i=!1;let m=ee.value.length;ee.setSelectionRange(m,m)},fc=()=>{$i||ka()},hc=c=>{if(ee){if(_f()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let m=ee.selectionStart===0&&ee.selectionEnd===0,h=Gm({direction:c.key==="ArrowUp"?"up":"down",history:$f(),currentValue:ee.value,atStart:m,state:_i});if(_i=h.state,h.handled){c.preventDefault(),h.value!==void 0&&jf(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if($.isStreaming()){c.preventDefault();return}ka(),c.preventDefault(),je.click()}}},yc=c=>{c.key!=="Escape"||c.isComposing||$.isStreaming()&&c.composedPath().includes(Se)&&($.cancel(),X==null||X.reset(),He==null||He.update(),ka(),c.preventDefault(),c.stopImmediatePropagation())},bc=async c=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!vt)return;let m=bw(c.clipboardData);m.length!==0&&(c.preventDefault(),await vt.handleFiles(m))},Qn=null,Wr=!1,ps=null,lt=null,xc=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,La=(c="user")=>{var W,q,_,D,de,le,Q;if(Wr||$.isStreaming())return;let m=xc();if(!m)return;Qn=new m;let b=(q=((W=r.voiceRecognition)!=null?W:{}).pauseDuration)!=null?q:2e3;Qn.continuous=!0,Qn.interimResults=!0,Qn.lang="en-US";let S=ee.value;Qn.onresult=we=>{let Fe="",Ee="";for(let Ue=0;Ue<we.results.length;Ue++){let ct=we.results[Ue],rt=ct[0].transcript;ct.isFinal?Fe+=rt+" ":Ee=rt}let Ze=S+Fe+Ee;ee.value=Ze,ps&&clearTimeout(ps),(Fe||Ee)&&(ps=window.setTimeout(()=>{let Ue=ee.value.trim();Ue&&Qn&&Wr&&(go(),ee.value="",ee.style.height="auto",$.sendMessage(Ue,{viaVoice:!0}))},b))},Qn.onerror=we=>{we.error!=="no-speech"&&go()},Qn.onend=()=>{if(Wr){let we=ee.value.trim();we&&we!==S.trim()&&(ee.value="",ee.style.height="auto",$.sendMessage(we,{viaVoice:!0})),go()}};try{if(Qn.start(),Wr=!0,re.active=!0,c!=="system"&&(re.manuallyDeactivated=!1),pt(c),Dn(),B){let we=(_=r.voiceRecognition)!=null?_:{};lt={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(D=we.iconName)!=null?D:"mic",iconSize:parseFloat((Q=(le=we.iconSize)!=null?le:(de=r.sendButton)==null?void 0:de.size)!=null?Q:"40")||24};let Fe=we.recordingBackgroundColor,Ee=we.recordingIconColor,Ze=we.recordingBorderColor;if(B.classList.add("persona-voice-recording"),B.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=Ee!=null?Ee:"var(--persona-voice-recording-indicator, #ffffff)",Ee){let Ue=B.querySelector("svg");Ue&&Ue.setAttribute("stroke",Ee)}Ze&&(B.style.borderColor=Ze),B.setAttribute("aria-label","Stop voice recognition")}}catch{go("system")}},go=(c="user")=>{if(Wr){if(Wr=!1,ps&&(clearTimeout(ps),ps=null),Qn){try{Qn.stop()}catch{}Qn=null}if(re.active=!1,pt(c),Dn(),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 m=B.querySelector("svg");m&&m.setAttribute("stroke",lt.color||"currentColor"),lt=null}B.setAttribute("aria-label","Start voice recognition")}}},Uf=(c,m)=>{var rt,Re,Pe,ze,Ke,gt,I,De,We;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),b=((rt=c==null?void 0:c.provider)==null?void 0:rt.type)==="runtype",S=((Re=c==null?void 0:c.provider)==null?void 0:Re.type)==="custom";if(!(h||b||S))return null;let q=y("div","persona-send-button-wrapper"),_=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");_.type="button",_.setAttribute("aria-label","Start voice recognition");let D=(Pe=c==null?void 0:c.iconName)!=null?Pe:"mic",de=(ze=m==null?void 0:m.size)!=null?ze:"40px",le=(Ke=c==null?void 0:c.iconSize)!=null?Ke:de,Q=parseFloat(le)||24,we=(gt=c==null?void 0:c.backgroundColor)!=null?gt:m==null?void 0:m.backgroundColor,Fe=(I=c==null?void 0:c.iconColor)!=null?I:m==null?void 0:m.textColor;_.style.width=le,_.style.height=le,_.style.minWidth=le,_.style.minHeight=le,_.style.fontSize="18px",_.style.lineHeight="1",Fe?_.style.color=Fe:_.style.color="var(--persona-text, #111827)";let Ze=ge(D,Q,Fe||"currentColor",1.5);Ze?_.appendChild(Ze):_.textContent="\u{1F3A4}",we?_.style.backgroundColor=we:_.style.backgroundColor="",c!=null&&c.borderWidth&&(_.style.borderWidth=c.borderWidth,_.style.borderStyle="solid"),c!=null&&c.borderColor&&(_.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(_.style.paddingLeft=c.paddingX,_.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(_.style.paddingTop=c.paddingY,_.style.paddingBottom=c.paddingY),q.appendChild(_);let Ue=(De=c==null?void 0:c.tooltipText)!=null?De:"Start voice recognition";if(((We=c==null?void 0:c.showTooltip)!=null?We:!1)&&Ue){let me=y("div","persona-send-button-tooltip");me.textContent=Ue,q.appendChild(me)}return{micButton:_,micButtonWrapper:q}},ji=()=>{var m,h,b,S,W;if(!B||lt)return;let c=(m=r.voiceRecognition)!=null?m:{};lt={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((W=(S=c.iconSize)!=null?S:(b=r.sendButton)==null?void 0:b.size)!=null?W:"40")||24}},Ui=(c,m)=>{var W,q,_,D,de;if(!B)return;let h=B.querySelector("svg");h&&h.remove();let b=(de=lt==null?void 0:lt.iconSize)!=null?de:parseFloat((D=(_=(W=r.voiceRecognition)==null?void 0:W.iconSize)!=null?_:(q=r.sendButton)==null?void 0:q.size)!=null?D:"40")||24,S=ge(c,b,m,1.5);S&&B.appendChild(S)},Pa=()=>{B&&B.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},us=()=>{var S;if(!B)return;ji();let c=(S=r.voiceRecognition)!=null?S:{},m=c.recordingBackgroundColor,h=c.recordingIconColor,b=c.recordingBorderColor;if(Pa(),B.classList.add("persona-voice-recording"),B.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let W=B.querySelector("svg");W&&W.setAttribute("stroke",h)}b&&(B.style.borderColor=b),B.setAttribute("aria-label","Stop voice recognition")},qf=()=>{var _,D,de,le,Q,we,Fe,Ee;if(!B)return;ji();let c=(_=r.voiceRecognition)!=null?_:{},m=$.getVoiceInterruptionMode(),h=(D=c.processingIconName)!=null?D:"loader",b=(le=(de=c.processingIconColor)!=null?de:lt==null?void 0:lt.color)!=null?le:"",S=(we=(Q=c.processingBackgroundColor)!=null?Q:lt==null?void 0:lt.backgroundColor)!=null?we:"",W=(Ee=(Fe=c.processingBorderColor)!=null?Fe:lt==null?void 0:lt.borderColor)!=null?Ee:"";Pa(),B.classList.add("persona-voice-processing"),B.style.backgroundColor=S,B.style.borderColor=W;let q=b||"currentColor";B.style.color=q,Ui(h,q),B.setAttribute("aria-label","Processing voice input"),m==="none"&&(B.style.cursor="default")},zf=()=>{var de,le,Q,we,Fe,Ee,Ze,Ue,ct,rt,Re,Pe;if(!B)return;ji();let c=(de=r.voiceRecognition)!=null?de:{},m=$.getVoiceInterruptionMode(),h=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",b=(le=c.speakingIconName)!=null?le:h,S=(Ee=c.speakingIconColor)!=null?Ee:m==="barge-in"?(we=(Q=c.recordingIconColor)!=null?Q:lt==null?void 0:lt.color)!=null?we:"":(Fe=lt==null?void 0:lt.color)!=null?Fe:"",W=(ct=c.speakingBackgroundColor)!=null?ct:m==="barge-in"?(Ze=c.recordingBackgroundColor)!=null?Ze:"var(--persona-voice-recording-bg, #ef4444)":(Ue=lt==null?void 0:lt.backgroundColor)!=null?Ue:"",q=(Pe=c.speakingBorderColor)!=null?Pe:m==="barge-in"?(rt=c.recordingBorderColor)!=null?rt:"":(Re=lt==null?void 0:lt.borderColor)!=null?Re:"";Pa(),B.classList.add("persona-voice-speaking"),B.style.backgroundColor=W,B.style.borderColor=q;let _=S||"currentColor";B.style.color=_,Ui(b,_);let D=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";B.setAttribute("aria-label",D),m==="none"&&(B.style.cursor="default"),m==="barge-in"&&B.classList.add("persona-voice-recording")},Xr=()=>{var c,m,h;B&&(Pa(),lt&&(B.style.backgroundColor=(c=lt.backgroundColor)!=null?c:"",B.style.color=(m=lt.color)!=null?m:"",B.style.borderColor=(h=lt.borderColor)!=null?h:"",Ui(lt.iconName,lt.color||"currentColor"),lt=null),B.style.cursor="",B.setAttribute("aria-label","Start voice recognition"))},Ia=()=>{var c,m;if(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"){let h=$.getVoiceStatus(),b=$.getVoiceInterruptionMode();if(b==="none"&&(h==="processing"||h==="speaking"))return;if(b==="cancel"&&(h==="processing"||h==="speaking")){$.stopVoicePlayback();return}if($.isBargeInActive()){$.stopVoicePlayback(),$.deactivateBargeIn().then(()=>{re.active=!1,re.manuallyDeactivated=!0,Dn(),pt("user"),Xr()});return}$.toggleVoice().then(()=>{re.active=$.isVoiceActive(),re.manuallyDeactivated=!$.isVoiceActive(),Dn(),pt("user"),$.isVoiceActive()?us():Xr()});return}if(Wr){let h=ee.value.trim();re.manuallyDeactivated=!0,Dn(),go("user"),h&&(ee.value="",ee.style.height="auto",$.sendMessage(h))}else re.manuallyDeactivated=!1,Dn(),La("user")};Ar=Ia,B&&(B.addEventListener("click",Ia),it.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),Xr()):go("system"),B&&B.removeEventListener("click",Ia)}));let Vf=i.on("assistant:complete",()=>{mt&&(re.active||re.manuallyDeactivated||mt==="assistant"&&!re.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!re.active&&!re.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?$.toggleVoice().then(()=>{re.active=$.isVoiceActive(),pt("auto"),$.isVoiceActive()&&us()}):La("auto"))},600))});it.push(Vf);let Kf=i.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});it.push(Kf);let vc=()=>{$t(!N,"user")},Yt=null,an=null;if(k&&!H()){let{instance:c,element:m}=Tl({config:r,plugins:o,onToggle:vc});Yt=c,c||(an=m)}Yt?e.appendChild(Yt.element):an&&e.appendChild(an),Us(),as(),uc(),Ni($.isStreaming()),ic()||(Ft()==="follow"?mo(!0):sc()),po(),P&&(!k||H()?setTimeout(()=>Oi(),0):N&&setTimeout(()=>Oi(),200));let qs=()=>{var D,de,le,Q,we,Fe,Ee,Ze,Ue,ct,rt,Re,Pe,ze,Ke,gt,I,De,We,me,Wt,It;if(H()){qn(),Us();return}let c=dn(r),m=(de=(D=r.launcher)==null?void 0:D.sidebarMode)!=null?de:!1,h=c||m||((Q=(le=r.launcher)==null?void 0:le.fullHeight)!=null?Q:!1),b=(we=e.ownerDocument.defaultView)!=null?we:window,S=(Ee=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Ee:!0,W=(Ue=(Ze=r.launcher)==null?void 0:Ze.mobileBreakpoint)!=null?Ue:640,q=b.innerWidth<=W,_=S&&q&&k;try{if(_){co(),Zo(e,r);return}if(j&&(j=!1,co(),Zo(e,r)),!k&&!c){J.style.height="",J.style.width="";return}if(!m&&!c){let Vt=(rt=(ct=r==null?void 0:r.launcher)==null?void 0:ct.width)!=null?rt:r==null?void 0:r.launcherWidth,ft=Vt!=null?Vt:nr;J.style.width=ft,J.style.maxWidth=ft}if(Bo(),!h){let Vt=b.innerHeight,ft=64,jt=(Pe=(Re=r.launcher)==null?void 0:Re.heightOffset)!=null?Pe:0,Fn=Math.max(200,Vt-ft),Zt=Math.min(640,Fn),Je=Math.max(200,Zt-jt);J.style.height=`${Je}px`}}finally{if(qn(),Us(),N&&k){let ft=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((gt=(Ke=r.launcher)==null?void 0:Ke.mobileBreakpoint)!=null?gt:640),jt=(De=(I=r.launcher)==null?void 0:I.sidebarMode)!=null?De:!1,Fn=(me=(We=r.launcher)==null?void 0:We.mobileFullscreen)!=null?me:!0,Zt=dn(r)&&Fn&&ft,Je=jt||Fn&&ft&&k||Zt;if(Je&&!on){let Tt=e.getRootNode(),nn=Tt instanceof ShadowRoot?Tt.host:e.closest(".persona-host");nn&&!rn&&(rn=vl(nn,(It=(Wt=r.launcher)==null?void 0:Wt.zIndex)!=null?It:vn)),on=wl(e.ownerDocument)}else Je||(rn==null||rn(),rn=null,on==null||on(),on=null)}}};qs();let wc=(Ed=e.ownerDocument.defaultView)!=null?Ed:window;if(wc.addEventListener("resize",qs),it.push(()=>wc.removeEventListener("resize",qs)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{qn()});c.observe(Oe),it.push(()=>c.disconnect())}An=ve.scrollTop;let Cc=Fr(ve),Gf=()=>{let c=ve.getRootNode(),m=typeof c.getSelection=="function"?c.getSelection():null;return m!=null?m:ve.ownerDocument.getSelection()},qi=()=>eg(Gf(),ve),Ac=()=>{let c=ve.scrollTop,m=Fr(ve),h=m<Cc;if(Cc=m,!en()){An=c,On();return}let{action:b,nextLastScrollTop:S}=ri({following:hn.isFollowing(),currentScrollTop:c,lastScrollTop:An,nearBottom:So(ve,U),userScrollThreshold:z,isAutoScrolling:Sn||No||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(An=S,b==="resume"){qi()||uo();return}b==="pause"&&Ns()};if(ve.addEventListener("scroll",Ac,{passive:!0}),it.push(()=>ve.removeEventListener("scroll",Ac)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Pf()});c.observe(nt),c.observe(ve),it.push(()=>c.disconnect())}let Sc=()=>{en()&&hn.isFollowing()&&qi()&&Ns()},Tc=ve.ownerDocument;Tc.addEventListener("selectionchange",Sc),it.push(()=>{Tc.removeEventListener("selectionchange",Sc)});let Jf=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Ec=c=>{sr()&&en()&&hn.isFollowing()&&Jf.has(c.key)&&Ns()},Mc=c=>{if(!sr()||!en()||!hn.isFollowing())return;let m=c.target;m&&m.closest("a, button, [tabindex], input, textarea, select")&&Ns()};ve.addEventListener("keydown",Ec),ve.addEventListener("focusin",Mc),it.push(()=>{ve.removeEventListener("keydown",Ec),ve.removeEventListener("focusin",Mc)});let kc=c=>{if(!en())return;let m=oi({following:hn.isFollowing(),deltaY:c.deltaY,nearBottom:So(ve,U),resumeWhenNearBottom:!0});m==="pause"?Ns():m==="resume"&&!qi()&&uo()};ve.addEventListener("wheel",kc,{passive:!0}),it.push(()=>ve.removeEventListener("wheel",kc)),qt.addEventListener("click",()=>{Os(),ve.scrollTop=ve.scrollHeight,An=ve.scrollTop,uo(),mo(!0),On()}),it.push(()=>qt.remove()),it.push(()=>{Tn(),Os()});let Lc=()=>{A&&(kr&&(A.removeEventListener("click",kr),kr=null),O()?(A.style.display="",kr=()=>{$t(!1,"user")},A.addEventListener("click",kr)):A.style.display="none")};Lc(),(()=>{let{clearChatButton:c}=qe;c&&c.addEventListener("click",()=>{$.clearMessages(),Lr.clear(),uo(),Jo(qe.composerOverlay);try{localStorage.removeItem(Ws),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ws}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ws)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),l!=null&&l.clear)try{let h=l.clear();h instanceof Promise&&h.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}p={},L.syncFromMetadata(),V==null||V.clear(),X==null||X.reset(),He==null||He.update()})})(),bt&&bt.addEventListener("submit",gc),ee==null||ee.addEventListener("keydown",hc),ee==null||ee.addEventListener("input",fc),ee==null||ee.addEventListener("paste",bc);let Pc=(Md=e.ownerDocument)!=null?Md:document;Pc.addEventListener("keydown",yc,!0);let Ic="persona-attachment-drop-active",zs=0,zi=()=>{zs=0,Se.classList.remove(Ic)},ms=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&vt!==null},Rc=c=>{!Ei(c.dataTransfer)||!ms()||(zs++,zs===1&&Se.classList.add(Ic))},Wc=c=>{!Ei(c.dataTransfer)||!ms()||(zs--,zs<=0&&zi())},Hc=c=>{!Ei(c.dataTransfer)||!ms()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Bc=c=>{var h;if(!Ei(c.dataTransfer)||!ms())return;c.preventDefault(),c.stopPropagation(),zi();let m=Array.from((h=c.dataTransfer.files)!=null?h:[]);m.length!==0&&vt.handleFiles(m)},fo=!0;Se.addEventListener("dragenter",Rc,fo),Se.addEventListener("dragleave",Wc,fo),e.addEventListener("dragover",Hc,fo),e.addEventListener("drop",Bc,fo);let Ra=e.ownerDocument,Dc=c=>{ms()&&c.preventDefault()},Nc=c=>{ms()&&c.preventDefault()};Ra.addEventListener("dragover",Dc),Ra.addEventListener("drop",Nc),it.push(()=>{bt&&bt.removeEventListener("submit",gc),ee==null||ee.removeEventListener("keydown",hc),ee==null||ee.removeEventListener("input",fc),ee==null||ee.removeEventListener("paste",bc),Pc.removeEventListener("keydown",yc,!0)}),it.push(()=>{Se.removeEventListener("dragenter",Rc,fo),Se.removeEventListener("dragleave",Wc,fo),e.removeEventListener("dragover",Hc,fo),e.removeEventListener("drop",Bc,fo),Ra.removeEventListener("dragover",Dc),Ra.removeEventListener("drop",Nc),zi()}),it.push(()=>{$.cancel()}),Yt?it.push(()=>{Yt==null||Yt.destroy()}):an&&it.push(()=>{an==null||an.remove()});let tn={update(c){var Nt,un,$n,Br,mn,gn,er,bo,Hd,Bd,Dd,Nd,Od,Fd,_d,$d,jd,Ud,qd,zd,Vd,Kd,Gd,Jd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,xp,vp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Np,Op,Fp,_p,$p,jp,Up,qp,zp,Vp,Kp,Gp,Jp,Xp,Qp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,yu,bu,xu,vu,wu,Cu,Au,Su,Tu,Eu,Mu,ku,Lu,Pu,Iu,Ru;let m=r.toolCall,h=r.messageActions,b=(Nt=r.layout)==null?void 0:Nt.messages,S=r.colorScheme,W=r.loadingIndicator,q=r.iterationDisplay,_=(un=r.features)==null?void 0:un.showReasoning,D=($n=r.features)==null?void 0:$n.showToolCalls,de=(Br=r.features)==null?void 0:Br.toolCallDisplay,le=(mn=r.features)==null?void 0:mn.reasoningDisplay;r={...r,...c},co(),Zo(e,r),wi(e,r),Ci(e,r),Er(),r.colorScheme!==S&&Ds();let Q=Ai.getForInstance(r.plugins);o.length=0,o.push(...Q),k=(er=(gn=r.launcher)==null?void 0:gn.enabled)!=null?er:!0,M=(Hd=(bo=r.launcher)==null?void 0:bo.autoExpand)!=null?Hd:!1,Te=(Dd=(Bd=r.features)==null?void 0:Bd.showReasoning)!=null?Dd:!0,Le=(Od=(Nd=r.features)==null?void 0:Nd.showToolCalls)!=null?Od:!0,Ae=(_d=(Fd=r.features)==null?void 0:Fd.scrollToBottom)!=null?_d:{};let we=Ft();se=(jd=($d=r.features)==null?void 0:$d.scrollBehavior)!=null?jd:{},we!==Ft()&&(Os(),uo()),ro(),On();let Fe=oe;if(oe=(qd=(Ud=r.features)==null?void 0:Ud.showEventStreamToggle)!=null?qd:!1,oe&&!Fe){if(V||(xe=new Sa(ae),V=new Aa(Be,xe),X=X!=null?X:new Ta,xe.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),$.setSSEEventCallback((ne,Ct)=>{var Ut;(Ut=r.onSSEEvent)==null||Ut.call(r,ne,Ct),X==null||X.processEvent(ne,Ct),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(Ct)})})),!ut&&Ie){let ne=(Vd=(zd=r.features)==null?void 0:zd.eventStream)==null?void 0:Vd.classNames,Ct="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:"");ut=y("button",Ct),ut.style.width="28px",ut.style.height="28px",ut.style.color=Mn.actionIconColor,ut.type="button",ut.setAttribute("aria-label","Event Stream"),ut.title="Event Stream";let Ut=ge("activity","18px","currentColor",1.5);Ut&&ut.appendChild(Ut);let ot=qe.clearChatButtonWrapper,Mt=qe.closeButtonWrapper,ln=ot||Mt;ln&&ln.parentNode===Ie?Ie.insertBefore(ut,ln):Ie.appendChild(ut),ut.addEventListener("click",()=>{K?cr():Ur()})}}else!oe&&Fe&&(cr(),ut&&(ut.remove(),ut=null),V==null||V.clear(),xe==null||xe.destroy(),V=null,xe=null,X==null||X.reset(),X=null);if(((Kd=r.launcher)==null?void 0:Kd.enabled)===!1&&Yt&&(Yt.destroy(),Yt=null),((Gd=r.launcher)==null?void 0:Gd.enabled)===!1&&an&&(an.remove(),an=null),((Jd=r.launcher)==null?void 0:Jd.enabled)!==!1&&!Yt&&!an){let{instance:ne,element:Ct}=Tl({config:r,plugins:o,onToggle:vc});Yt=ne,ne||(an=Ct),e.appendChild(Ct)}Yt&&Yt.update(r),Me&&((Xd=r.launcher)==null?void 0:Xd.title)!==void 0&&(Me.textContent=r.launcher.title),Ne&&((Qd=r.launcher)==null?void 0:Qd.subtitle)!==void 0&&(Ne.textContent=r.launcher.subtitle);let Ee=(Yd=r.layout)==null?void 0:Yd.header;if((Ee==null?void 0:Ee.layout)!==F&&Ie){let ne=Ee?va(r,Ee,{showClose:O(),onClose:()=>$t(!1,"user")}):ko({config:r,showClose:O(),onClose:()=>$t(!1,"user")});Xe.replaceHeader(ne),Ie=Xe.header.element,te=Xe.header.iconHolder,Me=Xe.header.headerTitle,Ne=Xe.header.headerSubtitle,A=Xe.header.closeButton,F=Ee==null?void 0:Ee.layout}else if(Ee&&(te&&(te.style.display=Ee.showIcon===!1?"none":""),Me&&(Me.style.display=Ee.showTitle===!1?"none":""),Ne&&(Ne.style.display=Ee.showSubtitle===!1?"none":""),A&&(A.style.display=Ee.showCloseButton===!1?"none":""),qe.clearChatButtonWrapper)){let ne=Ee.showClearChat;if(ne!==void 0){qe.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:Ct}=qe;Ct&&!Ct.classList.contains("persona-absolute")&&(ne?Ct.classList.remove("persona-ml-auto"):Ct.classList.add("persona-ml-auto"))}}let Ue=((Zd=r.layout)==null?void 0:Zd.showHeader)!==!1;Ie&&(Ie.style.display=Ue?"":"none");let ct=((ep=r.layout)==null?void 0:ep.showFooter)!==!1;Oe&&(Oe.style.display=ct?"":"none"),qn(),On(),k!==R?k?$t(M,"auto"):(N=!0,Us()):M!==C&&$t(M,"auto"),C=M,R=k,qs(),Lc();let Pe=JSON.stringify(c.toolCall)!==JSON.stringify(m),ze=JSON.stringify(r.messageActions)!==JSON.stringify(h),Ke=JSON.stringify((tp=r.layout)==null?void 0:tp.messages)!==JSON.stringify(b),gt=((np=r.loadingIndicator)==null?void 0:np.render)!==(W==null?void 0:W.render)||((rp=r.loadingIndicator)==null?void 0:rp.renderIdle)!==(W==null?void 0:W.renderIdle)||((op=r.loadingIndicator)==null?void 0:op.showBubble)!==(W==null?void 0:W.showBubble),I=r.iterationDisplay!==q,De=((ap=(sp=r.features)==null?void 0:sp.showReasoning)!=null?ap:!0)!==(_!=null?_:!0)||((lp=(ip=r.features)==null?void 0:ip.showToolCalls)!=null?lp:!0)!==(D!=null?D:!0)||JSON.stringify((cp=r.features)==null?void 0:cp.toolCallDisplay)!==JSON.stringify(de)||JSON.stringify((dp=r.features)==null?void 0:dp.reasoningDisplay)!==JSON.stringify(le);(Pe||ze||Ke||gt||I||De)&&$&&(is++,Fs(nt,$.getMessages(),Z));let me=(pp=r.launcher)!=null?pp:{},Wt=(up=me.headerIconHidden)!=null?up:!1,It=(gp=(mp=r.layout)==null?void 0:mp.header)==null?void 0:gp.showIcon,Vt=Wt||It===!1,ft=me.headerIconName,jt=(fp=me.headerIconSize)!=null?fp:"48px";if(te){let ne=Se.querySelector(".persona-border-b-persona-divider"),Ct=ne==null?void 0:ne.querySelector(".persona-flex-col");if(Vt)te.style.display="none",ne&&Ct&&!ne.contains(Ct)&&ne.insertBefore(Ct,ne.firstChild);else{if(te.style.display="",te.style.height=jt,te.style.width=jt,ne&&Ct&&(ne.contains(te)?te.nextSibling!==Ct&&(te.remove(),ne.insertBefore(te,Ct)):ne.insertBefore(te,Ct)),ft){let ot=parseFloat(jt)||24,Mt=ge(ft,ot*.6,"currentColor",1);Mt?te.replaceChildren(Mt):te.textContent=(hp=me.agentIconText)!=null?hp:"\u{1F4AC}"}else if(me.iconUrl){let ot=te.querySelector("img");if(ot)ot.src=me.iconUrl,ot.style.height=jt,ot.style.width=jt;else{let Mt=document.createElement("img");Mt.src=me.iconUrl,Mt.alt="",Mt.className="persona-rounded-xl persona-object-cover",Mt.style.height=jt,Mt.style.width=jt,te.replaceChildren(Mt)}}else{let ot=te.querySelector("svg"),Mt=te.querySelector("img");(ot||Mt)&&te.replaceChildren(),te.textContent=(yp=me.agentIconText)!=null?yp:"\u{1F4AC}"}let Ut=te.querySelector("img");Ut&&(Ut.style.height=jt,Ut.style.width=jt)}}let Fn=(xp=(bp=r.layout)==null?void 0:bp.header)==null?void 0:xp.showTitle,Zt=(wp=(vp=r.layout)==null?void 0:vp.header)==null?void 0:wp.showSubtitle;if(Me&&(Me.style.display=Fn===!1?"none":""),Ne&&(Ne.style.display=Zt===!1?"none":""),A){((Ap=(Cp=r.layout)==null?void 0:Cp.header)==null?void 0:Ap.showCloseButton)===!1?A.style.display="none":A.style.display="";let Ct=(Sp=me.closeButtonSize)!=null?Sp:"32px",Ut=(Tp=me.closeButtonPlacement)!=null?Tp:"inline";A.style.height=Ct,A.style.width=Ct;let{closeButtonWrapper:ot}=qe,Mt=Ut==="top-right",ln=ot==null?void 0:ot.classList.contains("persona-absolute");if(ot&&Mt!==ln)if(ot.remove(),Mt)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Se.style.position="relative",Se.appendChild(ot);else{let st=(Mp=(Ep=me.clearChat)==null?void 0:Ep.placement)!=null?Mp:"inline",cn=(Lp=(kp=me.clearChat)==null?void 0:kp.enabled)!=null?Lp:!0;ot.className=cn&&st==="inline"?"":"persona-ml-auto";let Pn=Se.querySelector(".persona-border-b-persona-divider");Pn&&Pn.appendChild(ot)}if(A.style.color=me.closeButtonColor||Mn.actionIconColor,me.closeButtonBackgroundColor?(A.style.backgroundColor=me.closeButtonBackgroundColor,A.classList.remove("hover:persona-bg-gray-100")):(A.style.backgroundColor="",A.classList.add("hover:persona-bg-gray-100")),me.closeButtonBorderWidth||me.closeButtonBorderColor){let st=me.closeButtonBorderWidth||"0px",cn=me.closeButtonBorderColor||"transparent";A.style.border=`${st} solid ${cn}`,A.classList.remove("persona-border-none")}else A.style.border="",A.classList.add("persona-border-none");me.closeButtonBorderRadius?(A.style.borderRadius=me.closeButtonBorderRadius,A.classList.remove("persona-rounded-full")):(A.style.borderRadius="",A.classList.add("persona-rounded-full")),me.closeButtonPaddingX?(A.style.paddingLeft=me.closeButtonPaddingX,A.style.paddingRight=me.closeButtonPaddingX):(A.style.paddingLeft="",A.style.paddingRight=""),me.closeButtonPaddingY?(A.style.paddingTop=me.closeButtonPaddingY,A.style.paddingBottom=me.closeButtonPaddingY):(A.style.paddingTop="",A.style.paddingBottom="");let bn=(Pp=me.closeButtonIconName)!=null?Pp:"x",fr=(Ip=me.closeButtonIconText)!=null?Ip:"\xD7";A.innerHTML="";let En=ge(bn,"28px","currentColor",1);En?A.appendChild(En):A.textContent=fr;let Qt=(Rp=me.closeButtonTooltipText)!=null?Rp:"Close chat",jn=(Wp=me.closeButtonShowTooltip)!=null?Wp:!0;if(A.setAttribute("aria-label",Qt),ot&&(ot._cleanupTooltip&&(ot._cleanupTooltip(),delete ot._cleanupTooltip),jn&&Qt)){let st=null,cn=()=>{if(st||!A)return;let qo=A.ownerDocument,Vs=qo.body;if(!Vs)return;st=Nr(qo,"div","persona-clear-chat-tooltip"),st.textContent=Qt;let Ks=Nr(qo,"div");Ks.className="persona-clear-chat-tooltip-arrow",st.appendChild(Ks);let zo=A.getBoundingClientRect();st.style.position="fixed",st.style.zIndex=String(To),st.style.left=`${zo.left+zo.width/2}px`,st.style.top=`${zo.top-8}px`,st.style.transform="translate(-50%, -100%)",Vs.appendChild(st)},Pn=()=>{st&&st.parentNode&&(st.parentNode.removeChild(st),st=null)};ot.addEventListener("mouseenter",cn),ot.addEventListener("mouseleave",Pn),A.addEventListener("focus",cn),A.addEventListener("blur",Pn),ot._cleanupTooltip=()=>{Pn(),ot&&(ot.removeEventListener("mouseenter",cn),ot.removeEventListener("mouseleave",Pn)),A&&(A.removeEventListener("focus",cn),A.removeEventListener("blur",Pn))}}}let{clearChatButton:Je,clearChatButtonWrapper:Tt}=qe;if(Je){let ne=(Hp=me.clearChat)!=null?Hp:{},Ct=(Bp=ne.enabled)!=null?Bp:!0,Ut=(Np=(Dp=r.layout)==null?void 0:Dp.header)==null?void 0:Np.showClearChat,ot=Ut!==void 0?Ut:Ct,Mt=(Op=ne.placement)!=null?Op:"inline";if(Tt){Tt.style.display=ot?"":"none";let{closeButtonWrapper:ln}=qe;!H()&&ln&&!ln.classList.contains("persona-absolute")&&(ot?ln.classList.remove("persona-ml-auto"):ln.classList.add("persona-ml-auto"));let bn=Mt==="top-right",fr=Tt.classList.contains("persona-absolute");if(!H()&&bn!==fr&&ot){if(Tt.remove(),bn)Tt.className="persona-absolute persona-top-4 persona-z-50",Tt.style.right="48px",Se.style.position="relative",Se.appendChild(Tt);else{Tt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Tt.style.right="";let Qt=Se.querySelector(".persona-border-b-persona-divider"),jn=qe.closeButtonWrapper;Qt&&jn&&jn.parentElement===Qt?Qt.insertBefore(Tt,jn):Qt&&Qt.appendChild(Tt)}let En=qe.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(bn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(ot){if(!H()){let st=(Fp=ne.size)!=null?Fp:"32px";Je.style.height=st,Je.style.width=st}let ln=(_p=ne.iconName)!=null?_p:"refresh-cw",bn=($p=ne.iconColor)!=null?$p:"";Je.style.color=bn||Mn.actionIconColor,Je.innerHTML="";let fr=H()?"14px":"20px",En=ge(ln,fr,"currentColor",2);if(En&&Je.appendChild(En),ne.backgroundColor?(Je.style.backgroundColor=ne.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),ne.borderWidth||ne.borderColor){let st=ne.borderWidth||"0px",cn=ne.borderColor||"transparent";Je.style.border=`${st} solid ${cn}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");ne.borderRadius?(Je.style.borderRadius=ne.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),ne.paddingX?(Je.style.paddingLeft=ne.paddingX,Je.style.paddingRight=ne.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),ne.paddingY?(Je.style.paddingTop=ne.paddingY,Je.style.paddingBottom=ne.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let Qt=(jp=ne.tooltipText)!=null?jp:"Clear chat",jn=(Up=ne.showTooltip)!=null?Up:!0;if(Je.setAttribute("aria-label",Qt),Tt&&(Tt._cleanupTooltip&&(Tt._cleanupTooltip(),delete Tt._cleanupTooltip),jn&&Qt)){let st=null,cn=()=>{if(st||!Je)return;let qo=Je.ownerDocument,Vs=qo.body;if(!Vs)return;st=Nr(qo,"div","persona-clear-chat-tooltip"),st.textContent=Qt;let Ks=Nr(qo,"div");Ks.className="persona-clear-chat-tooltip-arrow",st.appendChild(Ks);let zo=Je.getBoundingClientRect();st.style.position="fixed",st.style.zIndex=String(To),st.style.left=`${zo.left+zo.width/2}px`,st.style.top=`${zo.top-8}px`,st.style.transform="translate(-50%, -100%)",Vs.appendChild(st)},Pn=()=>{st&&st.parentNode&&(st.parentNode.removeChild(st),st=null)};Tt.addEventListener("mouseenter",cn),Tt.addEventListener("mouseleave",Pn),Je.addEventListener("focus",cn),Je.addEventListener("blur",Pn),Tt._cleanupTooltip=()=>{Pn(),Tt&&(Tt.removeEventListener("mouseenter",cn),Tt.removeEventListener("mouseleave",Pn)),Je&&(Je.removeEventListener("focus",cn),Je.removeEventListener("blur",Pn))}}}}let nn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Si],Zn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Rs.message,Rs.messageAndClick];L=Ti({parsers:nn,handlers:Zn,getSessionMetadata:v,updateSessionMetadata:x,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),Z=Vg(r,L,pe),$.updateConfig(r),Fs(nt,$.getMessages(),Z),as(),uc(),Ni($.isStreaming());let _n=((qp=r.voiceRecognition)==null?void 0:qp.enabled)===!0,_o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),$o=((Vp=(zp=r.voiceRecognition)==null?void 0:zp.provider)==null?void 0:Vp.type)==="runtype";if(_n&&(_o||$o))if(!B||!be){let ne=Uf(r.voiceRecognition,r.sendButton);ne&&(B=ne.micButton,be=ne.micButtonWrapper,Pt.insertBefore(be,wn),B.addEventListener("click",Ia),B.disabled=$.isStreaming())}else{let ne=(Kp=r.voiceRecognition)!=null?Kp:{},Ct=(Gp=r.sendButton)!=null?Gp:{},Ut=(Jp=ne.iconName)!=null?Jp:"mic",ot=(Xp=Ct.size)!=null?Xp:"40px",Mt=(Qp=ne.iconSize)!=null?Qp:ot,ln=parseFloat(Mt)||24;B.style.width=Mt,B.style.height=Mt,B.style.minWidth=Mt,B.style.minHeight=Mt;let bn=(Zp=(Yp=ne.iconColor)!=null?Yp:Ct.textColor)!=null?Zp:"currentColor";B.innerHTML="";let fr=ge(Ut,ln,bn,2);fr?B.appendChild(fr):B.textContent="\u{1F3A4}";let En=(eu=ne.backgroundColor)!=null?eu:Ct.backgroundColor;En?B.style.backgroundColor=En:B.style.backgroundColor="",bn?B.style.color=bn:B.style.color="var(--persona-text, #111827)",ne.borderWidth?(B.style.borderWidth=ne.borderWidth,B.style.borderStyle="solid"):(B.style.borderWidth="",B.style.borderStyle=""),ne.borderColor?B.style.borderColor=ne.borderColor:B.style.borderColor="",ne.paddingX?(B.style.paddingLeft=ne.paddingX,B.style.paddingRight=ne.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),ne.paddingY?(B.style.paddingTop=ne.paddingY,B.style.paddingBottom=ne.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let Qt=be==null?void 0:be.querySelector(".persona-send-button-tooltip"),jn=(tu=ne.tooltipText)!=null?tu:"Start voice recognition";if(((nu=ne.showTooltip)!=null?nu:!1)&&jn)if(Qt)Qt.textContent=jn,Qt.style.display="";else{let cn=document.createElement("div");cn.className="persona-send-button-tooltip",cn.textContent=jn,be==null||be.insertBefore(cn,B)}else Qt&&(Qt.style.display="none");be.style.display="",B.disabled=$.isStreaming()}else B&&be&&(be.style.display="none",((ou=(ru=r.voiceRecognition)==null?void 0:ru.provider)==null?void 0:ou.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():Wr&&go());if(((su=r.attachments)==null?void 0:su.enabled)===!0)if(!xt||!_e){let ne=(au=r.attachments)!=null?au:{},Ut=(lu=((iu=r.sendButton)!=null?iu:{}).size)!=null?lu:"40px";Rt||(Rt=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Rt.style.display="none",bt.insertBefore(Rt,ee)),Ye||(Ye=document.createElement("input"),Ye.type="file",Ye.accept=((cu=ne.allowedTypes)!=null?cu:Zr).join(","),Ye.multiple=((du=ne.maxFiles)!=null?du:4)>1,Ye.style.display="none",Ye.setAttribute("aria-label","Attach files"),bt.insertBefore(Ye,ee)),xt=y("div","persona-send-button-wrapper"),_e=y("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",(pu=ne.buttonTooltipText)!=null?pu:"Attach file");let ot=(uu=ne.buttonIconName)!=null?uu:"paperclip",Mt=Ut,ln=parseFloat(Mt)||40,bn=Math.round(ln*.6);_e.style.width=Mt,_e.style.height=Mt,_e.style.minWidth=Mt,_e.style.minHeight=Mt,_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 fr=ge(ot,bn,"currentColor",1.5);fr?_e.appendChild(fr):_e.textContent="\u{1F4CE}",_e.addEventListener("click",jn=>{jn.preventDefault(),Ye==null||Ye.click()}),xt.appendChild(_e);let En=(mu=ne.buttonTooltipText)!=null?mu:"Attach file",Qt=y("div","persona-send-button-tooltip");Qt.textContent=En,xt.appendChild(Qt),at.append(xt),!vt&&Ye&&Rt&&(vt=Ts.fromConfig(ne),vt.setPreviewsContainer(Rt),Ye.addEventListener("change",async()=>{vt&&(Ye!=null&&Ye.files)&&(await vt.handleFileSelect(Ye.files),Ye.value="")})),Se.querySelector(".persona-attachment-drop-overlay")||Se.appendChild(Kg(ne.dropOverlay))}else{xt.style.display="";let ne=(gu=r.attachments)!=null?gu:{};Ye&&(Ye.accept=((fu=ne.allowedTypes)!=null?fu:Zr).join(","),Ye.multiple=((hu=ne.maxFiles)!=null?hu:4)>1),vt&&vt.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}else xt&&(xt.style.display="none"),vt&&vt.clearAttachments(),(yu=Se.querySelector(".persona-attachment-drop-overlay"))==null||yu.remove();let Gt=(bu=r.sendButton)!=null?bu:{},jo=(xu=Gt.useIcon)!=null?xu:!1,ho=(vu=Gt.iconText)!=null?vu:"\u2191",yo=Gt.iconName,Qr=(wu=Gt.tooltipText)!=null?wu:"Send message",Uo=(Cu=Gt.showTooltip)!=null?Cu:!1,gr=(Au=Gt.size)!=null?Au:"40px",Hr=Gt.backgroundColor,Qe=Gt.textColor;if(jo){if(je.style.width=gr,je.style.height=gr,je.style.minWidth=gr,je.style.minHeight=gr,je.style.fontSize="18px",je.style.lineHeight="1",je.innerHTML="",Qe?je.style.color=Qe:je.style.color="var(--persona-button-primary-fg, #ffffff)",yo){let ne=parseFloat(gr)||24,Ct=(Qe==null?void 0:Qe.trim())||"currentColor",Ut=ge(yo,ne,Ct,2);Ut?je.appendChild(Ut):je.textContent=ho}else je.textContent=ho;je.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Hr?(je.style.backgroundColor=Hr,je.classList.remove("persona-bg-persona-primary")):(je.style.backgroundColor="",je.classList.add("persona-bg-persona-primary"))}else je.textContent=(Tu=(Su=r.copy)==null?void 0:Su.sendButtonLabel)!=null?Tu:"Send",je.style.width="",je.style.height="",je.style.minWidth="",je.style.minHeight="",je.style.fontSize="",je.style.lineHeight="",je.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",Hr?(je.style.backgroundColor=Hr,je.classList.remove("persona-bg-persona-accent")):je.classList.add("persona-bg-persona-accent"),Qe?je.style.color=Qe:je.classList.add("persona-text-white");Gt.borderWidth?(je.style.borderWidth=Gt.borderWidth,je.style.borderStyle="solid"):(je.style.borderWidth="",je.style.borderStyle=""),Gt.borderColor?je.style.borderColor=Gt.borderColor:je.style.borderColor="",Gt.paddingX?(je.style.paddingLeft=Gt.paddingX,je.style.paddingRight=Gt.paddingX):(je.style.paddingLeft="",je.style.paddingRight=""),Gt.paddingY?(je.style.paddingTop=Gt.paddingY,je.style.paddingBottom=Gt.paddingY):(je.style.paddingTop="",je.style.paddingBottom="");let Ht=wn==null?void 0:wn.querySelector(".persona-send-button-tooltip");if(Uo&&Qr)if(Ht)Ht.textContent=Qr,Ht.style.display="";else{let ne=document.createElement("div");ne.className="persona-send-button-tooltip",ne.textContent=Qr,wn==null||wn.insertBefore(ne,je)}else Ht&&(Ht.style.display="none");let zt=(Pu=(Eu=r.layout)==null?void 0:Eu.contentMaxWidth)!=null?Pu:H()?(Lu=(ku=(Mu=r.launcher)==null?void 0:Mu.composerBar)==null?void 0:ku.contentMaxWidth)!=null?Lu:"720px":void 0;zt?(nt.style.maxWidth=zt,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%",bt&&(bt.style.maxWidth=zt,bt.style.marginLeft="auto",bt.style.marginRight="auto"),Lt&&(Lt.style.maxWidth=zt,Lt.style.marginLeft="auto",Lt.style.marginRight="auto")):(nt.style.maxWidth="",nt.style.marginLeft="",nt.style.marginRight="",nt.style.width="",bt&&(bt.style.maxWidth="",bt.style.marginLeft="",bt.style.marginRight=""),Lt&&(Lt.style.maxWidth="",Lt.style.marginLeft="",Lt.style.marginRight=""));let Bt=(Iu=r.statusIndicator)!=null?Iu:{},Jt=(Ru=Bt.visible)!=null?Ru:!0;if(fn.style.display=Jt?"":"none",$){let ne=$.getStatus();Ot(fn,(Ut=>{var ot,Mt,ln,bn;return Ut==="idle"?(ot=Bt.idleText)!=null?ot:xn.idle:Ut==="connecting"?(Mt=Bt.connectingText)!=null?Mt:xn.connecting:Ut==="connected"?(ln=Bt.connectedText)!=null?ln:xn.connected:Ut==="error"?(bn=Bt.errorText)!=null?bn:xn.error:xn[Ut]})(ne),Bt,ne)}fn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Et=Bt.align==="left"?"persona-text-left":Bt.align==="center"?"persona-text-center":"persona-text-right";fn.classList.add(Et)},open(){O()&&$t(!0,"api")},close(){O()&&$t(!1,"api")},toggle(){O()&&$t(!N,"api")},clearChat(){Cn=!1,$.clearMessages(),Lr.clear(),uo();try{localStorage.removeItem(Ws),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ws}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ws)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),l!=null&&l.clear)try{let m=l.clear();m instanceof Promise&&m.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}p={},L.syncFromMetadata(),V==null||V.clear(),X==null||X.reset(),He==null||He.update()},setMessage(c){return!ee||$.isStreaming()?!1:(!N&&O()&&$t(!0,"system"),ee.value=c,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if($.isStreaming())return!1;let m=(c==null?void 0:c.trim())||ee.value.trim();return m?(!N&&O()&&$t(!0,"system"),ee.value="",ee.style.height="auto",$.sendMessage(m),!0):!1},startVoiceRecognition(){var m,h;return $.isStreaming()?!1:((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype"?($.isVoiceActive()||(!N&&O()&&$t(!0,"system"),re.manuallyDeactivated=!1,Dn(),$.toggleVoice().then(()=>{re.active=$.isVoiceActive(),pt("user"),$.isVoiceActive()&&us()})),!0):Wr?!0:xc()?(!N&&O()&&$t(!0,"system"),re.manuallyDeactivated=!1,Dn(),La("user"),!0):!1},stopVoiceRecognition(){var c,m;return((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?$.isVoiceActive()?($.toggleVoice().then(()=>{re.active=!1,re.manuallyDeactivated=!0,Dn(),pt("user"),Xr()}),!0):!1:Wr?(re.manuallyDeactivated=!0,Dn(),go("user"),!0):!1},injectMessage(c){return!N&&O()&&$t(!0,"system"),$.injectMessage(c)},injectAssistantMessage(c){!N&&O()&&$t(!0,"system");let m=$.injectAssistantMessage(c);return Y&&(Y=!1,ke&&(clearTimeout(ke),ke=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),m},injectUserMessage(c){return!N&&O()&&$t(!0,"system"),$.injectUserMessage(c)},injectSystemMessage(c){return!N&&O()&&$t(!0,"system"),$.injectSystemMessage(c)},injectMessageBatch(c){return!N&&O()&&$t(!0,"system"),$.injectMessageBatch(c)},injectComponentDirective(c){return!N&&O()&&$t(!0,"system"),$.injectComponentDirective(c)},injectTestMessage(c){!N&&O()&&$t(!0,"system"),$.injectTestEvent(c)},async connectStream(c,m){return $.connectStream(c,m)},__pushEventStreamEvent(c){V&&(X==null||X.processEvent(c.type,c.payload),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!oe||!V||Ur()},hideEventStream(){K&&cr()},isEventStreamVisible(){return K},showArtifacts(){or(r)&&(Cn=!1,Er(),yt==null||yt.setMobileOpen(!0))},hideArtifacts(){or(r)&&(Cn=!0,Er())},upsertArtifact(c){return or(r)?(Cn=!1,$.upsertArtifact(c)):null},selectArtifact(c){or(r)&&$.selectArtifact(c)},clearArtifacts(){or(r)&&$.clearArtifacts()},getArtifacts(){var c;return(c=$==null?void 0:$.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=$==null?void 0:$.getSelectedArtifactId())!=null?c:null},focusInput(){return k&&!N&&!H()||!ee?!1:(ee.focus(),!0)},async resolveApproval(c,m,h){let S=$.getMessages().find(W=>{var q;return W.variant==="approval"&&((q=W.approval)==null?void 0:q.id)===c});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${c}`);if(S.approval.toolType==="webmcp"){$.resolveWebMcpApproval(S.id,m);return}return $.resolveApproval(S.approval,m,h)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(c){x(c)},on(c,m){return i.on(c,m)},off(c,m){i.off(c,m)},isOpen(){return O()&&N},isVoiceActive(){return re.active},toggleReadAloud(c){$.toggleReadAloud(c)},stopReadAloud(){$.stopSpeaking()},getReadAloudState(c){return $.getReadAloudState(c)},onReadAloudChange(c){return $.onReadAloudChange(c)},getState(){return{open:O()&&N,launcherEnabled:k,voiceActive:re.active,streaming:$.isStreaming()}},showCSATFeedback(c){!N&&O()&&$t(!0,"system");let m=nt.querySelector(".persona-feedback-container");m&&m.remove();let h=Ul({onSubmit:async(b,S)=>{var W;$.isClientTokenMode()&&await $.submitCSATFeedback(b,S),(W=c==null?void 0:c.onSubmit)==null||W.call(c,b,S)},onDismiss:c==null?void 0:c.onDismiss,...c});nt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!N&&O()&&$t(!0,"system");let m=nt.querySelector(".persona-feedback-container");m&&m.remove();let h=ql({onSubmit:async(b,S)=>{var W;$.isClientTokenMode()&&await $.submitNPSFeedback(b,S),(W=c==null?void 0:c.onSubmit)==null||W.call(c,b,S)},onDismiss:c==null?void 0:c.onDismiss,...c});nt.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,m){return $.submitCSATFeedback(c,m)},async submitNPSFeedback(c,m){return $.submitNPSFeedback(c,m)},destroy(){Fo!=null&&(clearInterval(Fo),Fo=null),it.forEach(c=>c()),ye.remove(),dt==null||dt.remove(),Yt==null||Yt.destroy(),an==null||an.remove(),kr&&A.removeEventListener("click",kr)}};if((((kd=n==null?void 0:n.debugTools)!=null?kd:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,m={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:h=>h?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=m,it.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",m),it.push(()=>{window.removeEventListener("persona:focusInput",m)}),oe){let _=de=>{let le=de.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&tn.showEventStream()},D=de=>{let le=de.detail;(!(le!=null&&le.instanceId)||le.instanceId===c)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",_),window.addEventListener("persona:hideEventStream",D),it.push(()=>{window.removeEventListener("persona:showEventStream",_),window.removeEventListener("persona:hideEventStream",D)})}let h=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&tn.showArtifacts()},b=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&tn.hideArtifacts()},S=_=>{let D=_.detail;D!=null&&D.instanceId&&D.instanceId!==c||D!=null&&D.artifact&&tn.upsertArtifact(D.artifact)},W=_=>{let D=_.detail;D!=null&&D.instanceId&&D.instanceId!==c||typeof(D==null?void 0:D.id)=="string"&&tn.selectArtifact(D.id)},q=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===c)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",b),window.addEventListener("persona:upsertArtifact",S),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",q),it.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",q)})}let Yn=xw(r.persistState);if(Yn&&O()){let c=vw(Yn.storage),m=`${Yn.keyPrefix}widget-open`,h=`${Yn.keyPrefix}widget-voice`,b=`${Yn.keyPrefix}widget-voice-mode`;if(c){let S=((Ld=Yn.persist)==null?void 0:Ld.openState)&&c.getItem(m)==="true",W=((Pd=Yn.persist)==null?void 0:Pd.voiceState)&&c.getItem(h)==="true",q=((Id=Yn.persist)==null?void 0:Id.voiceState)&&c.getItem(b)==="true";if(S&&setTimeout(()=>{tn.open(),setTimeout(()=>{var _;if(W||q)tn.startVoiceRecognition();else if((_=Yn.persist)!=null&&_.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(Rd=Yn.persist)!=null&&Rd.openState&&(i.on("widget:opened",()=>{c.setItem(m,"true")}),i.on("widget:closed",()=>{c.setItem(m,"false")})),(Wd=Yn.persist)!=null&&Wd.voiceState&&(i.on("voice:state",_=>{c.setItem(h,_.active?"true":"false")}),i.on("user:message",_=>{c.setItem(b,_.viaVoice?"true":"false")})),Yn.clearOnChatClear){let _=()=>{c.removeItem(m),c.removeItem(h),c.removeItem(b)},D=()=>_();window.addEventListener("persona:clear-chat",D),it.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return g&&O()&&setTimeout(()=>{tn.open()},0),ds(),Ma||Ou().then(()=>{$&&(is++,Lr.clear(),Fs(nt,$.getMessages(),Z))}).catch(()=>{}),tn};var ww=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(n);return o?Math.max(0,t*parseFloat(o[1])/100):420},Cw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Aw=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Sw=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Gg=(e,t)=>{var r,o;let n=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},Xl=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Jg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Xl(e)},Kl=e=>{e.style.transition=""},Gl=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},Jl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Mi=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Tw=(e,t,n,r,o)=>{o?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Ew=(e,t,n,r,o,s)=>{let a=s?t:e;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},Xg=(e,t,n,r,o,s,a)=>{var v,x,E,T,L,k;let i=rr(s),d=i.reveal==="push";Tw(e,t,n,r,d),Ew(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(x=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?x:!0,u=(T=(E=s==null?void 0:s.launcher)==null?void 0:E.mobileBreakpoint)!=null?T:640,g=l!=null?l.innerWidth<=u:!1;if(p&&g&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Gl(t),Kl(r),Jg(r),Jl(n),Mi(o,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((k=(L=s==null?void 0:s.launcher)==null?void 0:L.zIndex)!=null?k:vn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Jg(r),Cw(r,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Gl(t),Kl(r),Jl(n),Mi(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"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Kl(r),Xl(r),Mi(o,r);let M=ww(i.width,e.clientWidth),P=Math.max(0,e.clientWidth),C=i.animate?"margin-left 180ms ease":"none",R=i.side==="right"?a?-M:0:a?0:-M;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${P+M}px`,t.style.transition=C,t.style.marginLeft=`${R}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${P}px`,n.style.maxWidth=`${P}px`,n.style.minWidth=`${P}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Gl(t),Xl(r),Jl(n),Mi(o,r);let M=i.reveal==="emerge";M?e.dataset.personaDockReveal="emerge":e.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",R=!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",Aw(r,i.maxHeight),r.style.overflow=M||R?"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")}},Mw=(e,t)=>{let n=e.ownerDocument.createElement("div");return Gg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Gg(n,r)},destroy(){n.remove()}}},kw=(e,t)=>{var k,M,P,C;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),p=n.createElement("div"),u=(M=(k=t==null?void 0:t.launcher)==null?void 0:k.enabled)==null||M?(C=(P=t==null?void 0:t.launcher)==null?void 0:P.autoExpand)!=null?C:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let g=null,f=()=>{g==null||g.disconnect(),g=null},v=()=>{f(),rr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Xg(a,i,d,l,p,t,u)}),g.observe(a))},x=!1,E=()=>{Xg(a,i,d,l,p,t,u),v(),u&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,Sw(a,rr(t)))},T=a.ownerDocument.defaultView,L=()=>{E()};return T==null||T.addEventListener("resize",L),rr(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),E(),{mode:"docked",host:p,shell:a,syncWidgetState(R){let F=R.launcherEnabled?R.open:!0;u!==F&&(u=F,E())},updateConfig(R){var F,j;t=R,((j=(F=t==null?void 0:t.launcher)==null?void 0:F.enabled)!=null?j:!0)===!1&&(u=!0),E()},destroy(){T==null||T.removeEventListener("resize",L),f(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},ki=(e,t)=>dn(t)?kw(e,t):Mw(e,t);var Ql={},Lw=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Pw=()=>{try{if(typeof Ql!="undefined"&&Ql.url)return new URL("../widget.css",Ql.url).href}catch{}return null},Qg=(e,t)=>{let n=Pw(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),t.head.appendChild(s)}},Yg=e=>{var E;let t=Lw(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=ki(t,o),a,i=[],d=(T,L)=>{var C,R;let M=!((R=(C=L==null?void 0:L.launcher)==null?void 0:C.enabled)!=null?R:!0)||dn(L),P=r.createElement("div");if(P.setAttribute("data-persona-root","true"),M&&(P.style.height="100%",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1",P.style.minHeight="0"),n){let F=T.attachShadow({mode:"open"});F.appendChild(P),Qg(F,r)}else T.appendChild(P),Qg(T,r);return t.id&&P.setAttribute("data-persona-instance",t.id),P},l=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(T=>T()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},u=()=>{let T=d(s.host,o);a=Vl(T,o,{debugTools:e.debugTools}),p()},g=()=>{i.forEach(T=>T()),i=[],a.destroy()};u(),(E=e.onChatReady)==null||E.call(e);let f=T=>{g(),s.destroy(),s=ki(t,T),o=T,u()},v={update(T){var R,F,j,H,O,N;let L={...o,...T,launcher:{...(R=o==null?void 0:o.launcher)!=null?R:{},...(F=T==null?void 0:T.launcher)!=null?F:{},dock:{...(H=(j=o==null?void 0:o.launcher)==null?void 0:j.dock)!=null?H:{},...(N=(O=T==null?void 0:T.launcher)==null?void 0:O.dock)!=null?N:{}}}},k=dn(o),M=dn(L),P=Mo(o),C=Mo(L);if(k!==M||P!==C){f(L);return}o=L,s.updateConfig(o),a.update(T),l()},destroy(){g(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},x=new Proxy(v,{get(T,L,k){if(L==="host")return s.host;if(L in T)return Reflect.get(T,L,k);let M=a[L];return typeof M=="function"?M.bind(a):M}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=x),x};var rf=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Iw=new Set(["button","a","input","select","textarea","details","summary"]),Rw=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Yl=/\b(product|card|item|listing|result)\b/i,ec=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Ww=3e3,Hw=100;function of(e){let t=typeof e.className=="string"?e.className:"";if(Yl.test(t)||e.id&&Yl.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&Yl.test(r.value))return!0}return!1}function sf(e){var t;return ec.test(((t=e.textContent)!=null?t:"").trim())}function af(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let o=(n=t[r].getAttribute("href"))!=null?n:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function Bw(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Zg(e){let t=e.match(ec);return t?t[0]:null}function ef(e){var r,o,s;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((o=t.textContent)!=null&&o.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(s=n==null?void 0:n.textContent)!=null&&s.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Dw(e){let t=[],n=r=>{let o=r.trim();o&&!t.includes(o)&&t.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;n((o=r.value)!=null?o:"")}),t.slice(0,6)}var Nw="commerce-card",Ow="result-card";function tf(e){return!of(e)||!sf(e)||!af(e)&&!Bw(e)?0:5200}function nf(e){var r;return!of(e)||sf(e)||!af(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var lf=[{id:Nw,scoreElement(e){return tf(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||ec.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(tf(e)===0)return null;let{title:n,href:r}=ef(e),o=(p=(l=Zg(((d=e.textContent)!=null?d:"").trim()))!=null?l:Zg(t.text))!=null?p:"",s=Dw(e);return[r&&n?`[${n}](${r})${o?`: ${o}`:""}`:n?`${n}${o?`: ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
112
- `)}},{id:Ow,scoreElement(e){return nf(e)},formatSummary(e,t){if(nf(e)===0)return null;let{title:n,href:r}=ef(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
113
- `)}}];function Fw(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function _w(e){var p,u,g,f,v,x,E,T,L,k,M,P,C;let t=(p=e.options)!=null?p:{},n=(g=(u=t.maxElements)!=null?u:e.maxElements)!=null?g:80,r=(v=(f=t.excludeSelector)!=null?f:e.excludeSelector)!=null?v:".persona-host",o=(E=(x=t.maxTextLength)!=null?x:e.maxTextLength)!=null?E:200,s=(L=(T=t.visibleOnly)!=null?T:e.visibleOnly)!=null?L:!0,a=(k=t.root)!=null?k:e.root,i=(M=t.mode)!=null?M:"structured",d=(P=t.maxCandidates)!=null?P:Math.max(500,n*10),l=(C=e.rules)!=null?C:lf;return i==="simple"&&e.rules&&e.rules.length>0?(Fw(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function Zl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var $w=["data-testid","data-product","data-action","data-id","data-name","data-type"];function jw(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||Iw.has(t)||n&&Rw.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function cf(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Uw(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);let s=e.getAttribute("type");s&&(t.type=s);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let l=0;l<e.attributes.length;l++){let p=e.attributes[l];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function df(e){let t=e.tagName.toLowerCase();if(e.id){let o=`#${Zl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of $w){let s=e.getAttribute(o);if(s){let a=`${t}[${o}="${Zl(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(n.length>0){let o=`${t}.${n.map(a=>Zl(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let s=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function qw(e){return e==="static"?Hw:Ww}function pf(e,t){var o;let n=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,t);return{selector:df(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:jw(e),attributes:Uw(e)}}function zw(e,t,n,r){let o=qw(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function Vw(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function Kw(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(rf.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!cf(l)){i=a.nextNode();continue}let u=pf(l,e.maxTextLength),g=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(E=>E==="role");if(!g&&!f){i=a.nextNode();continue}if(r.has(u.selector)){i=a.nextNode();continue}r.add(u.selector);let{score:v,formattingRule:x}=zw(l,u,e.rules,n);o.push({el:l,domIndex:s,enriched:u,score:v,formattingRule:x}),s+=1}i=a.nextNode()}o.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return u!==g?u-g:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of o){if(d.length>=e.maxElements)break;Vw(d,l)||d.push(l)}return d.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,g=p.enriched.interactivity==="static"?1:0;return u!==g?u-g:u===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var g;let p;if((g=l.formattingRule)!=null&&g.formatSummary){let f=l.formattingRule.formatSummary(l.el,l.enriched,n);f&&(p=f)}let u={...l.enriched};return p&&(u.formattedSummary=p),u})}function Gw(e,t){let n=[],r=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,l=d.tagName.toLowerCase();if(rf.has(l)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!cf(d)){s=o.nextNode();continue}let p=pf(d,e.maxTextLength),u=p.text.length>0,g=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(f=>f==="role");if(!u&&!g){s=o.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}s=o.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function Jw(e={}){var r;let t=_w(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?Gw(t,n):Kw(t,n):[]}var Li=100;function Xw(e,t={}){var s;if(e.length===0)return"No page elements found.";let n=(s=t.mode)!=null?s:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
111
+ `}if(!x&&!l){let Nt="max-height: -moz-available !important; max-height: stretch !important;",Bt=m?"":"padding-top: 1.25em !important;",Vt=m?"":`z-index: ${(et=(Uo=r.launcher)==null?void 0:Uo.zIndex)!=null?et:xn} !important;`;ge.style.cssText+=Nt+Bt+Vt}Xe()};oo(),es(e,r),Ci(e,r),Ai(e,r);let lt=[];lt.push(()=>{document.removeEventListener("keydown",$r)}),lt.push(()=>{ir!==null&&clearTimeout(ir)});let rn=null,on=null;lt.push(()=>{rn==null||rn(),rn=null,on==null||on(),on=null}),Dn&&lt.push(()=>{Dn==null||Dn.disconnect(),Dn=null}),lt.push(()=>{Jn==null||Jn(),Jn=null,as(),Ft&&(Ft.remove(),Ft=null),vt==null||vt.element.style.removeProperty("width"),vt==null||vt.element.style.removeProperty("maxWidth")}),ne&&lt.push(()=>{le!==null&&(cancelAnimationFrame(le),le=null),Me==null||Me.destroy(),Me=null,V==null||V.destroy(),V=null,fe=null});let Tr=null,Os=()=>{Tr&&(Tr(),Tr=null),r.colorScheme==="auto"&&(Tr=xl(()=>{es(e,r)}))};Os(),lt.push(()=>{Tr&&(Tr(),Tr=null)}),lt.push(a);let Ur=(Sd=r.features)==null?void 0:Sd.streamAnimation;if(Ur!=null&&Ur.type&&Ur.type!=="none"){let l=ks(Ur.type,Ur.plugins);l&&(li(l,e),lt.push(()=>hg(e)))}let Ho=Fg(qt),Er=null,F,is=l=>{var x,A;if(!F)return;let m=l!=null?l:F.getMessages(),h=((A=(x=r.features)==null?void 0:x.suggestReplies)==null?void 0:A.enabled)!==!1?rl(m):null;h?Ho.render(h,F,be,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(W=>W.role==="user")?Ho.render([],F,be,m):Ho.render(r.suggestionChips,F,be,m,r.suggestionChipsConfig)},cr=!1,Mr=ig(),qr=new Map,kr=new Map,dr=new Map,ls=0,Ma=Vo()!==null,hn=ni(),Cn=0,pr=null,An=!1,Bo=!1,ur=0,yn=null,Lr=null,cs=!1,Do=!1,ds=null,so=!0,ao=!1,ot=null,w=4,z=24,q=80,G=new Map,K={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ne=(Ed=(Td=r.voiceRecognition)==null?void 0:Td.autoResume)!=null?Ed:!1,rt=l=>{i.emit("voice:state",{active:K.active,source:l,timestamp:Date.now()})},ct=()=>{v(l=>({...l,voiceState:{active:K.active,timestamp:Date.now(),manuallyDeactivated:K.manuallyDeactivated}}))},Di=()=>{var x,A;if(((x=r.voiceRecognition)==null?void 0:x.enabled)===!1)return;let l=Kl(p.voiceState),m=!!l.active,h=Number((A=l.timestamp)!=null?A:0);K.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-h<Lw&&setTimeout(()=>{var W,U;K.active||(K.manuallyDeactivated=!1,((U=(W=r.voiceRecognition)==null?void 0:W.provider)==null?void 0:U.type)==="runtype"?F.toggleVoice().then(()=>{K.active=F.isVoiceActive(),rt("restore"),F.isVoiceActive()&&ms()}):La("restore"))},1e3)},io=()=>F?nf(F.getMessages()).filter(l=>!l.__skipPersist):[];function Pn(l){if(!(c!=null&&c.save))return;let h={messages:l?nf(l):F?io():[],metadata:p,artifacts:Nn.artifacts,selectedArtifactId:Nn.selectedId};try{let x=c.save(h);x instanceof Promise&&x.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)})}catch(x){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",x)}}let Qt=null,lo=()=>ge.querySelector("#persona-scroll-container")||we,Xn=()=>{Qt!==null&&(cancelAnimationFrame(Qt),Qt=null),An=!1},Sn=()=>{pr!==null&&(cancelAnimationFrame(pr),pr=null),Bo=!1,Xn()},In=()=>cr&&Ni()&&(Ot()!=="anchor-top"||sr()),Tn=()=>{let l=xt()||"Jump to latest",m=In();zt.toggleAttribute("data-persona-scroll-to-bottom-streaming",m),ur>0?(Hn.textContent=String(ur),Hn.style.display="",zt.setAttribute("aria-label",`${l} (${ur} new)`)):(Hn.textContent="",Hn.style.display="none",zt.setAttribute("aria-label",m?`${l} (response streaming below)`:l))},sc=()=>{ur!==0&&(ur=0,Tn())},Ni=()=>en()?!hn.isFollowing():!Co(we,z),Fn=()=>{if(!Xt()||J){zt.parentNode&&zt.remove(),zt.style.display="none";return}zt.parentNode!==Se&&Se.appendChild(zt),zn();let m=Br(we)>0&&Ni();m?Tn():sc(),zt.style.display=m?"":"none"},Fs=()=>{hn.pause()&&(Sn(),Fn())},co=()=>{hn.resume(),sc(),Fn()},po=(l=!1)=>{en()&&hn.isFollowing()&&(!l&&!cr||(pr!==null&&(cancelAnimationFrame(pr),pr=null),Bo=!0,pr=requestAnimationFrame(()=>{pr=null,Bo=!1,hn.isFollowing()&&Ff(lo(),l?220:140)})))},ac=(l,m,h,x=()=>!0)=>{let A=l.scrollTop,W=m(),U=W-A;if(Xn(),Math.abs(U)<1){An=!0,l.scrollTop=W,Cn=l.scrollTop,An=!1;return}let _=performance.now();An=!0;let D=oe=>1-Math.pow(1-oe,3),ie=oe=>{if(!x()){Xn();return}let Y=m();Y!==W&&(W=Y,U=W-A);let ve=oe-_,Oe=Math.min(ve/h,1),Fe=D(Oe),je=A+U*Fe;l.scrollTop=je,Cn=l.scrollTop,Oe<1?Qt=requestAnimationFrame(ie):(l.scrollTop=W,Cn=l.scrollTop,Qt=null,An=!1)};Qt=requestAnimationFrame(ie)},Ff=(l,m=500)=>{let h=Br(l)-l.scrollTop;if(Math.abs(h)<1){Cn=l.scrollTop;return}if(Math.abs(h)>=q){Xn(),An=!0,l.scrollTop=Br(l),Cn=l.scrollTop,An=!1;return}ac(l,()=>Br(l),m,()=>hn.isFollowing())},ic=()=>{let l=lo();An=!0,l.scrollTop=Br(l),Cn=l.scrollTop,An=!1,Fn()},lc=l=>{let m=0,h=l;for(;h&&h!==we;)m+=h.offsetTop,h=h.offsetParent;return m},cc=()=>{var W;if(Nr()!=="last-user-turn")return!1;let l=(W=F==null?void 0:F.getMessages())!=null?W:[];if(l.length<2)return!1;let m=[...l].reverse().find(U=>U.role==="user");if(!m)return!1;let h=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(m.id):m.id.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),x=we.querySelector(`[data-message-id="${h}"]`);if(!x)return!1;let A=Math.min(Math.max(0,lc(x)-xr()),Br(we));return An=!0,we.scrollTop=A,Cn=we.scrollTop,An=!1,Ot()==="follow"&&!Co(we,z)&&hn.pause(),Fn(),!0},dc=l=>{kn.style.height=`${Math.max(0,Math.round(l))}px`,yn&&(yn.spacerHeight=Math.max(0,l))},_s=()=>{Lr!==null&&(cancelAnimationFrame(Lr),Lr=null),Xn(),yn=null,kn.style.height="0px"},_f=l=>{Lr!==null&&cancelAnimationFrame(Lr),Lr=requestAnimationFrame(()=>{var D;Lr=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(l):l.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),h=we.querySelector(`[data-message-id="${m}"]`);if(!h)return;let x=lc(h),A=(D=yn==null?void 0:yn.spacerHeight)!=null?D:0,W=we.scrollHeight-A,{targetScrollTop:U,spacerHeight:_}=ug({anchorOffsetTop:x,topOffset:xr(),viewportHeight:we.clientHeight,contentHeight:W});yn={initialSpacerHeight:_,contentHeightAtAnchor:W,spacerHeight:_},dc(_),ac(we,()=>U,220)})},$f=()=>{if(en()){if(!hn.isFollowing()||Co(we,1))return;po(!cr);return}if(yn&&yn.initialSpacerHeight>0){let l=we.scrollHeight-yn.spacerHeight,m=mg({initialSpacerHeight:yn.initialSpacerHeight,contentHeightAtAnchor:yn.contentHeightAtAnchor,currentContentHeight:l});m!==yn.spacerHeight&&dc(m)}Fn()},jf=l=>{let m=Ot();m==="follow"?(co(),po(!0)):m==="anchor-top"&&(so=!1,ao=!0,_f(l))},Uf=()=>{if(Ot()==="anchor-top"){if(ao){so=!1;return}so=!0,_s(),co(),po(!0)}},qf=l=>{let m=new Map;l.forEach(h=>{let x=G.get(h.id);m.set(h.id,{streaming:h.streaming,role:h.role}),!x&&h.role==="assistant"&&(i.emit("assistant:message",h),!Do&&(Ot()!=="anchor-top"||sr())&&Ni()&&(ur+=1,Tn(),Fn(),Qr(ur===1?"1 new message below.":`${ur} new messages below.`))),h.role==="assistant"&&(x!=null&&x.streaming)&&h.streaming===!1&&i.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(x?h.approval.status!=="pending"&&i.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):i.emit("approval:requested",{approval:h.approval,message:h}))}),G.clear(),m.forEach((h,x)=>{G.set(x,h)})},zf=(l,m,h)=>{var st,Be,Re,ze,Xe,bt;let x=document.createElement("div"),W=(()=>{var De;let H=o.find(We=>We.renderLoadingIndicator);if(H!=null&&H.renderLoadingIndicator)return H.renderLoadingIndicator;if((De=r.loadingIndicator)!=null&&De.render)return r.loadingIndicator.render})(),U=(H,De)=>De==null?!1:typeof De=="string"?(H.textContent=De,!0):(H.appendChild(De),!0),_=new Set,D=new Set,ie=o.some(H=>H.renderAskUserQuestion),oe=[],Y=[],ve=r.enableComponentStreaming!==!1,Oe=r.approval!==!1,Fe=[];if(m.forEach(H=>{var mn,_n,Ge,It,$n,Oo,Fo,_o,$o,fs,hs,Jt,jo,go,fo,Vr,Uo;_.add(H.id);let De=ie&&yo(H),We=Oe&&H.variant==="approval"&&!!H.approval,Ye=!De&&H.role==="assistant"&&!H.variant&&ve&&Ul(H);if(!We&&dr.has(H.id)){let et=l.querySelector(`#wrapper-${H.id}`);et==null||et.removeAttribute("data-preserve-runtime"),dr.delete(H.id)}if(!Ye&&kr.has(H.id)){let et=l.querySelector(`#wrapper-${H.id}`);et==null||et.removeAttribute("data-preserve-runtime"),kr.delete(H.id)}let Pt=yo(H)?`:${(mn=H.agentMetadata)!=null&&mn.askUserQuestionAnswered?"a":"u"}:${(_n=H.agentMetadata)!=null&&_n.askUserQuestionAnswers?Object.keys(H.agentMetadata.askUserQuestionAnswers).length:0}`:"",_e=ag(H,ls)+Pt,Kt=De||We||Ye?null:lg(Mr,H.id,_e);if(Kt){x.appendChild(Kt.cloneNode(!0)),yo(H)&&((Ge=H.toolCall)!=null&&Ge.id)&&((It=H.agentMetadata)==null?void 0:It.awaitingLocalTool)===!0&&!(($n=H.agentMetadata)!=null&&$n.askUserQuestionAnswered)&&(D.add(H.toolCall.id),na(H,r,Ve.composerOverlay));return}let wt=null,an=o.find(et=>!!(H.variant==="reasoning"&&et.renderReasoning||H.variant==="tool"&&et.renderToolCall||!H.variant&&et.renderMessage)),Rn=(Oo=r.layout)==null?void 0:Oo.messages;if(yo(H)&&((Fo=H.agentMetadata)==null?void 0:Fo.askUserQuestionAnswered)===!0){qr.delete(H.id);let et=l.querySelector(`#wrapper-${H.id}`);et==null||et.removeAttribute("data-preserve-runtime");return}if(Fa(H)&&(($o=(_o=r.features)==null?void 0:_o.suggestReplies)==null?void 0:$o.enabled)!==!1)return;if(yo(H)&&((hs=(fs=r.features)==null?void 0:fs.askUserQuestion)==null?void 0:hs.enabled)!==!1){let et=o.find(Nt=>typeof Nt.renderAskUserQuestion=="function");if(et&&St.current){let Nt=qr.get(H.id),Bt=Nt!==_e,Vt=null;if(Bt){let{payload:jt,complete:gn}=bo(H),jn=H.id,Ir=()=>{var pn;return(pn=St.current)==null?void 0:pn.getMessages().find(un=>un.id===jn)};Vt=et.renderAskUserQuestion({message:H,payload:jt,complete:gn,resolve:pn=>{var Zn;let un=Ir();un&&((Zn=St.current)==null||Zn.resolveAskUserQuestion(un,pn))},dismiss:()=>{var un,Zn,ho;let pn=Ir();(un=pn==null?void 0:pn.agentMetadata)!=null&&un.awaitingLocalTool&&((Zn=St.current)==null||Zn.markAskUserQuestionResolved(pn),(ho=St.current)==null||ho.resolveAskUserQuestion(pn,"(dismissed)"))},config:r})}let $t=Nt!=null;if(Bt&&Vt===null&&!$t){((Jt=H.agentMetadata)==null?void 0:Jt.awaitingLocalTool)===!0&&!((jo=H.agentMetadata)!=null&&jo.askUserQuestionAnswered)&&(D.add(H.toolCall.id),na(H,r,Ve.composerOverlay));return}let mt=document.createElement("div");mt.className="persona-flex",mt.id=`wrapper-${H.id}`,mt.setAttribute("data-wrapper-id",H.id),mt.setAttribute("data-ask-plugin-stub","true"),mt.setAttribute("data-preserve-runtime","true"),x.appendChild(mt),oe.push({messageId:H.id,fingerprint:_e,bubble:Vt});return}else{((go=H.agentMetadata)==null?void 0:go.awaitingLocalTool)===!0&&!((fo=H.agentMetadata)!=null&&fo.askUserQuestionAnswered)&&(D.add(H.toolCall.id),na(H,r,Ve.composerOverlay));return}}else if(We){let et=(Vr=o.find($t=>typeof $t.renderApproval=="function"))!=null?Vr:s,Bt=dr.get(H.id)!==_e,Vt=null;if(Bt&&(et!=null&&et.renderApproval)){let $t=H.id,mt=(jt,gn)=>{var Ir,pn,un;let jn=(Ir=St.current)==null?void 0:Ir.getMessages().find(Zn=>Zn.id===$t);jn!=null&&jn.approval&&(jn.approval.toolType==="webmcp"?(pn=St.current)==null||pn.resolveWebMcpApproval(jn.id,jt):(un=St.current)==null||un.resolveApproval(jn.approval,jt,gn))};Vt=et.renderApproval({message:H,defaultRenderer:()=>vi(H,r),config:r,approve:jt=>mt("approved",jt),deny:jt=>mt("denied",jt)})}if(Bt&&Vt===null){let $t=l.querySelector(`#wrapper-${H.id}`);$t==null||$t.removeAttribute("data-preserve-runtime"),dr.delete(H.id),wt=vi(H,r)}else{let $t=document.createElement("div");$t.className="persona-flex",$t.id=`wrapper-${H.id}`,$t.setAttribute("data-wrapper-id",H.id),$t.setAttribute("data-approval-plugin-stub","true"),$t.setAttribute("data-preserve-runtime","true"),x.appendChild($t),Fe.push({messageId:H.id,fingerprint:_e,bubble:Vt});return}}else if(an)if(H.variant==="reasoning"&&H.reasoning&&an.renderReasoning){if(!Le)return;wt=an.renderReasoning({message:H,defaultRenderer:()=>Pl(H,r),config:r})}else if(H.variant==="tool"&&H.toolCall&&an.renderToolCall){if(!Pe)return;wt=an.renderToolCall({message:H,defaultRenderer:()=>Rl(H,r),config:r})}else an.renderMessage&&(wt=an.renderMessage({message:H,defaultRenderer:()=>{let et=Ca(H,h,Rn,r.messageActions,he,{loadingIndicatorRenderer:W,widgetConfig:r});return H.role!=="user"&&Nl(et,H,r,F),et},config:r}));if(!wt&&Ye){let et=ql(H);if(et){let Nt=kr.get(H.id),Bt=Nt!==_e,Vt=r.wrapComponentDirectiveInBubble!==!1,$t=null;if(Bt){let mt=jl(et,{config:r,message:H,transform:h});if(mt)if(Vt){let jt=document.createElement("div");if(jt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),jt.id=`bubble-${H.id}`,jt.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let gn=document.createElement("div");gn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",gn.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),jt.appendChild(gn)}jt.appendChild(mt),$t=jt}else{let jt=document.createElement("div");if(jt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",jt.id=`bubble-${H.id}`,jt.setAttribute("data-message-id",H.id),jt.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let gn=document.createElement("div");gn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",gn.innerHTML=h({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),jt.appendChild(gn)}jt.appendChild(mt),$t=jt}}if($t||Nt!=null){let mt=document.createElement("div");mt.className="persona-flex",mt.id=`wrapper-${H.id}`,mt.setAttribute("data-wrapper-id",H.id),mt.setAttribute("data-component-directive-stub","true"),mt.setAttribute("data-preserve-runtime","true"),Vt||mt.classList.add("persona-w-full"),x.appendChild(mt),Y.push({messageId:H.id,fingerprint:_e,bubble:$t});return}}}if(!wt)if(H.variant==="reasoning"&&H.reasoning){if(!Le)return;wt=Pl(H,r)}else if(H.variant==="tool"&&H.toolCall){if(!Pe)return;wt=Rl(H,r)}else if(H.variant==="approval"&&H.approval){if(r.approval===!1)return;wt=vi(H,r)}else{let et=(Uo=r.layout)==null?void 0:Uo.messages;et!=null&&et.renderUserMessage&&H.role==="user"?wt=et.renderUserMessage({message:H,config:r,streaming:!!H.streaming}):et!=null&&et.renderAssistantMessage&&H.role==="assistant"?wt=et.renderAssistantMessage({message:H,config:r,streaming:!!H.streaming}):wt=Ca(H,h,et,r.messageActions,he,{loadingIndicatorRenderer:W,widgetConfig:r}),H.role!=="user"&&wt&&Nl(wt,H,r,F)}let Ht=document.createElement("div");Ht.className="persona-flex",Ht.id=`wrapper-${H.id}`,Ht.setAttribute("data-wrapper-id",H.id),H.role==="user"&&Ht.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&Ht.classList.add("persona-w-full"),Ht.appendChild(wt),cg(Mr,H.id,_e,Ht),x.appendChild(Ht)}),Ve.composerOverlay&&Ve.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(De=>{let We=De.getAttribute("data-persona-ask-sheet-for");We&&!D.has(We)&&Jo(Ve.composerOverlay,We)}),(Be=(st=r.features)==null?void 0:st.toolCallDisplay)!=null&&Be.grouped){let H=[],De=[];m.forEach(We=>{if(We.variant==="tool"&&We.toolCall&&Pe){De.push(We);return}De.length>1&&H.push(De),De=[]}),De.length>1&&H.push(De),H.forEach((We,Ye)=>{var mn,_n;let Pt=We.map(Ge=>Array.from(x.children).find(It=>It instanceof HTMLElement&&It.getAttribute("data-wrapper-id")===Ge.id)).filter(Ge=>!!Ge);if(Pt.length<2)return;let _e=document.createElement("div");_e.className="persona-flex",_e.id=`wrapper-tool-group-${Ye}-${We[0].id}`,_e.setAttribute("data-wrapper-id",`tool-group-${Ye}-${We[0].id}`);let Kt=document.createElement("div");Kt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Kt.setAttribute("data-persona-tool-group","true");let wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let an=`Called ${We.length} tools`,Rn=(_n=(mn=r.toolCall)==null?void 0:mn.renderGroupedSummary)==null?void 0:_n.call(mn,{messages:We,toolCalls:We.map(Ge=>Ge.toolCall).filter(Ge=>!!Ge),defaultSummary:an,config:r});U(wt,Rn)||(wt.textContent=an);let Ht=document.createElement("div");Ht.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(wt,Ht),_e.appendChild(Kt),Pt[0].before(_e),Pt.forEach((Ge,It)=>{let $n=document.createElement("div");$n.className="persona-tool-group-item persona-relative",$n.setAttribute("data-persona-tool-group-item","true"),It<Pt.length-1&&$n.setAttribute("data-persona-tool-group-connector","true"),$n.appendChild(Ge),Ht.appendChild($n)})})}dg(Mr,_);let je=m.some(H=>H.role==="assistant"&&H.streaming),qe=m[m.length-1],ut=(qe==null?void 0:qe.role)==="assistant"&&!qe.streaming&&qe.variant!=="approval";if(cr&&m.some(H=>H.role==="user")&&!je&&!ut){let H={config:r,streaming:!0,location:"standalone",defaultRenderer:Ps},De=o.find(Ye=>Ye.renderLoadingIndicator),We=null;if(De!=null&&De.renderLoadingIndicator&&(We=De.renderLoadingIndicator(H)),We===null&&((Re=r.loadingIndicator)!=null&&Re.render)&&(We=r.loadingIndicator.render(H)),We===null&&(We=Ps()),We){let Ye=document.createElement("div"),Pt=((ze=r.loadingIndicator)==null?void 0:ze.showBubble)!==!1;Ye.className=Pt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ye.setAttribute("data-typing-indicator","true"),Ye.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ye.appendChild(We);let _e=document.createElement("div");_e.className="persona-flex",_e.id="wrapper-typing-indicator",_e.setAttribute("data-wrapper-id","typing-indicator"),_e.appendChild(Ye),x.appendChild(_e)}}if(!cr&&m.length>0){let H=m[m.length-1],De={config:r,lastMessage:H,messageCount:m.length},We=o.find(Pt=>Pt.renderIdleIndicator),Ye=null;if(We!=null&&We.renderIdleIndicator&&(Ye=We.renderIdleIndicator(De)),Ye===null&&((Xe=r.loadingIndicator)!=null&&Xe.renderIdle)&&(Ye=r.loadingIndicator.renderIdle(De)),Ye){let Pt=document.createElement("div"),_e=((bt=r.loadingIndicator)==null?void 0:bt.showBubble)!==!1;Pt.className=_e?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Pt.setAttribute("data-idle-indicator","true"),Pt.appendChild(Ye);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-idle-indicator",Kt.setAttribute("data-wrapper-id","idle-indicator"),Kt.appendChild(Pt),x.appendChild(Kt)}}if(ei(l,x),oe.length>0)for(let{messageId:H,fingerprint:De,bubble:We}of oe){let Ye=l.querySelector(`#wrapper-${H}`);Ye&&We!==null&&(Ye.replaceChildren(We),Ye.setAttribute("data-bubble-fp",De),qr.set(H,De))}if(qr.size>0)for(let H of qr.keys())_.has(H)||qr.delete(H);if(Y.length>0)for(let{messageId:H,fingerprint:De,bubble:We}of Y){let Ye=l.querySelector(`#wrapper-${H}`);Ye&&We!==null&&(Ye.replaceChildren(We),Ye.setAttribute("data-bubble-fp",De),kr.set(H,De))}if(kr.size>0)for(let H of kr.keys())_.has(H)||kr.delete(H);if(Fe.length>0)for(let{messageId:H,fingerprint:De,bubble:We}of Fe){let Ye=l.querySelector(`#wrapper-${H}`);Ye&&We!==null&&(Ye.replaceChildren(We),Ye.setAttribute("data-bubble-fp",De),dr.set(H,De))}if(dr.size>0)for(let H of dr.keys())_.has(H)||dr.delete(H)},$s=(l,m,h)=>{zf(l,m,h),no()},js=null,Vf=()=>{var h;if(js)return;let l=x=>{let A=x.composedPath();A.includes(ge)||it&&A.includes(it)||_t(!1,"user")};js=l,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",l,!0)},pc=()=>{var m;if(!js)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",js,!0),js=null};lt.push(()=>pc());let Us=null,Kf=()=>{var h;if(Us)return;let l=x=>{x.key==="Escape"&&(x.isComposing||_t(!1,"user"))};Us=l,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",l,!0)},uc=()=>{var m;if(!Us)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",Us,!0),Us=null};lt.push(()=>uc());let qs=!1,mc=new Set,Gf=()=>{var m,h,x,A;let l=(x=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.peek)==null?void 0:x.streamAnimation;return l||((A=r.features)==null?void 0:A.streamAnimation)},ps=()=>{var ut,st,Be,Re;if(!R())return;let l=Ve.peekBanner,m=Ve.peekTextNode;if(!l||!m)return;if(O){l.classList.remove("persona-pill-peek--visible");return}let h=(ut=F==null?void 0:F.getMessages())!=null?ut:[],x;for(let ze=h.length-1;ze>=0;ze--){let Xe=h[ze];if(Xe.role==="assistant"&&Xe.content){x=Xe;break}}if(!x){l.classList.remove("persona-pill-peek--visible");return}let A=x.content,W=!!x.streaming,U=Gf(),_=si(U),D=_.type!=="none"?ks(_.type,U==null?void 0:U.plugins):null,ie=((st=D==null?void 0:D.isAnimating)==null?void 0:st.call(D,x))===!0,oe=D!==null&&(W||ie);oe&&D&&!mc.has(D.name)&&(li(D,e),mc.add(D.name));let Y=oe&&(D!=null&&D.containerClass)?D.containerClass:null,ve=(Be=m.dataset.personaPeekStreamClass)!=null?Be:null;ve&&ve!==Y&&(m.classList.remove(ve),delete m.dataset.personaPeekStreamClass),Y&&ve!==Y&&(m.classList.add(Y),m.dataset.personaPeekStreamClass=Y),oe?(m.style.setProperty("--persona-stream-step",`${_.speed}ms`),m.style.setProperty("--persona-stream-duration",`${_.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let Oe=oe?ai(A,_.buffer,D,x,W):A;if(oe&&_.placeholder==="skeleton"&&W&&(!Oe||!Oe.trim())){let ze=document.createElement("div"),Xe=ya();Xe.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Xe),ei(m,ze)}else{let ze=Math.max(0,Oe.length-100),Xe=Oe.length>100?Oe.slice(-100):Oe,bt=Kr(Xe);if(!oe||!D){let H=Oe.length>100?`\u2026${Xe}`:Xe;m.textContent!==H&&(m.textContent=H)}else{let H=bt;(D.wrap==="char"||D.wrap==="word")&&(H=ha(bt,D.wrap,`peek-${x.id}`,{skipTags:D.skipTags,startIndex:ze}));let De=document.createElement("div");if(De.innerHTML=H,D.useCaret&&Xe.length>0){let We=ii(),Ye=De.querySelectorAll(".persona-stream-char, .persona-stream-word"),Pt=Ye[Ye.length-1];Pt!=null&&Pt.parentNode?Pt.parentNode.insertBefore(We,Pt.nextSibling):De.appendChild(We)}ei(m,De),(Re=D.onAfterRender)==null||Re.call(D,{container:m,bubble:l,messageId:x.id,message:x,speed:_.speed,duration:_.duration})}}let qe=cr||qs;l.classList.toggle("persona-pill-peek--visible",qe)};if(R()){let l=Ve.peekBanner;if(l){let x=A=>{A.preventDefault(),A.stopPropagation(),_t(!0,"user")};l.addEventListener("pointerdown",x),lt.push(()=>{l.removeEventListener("pointerdown",x)})}let m=()=>{qs||(qs=!0,ps())},h=()=>{qs&&(qs=!1,ps())};X.addEventListener("pointerenter",m),X.addEventListener("pointerleave",h),lt.push(()=>{X.removeEventListener("pointerenter",m),X.removeEventListener("pointerleave",h)}),it&&(it.addEventListener("pointerenter",m),it.addEventListener("pointerleave",h),lt.push(()=>{it.removeEventListener("pointerenter",m),it.removeEventListener("pointerleave",h)}))}let Jf=l=>{var ve,Oe,Fe,je,qe,ut,st,Be;let m=(Oe=(ve=r.launcher)==null?void 0:ve.composerBar)!=null?Oe:{},h=(Fe=m.expandedSize)!=null?Fe:"anchored",x=(je=m.bottomOffset)!=null?je:"16px",A=m.collapsedMaxWidth,W=(qe=m.expandedMaxWidth)!=null?qe:"880px",U=(ut=m.expandedTopOffset)!=null?ut:"5vh",_=(st=m.modalMaxWidth)!=null?st:"880px",D=(Be=m.modalMaxHeight)!=null?Be:"min(90vh, 800px)",ie="calc(100vw - 32px)",oe="var(--persona-pill-area-height, 80px)",Y=ge.style;if(Y.left="",Y.right="",Y.top="",Y.bottom="",Y.transform="",Y.width="",Y.maxWidth="",Y.height="",Y.maxHeight="",it){let Re=it.style;Re.bottom=x,Re.width=A!=null?A:""}if(l&&h!=="fullscreen"){if(h==="modal"){Y.top="50%",Y.left="50%",Y.transform="translate(-50%, -50%)",Y.bottom="auto",Y.right="auto",Y.width=_,Y.maxWidth=ie,Y.maxHeight=D,Y.height=D;return}Y.left="50%",Y.transform="translateX(-50%)",Y.bottom=`calc(${x} + ${oe})`,Y.top=U,Y.width=W,Y.maxWidth=ie}},zs=()=>{var D,ie,oe,Y,ve,Oe,Fe,je;if(!N())return;if(R()){let ut=(oe=((ie=(D=r.launcher)==null?void 0:D.composerBar)!=null?ie:{}).expandedSize)!=null?oe:"anchored",st=O?"expanded":"collapsed";ge.dataset.state=st,ge.dataset.expandedSize=ut,it&&(it.dataset.state=st,it.dataset.expandedSize=ut),ge.style.removeProperty("display"),ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Jf(O),Se.style.display=O?"flex":"none",oo(),O?(Vf(),Kf()):(pc(),uc()),ps();return}let l=dn(r),m=(Y=e.ownerDocument.defaultView)!=null?Y:window,h=(Oe=(ve=r.launcher)==null?void 0:ve.mobileBreakpoint)!=null?Oe:640,x=(je=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?je:!0,A=m.innerWidth<=h,W=x&&A&&P,U=nr(r).reveal;O?(ge.style.removeProperty("display"),ge.style.display=l?"flex":"",ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-95","persona-opacity-0"),X.classList.add("persona-scale-100","persona-opacity-100"),Zt?Zt.element.style.display="none":sn&&(sn.style.display="none")):(l?l&&(U==="overlay"||U==="push")&&!W?(ge.style.removeProperty("display"),ge.style.display="flex",ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ge.style.setProperty("display","none","important"),ge.classList.remove("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ge.style.display="",ge.classList.add("persona-pointer-events-none","persona-opacity-0"),X.classList.remove("persona-scale-100","persona-opacity-100"),X.classList.add("persona-scale-95","persona-opacity-0")),Zt?Zt.element.style.display=l?"none":"":sn&&(sn.style.display=l?"none":""))},_t=(l,m="user")=>{var W,U;if(!N()||O===l)return;let h=O;O=l,zs();let x=(()=>{var Fe,je,qe,ut,st,Be,Re,ze,Xe,bt;let _=(je=(Fe=r.launcher)==null?void 0:Fe.sidebarMode)!=null?je:!1,D=(qe=e.ownerDocument.defaultView)!=null?qe:window,ie=(st=(ut=r.launcher)==null?void 0:ut.mobileFullscreen)!=null?st:!0,oe=(Re=(Be=r.launcher)==null?void 0:Be.mobileBreakpoint)!=null?Re:640,Y=D.innerWidth<=oe,ve=dn(r)&&ie&&Y,Oe=R()&&((bt=(Xe=(ze=r.launcher)==null?void 0:ze.composerBar)==null?void 0:Xe.expandedSize)!=null?bt:"fullscreen")==="fullscreen";return _||ie&&Y&&P||ve||Oe})();if(O&&x){if(!rn){let _=e.getRootNode(),D=_ instanceof ShadowRoot?_.host:e.closest(".persona-host");D&&(rn=Cl(D,(U=(W=r.launcher)==null?void 0:W.zIndex)!=null?U:xn))}on||(on=Al(e.ownerDocument))}else O||(rn==null||rn(),rn=null,on==null||on(),on=null);O&&(Vs(),cc()||(Ot()==="follow"?po(!0):ic()));let A={open:O,source:m,timestamp:Date.now()};O&&!h?i.emit("widget:opened",A):!O&&h&&i.emit("widget:closed",A),i.emit("widget:state",{open:O,launcherEnabled:P,voiceActive:K.active,streaming:F.isStreaming()})},Oi=l=>{me(l?"stop":"send"),B&&(B.disabled=l),Ho.buttons.forEach(m=>{m.disabled=l}),He.dataset.personaComposerStreaming=l?"true":"false",He.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},Fi=()=>{K.active||be&&be.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Fi(),200)});let gc=()=>{var h,x,A,W,U,_,D,ie,oe,Y,ve;yr.textContent=(x=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?x:"Hello \u{1F44B}",br.textContent=(W=(A=r.copy)==null?void 0:A.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",be.placeholder=(_=(U=r.copy)==null?void 0:U.inputPlaceholder)!=null?_:"How can I help...";let l=we.querySelector("[data-persona-intro-card]");if(l){let Oe=((D=r.copy)==null?void 0:D.showWelcomeCard)!==!1;l.style.display=Oe?"":"none",Oe?(we.classList.remove("persona-gap-3"),we.classList.add("persona-gap-6")):(we.classList.remove("persona-gap-6"),we.classList.add("persona-gap-3"))}!((oe=(ie=r.sendButton)==null?void 0:ie.useIcon)!=null&&oe)&&!(F!=null&&F.isStreaming())&&(pe.textContent=(ve=(Y=r.copy)==null?void 0:Y.sendButtonLabel)!=null?ve:"Send"),be.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',be.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=p.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{v(m=>({...m,sessionId:l}))}});let No=null,Xf=()=>{No==null&&(No=setInterval(()=>{let l=Ze.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(No),No=null;return}let m=Date.now();l.forEach(h=>{let x=Number(h.getAttribute("data-tool-elapsed"));x&&(h.textContent=ja(m-x))})},100))};F=new da(r,{onMessagesChanged(l){var A,W;$s(Ze,l,ee),Xf(),is(l),po(!cr),qf(l);let m=[...l].reverse().find(U=>U.role==="user"),h=[...l].reverse().find(U=>U.role==="assistant");l.length===0&&(_s(),so=!0,ao=!1),!cs||Do?(cs=!0,ds=(A=m==null?void 0:m.id)!=null?A:null,ot=(W=h==null?void 0:h.id)!=null?W:null):m&&m.id!==ds?(ds=m.id,jf(m.id)):h&&h.id!==ot&&Uf(),h&&(ot=h.id);let x=K.lastUserMessageId;m&&m.id!==x&&(K.lastUserMessageId=m.id,i.emit("user:message",m)),K.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Pn(l),ps()},onStatusChanged(l){var x;let m=(x=r.statusIndicator)!=null?x:{};Wt(fn,(A=>{var W,U,_,D,ie,oe;return A==="idle"?(W=m.idleText)!=null?W:nn.idle:A==="connecting"?(U=m.connectingText)!=null?U:nn.connecting:A==="connected"?(_=m.connectedText)!=null?_:nn.connected:A==="error"?(D=m.errorText)!=null?D:nn.error:A==="paused"?(ie=m.pausedText)!=null?ie:nn.paused:A==="resuming"?(oe=m.resumingText)!=null?oe:nn.resuming:nn[A]})(l),m,l)},onStreamingChanged(l){cr=l,Oi(l),F&&$s(Ze,F.getMessages(),ee),l||po(!0),Fn(),Qr(l?"Responding\u2026":"Response complete."),ps()},onVoiceStatusChanged(l){var m,h;if(i.emit("voice:status",{status:l,timestamp:Date.now()}),((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":zr(),ms();break;case"processing":zr(),th();break;case"speaking":zr(),nh();break;default:l==="idle"&&F.isBargeInActive()?(zr(),ms(),B==null||B.setAttribute("aria-label","End voice session")):(K.active=!1,zr(),rt("system"),ct());break}},onArtifactsState(l){Nn=l,Sr(),Pn()},onReconnect(l){var x;let{executionId:m,lastEventId:h}=l.handle;l.phase==="paused"?i.emit("stream:paused",{executionId:m,after:h}):l.phase==="resuming"?i.emit("stream:resuming",{executionId:m,after:h,attempt:(x=l.attempt)!=null?x:1}):i.emit("stream:resumed",{executionId:m,after:h})}}),St.current=F,lt.push(()=>F.cancel());let _i=null;if(F.onReadAloudChange((l,m)=>{var A;eo=l,to=m,no();let h=l!=null?l:_i;l&&(_i=l);let x=h&&(A=F.getMessages().find(W=>W.id===h))!=null?A:null;i.emit("message:read-aloud",{messageId:h,message:x,state:m,timestamp:Date.now()}),m==="idle"&&(_i=null)}),cs=!0,((kd=(Md=r.voiceRecognition)==null?void 0:Md.provider)==null?void 0:kd.type)==="runtype")try{F.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&F.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(V||r.onSSEEvent)&&F.setSSEEventCallback((l,m)=>{var h;(h=r.onSSEEvent)==null||h.call(r,l,m),Q==null||Q.processEvent(l,m),V==null||V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})});let fc=()=>{r.resume&&typeof r.reconnectStream=="function"&&F.resumeFromHandle(r.resume)};u?u.then(l=>{var m,h,x;if(l){if(l.metadata&&(p=Kl(l.metadata),L.syncFromMetadata()),(m=l.messages)!=null&&m.length){Do=!0;try{F.hydrateMessages(l.messages)}finally{Do=!1}}(h=l.artifacts)!=null&&h.length&&F.hydrateArtifacts(l.artifacts,(x=l.selectedArtifactId)!=null?x:null)}}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)}).finally(()=>fc()):fc();let hc=()=>{var m,h,x;!R()||O||!((x=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.expandOnSubmit)==null||x)||_t(!0,"auto")},yc=l=>{var A;if(l.preventDefault(),F.isStreaming()){F.cancel(),Q==null||Q.reset(),Me==null||Me.update();return}let m=be.value.trim(),h=(A=At==null?void 0:At.hasAttachments())!=null?A:!1;if(!m&&!h)return;hc();let x;h&&(x=[],x.push(...At.getContentParts()),m&&x.push(Ka(m))),be.value="",be.style.height="auto",ka(),F.sendMessage(m,{contentParts:x}),h&&At.clearAttachments()},Qf=()=>{var l;return((l=r.features)==null?void 0:l.composerHistory)!==!1},$i={...ti},ji=!1,ka=()=>{$i={...ti}},Yf=()=>F.getMessages().filter(l=>l.role==="user").map(l=>{var m;return(m=l.content)!=null?m:""}).filter(l=>l.length>0),Zf=l=>{if(!be)return;ji=!0,be.value=l,be.dispatchEvent(new Event("input",{bubbles:!0})),ji=!1;let m=be.value.length;be.setSelectionRange(m,m)},bc=()=>{ji||ka()},xc=l=>{if(be){if(Qf()&&(l.key==="ArrowUp"||l.key==="ArrowDown")&&!l.shiftKey&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.isComposing){let m=be.selectionStart===0&&be.selectionEnd===0,h=sg({direction:l.key==="ArrowUp"?"up":"down",history:Yf(),currentValue:be.value,atStart:m,state:$i});if($i=h.state,h.handled){l.preventDefault(),h.value!==void 0&&Zf(h.value);return}}if(l.key==="Enter"&&!l.shiftKey){if(F.isStreaming()){l.preventDefault();return}ka(),l.preventDefault(),pe.click()}}},vc=l=>{l.key!=="Escape"||l.isComposing||F.isStreaming()&&l.composedPath().includes(Se)&&(F.cancel(),Q==null||Q.reset(),Me==null||Me.update(),ka(),l.preventDefault(),l.stopImmediatePropagation())},wc=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!At)return;let m=Iw(l.clipboardData);m.length!==0&&(l.preventDefault(),await At.handleFiles(m))},Qn=null,Pr=!1,us=null,pt=null,Cc=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,La=(l="user")=>{var W,U,_,D,ie,oe,Y;if(Pr||F.isStreaming())return;let m=Cc();if(!m)return;Qn=new m;let x=(U=((W=r.voiceRecognition)!=null?W:{}).pauseDuration)!=null?U:2e3;Qn.continuous=!0,Qn.interimResults=!0,Qn.lang="en-US";let A=be.value;Qn.onresult=ve=>{let Oe="",Fe="";for(let qe=0;qe<ve.results.length;qe++){let ut=ve.results[qe],st=ut[0].transcript;ut.isFinal?Oe+=st+" ":Fe=st}let je=A+Oe+Fe;be.value=je,us&&clearTimeout(us),(Oe||Fe)&&(us=window.setTimeout(()=>{let qe=be.value.trim();qe&&Qn&&Pr&&(uo(),be.value="",be.style.height="auto",F.sendMessage(qe,{viaVoice:!0}))},x))},Qn.onerror=ve=>{ve.error!=="no-speech"&&uo()},Qn.onend=()=>{if(Pr){let ve=be.value.trim();ve&&ve!==A.trim()&&(be.value="",be.style.height="auto",F.sendMessage(ve,{viaVoice:!0})),uo()}};try{if(Qn.start(),Pr=!0,K.active=!0,l!=="system"&&(K.manuallyDeactivated=!1),rt(l),ct(),B){let ve=(_=r.voiceRecognition)!=null?_:{};pt={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(D=ve.iconName)!=null?D:"mic",iconSize:parseFloat((Y=(oe=ve.iconSize)!=null?oe:(ie=r.sendButton)==null?void 0:ie.size)!=null?Y:"40")||24};let Oe=ve.recordingBackgroundColor,Fe=ve.recordingIconColor,je=ve.recordingBorderColor;if(B.classList.add("persona-voice-recording"),B.style.backgroundColor=Oe!=null?Oe:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=Fe!=null?Fe:"var(--persona-voice-recording-indicator, #ffffff)",Fe){let qe=B.querySelector("svg");qe&&qe.setAttribute("stroke",Fe)}je&&(B.style.borderColor=je),B.setAttribute("aria-label","Stop voice recognition")}}catch{uo("system")}},uo=(l="user")=>{if(Pr){if(Pr=!1,us&&(clearTimeout(us),us=null),Qn){try{Qn.stop()}catch{}Qn=null}if(K.active=!1,rt(l),ct(),B){if(B.classList.remove("persona-voice-recording"),pt){B.style.backgroundColor=pt.backgroundColor,B.style.color=pt.color,B.style.borderColor=pt.borderColor;let m=B.querySelector("svg");m&&m.setAttribute("stroke",pt.color||"currentColor"),pt=null}B.setAttribute("aria-label","Start voice recognition")}}},eh=(l,m)=>{var st,Be,Re,ze,Xe,bt,H,De,We;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),x=((st=l==null?void 0:l.provider)==null?void 0:st.type)==="runtype",A=((Be=l==null?void 0:l.provider)==null?void 0:Be.type)==="custom";if(!(h||x||A))return null;let U=y("div","persona-send-button-wrapper"),_=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");_.type="button",_.setAttribute("aria-label","Start voice recognition");let D=(Re=l==null?void 0:l.iconName)!=null?Re:"mic",ie=(ze=m==null?void 0:m.size)!=null?ze:"40px",oe=(Xe=l==null?void 0:l.iconSize)!=null?Xe:ie,Y=parseFloat(oe)||24,ve=(bt=l==null?void 0:l.backgroundColor)!=null?bt:m==null?void 0:m.backgroundColor,Oe=(H=l==null?void 0:l.iconColor)!=null?H:m==null?void 0:m.textColor;_.style.width=oe,_.style.height=oe,_.style.minWidth=oe,_.style.minHeight=oe,_.style.fontSize="18px",_.style.lineHeight="1",Oe?_.style.color=Oe:_.style.color="var(--persona-text, #111827)";let je=ye(D,Y,Oe||"currentColor",1.5);je?_.appendChild(je):_.textContent="\u{1F3A4}",ve?_.style.backgroundColor=ve:_.style.backgroundColor="",l!=null&&l.borderWidth&&(_.style.borderWidth=l.borderWidth,_.style.borderStyle="solid"),l!=null&&l.borderColor&&(_.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(_.style.paddingLeft=l.paddingX,_.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(_.style.paddingTop=l.paddingY,_.style.paddingBottom=l.paddingY),U.appendChild(_);let qe=(De=l==null?void 0:l.tooltipText)!=null?De:"Start voice recognition";if(((We=l==null?void 0:l.showTooltip)!=null?We:!1)&&qe){let Ye=y("div","persona-send-button-tooltip");Ye.textContent=qe,U.appendChild(Ye)}return{micButton:_,micButtonWrapper:U}},Ui=()=>{var m,h,x,A,W;if(!B||pt)return;let l=(m=r.voiceRecognition)!=null?m:{};pt={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((W=(A=l.iconSize)!=null?A:(x=r.sendButton)==null?void 0:x.size)!=null?W:"40")||24}},qi=(l,m)=>{var W,U,_,D,ie;if(!B)return;let h=B.querySelector("svg");h&&h.remove();let x=(ie=pt==null?void 0:pt.iconSize)!=null?ie:parseFloat((D=(_=(W=r.voiceRecognition)==null?void 0:W.iconSize)!=null?_:(U=r.sendButton)==null?void 0:U.size)!=null?D:"40")||24,A=ye(l,x,m,1.5);A&&B.appendChild(A)},Pa=()=>{B&&B.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},ms=()=>{var A;if(!B)return;Ui();let l=(A=r.voiceRecognition)!=null?A:{},m=l.recordingBackgroundColor,h=l.recordingIconColor,x=l.recordingBorderColor;if(Pa(),B.classList.add("persona-voice-recording"),B.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",B.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let W=B.querySelector("svg");W&&W.setAttribute("stroke",h)}x&&(B.style.borderColor=x),B.setAttribute("aria-label","Stop voice recognition")},th=()=>{var _,D,ie,oe,Y,ve,Oe,Fe;if(!B)return;Ui();let l=(_=r.voiceRecognition)!=null?_:{},m=F.getVoiceInterruptionMode(),h=(D=l.processingIconName)!=null?D:"loader",x=(oe=(ie=l.processingIconColor)!=null?ie:pt==null?void 0:pt.color)!=null?oe:"",A=(ve=(Y=l.processingBackgroundColor)!=null?Y:pt==null?void 0:pt.backgroundColor)!=null?ve:"",W=(Fe=(Oe=l.processingBorderColor)!=null?Oe:pt==null?void 0:pt.borderColor)!=null?Fe:"";Pa(),B.classList.add("persona-voice-processing"),B.style.backgroundColor=A,B.style.borderColor=W;let U=x||"currentColor";B.style.color=U,qi(h,U),B.setAttribute("aria-label","Processing voice input"),m==="none"&&(B.style.cursor="default")},nh=()=>{var ie,oe,Y,ve,Oe,Fe,je,qe,ut,st,Be,Re;if(!B)return;Ui();let l=(ie=r.voiceRecognition)!=null?ie:{},m=F.getVoiceInterruptionMode(),h=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",x=(oe=l.speakingIconName)!=null?oe:h,A=(Fe=l.speakingIconColor)!=null?Fe:m==="barge-in"?(ve=(Y=l.recordingIconColor)!=null?Y:pt==null?void 0:pt.color)!=null?ve:"":(Oe=pt==null?void 0:pt.color)!=null?Oe:"",W=(ut=l.speakingBackgroundColor)!=null?ut:m==="barge-in"?(je=l.recordingBackgroundColor)!=null?je:"var(--persona-voice-recording-bg, #ef4444)":(qe=pt==null?void 0:pt.backgroundColor)!=null?qe:"",U=(Re=l.speakingBorderColor)!=null?Re:m==="barge-in"?(st=l.recordingBorderColor)!=null?st:"":(Be=pt==null?void 0:pt.borderColor)!=null?Be:"";Pa(),B.classList.add("persona-voice-speaking"),B.style.backgroundColor=W,B.style.borderColor=U;let _=A||"currentColor";B.style.color=_,qi(x,_);let D=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";B.setAttribute("aria-label",D),m==="none"&&(B.style.cursor="default"),m==="barge-in"&&B.classList.add("persona-voice-recording")},zr=()=>{var l,m,h;B&&(Pa(),pt&&(B.style.backgroundColor=(l=pt.backgroundColor)!=null?l:"",B.style.color=(m=pt.color)!=null?m:"",B.style.borderColor=(h=pt.borderColor)!=null?h:"",qi(pt.iconName,pt.color||"currentColor"),pt=null),B.style.cursor="",B.setAttribute("aria-label","Start voice recognition"))},Ia=()=>{var l,m;if(((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let h=F.getVoiceStatus(),x=F.getVoiceInterruptionMode();if(x==="none"&&(h==="processing"||h==="speaking"))return;if(x==="cancel"&&(h==="processing"||h==="speaking")){F.stopVoicePlayback();return}if(F.isBargeInActive()){F.stopVoicePlayback(),F.deactivateBargeIn().then(()=>{K.active=!1,K.manuallyDeactivated=!0,ct(),rt("user"),zr()});return}F.toggleVoice().then(()=>{K.active=F.isVoiceActive(),K.manuallyDeactivated=!F.isVoiceActive(),ct(),rt("user"),F.isVoiceActive()?ms():zr()});return}if(Pr){let h=be.value.trim();K.manuallyDeactivated=!0,ct(),uo("user"),h&&(be.value="",be.style.height="auto",F.sendMessage(h))}else K.manuallyDeactivated=!1,ct(),La("user")};wr=Ia,B&&(B.addEventListener("click",Ia),lt.push(()=>{var l,m;((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?(F.isVoiceActive()&&F.toggleVoice(),zr()):uo("system"),B&&B.removeEventListener("click",Ia)}));let rh=i.on("assistant:complete",()=>{Ne&&(K.active||K.manuallyDeactivated||Ne==="assistant"&&!K.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!K.active&&!K.manuallyDeactivated&&(((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?F.toggleVoice().then(()=>{K.active=F.isVoiceActive(),rt("auto"),F.isVoiceActive()&&ms()}):La("auto"))},600))});lt.push(rh);let oh=i.on("action:resubmit",()=>{setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)});lt.push(oh);let Ac=()=>{_t(!O,"user")},Zt=null,sn=null;if(P&&!R()){let{instance:l,element:m}=Ml({config:r,plugins:o,onToggle:Ac});Zt=l,l||(sn=m)}Zt?e.appendChild(Zt.element):sn&&e.appendChild(sn),zs(),is(),gc(),Oi(F.isStreaming()),cc()||(Ot()==="follow"?po(!0):ic()),Di(),k&&(!P||R()?setTimeout(()=>Fi(),0):O&&setTimeout(()=>Fi(),200));let Vs=()=>{var D,ie,oe,Y,ve,Oe,Fe,je,qe,ut,st,Be,Re,ze,Xe,bt,H,De,We,Ye,Pt,_e;if(R()){zn(),zs();return}let l=dn(r),m=(ie=(D=r.launcher)==null?void 0:D.sidebarMode)!=null?ie:!1,h=l||m||((Y=(oe=r.launcher)==null?void 0:oe.fullHeight)!=null?Y:!1),x=(ve=e.ownerDocument.defaultView)!=null?ve:window,A=(Fe=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?Fe:!0,W=(qe=(je=r.launcher)==null?void 0:je.mobileBreakpoint)!=null?qe:640,U=x.innerWidth<=W,_=A&&U&&P;try{if(_){oo(),es(e,r);return}if($&&($=!1,oo(),es(e,r)),!P&&!l){X.style.height="",X.style.width="";return}if(!m&&!l){let Kt=(st=(ut=r==null?void 0:r.launcher)==null?void 0:ut.width)!=null?st:r==null?void 0:r.launcherWidth,wt=Kt!=null?Kt:tr;X.style.width=wt,X.style.maxWidth=wt}if(Wo(),!h){let Kt=x.innerHeight,wt=64,an=(Re=(Be=r.launcher)==null?void 0:Be.heightOffset)!=null?Re:0,Rn=Math.max(200,Kt-wt),Ht=Math.min(640,Rn),mn=Math.max(200,Ht-an);X.style.height=`${mn}px`}}finally{if(zn(),zs(),O&&P){let wt=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((bt=(Xe=r.launcher)==null?void 0:Xe.mobileBreakpoint)!=null?bt:640),an=(De=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?De:!1,Rn=(Ye=(We=r.launcher)==null?void 0:We.mobileFullscreen)!=null?Ye:!0,Ht=dn(r)&&Rn&&wt,mn=an||Rn&&wt&&P||Ht;if(mn&&!on){let _n=e.getRootNode(),Ge=_n instanceof ShadowRoot?_n.host:e.closest(".persona-host");Ge&&!rn&&(rn=Cl(Ge,(_e=(Pt=r.launcher)==null?void 0:Pt.zIndex)!=null?_e:xn)),on=Al(e.ownerDocument)}else mn||(rn==null||rn(),rn=null,on==null||on(),on=null)}}};Vs();let Sc=(Ld=e.ownerDocument.defaultView)!=null?Ld:window;if(Sc.addEventListener("resize",Vs),lt.push(()=>Sc.removeEventListener("resize",Vs)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{zn()});l.observe(He),lt.push(()=>l.disconnect())}Cn=we.scrollTop;let Tc=Br(we),sh=()=>{let l=we.getRootNode(),m=typeof l.getSelection=="function"?l.getSelection():null;return m!=null?m:we.ownerDocument.getSelection()},zi=()=>pg(sh(),we),Ec=()=>{let l=we.scrollTop,m=Br(we),h=m<Tc;if(Tc=m,!en()){Cn=l,Fn();return}let{action:x,nextLastScrollTop:A}=ri({following:hn.isFollowing(),currentScrollTop:l,lastScrollTop:Cn,nearBottom:Co(we,z),userScrollThreshold:w,isAutoScrolling:An||Bo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Cn=A,x==="resume"){zi()||co();return}x==="pause"&&Fs()};if(we.addEventListener("scroll",Ec,{passive:!0}),lt.push(()=>we.removeEventListener("scroll",Ec)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{$f()});l.observe(Ze),l.observe(we),lt.push(()=>l.disconnect())}let Mc=()=>{en()&&hn.isFollowing()&&zi()&&Fs()},kc=we.ownerDocument;kc.addEventListener("selectionchange",Mc),lt.push(()=>{kc.removeEventListener("selectionchange",Mc)});let ah=new Set(["PageUp","PageDown","Home","End","ArrowUp","ArrowDown"]),Lc=l=>{or()&&en()&&hn.isFollowing()&&ah.has(l.key)&&Fs()},Pc=l=>{if(!or()||!en()||!hn.isFollowing())return;let m=l.target;m&&m.closest("a, button, [tabindex], input, textarea, select")&&Fs()};we.addEventListener("keydown",Lc),we.addEventListener("focusin",Pc),lt.push(()=>{we.removeEventListener("keydown",Lc),we.removeEventListener("focusin",Pc)});let Ic=l=>{if(!en())return;let m=oi({following:hn.isFollowing(),deltaY:l.deltaY,nearBottom:Co(we,z),resumeWhenNearBottom:!0});m==="pause"?Fs():m==="resume"&&!zi()&&co()};we.addEventListener("wheel",Ic,{passive:!0}),lt.push(()=>we.removeEventListener("wheel",Ic)),zt.addEventListener("click",()=>{_s(),we.scrollTop=we.scrollHeight,Cn=we.scrollTop,co(),po(!0),Fn()}),lt.push(()=>zt.remove()),lt.push(()=>{Sn(),_s()});let Rc=()=>{Ue&&(Er&&(Ue.removeEventListener("click",Er),Er=null),N()?(Ue.style.display="",Er=()=>{_t(!1,"user")},Ue.addEventListener("click",Er)):Ue.style.display="none")};Rc(),(()=>{let{clearChatButton:l}=Ve;l&&l.addEventListener("click",()=>{F.clearMessages(),Mr.clear(),co(),Jo(Ve.composerOverlay);try{localStorage.removeItem(Bs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Bs}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Bs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),c!=null&&c.clear)try{let h=c.clear();h instanceof Promise&&h.catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",x)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}p={},L.syncFromMetadata(),V==null||V.clear(),Q==null||Q.reset(),Me==null||Me.update()})})(),Ct&&Ct.addEventListener("submit",yc),be==null||be.addEventListener("keydown",xc),be==null||be.addEventListener("input",bc),be==null||be.addEventListener("paste",wc);let Wc=(Pd=e.ownerDocument)!=null?Pd:document;Wc.addEventListener("keydown",vc,!0);let Hc="persona-attachment-drop-active",Ks=0,Vi=()=>{Ks=0,Se.classList.remove(Hc)},gs=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&At!==null},Bc=l=>{!Mi(l.dataTransfer)||!gs()||(Ks++,Ks===1&&Se.classList.add(Hc))},Dc=l=>{!Mi(l.dataTransfer)||!gs()||(Ks--,Ks<=0&&Vi())},Nc=l=>{!Mi(l.dataTransfer)||!gs()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},Oc=l=>{var h;if(!Mi(l.dataTransfer)||!gs())return;l.preventDefault(),l.stopPropagation(),Vi();let m=Array.from((h=l.dataTransfer.files)!=null?h:[]);m.length!==0&&At.handleFiles(m)},mo=!0;Se.addEventListener("dragenter",Bc,mo),Se.addEventListener("dragleave",Dc,mo),e.addEventListener("dragover",Nc,mo),e.addEventListener("drop",Oc,mo);let Ra=e.ownerDocument,Fc=l=>{gs()&&l.preventDefault()},_c=l=>{gs()&&l.preventDefault()};Ra.addEventListener("dragover",Fc),Ra.addEventListener("drop",_c),lt.push(()=>{Ct&&Ct.removeEventListener("submit",yc),be==null||be.removeEventListener("keydown",xc),be==null||be.removeEventListener("input",bc),be==null||be.removeEventListener("paste",wc),Wc.removeEventListener("keydown",vc,!0)}),lt.push(()=>{Se.removeEventListener("dragenter",Bc,mo),Se.removeEventListener("dragleave",Dc,mo),e.removeEventListener("dragover",Nc,mo),e.removeEventListener("drop",Oc,mo),Ra.removeEventListener("dragover",Fc),Ra.removeEventListener("drop",_c),Vi()}),lt.push(()=>{F.cancel()}),Zt?lt.push(()=>{Zt==null||Zt.destroy()}):sn&&lt.push(()=>{sn==null||sn.remove()});let tn={update(l){var jn,Ir,pn,un,Zn,ho,Nd,Od,Fd,_d,$d,jd,Ud,qd,zd,Vd,Kd,Gd,Jd,Xd,Qd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,yp,bp,xp,vp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Np,Op,Fp,_p,$p,jp,Up,qp,zp,Vp,Kp,Gp,Jp,Xp,Qp,Yp,Zp,eu,tu,nu,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,yu,bu,xu,vu,wu,Cu,Au,Su,Tu,Eu,Mu,ku,Lu,Pu,Iu,Ru,Wu,Hu,Bu,Du,Nu,Ou,Fu,_u,$u,ju,Uu;let m=r.toolCall,h=r.messageActions,x=(jn=r.layout)==null?void 0:jn.messages,A=r.colorScheme,W=r.loadingIndicator,U=r.iterationDisplay,_=(Ir=r.features)==null?void 0:Ir.showReasoning,D=(pn=r.features)==null?void 0:pn.showToolCalls,ie=(un=r.features)==null?void 0:un.toolCallDisplay,oe=(Zn=r.features)==null?void 0:Zn.reasoningDisplay,Y=(Nd=(ho=r.features)==null?void 0:ho.streamAnimation)==null?void 0:Nd.type;r={...r,...l},oo(),es(e,r),Ci(e,r),Ai(e,r),Sr(),r.colorScheme!==A&&Os();let ve=Si.getForInstance(r.plugins);o.length=0,o.push(...ve),P=(Fd=(Od=r.launcher)==null?void 0:Od.enabled)!=null?Fd:!0,E=($d=(_d=r.launcher)==null?void 0:_d.autoExpand)!=null?$d:!1,Le=(Ud=(jd=r.features)==null?void 0:jd.showReasoning)!=null?Ud:!0,Pe=(zd=(qd=r.features)==null?void 0:qd.showToolCalls)!=null?zd:!0,Ae=(Kd=(Vd=r.features)==null?void 0:Vd.scrollToBottom)!=null?Kd:{};let Oe=Ot();re=(Jd=(Gd=r.features)==null?void 0:Gd.scrollBehavior)!=null?Jd:{},Oe!==Ot()&&(_s(),co()),Yr(),Fn();let Fe=ne;if(ne=(Qd=(Xd=r.features)==null?void 0:Xd.showEventStreamToggle)!=null?Qd:!1,ne&&!Fe){if(V||(fe=new Sa(ae),V=new Aa($e,fe),Q=Q!=null?Q:new Ta,fe.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),F.setSSEEventCallback((te,Tt)=>{var Ut;(Ut=r.onSSEEvent)==null||Ut.call(r,te,Tt),Q==null||Q.processEvent(te,Tt),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:te,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!yt&&ke){let te=(Zd=(Yd=r.features)==null?void 0:Yd.eventStream)==null?void 0:Zd.classNames,Tt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(te!=null&&te.toggleButton?" "+te.toggleButton:"");yt=y("button",Tt),yt.style.width="28px",yt.style.height="28px",yt.style.color=Mn.actionIconColor,yt.type="button",yt.setAttribute("aria-label","Event Stream"),yt.title="Event Stream";let Ut=ye("activity","18px","currentColor",1.5);Ut&&yt.appendChild(Ut);let at=Ve.clearChatButtonWrapper,kt=Ve.closeButtonWrapper,ln=at||kt;ln&&ln.parentNode===ke?ke.insertBefore(yt,ln):ke.appendChild(yt),yt.addEventListener("click",()=>{J?lr():Fr()})}}else!ne&&Fe&&(lr(),yt&&(yt.remove(),yt=null),V==null||V.clear(),fe==null||fe.destroy(),V=null,fe=null,Q==null||Q.reset(),Q=null);if(((ep=r.launcher)==null?void 0:ep.enabled)===!1&&Zt&&(Zt.destroy(),Zt=null),((tp=r.launcher)==null?void 0:tp.enabled)===!1&&sn&&(sn.remove(),sn=null),((np=r.launcher)==null?void 0:np.enabled)!==!1&&!Zt&&!sn){let{instance:te,element:Tt}=Ml({config:r,plugins:o,onToggle:Ac});Zt=te,te||(sn=Tt),e.appendChild(Tt)}Zt&&Zt.update(r),ue&&((rp=r.launcher)==null?void 0:rp.title)!==void 0&&(ue.textContent=r.launcher.title),Te&&((op=r.launcher)==null?void 0:op.subtitle)!==void 0&&(Te.textContent=r.launcher.subtitle);let je=(sp=r.layout)==null?void 0:sp.header;if((je==null?void 0:je.layout)!==j&&ke){let te=je?va(r,je,{showClose:N(),onClose:()=>_t(!1,"user")}):Eo({config:r,showClose:N(),onClose:()=>_t(!1,"user")});tt.replaceHeader(te),ke=tt.header.element,M=tt.header.iconHolder,ue=tt.header.headerTitle,Te=tt.header.headerSubtitle,Ue=tt.header.closeButton,j=je==null?void 0:je.layout}else if(je&&(M&&(M.style.display=je.showIcon===!1?"none":""),ue&&(ue.style.display=je.showTitle===!1?"none":""),Te&&(Te.style.display=je.showSubtitle===!1?"none":""),Ue&&(Ue.style.display=je.showCloseButton===!1?"none":""),Ve.clearChatButtonWrapper)){let te=je.showClearChat;if(te!==void 0){Ve.clearChatButtonWrapper.style.display=te?"":"none";let{closeButtonWrapper:Tt}=Ve;Tt&&!Tt.classList.contains("persona-absolute")&&(te?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let ut=((ap=r.layout)==null?void 0:ap.showHeader)!==!1;ke&&(ke.style.display=ut?"":"none");let st=((ip=r.layout)==null?void 0:ip.showFooter)!==!1;He&&(He.style.display=st?"":"none"),zn(),Fn(),P!==I?P?_t(E,"auto"):(O=!0,zs()):E!==C&&_t(E,"auto"),C=E,I=P,Vs(),Rc();let ze=JSON.stringify(l.toolCall)!==JSON.stringify(m),Xe=JSON.stringify(r.messageActions)!==JSON.stringify(h),bt=JSON.stringify((lp=r.layout)==null?void 0:lp.messages)!==JSON.stringify(x),H=((cp=r.loadingIndicator)==null?void 0:cp.render)!==(W==null?void 0:W.render)||((dp=r.loadingIndicator)==null?void 0:dp.renderIdle)!==(W==null?void 0:W.renderIdle)||((pp=r.loadingIndicator)==null?void 0:pp.showBubble)!==(W==null?void 0:W.showBubble),De=r.iterationDisplay!==U,We=((mp=(up=r.features)==null?void 0:up.showReasoning)!=null?mp:!0)!==(_!=null?_:!0)||((fp=(gp=r.features)==null?void 0:gp.showToolCalls)!=null?fp:!0)!==(D!=null?D:!0)||JSON.stringify((hp=r.features)==null?void 0:hp.toolCallDisplay)!==JSON.stringify(ie)||JSON.stringify((yp=r.features)==null?void 0:yp.reasoningDisplay)!==JSON.stringify(oe);(ze||Xe||bt||H||De||We)&&F&&(ls++,$s(Ze,F.getMessages(),ee));let Pt=(xp=(bp=r.features)==null?void 0:bp.streamAnimation)==null?void 0:xp.type;if(Pt!==Y&&Pt&&Pt!=="none"){let te=ks(Pt,(wp=(vp=r.features)==null?void 0:vp.streamAnimation)==null?void 0:wp.plugins);te&&li(te,e)}let _e=(Cp=r.launcher)!=null?Cp:{},Kt=(Ap=_e.headerIconHidden)!=null?Ap:!1,wt=(Tp=(Sp=r.layout)==null?void 0:Sp.header)==null?void 0:Tp.showIcon,an=Kt||wt===!1,Rn=_e.headerIconName,Ht=(Ep=_e.headerIconSize)!=null?Ep:"48px";if(M){let te=Se.querySelector(".persona-border-b-persona-divider"),Tt=te==null?void 0:te.querySelector(".persona-flex-col");if(an)M.style.display="none",te&&Tt&&!te.contains(Tt)&&te.insertBefore(Tt,te.firstChild);else{if(M.style.display="",M.style.height=Ht,M.style.width=Ht,te&&Tt&&(te.contains(M)?M.nextSibling!==Tt&&(M.remove(),te.insertBefore(M,Tt)):te.insertBefore(M,Tt)),Rn){let at=parseFloat(Ht)||24,kt=ye(Rn,at*.6,"currentColor",1);kt?M.replaceChildren(kt):M.textContent=(Mp=_e.agentIconText)!=null?Mp:"\u{1F4AC}"}else if(_e.iconUrl){let at=M.querySelector("img");if(at)at.src=_e.iconUrl,at.style.height=Ht,at.style.width=Ht;else{let kt=document.createElement("img");kt.src=_e.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=Ht,kt.style.width=Ht,M.replaceChildren(kt)}}else{let at=M.querySelector("svg"),kt=M.querySelector("img");(at||kt)&&M.replaceChildren(),M.textContent=(kp=_e.agentIconText)!=null?kp:"\u{1F4AC}"}let Ut=M.querySelector("img");Ut&&(Ut.style.height=Ht,Ut.style.width=Ht)}}let mn=(Pp=(Lp=r.layout)==null?void 0:Lp.header)==null?void 0:Pp.showTitle,_n=(Rp=(Ip=r.layout)==null?void 0:Ip.header)==null?void 0:Rp.showSubtitle;if(ue&&(ue.style.display=mn===!1?"none":""),Te&&(Te.style.display=_n===!1?"none":""),Ue){((Hp=(Wp=r.layout)==null?void 0:Wp.header)==null?void 0:Hp.showCloseButton)===!1?Ue.style.display="none":Ue.style.display="";let Tt=(Bp=_e.closeButtonSize)!=null?Bp:"32px",Ut=(Dp=_e.closeButtonPlacement)!=null?Dp:"inline";Ue.style.height=Tt,Ue.style.width=Tt;let{closeButtonWrapper:at}=Ve,kt=Ut==="top-right",ln=at==null?void 0:at.classList.contains("persona-absolute");if(at&&kt!==ln)if(at.remove(),kt)at.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Se.style.position="relative",Se.appendChild(at);else{let dt=(Op=(Np=_e.clearChat)==null?void 0:Np.placement)!=null?Op:"inline",cn=(_p=(Fp=_e.clearChat)==null?void 0:Fp.enabled)!=null?_p:!0;at.className=cn&&dt==="inline"?"":"persona-ml-auto";let Wn=Se.querySelector(".persona-border-b-persona-divider");Wn&&Wn.appendChild(at)}if(Ue.style.color=_e.closeButtonColor||Mn.actionIconColor,_e.closeButtonBackgroundColor?(Ue.style.backgroundColor=_e.closeButtonBackgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),_e.closeButtonBorderWidth||_e.closeButtonBorderColor){let dt=_e.closeButtonBorderWidth||"0px",cn=_e.closeButtonBorderColor||"transparent";Ue.style.border=`${dt} solid ${cn}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");_e.closeButtonBorderRadius?(Ue.style.borderRadius=_e.closeButtonBorderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),_e.closeButtonPaddingX?(Ue.style.paddingLeft=_e.closeButtonPaddingX,Ue.style.paddingRight=_e.closeButtonPaddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),_e.closeButtonPaddingY?(Ue.style.paddingTop=_e.closeButtonPaddingY,Ue.style.paddingBottom=_e.closeButtonPaddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let bn=($p=_e.closeButtonIconName)!=null?$p:"x",mr=(jp=_e.closeButtonIconText)!=null?jp:"\xD7";Ue.innerHTML="";let En=ye(bn,"28px","currentColor",1);En?Ue.appendChild(En):Ue.textContent=mr;let Yt=(Up=_e.closeButtonTooltipText)!=null?Up:"Close chat",Un=(qp=_e.closeButtonShowTooltip)!=null?qp:!0;if(Ue.setAttribute("aria-label",Yt),at&&(at._cleanupTooltip&&(at._cleanupTooltip(),delete at._cleanupTooltip),Un&&Yt)){let dt=null,cn=()=>{if(dt||!Ue)return;let qo=Ue.ownerDocument,Gs=qo.body;if(!Gs)return;dt=Wr(qo,"div","persona-clear-chat-tooltip"),dt.textContent=Yt;let Js=Wr(qo,"div");Js.className="persona-clear-chat-tooltip-arrow",dt.appendChild(Js);let zo=Ue.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(Ao),dt.style.left=`${zo.left+zo.width/2}px`,dt.style.top=`${zo.top-8}px`,dt.style.transform="translate(-50%, -100%)",Gs.appendChild(dt)},Wn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};at.addEventListener("mouseenter",cn),at.addEventListener("mouseleave",Wn),Ue.addEventListener("focus",cn),Ue.addEventListener("blur",Wn),at._cleanupTooltip=()=>{Wn(),at&&(at.removeEventListener("mouseenter",cn),at.removeEventListener("mouseleave",Wn)),Ue&&(Ue.removeEventListener("focus",cn),Ue.removeEventListener("blur",Wn))}}}let{clearChatButton:Ge,clearChatButtonWrapper:It}=Ve;if(Ge){let te=(zp=_e.clearChat)!=null?zp:{},Tt=(Vp=te.enabled)!=null?Vp:!0,Ut=(Gp=(Kp=r.layout)==null?void 0:Kp.header)==null?void 0:Gp.showClearChat,at=Ut!==void 0?Ut:Tt,kt=(Jp=te.placement)!=null?Jp:"inline";if(It){It.style.display=at?"":"none";let{closeButtonWrapper:ln}=Ve;!R()&&ln&&!ln.classList.contains("persona-absolute")&&(at?ln.classList.remove("persona-ml-auto"):ln.classList.add("persona-ml-auto"));let bn=kt==="top-right",mr=It.classList.contains("persona-absolute");if(!R()&&bn!==mr&&at){if(It.remove(),bn)It.className="persona-absolute persona-top-4 persona-z-50",It.style.right="48px",Se.style.position="relative",Se.appendChild(It);else{It.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",It.style.right="";let Yt=Se.querySelector(".persona-border-b-persona-divider"),Un=Ve.closeButtonWrapper;Yt&&Un&&Un.parentElement===Yt?Yt.insertBefore(It,Un):Yt&&Yt.appendChild(It)}let En=Ve.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(bn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(at){if(!R()){let dt=(Xp=te.size)!=null?Xp:"32px";Ge.style.height=dt,Ge.style.width=dt}let ln=(Qp=te.iconName)!=null?Qp:"refresh-cw",bn=(Yp=te.iconColor)!=null?Yp:"";Ge.style.color=bn||Mn.actionIconColor,Ge.innerHTML="";let mr=R()?"14px":"20px",En=ye(ln,mr,"currentColor",2);if(En&&Ge.appendChild(En),te.backgroundColor?(Ge.style.backgroundColor=te.backgroundColor,Ge.classList.remove("hover:persona-bg-gray-100")):(Ge.style.backgroundColor="",Ge.classList.add("hover:persona-bg-gray-100")),te.borderWidth||te.borderColor){let dt=te.borderWidth||"0px",cn=te.borderColor||"transparent";Ge.style.border=`${dt} solid ${cn}`,Ge.classList.remove("persona-border-none")}else Ge.style.border="",Ge.classList.add("persona-border-none");te.borderRadius?(Ge.style.borderRadius=te.borderRadius,Ge.classList.remove("persona-rounded-full")):(Ge.style.borderRadius="",Ge.classList.add("persona-rounded-full")),te.paddingX?(Ge.style.paddingLeft=te.paddingX,Ge.style.paddingRight=te.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),te.paddingY?(Ge.style.paddingTop=te.paddingY,Ge.style.paddingBottom=te.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let Yt=(Zp=te.tooltipText)!=null?Zp:"Clear chat",Un=(eu=te.showTooltip)!=null?eu:!0;if(Ge.setAttribute("aria-label",Yt),It&&(It._cleanupTooltip&&(It._cleanupTooltip(),delete It._cleanupTooltip),Un&&Yt)){let dt=null,cn=()=>{if(dt||!Ge)return;let qo=Ge.ownerDocument,Gs=qo.body;if(!Gs)return;dt=Wr(qo,"div","persona-clear-chat-tooltip"),dt.textContent=Yt;let Js=Wr(qo,"div");Js.className="persona-clear-chat-tooltip-arrow",dt.appendChild(Js);let zo=Ge.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(Ao),dt.style.left=`${zo.left+zo.width/2}px`,dt.style.top=`${zo.top-8}px`,dt.style.transform="translate(-50%, -100%)",Gs.appendChild(dt)},Wn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};It.addEventListener("mouseenter",cn),It.addEventListener("mouseleave",Wn),Ge.addEventListener("focus",cn),Ge.addEventListener("blur",Wn),It._cleanupTooltip=()=>{Wn(),It&&(It.removeEventListener("mouseenter",cn),It.removeEventListener("mouseleave",Wn)),Ge&&(Ge.removeEventListener("focus",cn),Ge.removeEventListener("blur",Wn))}}}}let $n=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ti],Oo=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Hs.message,Hs.messageAndClick];L=Ei({parsers:$n,handlers:Oo,getSessionMetadata:b,updateSessionMetadata:v,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),ee=rf(r,L,de),F.updateConfig(r),$s(Ze,F.getMessages(),ee),is(),gc(),Oi(F.isStreaming());let Fo=((tu=r.voiceRecognition)==null?void 0:tu.enabled)===!0,_o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),$o=((ru=(nu=r.voiceRecognition)==null?void 0:nu.provider)==null?void 0:ru.type)==="runtype";if(Fo&&(_o||$o))if(!B||!xe){let te=eh(r.voiceRecognition,r.sendButton);te&&(B=te.micButton,xe=te.micButtonWrapper,ht.insertBefore(xe,vn),B.addEventListener("click",Ia),B.disabled=F.isStreaming())}else{let te=(ou=r.voiceRecognition)!=null?ou:{},Tt=(su=r.sendButton)!=null?su:{},Ut=(au=te.iconName)!=null?au:"mic",at=(iu=Tt.size)!=null?iu:"40px",kt=(lu=te.iconSize)!=null?lu:at,ln=parseFloat(kt)||24;B.style.width=kt,B.style.height=kt,B.style.minWidth=kt,B.style.minHeight=kt;let bn=(du=(cu=te.iconColor)!=null?cu:Tt.textColor)!=null?du:"currentColor";B.innerHTML="";let mr=ye(Ut,ln,bn,2);mr?B.appendChild(mr):B.textContent="\u{1F3A4}";let En=(pu=te.backgroundColor)!=null?pu:Tt.backgroundColor;En?B.style.backgroundColor=En:B.style.backgroundColor="",bn?B.style.color=bn:B.style.color="var(--persona-text, #111827)",te.borderWidth?(B.style.borderWidth=te.borderWidth,B.style.borderStyle="solid"):(B.style.borderWidth="",B.style.borderStyle=""),te.borderColor?B.style.borderColor=te.borderColor:B.style.borderColor="",te.paddingX?(B.style.paddingLeft=te.paddingX,B.style.paddingRight=te.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),te.paddingY?(B.style.paddingTop=te.paddingY,B.style.paddingBottom=te.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let Yt=xe==null?void 0:xe.querySelector(".persona-send-button-tooltip"),Un=(uu=te.tooltipText)!=null?uu:"Start voice recognition";if(((mu=te.showTooltip)!=null?mu:!1)&&Un)if(Yt)Yt.textContent=Un,Yt.style.display="";else{let cn=document.createElement("div");cn.className="persona-send-button-tooltip",cn.textContent=Un,xe==null||xe.insertBefore(cn,B)}else Yt&&(Yt.style.display="none");xe.style.display="",B.disabled=F.isStreaming()}else B&&xe&&(xe.style.display="none",((fu=(gu=r.voiceRecognition)==null?void 0:gu.provider)==null?void 0:fu.type)==="runtype"?F.isVoiceActive()&&F.toggleVoice():Pr&&uo());if(((hu=r.attachments)==null?void 0:hu.enabled)===!0)if(!ft||!ce){let te=(yu=r.attachments)!=null?yu:{},Ut=(xu=((bu=r.sendButton)!=null?bu:{}).size)!=null?xu:"40px";Lt||(Lt=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Lt.style.display="none",Ct.insertBefore(Lt,be)),Je||(Je=document.createElement("input"),Je.type="file",Je.accept=((vu=te.allowedTypes)!=null?vu:Gr).join(","),Je.multiple=((wu=te.maxFiles)!=null?wu:4)>1,Je.style.display="none",Je.setAttribute("aria-label","Attach files"),Ct.insertBefore(Je,be)),ft=y("div","persona-send-button-wrapper"),ce=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ce.type="button",ce.setAttribute("aria-label",(Cu=te.buttonTooltipText)!=null?Cu:"Attach file");let at=(Au=te.buttonIconName)!=null?Au:"paperclip",kt=Ut,ln=parseFloat(kt)||40,bn=Math.round(ln*.6);ce.style.width=kt,ce.style.height=kt,ce.style.minWidth=kt,ce.style.minHeight=kt,ce.style.fontSize="18px",ce.style.lineHeight="1",ce.style.backgroundColor="transparent",ce.style.color="var(--persona-primary, #111827)",ce.style.border="none",ce.style.borderRadius="6px",ce.style.transition="background-color 0.15s ease",ce.addEventListener("mouseenter",()=>{ce.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ce.addEventListener("mouseleave",()=>{ce.style.backgroundColor="transparent"});let mr=ye(at,bn,"currentColor",1.5);mr?ce.appendChild(mr):ce.textContent="\u{1F4CE}",ce.addEventListener("click",Un=>{Un.preventDefault(),Je==null||Je.click()}),ft.appendChild(ce);let En=(Su=te.buttonTooltipText)!=null?Su:"Attach file",Yt=y("div","persona-send-button-tooltip");Yt.textContent=En,ft.appendChild(Yt),Qe.append(ft),!At&&Je&&Lt&&(At=Es.fromConfig(te),At.setPreviewsContainer(Lt),Je.addEventListener("change",async()=>{At&&(Je!=null&&Je.files)&&(await At.handleFileSelect(Je.files),Je.value="")})),Se.querySelector(".persona-attachment-drop-overlay")||Se.appendChild(of(te.dropOverlay))}else{ft.style.display="";let te=(Tu=r.attachments)!=null?Tu:{};Je&&(Je.accept=((Eu=te.allowedTypes)!=null?Eu:Gr).join(","),Je.multiple=((Mu=te.maxFiles)!=null?Mu:4)>1),At&&At.updateConfig({allowedTypes:te.allowedTypes,maxFileSize:te.maxFileSize,maxFiles:te.maxFiles})}else ft&&(ft.style.display="none"),At&&At.clearAttachments(),(ku=Se.querySelector(".persona-attachment-drop-overlay"))==null||ku.remove();let Jt=(Lu=r.sendButton)!=null?Lu:{},jo=(Pu=Jt.useIcon)!=null?Pu:!1,go=(Iu=Jt.iconText)!=null?Iu:"\u2191",fo=Jt.iconName,Vr=(Ru=Jt.tooltipText)!=null?Ru:"Send message",Uo=(Wu=Jt.showTooltip)!=null?Wu:!1,et=(Hu=Jt.size)!=null?Hu:"40px",Nt=Jt.backgroundColor,Bt=Jt.textColor;if(jo){if(pe.style.width=et,pe.style.height=et,pe.style.minWidth=et,pe.style.minHeight=et,pe.style.fontSize="18px",pe.style.lineHeight="1",pe.innerHTML="",Bt?pe.style.color=Bt:pe.style.color="var(--persona-button-primary-fg, #ffffff)",fo){let te=parseFloat(et)||24,Tt=(Bt==null?void 0:Bt.trim())||"currentColor",Ut=ye(fo,te,Tt,2);Ut?pe.appendChild(Ut):pe.textContent=go}else pe.textContent=go;pe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Nt?(pe.style.backgroundColor=Nt,pe.classList.remove("persona-bg-persona-primary")):(pe.style.backgroundColor="",pe.classList.add("persona-bg-persona-primary"))}else pe.textContent=(Du=(Bu=r.copy)==null?void 0:Bu.sendButtonLabel)!=null?Du:"Send",pe.style.width="",pe.style.height="",pe.style.minWidth="",pe.style.minHeight="",pe.style.fontSize="",pe.style.lineHeight="",pe.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Nt?(pe.style.backgroundColor=Nt,pe.classList.remove("persona-bg-persona-accent")):pe.classList.add("persona-bg-persona-accent"),Bt?pe.style.color=Bt:pe.classList.add("persona-text-white");Jt.borderWidth?(pe.style.borderWidth=Jt.borderWidth,pe.style.borderStyle="solid"):(pe.style.borderWidth="",pe.style.borderStyle=""),Jt.borderColor?pe.style.borderColor=Jt.borderColor:pe.style.borderColor="",Jt.paddingX?(pe.style.paddingLeft=Jt.paddingX,pe.style.paddingRight=Jt.paddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),Jt.paddingY?(pe.style.paddingTop=Jt.paddingY,pe.style.paddingBottom=Jt.paddingY):(pe.style.paddingTop="",pe.style.paddingBottom="");let Vt=vn==null?void 0:vn.querySelector(".persona-send-button-tooltip");if(Uo&&Vr)if(Vt)Vt.textContent=Vr,Vt.style.display="";else{let te=document.createElement("div");te.className="persona-send-button-tooltip",te.textContent=Vr,vn==null||vn.insertBefore(te,pe)}else Vt&&(Vt.style.display="none");let $t=($u=(Nu=r.layout)==null?void 0:Nu.contentMaxWidth)!=null?$u:R()?(_u=(Fu=(Ou=r.launcher)==null?void 0:Ou.composerBar)==null?void 0:Fu.contentMaxWidth)!=null?_u:"720px":void 0;$t?(Ze.style.maxWidth=$t,Ze.style.marginLeft="auto",Ze.style.marginRight="auto",Ze.style.width="100%",Ct&&(Ct.style.maxWidth=$t,Ct.style.marginLeft="auto",Ct.style.marginRight="auto"),qt&&(qt.style.maxWidth=$t,qt.style.marginLeft="auto",qt.style.marginRight="auto")):(Ze.style.maxWidth="",Ze.style.marginLeft="",Ze.style.marginRight="",Ze.style.width="",Ct&&(Ct.style.maxWidth="",Ct.style.marginLeft="",Ct.style.marginRight=""),qt&&(qt.style.maxWidth="",qt.style.marginLeft="",qt.style.marginRight=""));let mt=(ju=r.statusIndicator)!=null?ju:{},jt=(Uu=mt.visible)!=null?Uu:!0;if(fn.style.display=jt?"":"none",F){let te=F.getStatus();Wt(fn,(Ut=>{var at,kt,ln,bn;return Ut==="idle"?(at=mt.idleText)!=null?at:nn.idle:Ut==="connecting"?(kt=mt.connectingText)!=null?kt:nn.connecting:Ut==="connected"?(ln=mt.connectedText)!=null?ln:nn.connected:Ut==="error"?(bn=mt.errorText)!=null?bn:nn.error:nn[Ut]})(te),mt,te)}fn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let gn=mt.align==="left"?"persona-text-left":mt.align==="center"?"persona-text-center":"persona-text-right";fn.classList.add(gn)},open(){N()&&_t(!0,"api")},close(){N()&&_t(!1,"api")},toggle(){N()&&_t(!O,"api")},reconnect(){F.reconnectNow()},clearChat(){wn=!1,F.clearMessages(),Mr.clear(),co();try{localStorage.removeItem(Bs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Bs}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Bs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),c!=null&&c.clear)try{let m=c.clear();m instanceof Promise&&m.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}p={},L.syncFromMetadata(),V==null||V.clear(),Q==null||Q.reset(),Me==null||Me.update()},setMessage(l){return!be||F.isStreaming()?!1:(!O&&N()&&_t(!0,"system"),be.value=l,be.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(F.isStreaming())return!1;let m=(l==null?void 0:l.trim())||be.value.trim();return m?(!O&&N()&&_t(!0,"system"),be.value="",be.style.height="auto",F.sendMessage(m),!0):!1},startVoiceRecognition(){var m,h;return F.isStreaming()?!1:((h=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:h.type)==="runtype"?(F.isVoiceActive()||(!O&&N()&&_t(!0,"system"),K.manuallyDeactivated=!1,ct(),F.toggleVoice().then(()=>{K.active=F.isVoiceActive(),rt("user"),F.isVoiceActive()&&ms()})),!0):Pr?!0:Cc()?(!O&&N()&&_t(!0,"system"),K.manuallyDeactivated=!1,ct(),La("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?F.isVoiceActive()?(F.toggleVoice().then(()=>{K.active=!1,K.manuallyDeactivated=!0,ct(),rt("user"),zr()}),!0):!1:Pr?(K.manuallyDeactivated=!0,ct(),uo("user"),!0):!1},injectMessage(l){return!O&&N()&&_t(!0,"system"),F.injectMessage(l)},injectAssistantMessage(l){!O&&N()&&_t(!0,"system");let m=F.injectAssistantMessage(l);return Z&&(Z=!1,Ee&&(clearTimeout(Ee),Ee=null),setTimeout(()=>{F&&!F.isStreaming()&&F.continueConversation()},100)),m},injectUserMessage(l){return!O&&N()&&_t(!0,"system"),F.injectUserMessage(l)},injectSystemMessage(l){return!O&&N()&&_t(!0,"system"),F.injectSystemMessage(l)},injectMessageBatch(l){return!O&&N()&&_t(!0,"system"),F.injectMessageBatch(l)},injectComponentDirective(l){return!O&&N()&&_t(!0,"system"),F.injectComponentDirective(l)},injectTestMessage(l){!O&&N()&&_t(!0,"system"),F.injectTestEvent(l)},async connectStream(l,m){return F.connectStream(l,m)},__pushEventStreamEvent(l){V&&(Q==null||Q.processEvent(l.type,l.payload),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)}))},showEventStream(){!ne||!V||Fr()},hideEventStream(){J&&lr()},isEventStreamVisible(){return J},showArtifacts(){rr(r)&&(wn=!1,Sr(),vt==null||vt.setMobileOpen(!0))},hideArtifacts(){rr(r)&&(wn=!0,Sr())},upsertArtifact(l){return rr(r)?(wn=!1,F.upsertArtifact(l)):null},selectArtifact(l){rr(r)&&F.selectArtifact(l)},clearArtifacts(){rr(r)&&F.clearArtifacts()},getArtifacts(){var l;return(l=F==null?void 0:F.getArtifacts())!=null?l:[]},getSelectedArtifactId(){var l;return(l=F==null?void 0:F.getSelectedArtifactId())!=null?l:null},focusInput(){return P&&!O&&!R()||!be?!1:(be.focus(),!0)},async resolveApproval(l,m,h){let A=F.getMessages().find(W=>{var U;return W.variant==="approval"&&((U=W.approval)==null?void 0:U.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);if(A.approval.toolType==="webmcp"){F.resolveWebMcpApproval(A.id,m);return}return F.resolveApproval(A.approval,m,h)},getMessages(){return F.getMessages()},getStatus(){return F.getStatus()},getPersistentMetadata(){return{...p}},updatePersistentMetadata(l){v(l)},on(l,m){return i.on(l,m)},off(l,m){i.off(l,m)},isOpen(){return N()&&O},isVoiceActive(){return K.active},toggleReadAloud(l){F.toggleReadAloud(l)},stopReadAloud(){F.stopSpeaking()},getReadAloudState(l){return F.getReadAloudState(l)},onReadAloudChange(l){return F.onReadAloudChange(l)},getState(){return{open:N()&&O,launcherEnabled:P,voiceActive:K.active,streaming:F.isStreaming()}},showCSATFeedback(l){!O&&N()&&_t(!0,"system");let m=Ze.querySelector(".persona-feedback-container");m&&m.remove();let h=zl({onSubmit:async(x,A)=>{var W;F.isClientTokenMode()&&await F.submitCSATFeedback(x,A),(W=l==null?void 0:l.onSubmit)==null||W.call(l,x,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!O&&N()&&_t(!0,"system");let m=Ze.querySelector(".persona-feedback-container");m&&m.remove();let h=Vl({onSubmit:async(x,A)=>{var W;F.isClientTokenMode()&&await F.submitNPSFeedback(x,A),(W=l==null?void 0:l.onSubmit)==null||W.call(l,x,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,m){return F.submitCSATFeedback(l,m)},async submitNPSFeedback(l,m){return F.submitNPSFeedback(l,m)},destroy(){No!=null&&(clearInterval(No),No=null),lt.forEach(l=>l()),ge.remove(),it==null||it.remove(),Zt==null||Zt.destroy(),sn==null||sn.remove(),Er&&Ue.removeEventListener("click",Er)}};if((((Id=n==null?void 0:n.debugTools)!=null?Id:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:tn,getMessages:tn.getMessages,getStatus:tn.getStatus,getMetadata:tn.getPersistentMetadata,updateMetadata:tn.updatePersistentMetadata,clearHistory:()=>tn.clearChat(),setVoiceActive:h=>h?tn.startVoiceRecognition():tn.stopVoiceRecognition()};window.AgentWidgetBrowser=m,lt.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&tn.focusInput()};if(window.addEventListener("persona:focusInput",m),lt.push(()=>{window.removeEventListener("persona:focusInput",m)}),ne){let _=ie=>{let oe=ie.detail;(!(oe!=null&&oe.instanceId)||oe.instanceId===l)&&tn.showEventStream()},D=ie=>{let oe=ie.detail;(!(oe!=null&&oe.instanceId)||oe.instanceId===l)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",_),window.addEventListener("persona:hideEventStream",D),lt.push(()=>{window.removeEventListener("persona:showEventStream",_),window.removeEventListener("persona:hideEventStream",D)})}let h=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&tn.showArtifacts()},x=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&tn.hideArtifacts()},A=_=>{let D=_.detail;D!=null&&D.instanceId&&D.instanceId!==l||D!=null&&D.artifact&&tn.upsertArtifact(D.artifact)},W=_=>{let D=_.detail;D!=null&&D.instanceId&&D.instanceId!==l||typeof(D==null?void 0:D.id)=="string"&&tn.selectArtifact(D.id)},U=_=>{let D=_.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&tn.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",A),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",U),lt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",A),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",U)})}let Yn=Rw(r.persistState);if(Yn&&N()){let l=Ww(Yn.storage),m=`${Yn.keyPrefix}widget-open`,h=`${Yn.keyPrefix}widget-voice`,x=`${Yn.keyPrefix}widget-voice-mode`;if(l){let A=((Rd=Yn.persist)==null?void 0:Rd.openState)&&l.getItem(m)==="true",W=((Wd=Yn.persist)==null?void 0:Wd.voiceState)&&l.getItem(h)==="true",U=((Hd=Yn.persist)==null?void 0:Hd.voiceState)&&l.getItem(x)==="true";if(A&&setTimeout(()=>{tn.open(),setTimeout(()=>{var _;if(W||U)tn.startVoiceRecognition();else if((_=Yn.persist)!=null&&_.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(Bd=Yn.persist)!=null&&Bd.openState&&(i.on("widget:opened",()=>{l.setItem(m,"true")}),i.on("widget:closed",()=>{l.setItem(m,"false")})),(Dd=Yn.persist)!=null&&Dd.voiceState&&(i.on("voice:state",_=>{l.setItem(h,_.active?"true":"false")}),i.on("user:message",_=>{l.setItem(x,_.viaVoice?"true":"false")})),Yn.clearOnChatClear){let _=()=>{l.removeItem(m),l.removeItem(h),l.removeItem(x)},D=()=>_();window.addEventListener("persona:clear-chat",D),lt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return f&&N()&&setTimeout(()=>{tn.open()},0),ps(),Ma||Gu().then(()=>{F&&(ls++,Mr.clear(),$s(Ze,F.getMessages(),ee))}).catch(()=>{}),tn};var Hw=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(n);return o?Math.max(0,t*parseFloat(o[1])/100):420},Bw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Dw=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Nw=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},sf=(e,t)=>{var r,o;let n=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},Yl=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},af=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Yl(e)},Jl=e=>{e.style.transition=""},Xl=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},Ql=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ki=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Ow=(e,t,n,r,o)=>{o?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Fw=(e,t,n,r,o,s)=>{let a=s?t:e;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},lf=(e,t,n,r,o,s,a)=>{var b,v,S,T,L,P;let i=nr(s),d=i.reveal==="push";Ow(e,t,n,r,d),Fw(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,p=(v=(b=s==null?void 0:s.launcher)==null?void 0:b.mobileFullscreen)!=null?v:!0,u=(T=(S=s==null?void 0:s.launcher)==null?void 0:S.mobileBreakpoint)!=null?T:640,f=c!=null?c.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Xl(t),Jl(r),af(r),Ql(n),ki(o,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((P=(L=s==null?void 0:s.launcher)==null?void 0:L.zIndex)!=null?P:xn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),af(r),Bw(r,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Xl(t),Jl(r),Ql(n),ki(o,r);let E=i.animate?"transform 180ms ease":"none",k=i.side==="right"?"translateX(100%)":"translateX(-100%)",C=a?"translateX(0)":k;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=E,r.style.transform=C,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Jl(r),Yl(r),ki(o,r);let E=Hw(i.width,e.clientWidth),k=Math.max(0,e.clientWidth),C=i.animate?"margin-left 180ms ease":"none",I=i.side==="right"?a?-E:0:a?0:-E;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${k+E}px`,t.style.transition=C,t.style.marginLeft=`${I}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${k}px`,n.style.maxWidth=`${k}px`,n.style.minWidth=`${k}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Xl(t),Yl(r),Ql(n),ki(o,r);let E=i.reveal==="emerge";E?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let k=a?i.width:"0px",C=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",I=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${k}`,r.style.width=k,r.style.maxWidth=k,r.style.minWidth=k,r.style.minHeight="0",Dw(r,i.maxHeight),r.style.overflow=E||I?"hidden":"visible",r.style.transition=C,E&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},_w=(e,t)=>{let n=e.ownerDocument.createElement("div");return sf(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){sf(n,r)},destroy(){n.remove()}}},$w=(e,t)=>{var P,E,k,C;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),c=n.createElement("aside"),p=n.createElement("div"),u=(E=(P=t==null?void 0:t.launcher)==null?void 0:P.enabled)==null||E?(C=(k=t==null?void 0:t.launcher)==null?void 0:k.autoExpand)!=null?C:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},b=()=>{g(),nr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{lf(a,i,d,c,p,t,u)}),f.observe(a))},v=!1,S=()=>{lf(a,i,d,c,p,t,u),b(),u&&!v&&a.dataset.personaDockMobileFullscreen!=="true"&&(v=!0,Nw(a,nr(t)))},T=a.ownerDocument.defaultView,L=()=>{S()};return T==null||T.addEventListener("resize",L),nr(t).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),S(),{mode:"docked",host:p,shell:a,syncWidgetState(I){let j=I.launcherEnabled?I.open:!0;u!==j&&(u=j,S())},updateConfig(I){var j,$;t=I,(($=(j=t==null?void 0:t.launcher)==null?void 0:j.enabled)!=null?$:!0)===!1&&(u=!0),S()},destroy(){T==null||T.removeEventListener("resize",L),g(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Li=(e,t)=>dn(t)?$w(e,t):_w(e,t);var Zl={},jw=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Uw=()=>{try{if(typeof Zl!="undefined"&&Zl.url)return new URL("../widget.css",Zl.url).href}catch{}return null},cf=(e,t)=>{let n=Uw(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),t.head.appendChild(s)}},df=e=>{var S;let t=jw(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=Li(t,o),a,i=[],d=(T,L)=>{var C,I;let E=!((I=(C=L==null?void 0:L.launcher)==null?void 0:C.enabled)!=null?I:!0)||dn(L),k=r.createElement("div");if(k.setAttribute("data-persona-root","true"),E&&(k.style.height="100%",k.style.display="flex",k.style.flexDirection="column",k.style.flex="1",k.style.minHeight="0"),n){let j=T.attachShadow({mode:"open"});j.appendChild(k),cf(j,r)}else T.appendChild(k),cf(T,r);return t.id&&k.setAttribute("data-persona-instance",t.id),k},c=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(T=>T()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},u=()=>{let T=d(s.host,o);a=Gl(T,o,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(T=>T()),i=[],a.destroy()};u(),(S=e.onChatReady)==null||S.call(e);let g=T=>{f(),s.destroy(),s=Li(t,T),o=T,u()},b={update(T){var I,j,$,R,N,O;let L={...o,...T,launcher:{...(I=o==null?void 0:o.launcher)!=null?I:{},...(j=T==null?void 0:T.launcher)!=null?j:{},dock:{...(R=($=o==null?void 0:o.launcher)==null?void 0:$.dock)!=null?R:{},...(O=(N=T==null?void 0:T.launcher)==null?void 0:N.dock)!=null?O:{}}}},P=dn(o),E=dn(L),k=To(o),C=To(L);if(P!==E||k!==C){g(L);return}o=L,s.updateConfig(o),a.update(T),c()},destroy(){f(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(b,{get(T,L,P){if(L==="host")return s.host;if(L in T)return Reflect.get(T,L,P);let E=a[L];return typeof E=="function"?E.bind(a):E}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var ff=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),qw=new Set(["button","a","input","select","textarea","details","summary"]),zw=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ec=/\b(product|card|item|listing|result)\b/i,nc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Vw=3e3,Kw=100;function hf(e){let t=typeof e.className=="string"?e.className:"";if(ec.test(t)||e.id&&ec.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&ec.test(r.value))return!0}return!1}function yf(e){var t;return nc.test(((t=e.textContent)!=null?t:"").trim())}function bf(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let o=(n=t[r].getAttribute("href"))!=null?n:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function Gw(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function pf(e){let t=e.match(nc);return t?t[0]:null}function uf(e){var r,o,s;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((o=t.textContent)!=null&&o.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(s=n==null?void 0:n.textContent)!=null&&s.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Jw(e){let t=[],n=r=>{let o=r.trim();o&&!t.includes(o)&&t.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;n((o=r.value)!=null?o:"")}),t.slice(0,6)}var Xw="commerce-card",Qw="result-card";function mf(e){return!hf(e)||!yf(e)||!bf(e)&&!Gw(e)?0:5200}function gf(e){var r;return!hf(e)||yf(e)||!bf(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var xf=[{id:Xw,scoreElement(e){return mf(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||nc.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,c,p;if(mf(e)===0)return null;let{title:n,href:r}=uf(e),o=(p=(c=pf(((d=e.textContent)!=null?d:"").trim()))!=null?c:pf(t.text))!=null?p:"",s=Jw(e);return[r&&n?`[${n}](${r})${o?`: ${o}`:""}`:n?`${n}${o?`: ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
112
+ `)}},{id:Qw,scoreElement(e){return gf(e)},formatSummary(e,t){if(gf(e)===0)return null;let{title:n,href:r}=uf(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
113
+ `)}}];function Yw(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Zw(e){var p,u,f,g,b,v,S,T,L,P,E,k,C;let t=(p=e.options)!=null?p:{},n=(f=(u=t.maxElements)!=null?u:e.maxElements)!=null?f:80,r=(b=(g=t.excludeSelector)!=null?g:e.excludeSelector)!=null?b:".persona-host",o=(S=(v=t.maxTextLength)!=null?v:e.maxTextLength)!=null?S:200,s=(L=(T=t.visibleOnly)!=null?T:e.visibleOnly)!=null?L:!0,a=(P=t.root)!=null?P:e.root,i=(E=t.mode)!=null?E:"structured",d=(k=t.maxCandidates)!=null?k:Math.max(500,n*10),c=(C=e.rules)!=null?C:xf;return i==="simple"&&e.rules&&e.rules.length>0?(Yw(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:c}}function tc(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var eC=["data-testid","data-product","data-action","data-id","data-name","data-type"];function tC(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||qw.has(t)||n&&zw.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function vf(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function nC(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);let s=e.getAttribute("type");s&&(t.type=s);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let c=0;c<e.attributes.length;c++){let p=e.attributes[c];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function wf(e){let t=e.tagName.toLowerCase();if(e.id){let o=`#${tc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of eC){let s=e.getAttribute(o);if(s){let a=`${t}[${o}="${tc(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(n.length>0){let o=`${t}.${n.map(a=>tc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let s=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function rC(e){return e==="static"?Kw:Vw}function Cf(e,t){var o;let n=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,t);return{selector:wf(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:tC(e),attributes:nC(e)}}function oC(e,t,n,r){let o=rC(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function sC(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function aC(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,p=c.tagName.toLowerCase();if(ff.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!vf(c)){i=a.nextNode();continue}let u=Cf(c,e.maxTextLength),f=u.text.length>0,g=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(S=>S==="role");if(!f&&!g){i=a.nextNode();continue}if(r.has(u.selector)){i=a.nextNode();continue}r.add(u.selector);let{score:b,formattingRule:v}=oC(c,u,e.rules,n);o.push({el:c,domIndex:s,enriched:u,score:b,formattingRule:v}),s+=1}i=a.nextNode()}o.sort((c,p)=>{let u=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex});let d=[];for(let c of o){if(d.length>=e.maxElements)break;sC(d,c)||d.push(c)}return d.sort((c,p)=>{let u=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:u===1&&p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex}),d.map(c=>{var f;let p;if((f=c.formattingRule)!=null&&f.formatSummary){let g=c.formattingRule.formatSummary(c.el,c.enriched,n);g&&(p=g)}let u={...c.enriched};return p&&(u.formattedSummary=p),u})}function iC(e,t){let n=[],r=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,c=d.tagName.toLowerCase();if(ff.has(c)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!vf(d)){s=o.nextNode();continue}let p=Cf(d,e.maxTextLength),u=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(g=>g==="role");if(!u&&!f){s=o.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}s=o.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function lC(e={}){var r;let t=Zw(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?iC(t,n):aC(t,n):[]}var Pi=100;function cC(e,t={}){var s;if(e.length===0)return"No page elements found.";let n=(s=t.mode)!=null?s:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
114
114
  ${a.map(i=>`- ${i.split(`
115
115
  `).join(`
116
116
  `)}`).join(`
117
- `)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Li)}" (clickable)`);r.push(`Interactive elements:
117
+ `)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of e)n==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Pi)}" (clickable)`);r.push(`Interactive elements:
118
118
  ${a.join(`
119
- `)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Li)}" (navigable)`);r.push(`Navigation links:
119
+ `)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Pi)}" (navigable)`);r.push(`Navigation links:
120
120
  ${a.join(`
121
- `)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Li)}" (input)`);r.push(`Form inputs:
121
+ `)}`)}if(o.input.length>0){let a=o.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Pi)}" (input)`);r.push(`Form inputs:
122
122
  ${a.join(`
123
- `)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Li)}"`);r.push(`Content:
123
+ `)}`)}if(o.static.length>0){let a=o.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Pi)}"`);r.push(`Content:
124
124
  ${a.join(`
125
125
  `)}`)}return r.join(`
126
126
 
127
- `)}function Qw(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function Yw(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Zw(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:_r(e.colors.primary,.95),100:_r(e.colors.primary,.9),200:_r(e.colors.primary,.8),300:_r(e.colors.primary,.7),400:_r(e.colors.primary,.6),500:e.colors.primary,600:_r(e.colors.primary,.8),700:_r(e.colors.primary,.7),800:_r(e.colors.primary,.6),900:_r(e.colors.primary,.5),950:_r(e.colors.primary,.45)}}),{...t,palette:n}}}}function eC(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function tC(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function _r(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(o+(255-o)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function nC(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var rC={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},uf={components:{panel:{borderRadius:"0",shadow:"none"}}},mf={id:"shop",label:"Shopping Assistant",config:{theme:rC,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:nr},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},gf={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:uf}},ff={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:uf}},hf={shop:mf,minimal:gf,fullscreen:ff};function oC(e){return hf[e]}var sC=Yg;function eo(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function aC(e){if(e)return{getHeaders:eo(e.getHeaders),onFeedback:eo(e.onFeedback),onCopy:eo(e.onCopy),requestMiddleware:eo(e.requestMiddleware),actionHandlers:eo(e.actionHandlers),actionParsers:eo(e.actionParsers),postprocessMessage:eo(e.postprocessMessage),contextProviders:eo(e.contextProviders),streamParser:eo(e.streamParser)}}var yf=`({ text, message }: any) => {
127
+ `)}function dC(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function pC(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function uC(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Dr(e.colors.primary,.95),100:Dr(e.colors.primary,.9),200:Dr(e.colors.primary,.8),300:Dr(e.colors.primary,.7),400:Dr(e.colors.primary,.6),500:e.colors.primary,600:Dr(e.colors.primary,.8),700:Dr(e.colors.primary,.7),800:Dr(e.colors.primary,.6),900:Dr(e.colors.primary,.5),950:Dr(e.colors.primary,.45)}}),{...t,palette:n}}}}function mC(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function gC(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Dr(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(o+(255-o)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function fC(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var hC={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Af={components:{panel:{borderRadius:"0",shadow:"none"}}},Sf={id:"shop",label:"Shopping Assistant",config:{theme:hC,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:tr},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Tf={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Af}},Ef={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Af}},Mf={shop:Sf,minimal:Tf,fullscreen:Ef};function yC(e){return Mf[e]}var bC=df;function Jr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function xC(e){if(e)return{getHeaders:Jr(e.getHeaders),onFeedback:Jr(e.onFeedback),onCopy:Jr(e.onCopy),requestMiddleware:Jr(e.requestMiddleware),actionHandlers:Jr(e.actionHandlers),actionParsers:Jr(e.actionParsers),postprocessMessage:Jr(e.postprocessMessage),contextProviders:Jr(e.contextProviders),streamParser:Jr(e.streamParser)}}var kf=`({ text, message }: any) => {
128
128
  const jsonSource = (message as any).rawContent || text || message.content;
129
129
  if (!jsonSource || typeof jsonSource !== 'string') return null;
130
130
  let cleanJson = jsonSource
@@ -137,7 +137,7 @@ ${a.join(`
137
137
  if (parsed.action) return { type: parsed.action, payload: parsed };
138
138
  } catch (e) { return null; }
139
139
  return null;
140
- }`,bf=`function(ctx) {
140
+ }`,Lf=`function(ctx) {
141
141
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
142
142
  if (!jsonSource || typeof jsonSource !== 'string') return null;
143
143
  var cleanJson = jsonSource
@@ -150,7 +150,7 @@ ${a.join(`
150
150
  if (parsed.action) return { type: parsed.action, payload: parsed };
151
151
  } catch (e) { return null; }
152
152
  return null;
153
- }`,xf=`(action: any, context: any) => {
153
+ }`,Pf=`(action: any, context: any) => {
154
154
  if (action.type !== 'nav_then_click') return;
155
155
  const payload = action.payload || action.raw || {};
156
156
  const url = payload?.page;
@@ -167,7 +167,7 @@ ${a.join(`
167
167
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
168
168
  window.location.href = targetUrl;
169
169
  return { handled: true, displayText: text };
170
- }`,vf=`function(action, context) {
170
+ }`,If=`function(action, context) {
171
171
  if (action.type !== 'nav_then_click') return;
172
172
  var payload = action.payload || action.raw || {};
173
173
  var url = payload.page;
@@ -184,26 +184,26 @@ ${a.join(`
184
184
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
185
185
  window.location.href = targetUrl;
186
186
  return { handled: true, displayText: text };
187
- }`,iC=`(parsed: any) => {
187
+ }`,vC=`(parsed: any) => {
188
188
  if (!parsed || typeof parsed !== 'object') return null;
189
189
  if (parsed.action === 'nav_then_click') return 'Navigating...';
190
190
  if (parsed.action === 'message') return parsed.text || '';
191
191
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
192
192
  return parsed.text || null;
193
- }`,lC=`function(parsed) {
193
+ }`,wC=`function(parsed) {
194
194
  if (!parsed || typeof parsed !== 'object') return null;
195
195
  if (parsed.action === 'nav_then_click') return 'Navigating...';
196
196
  if (parsed.action === 'message') return parsed.text || '';
197
197
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
198
198
  return parsed.text || null;
199
- }`;function cC(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function Pi(e){var t,n;return(n=(t=e.parserType)!=null?t:cC(e.streamParser))!=null?n:"plain"}function Ii(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,o])=>{typeof o=="string"&&n.push(`${t} ${r}: "${o}",`)}),n.push(`${t}},`)),n}function Ri(e,t,n){let r=[],o=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(o||s)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function Wi(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(r||o)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`)}),n.push(`${t} },`)),o&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Hi(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(r||o)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),o&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,l])=>{d!=="format"&&(typeof l=="string"?n.push(`${t} ${d}: "${l}",`):typeof l=="boolean"&&n.push(`${t} ${d}: ${l},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function tc(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function wf(e,t,n){Object.entries(t).forEach(([r,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${r}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${r}: {`),wf(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(o)},`)}})}function Po(e,t,n,r){n&&(e.push(`${r}${t}: {`),wf(e,n,`${r} `),e.push(`${r}},`))}function Ea(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function dC(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let o=n?{...n,hooks:aC(n.hooks)}:void 0;return t==="esm"?pC(r,o):t==="script-installer"?gC(r,o):t==="script-advanced"?hC(r,o):t==="react-component"?uC(r,o):t==="react-advanced"?mC(r,o):fC(r,o)}function pC(e,t){let n=t==null?void 0:t.hooks,r=Pi(e),o=r!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Ea(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Po(s,"theme",e.theme," "),e.launcher&&Po(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ii(e," ")),s.push(...Ri(e," ",n)),s.push(...Wi(e," ")),s.push(...Hi(e," ")),s.push(...tc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
200
- `)}function uC(e,t){let n=t==null?void 0:t.hooks,r=Pi(e),o=r!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${Ea(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Po(s,"theme",e.theme," "),e.launcher&&Po(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ii(e," ")),s.push(...Ri(e," ",n)),s.push(...Wi(e," ")),s.push(...Hi(e," ")),s.push(...tc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
201
- `)}function mC(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${Ea(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Po(r,"theme",e.theme," "),e.launcher&&Po(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"?r.push(` ${o}: ${s},`):typeof s=="number"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{r.push(` ${o}: ${s},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{r.push(` "${o}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Ii(e," ")),r.push(...Ri(e," ",n)),r.push(...Wi(e," ")),r.push(...Hi(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${iC}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${yf}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${yf}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${xf}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${xf}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
202
- `)}function Cf(e){var o;let t=Pi(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.agentId&&(r.agentId=e.agentId),e.target&&(r.target=e.target),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((o=e.suggestionChips)==null?void 0:o.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(s[a]=i)}),Object.keys(s).length>0&&(r.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(r.markdown=s)}if(e.layout){let s={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let l={};Object.entries(d).forEach(([p,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(l[p]=u)}),Object.keys(l).length>0&&(a.timestamp=l)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.messages=a)}Object.keys(s).length>0&&(r.layout=s)}return r}function gC(e,t){let n=Cf(e),o=!!(t!=null&&t.windowKey||t!=null&&t.target)?{config:n,...t!=null&&t.windowKey?{windowKey:t.windowKey}:{},...t!=null&&t.target?{target:t.target}:{}}:n,s=JSON.stringify(o,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${yr}/dist/install.global.js" data-config='${s}'></script>`}function fC(e,t){let n=t==null?void 0:t.hooks,r=Pi(e),o=r!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${yr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${yr}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Ea(t)}',`,...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Po(s,"theme",e.theme," "),e.launcher&&Po(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ii(e," ")),s.push(...Ri(e," ",n)),s.push(...Wi(e," ")),s.push(...Hi(e," ")),s.push(...tc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
203
- `)}function hC(e,t){let n=t==null?void 0:t.hooks,r=Cf(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
199
+ }`;function CC(e){if(!e)return null;let t=e.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function Ii(e){var t,n;return(n=(t=e.parserType)!=null?t:CC(e.streamParser))!=null?n:"plain"}function Ri(e,t){let n=[];return e.toolCall&&(n.push(`${t}toolCall: {`),Object.entries(e.toolCall).forEach(([r,o])=>{typeof o=="string"&&n.push(`${t} ${r}: "${o}",`)}),n.push(`${t}},`)),n}function Wi(e,t,n){let r=[],o=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=(n==null?void 0:n.onFeedback)||(n==null?void 0:n.onCopy);return(o||s)&&(r.push(`${t}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${t} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${a}: ${i},`))}),n!=null&&n.onFeedback&&r.push(`${t} onFeedback: ${n.onFeedback},`),n!=null&&n.onCopy&&r.push(`${t} onCopy: ${n.onCopy},`),r.push(`${t}},`)),r}function Hi(e,t){let n=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(r||o)&&(n.push(`${t}markdown: {`),r&&(n.push(`${t} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`)}),n.push(`${t} },`)),o&&n.push(`${t} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),n.push(`${t}},`))}return n}function Bi(e,t){let n=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(r||o)&&(n.push(`${t}layout: {`),r&&(n.push(`${t} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),o&&(n.push(`${t} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof a=="object"&&a!==null?(n.push(`${t} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?n.push(`${t} ${i}: "${d}",`):typeof d=="boolean"&&n.push(`${t} ${i}: ${d},`)}),n.push(`${t} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(n.push(`${t} timestamp: {`),Object.entries(a).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?n.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&n.push(`${t} ${d}: ${c},`))}),n.push(`${t} },`)):typeof a=="string"?n.push(`${t} ${s}: "${a}",`):typeof a=="boolean"&&n.push(`${t} ${s}: ${a},`))}),n.push(`${t} },`)),n.push(`${t}},`))}return n}function rc(e,t){let n=[];return e&&(e.getHeaders&&n.push(`${t}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&n.push(`${t}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&n.push(`${t}actionParsers: ${e.actionParsers},`),e.actionHandlers&&n.push(`${t}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&n.push(`${t}contextProviders: ${e.contextProviders},`),e.streamParser&&n.push(`${t}streamParser: ${e.streamParser},`)),n}function Rf(e,t,n){Object.entries(t).forEach(([r,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${n}${r}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${n}${r}: {`),Rf(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(o)},`)}})}function ko(e,t,n,r){n&&(e.push(`${r}${t}: {`),Rf(e,n,`${r} `),e.push(`${r}},`))}function Ea(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function AC(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let o=n?{...n,hooks:xC(n.hooks)}:void 0;return t==="esm"?SC(r,o):t==="script-installer"?MC(r,o):t==="script-advanced"?LC(r,o):t==="react-component"?TC(r,o):t==="react-advanced"?EC(r,o):kC(r,o)}function SC(e,t){let n=t==null?void 0:t.hooks,r=Ii(e),o=r!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${Ea(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(s,"theme",e.theme," "),e.launcher&&ko(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ri(e," ")),s.push(...Wi(e," ",n)),s.push(...Hi(e," ")),s.push(...Bi(e," ")),s.push(...rc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
200
+ `)}function TC(e,t){let n=t==null?void 0:t.hooks,r=Ii(e),o=r!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({",` target: '${Ea(t)}',`," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(s,"theme",e.theme," "),e.launcher&&ko(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ri(e," ")),s.push(...Wi(e," ",n)),s.push(...Hi(e," ")),s.push(...Bi(e," ")),s.push(...rc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
201
+ `)}function EC(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({",` target: '${Ea(t)}',`," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.agentId&&r.push(` agentId: "${e.agentId}",`),e.target&&r.push(` target: "${e.target}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(r,"theme",e.theme," "),e.launcher&&ko(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"?r.push(` ${o}: ${s},`):typeof s=="number"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{r.push(` ${o}: ${s},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{r.push(` "${o}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Ri(e," ")),r.push(...Wi(e," ",n)),r.push(...Hi(e," ")),r.push(...Bi(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${vC}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${kf}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${kf}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${Pf}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${Pf}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
202
+ `)}function Wf(e){var o;let t=Ii(e),n=t!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.agentId&&(r.agentId=e.agentId),e.target&&(r.target=e.target),e.flowId&&(r.flowId=e.flowId),n&&(r.parserType=t),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((o=e.suggestionChips)==null?void 0:o.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(s[a]=i)}),Object.keys(s).length>0&&(r.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(r.markdown=s)}if(e.layout){let s={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([p,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(c[p]=u)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.messages=a)}Object.keys(s).length>0&&(r.layout=s)}return r}function MC(e,t){let n=Wf(e),o=!!(t!=null&&t.windowKey||t!=null&&t.target)?{config:n,...t!=null&&t.windowKey?{windowKey:t.windowKey}:{},...t!=null&&t.target?{target:t.target}:{}}:n,s=JSON.stringify(o,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fr}/dist/install.global.js" data-config='${s}'></script>`}function kC(e,t){let n=t==null?void 0:t.hooks,r=Ii(e),o=r!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fr}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({",` target: '${Ea(t)}',`,...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.agentId&&s.push(` agentId: "${e.agentId}",`),e.target&&s.push(` target: "${e.target}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&ko(s,"theme",e.theme," "),e.launcher&&ko(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Ri(e," ")),s.push(...Wi(e," ",n)),s.push(...Hi(e," ")),s.push(...Bi(e," ")),s.push(...rc(n," ")),e.debug&&s.push(` debug: ${e.debug},`),n!=null&&n.postprocessMessage?s.push(` postprocessMessage: ${n.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
203
+ `)}function LC(e,t){let n=t==null?void 0:t.hooks,r=Wf(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
204
204
  `).map((a,i)=>i===0?a:" "+a).join(`
205
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${yr}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n!=null&&n.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n!=null&&n.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${lC});`),s.push(" };")),s.push(""),n!=null&&n.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${bf}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${bf}`),s.push(" ];")),s.push(""),n!=null&&n.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${vf}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${vf}`),s.push(" ];")),s.push(""),n!=null&&n.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n!=null&&n.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${Ea(t)}',`," useShadowDom: false,",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
206
- `)}var Af={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Sf=.1,Tf=.15,Ef=1.5,nc=24,Mf=40,yC=`
205
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${fr}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return n!=null&&n.getHeaders&&(s.push(` widgetConfig.getHeaders = ${n.getHeaders};`),s.push("")),n!=null&&n.contextProviders&&(s.push(` widgetConfig.contextProviders = ${n.contextProviders};`),s.push("")),n!=null&&n.streamParser?s.push(` widgetConfig.streamParser = ${n.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${wC});`),s.push(" };")),s.push(""),n!=null&&n.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${n.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Lf}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${Lf}`),s.push(" ];")),s.push(""),n!=null&&n.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${n.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${If}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${If}`),s.push(" ];")),s.push(""),n!=null&&n.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${n.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),n!=null&&n.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${n.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(n!=null&&n.onFeedback||n!=null&&n.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),n!=null&&n.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${n.onFeedback};`),n!=null&&n.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${n.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({",` target: '${Ea(t)}',`," useShadowDom: false,",...t!=null&&t.windowKey?[` windowKey: '${t.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
206
+ `)}var Hf={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Bf=.1,Df=.15,Nf=1.5,oc=24,Of=40,PC=`
207
207
  /* \u2500\u2500 Root \u2500\u2500 */
208
208
  .persona-dc-root {
209
209
  display: flex;
@@ -354,7 +354,7 @@ ${a.join(`
354
354
  .persona-dc-stage {
355
355
  height: 550px;
356
356
  min-height: 400px;
357
- padding: ${nc}px;
357
+ padding: ${oc}px;
358
358
  overflow: auto;
359
359
  background: #f0f1f3;
360
360
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -444,5 +444,5 @@ ${a.join(`
444
444
  min-height: 300px;
445
445
  }
446
446
  }
447
- `;function bC(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=yC,document.head.appendChild(e)}function xC(e,t){let n=e.clientWidth-nc*2-Mf,r=e.clientHeight-nc*2-Mf;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function vC(e,t,n,r,o){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=o==="mobile"?`${32*r}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${r})`}function wC(e,t){let{items:n,initialIndex:r=0,initialDevice:o="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:l}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");bC();let p=Math.max(0,Math.min(r,n.length-1)),u=o,g=s,f=null,v=1,x=!1,E=y("div","persona-dc-root"),T=y("div","persona-dc-toolbar"),L=y("div","persona-dc-toolbar-lead"),k=y("div","persona-dc-toolbar-trail"),M=Kt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>X(-1)}),P=y("div");P.style.position="relative";let C=y("button","persona-dc-title-btn");C.type="button",C.setAttribute("aria-expanded","false"),C.setAttribute("aria-haspopup","listbox");let R=y("span","persona-dc-title-text"),F=y("span","persona-dc-title-chevron"),j=ge("chevron-down",12,"currentColor",2);j&&F.appendChild(j),C.append(R,F);let H=y("div","persona-dc-dropdown");H.setAttribute("role","listbox"),H.style.display="none";let O=!1;function N(){H.innerHTML="";for(let fe=0;fe<n.length;fe++){let Ve=n[fe],et=y("button","persona-dc-dropdown-item");et.type="button",et.setAttribute("role","option"),et.setAttribute("aria-current",fe===p?"true":"false");let Ot=y("span");if(Ot.textContent=Ve.title,et.appendChild(Ot),Ve.description){let Xe=y("span","persona-dc-dropdown-desc");Xe.textContent=Ve.description,et.appendChild(Xe)}et.addEventListener("click",()=>{ke(),He(fe)}),H.appendChild(et)}}function Y(){O=!O,H.style.display=O?"":"none",C.setAttribute("aria-expanded",O?"true":"false"),O&&N()}function ke(){O&&(O=!1,H.style.display="none",C.setAttribute("aria-expanded","false"))}C.addEventListener("click",fe=>{fe.stopPropagation(),Y()});let pe=()=>ke();document.addEventListener("click",pe),P.append(C,H);let Z=Kt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>X(1)}),Te=y("span","persona-dc-counter");L.append(M,P,Z,Te);let Le=null;i&&(Le=pi({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:fe=>{u=fe,ae.dataset.device=u,f=null,K()}}),k.appendChild(Le.element));let oe=null;if(a){let fe=y("div","persona-dc-zoom-controls"),Ve=Kt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Xe=f!=null?f:v;f=Math.max(Tf,Xe-Sf),K()}});oe=y("span","persona-dc-zoom-level"),oe.title="Reset to 100%",oe.style.cursor="pointer",oe.addEventListener("click",()=>{f=1,K()});let et=Kt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Xe=f!=null?f:v;f=Math.min(Ef,Xe+Sf),K()}}),Ot=Kt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,K()}});fe.append(Ve,oe,et,Ot),k.appendChild(fe)}if(d){let fe=y("div","persona-dc-separator");k.appendChild(fe);let Ve=pi({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:g,onSelect:et=>{g=et,ae.dataset.colorScheme=g,Be()}});k.appendChild(Ve.element)}let Ae=y("div","persona-dc-separator");k.appendChild(Ae);let se=Kt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});k.appendChild(se),T.append(L,k);let ie=y("div","persona-dc-stage"),ae=y("div","persona-dc-iframe-wrapper");ae.dataset.device=u,ae.dataset.colorScheme=g;let xe=y("iframe","persona-dc-iframe");xe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),xe.setAttribute("loading","lazy"),xe.title=n[p].title,ae.appendChild(xe),ie.appendChild(ae),E.append(T,ie),e.appendChild(E);function Be(){var fe;try{let Ve=(fe=xe.contentDocument)==null?void 0:fe.body;if(!Ve)return;g==="dark"?Ve.classList.add("theme-dark"):Ve.classList.remove("theme-dark")}catch{}}xe.addEventListener("load",()=>Be());function V(){let fe=n[p];R.textContent=fe.title,Te.textContent=`${p+1} / ${n.length}`,xe.title=fe.title}function X(fe){let Ve=((p+fe)%n.length+n.length)%n.length;He(Ve)}function He(fe){fe<0||fe>=n.length||(p=fe,xe.src=n[p].url,V(),l==null||l(p,n[p]))}function K(){var et;if(x)return;let fe=(et=Af[u])!=null?et:Af.desktop;v=xC(ie,fe);let Ve=Math.max(Tf,Math.min(Ef,f!=null?f:v));vC(ae,xe,fe,Ve,u),oe&&(oe.textContent=`${Math.round(Ve*100)}%`)}let ue=new ResizeObserver(()=>K());ue.observe(ie),V(),xe.src=n[p].url,requestAnimationFrame(()=>K());function $e(){x||(x=!0,ue.disconnect(),document.removeEventListener("click",pe),E.remove())}return{element:E,goTo:He,next:()=>X(1),prev:()=>X(-1),getIndex:()=>p,setDevice(fe){u=fe,ae.dataset.device=fe,Le==null||Le.setSelected(fe),f=null,K()},setColorScheme(fe){g=fe,ae.dataset.colorScheme=fe},setZoom(fe){f=fe,K()},destroy:$e}}export{hm as ASK_USER_QUESTION_CLIENT_TOOL,fm as ASK_USER_QUESTION_PARAMETERS_SCHEMA,Ba as ASK_USER_QUESTION_TOOL_NAME,ws as AgentWidgetClient,ca as AgentWidgetSession,Ts as AttachmentManager,Yo as BrowserSpeechEngine,jm as DEFAULT_COMPONENTS,ul as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,nr as DEFAULT_FLOATING_LAUNCHER_WIDTH,_m as DEFAULT_PALETTE,$m as DEFAULT_SEMANTIC,Dt as DEFAULT_WIDGET_CONFIG,hf as PRESETS,ff as PRESET_FULLSCREEN,gf as PRESET_MINIMAL,mf as PRESET_SHOP,Ss as ReadAloudController,Zi as SUGGEST_REPLIES_CLIENT_TOOL,um as SUGGEST_REPLIES_PARAMETERS_SCHEMA,Or as SUGGEST_REPLIES_TOOL_NAME,Wx as THEME_ZONES,yr as VERSION,Dr as WEBMCP_TOOL_PREFIX,Xs as WebMcpBridge,Qw as accessibilityPlugin,Yw as animationsPlugin,Zo as applyThemeVariables,Ms as attachHeaderToContainer,Zw as brandPlugin,wa as buildComposer,ag as buildDefaultHeader,ko as buildHeader,va as buildHeaderWithLayout,ig as buildMinimalHeader,_a as builtInClientToolsForDispatch,Jw as collectEnrichedPageContext,Lo as componentRegistry,Ti as createActionManager,Vl as createAgentExperience,zh as createAskUserQuestionBubble,cl as createBestAvailableVoiceProvider,fv as createBubbleWithLayout,Ul as createCSATFeedback,Cl as createComboButton,gw as createComponentMiddleware,Fl as createComponentStreamParser,Uu as createDefaultSanitizer,wC as createDemoCarousel,rh as createDirectivePostprocessor,es as createDropdownMenu,Jh as createFlexibleJsonStreamParser,Kt as createIconButton,ay as createImagePart,sl as createJsonStreamParser,di as createLabelButton,Ol as createLocalStorageAdapter,Wa as createMarkdownProcessor,bs as createMarkdownProcessorFromConfig,yg as createMessageActions,ql as createNPSFeedback,rl as createPlainTextParser,nC as createPlugin,ol as createRegexJsonParser,Ca as createStandardBubble,Ka as createTextPart,pa as createTheme,hl as createThemeObserver,pi as createToggleGroup,ks as createTypingIndicator,Qo as createVoiceProvider,ki as createWidgetHostLayout,al as createXmlParser,sC as default,Rs as defaultActionHandlers,Si as defaultJsonActionParser,lf as defaultParseRules,Za as detectColorScheme,oh as directivePostprocessor,ta as ensureAskUserQuestionSheet,Yr as escapeHtml,jl as extractComponentDirectiveFromMessage,iy as fileToImagePart,Xw as formatEnrichedContext,Cs as generateAssistantMessageId,dC as generateCodeSnippet,ty as generateMessageId,df as generateStableSelector,sa as generateUserMessageId,ua as getActiveTheme,Vm as getColorScheme,ry as getDisplayText,lg as getHeaderLayout,sy as getImageParts,oC as getPreset,$l as hasComponentDirective,oy as hasImages,Al as headerLayouts,tC as highContrastPlugin,Yg as initAgentWidget,xo as isAskUserQuestionMessage,mw as isComponentDirectiveType,dn as isDockedMountMode,Fa as isSuggestRepliesMessage,Ja as isVoiceSupported,Ko as isWebMcpToolName,tl as latestAgentSuggestions,Ux as listRegisteredStreamAnimations,_u as markdownPostprocessor,ml as mergeWithDefaults,ny as normalizeContent,vo as parseAskUserQuestionPayload,mm as parseSuggestRepliesPayload,ia as pickBestVoice,Ai as pluginRegistry,eC as reducedMotionPlugin,$x as registerStreamAnimationPlugin,Jo as removeAskUserQuestionSheet,_l as renderComponentDirective,hg as renderLoadingIndicatorWithFallback,ge as renderLucideIcon,rr as resolveDockConfig,Js as resolveSanitizer,gl as resolveTokens,Ki as stripWebMcpPrefix,fl as themeToCssVariables,jx as unregisterStreamAnimationPlugin,ly as validateImageFile,Um as validateTheme};
447
+ `;function IC(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=PC,document.head.appendChild(e)}function RC(e,t){let n=e.clientWidth-oc*2-Of,r=e.clientHeight-oc*2-Of;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function WC(e,t,n,r,o){e.style.width=`${n.w*r}px`,e.style.height=`${n.h*r}px`,e.style.borderRadius=o==="mobile"?`${32*r}px`:"10px",t.style.width=`${n.w}px`,t.style.height=`${n.h}px`,t.style.transformOrigin="top left",t.style.transform=`scale(${r})`}function HC(e,t){let{items:n,initialIndex:r=0,initialDevice:o="desktop",initialColorScheme:s="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:c}=t;if(n.length===0)throw new Error("createDemoCarousel: items array must not be empty");IC();let p=Math.max(0,Math.min(r,n.length-1)),u=o,f=s,g=null,b=1,v=!1,S=y("div","persona-dc-root"),T=y("div","persona-dc-toolbar"),L=y("div","persona-dc-toolbar-lead"),P=y("div","persona-dc-toolbar-trail"),E=Gt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Q(-1)}),k=y("div");k.style.position="relative";let C=y("button","persona-dc-title-btn");C.type="button",C.setAttribute("aria-expanded","false"),C.setAttribute("aria-haspopup","listbox");let I=y("span","persona-dc-title-text"),j=y("span","persona-dc-title-chevron"),$=ye("chevron-down",12,"currentColor",2);$&&j.appendChild($),C.append(I,j);let R=y("div","persona-dc-dropdown");R.setAttribute("role","listbox"),R.style.display="none";let N=!1;function O(){R.innerHTML="";for(let he=0;he<n.length;he++){let Ke=n[he],gt=y("button","persona-dc-dropdown-item");gt.type="button",gt.setAttribute("role","option"),gt.setAttribute("aria-current",he===p?"true":"false");let Wt=y("span");if(Wt.textContent=Ke.title,gt.appendChild(Wt),Ke.description){let tt=y("span","persona-dc-dropdown-desc");tt.textContent=Ke.description,gt.appendChild(tt)}gt.addEventListener("click",()=>{Ee(),Me(he)}),R.appendChild(gt)}}function Z(){N=!N,R.style.display=N?"":"none",C.setAttribute("aria-expanded",N?"true":"false"),N&&O()}function Ee(){N&&(N=!1,R.style.display="none",C.setAttribute("aria-expanded","false"))}C.addEventListener("click",he=>{he.stopPropagation(),Z()});let de=()=>Ee();document.addEventListener("click",de),k.append(C,R);let ee=Gt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Q(1)}),Le=y("span","persona-dc-counter");L.append(E,k,ee,Le);let Pe=null;i&&(Pe=ui({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:he=>{u=he,ae.dataset.device=u,g=null,J()}}),P.appendChild(Pe.element));let ne=null;if(a){let he=y("div","persona-dc-zoom-controls"),Ke=Gt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let tt=g!=null?g:b;g=Math.max(Df,tt-Bf),J()}});ne=y("span","persona-dc-zoom-level"),ne.title="Reset to 100%",ne.style.cursor="pointer",ne.addEventListener("click",()=>{g=1,J()});let gt=Gt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let tt=g!=null?g:b;g=Math.min(Nf,tt+Bf),J()}}),Wt=Gt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,J()}});he.append(Ke,ne,gt,Wt),P.appendChild(he)}if(d){let he=y("div","persona-dc-separator");P.appendChild(he);let Ke=ui({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:gt=>{f=gt,ae.dataset.colorScheme=f,$e()}});P.appendChild(Ke.element)}let Ae=y("div","persona-dc-separator");P.appendChild(Ae);let re=Gt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});P.appendChild(re),T.append(L,P);let se=y("div","persona-dc-stage"),ae=y("div","persona-dc-iframe-wrapper");ae.dataset.device=u,ae.dataset.colorScheme=f;let fe=y("iframe","persona-dc-iframe");fe.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),fe.setAttribute("loading","lazy"),fe.title=n[p].title,ae.appendChild(fe),se.appendChild(ae),S.append(T,se),e.appendChild(S);function $e(){var he;try{let Ke=(he=fe.contentDocument)==null?void 0:he.body;if(!Ke)return;f==="dark"?Ke.classList.add("theme-dark"):Ke.classList.remove("theme-dark")}catch{}}fe.addEventListener("load",()=>$e());function V(){let he=n[p];I.textContent=he.title,Le.textContent=`${p+1} / ${n.length}`,fe.title=he.title}function Q(he){let Ke=((p+he)%n.length+n.length)%n.length;Me(Ke)}function Me(he){he<0||he>=n.length||(p=he,fe.src=n[p].url,V(),c==null||c(p,n[p]))}function J(){var gt;if(v)return;let he=(gt=Hf[u])!=null?gt:Hf.desktop;b=RC(se,he);let Ke=Math.max(Df,Math.min(Nf,g!=null?g:b));WC(ae,fe,he,Ke,u),ne&&(ne.textContent=`${Math.round(Ke*100)}%`)}let le=new ResizeObserver(()=>J());le.observe(se),V(),fe.src=n[p].url,requestAnimationFrame(()=>J());function Ie(){v||(v=!0,le.disconnect(),document.removeEventListener("click",de),S.remove())}return{element:S,goTo:Me,next:()=>Q(1),prev:()=>Q(-1),getIndex:()=>p,setDevice(he){u=he,ae.dataset.device=he,Pe==null||Pe.setSelected(he),g=null,J()},setColorScheme(he){f=he,ae.dataset.colorScheme=he},setZoom(he){g=he,J()},destroy:Ie}}export{Em as ASK_USER_QUESTION_CLIENT_TOOL,Tm as ASK_USER_QUESTION_PARAMETERS_SCHEMA,Ba as ASK_USER_QUESTION_TOOL_NAME,As as AgentWidgetClient,da as AgentWidgetSession,Es as AttachmentManager,Zo as BrowserSpeechEngine,Zm as DEFAULT_COMPONENTS,fl as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,tr as DEFAULT_FLOATING_LAUNCHER_WIDTH,Qm as DEFAULT_PALETTE,Ym as DEFAULT_SEMANTIC,Dt as DEFAULT_WIDGET_CONFIG,Mf as PRESETS,Ef as PRESET_FULLSCREEN,Tf as PRESET_MINIMAL,Sf as PRESET_SHOP,Ts as ReadAloudController,tl as SUGGEST_REPLIES_CLIENT_TOOL,Cm as SUGGEST_REPLIES_PARAMETERS_SCHEMA,Hr as SUGGEST_REPLIES_TOOL_NAME,Vx as THEME_ZONES,fr as VERSION,Rr as WEBMCP_TOOL_PREFIX,Qs as WebMcpBridge,dC as accessibilityPlugin,pC as animationsPlugin,es as applyThemeVariables,Ls as attachHeaderToContainer,uC as brandPlugin,wa as buildComposer,yg as buildDefaultHeader,Eo as buildHeader,va as buildHeaderWithLayout,bg as buildMinimalHeader,_a as builtInClientToolsForDispatch,lC as collectEnrichedPageContext,Mo as componentRegistry,Ei as createActionManager,Gl as createAgentExperience,ny as createAskUserQuestionBubble,pl as createBestAvailableVoiceProvider,kv as createBubbleWithLayout,zl as createCSATFeedback,Sl as createComboButton,Mw as createComponentMiddleware,$l as createComponentStreamParser,Zu as createDefaultSanitizer,HC as createDemoCarousel,gh as createDirectivePostprocessor,ts as createDropdownMenu,ay as createFlexibleJsonStreamParser,Gt as createIconButton,yy as createImagePart,il as createJsonStreamParser,pi as createLabelButton,_l as createLocalStorageAdapter,Wa as createMarkdownProcessor,vs as createMarkdownProcessorFromConfig,kg as createMessageActions,Vl as createNPSFeedback,sl as createPlainTextParser,fC as createPlugin,al as createRegexJsonParser,Ca as createStandardBubble,Ka as createTextPart,ua as createTheme,xl as createThemeObserver,ui as createToggleGroup,Ps as createTypingIndicator,Yo as createVoiceProvider,Li as createWidgetHostLayout,ll as createXmlParser,bC as default,Hs as defaultActionHandlers,Ti as defaultJsonActionParser,xf as defaultParseRules,Za as detectColorScheme,fh as directivePostprocessor,na as ensureAskUserQuestionSheet,Kr as escapeHtml,ql as extractComponentDirectiveFromMessage,by as fileToImagePart,cC as formatEnrichedContext,Xo as generateAssistantMessageId,AC as generateCodeSnippet,uy as generateMessageId,wf as generateStableSelector,aa as generateUserMessageId,ma as getActiveTheme,rg as getColorScheme,gy as getDisplayText,xg as getHeaderLayout,hy as getImageParts,yC as getPreset,Ul as hasComponentDirective,fy as hasImages,Tl as headerLayouts,gC as highContrastPlugin,df as initAgentWidget,yo as isAskUserQuestionMessage,Ew as isComponentDirectiveType,dn as isDockedMountMode,Fa as isSuggestRepliesMessage,Ja as isVoiceSupported,Ko as isWebMcpToolName,rl as latestAgentSuggestions,nv as listRegisteredStreamAnimations,Xu as markdownPostprocessor,hl as mergeWithDefaults,my as normalizeContent,bo as parseAskUserQuestionPayload,Am as parseSuggestRepliesPayload,la as pickBestVoice,Si as pluginRegistry,mC as reducedMotionPlugin,ev as registerStreamAnimationPlugin,Jo as removeAskUserQuestionSheet,jl as renderComponentDirective,Mg as renderLoadingIndicatorWithFallback,ye as renderLucideIcon,nr as resolveDockConfig,Xs as resolveSanitizer,yl as resolveTokens,Ji as stripWebMcpPrefix,bl as themeToCssVariables,tv as unregisterStreamAnimationPlugin,xy as validateImageFile,eg as validateTheme};
448
448
  //# sourceMappingURL=index.js.map