@runtypelabs/persona 4.4.2 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) 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-8RICZWQe.d.cts} +6 -0
  4. package/dist/animations/{types-C6tFDxKy.d.ts → types-8RICZWQe.d.ts} +6 -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 +1 -1
  9. package/dist/codegen.js +1 -1
  10. package/dist/index.cjs +50 -50
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +286 -11
  13. package/dist/index.d.ts +286 -11
  14. package/dist/index.global.js +39 -39
  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 +147 -8
  23. package/dist/smart-dom-reader.d.ts +147 -8
  24. package/dist/theme-editor-preview.cjs +48 -48
  25. package/dist/theme-editor-preview.d.cts +187 -9
  26. package/dist/theme-editor-preview.d.ts +187 -9
  27. package/dist/theme-editor-preview.js +48 -48
  28. package/dist/theme-editor.cjs +1 -1
  29. package/dist/theme-editor.d.cts +147 -8
  30. package/dist/theme-editor.d.ts +147 -8
  31. package/dist/theme-editor.js +1 -1
  32. package/package.json +2 -2
  33. package/src/client.ts +48 -7
  34. package/src/defaults.ts +9 -1
  35. package/src/generated/runtype-openapi-contract.ts +6 -0
  36. package/src/index-core.ts +5 -0
  37. package/src/reconnect-wake.test.ts +162 -0
  38. package/src/reconnect.test.ts +430 -0
  39. package/src/session-reconnect.ts +282 -0
  40. package/src/session.ts +408 -5
  41. package/src/types.ts +165 -9
  42. package/src/ui.scroll-additive.test.ts +451 -0
  43. package/src/ui.scroll.test.ts +8 -2
  44. package/src/ui.stream-animation-update.test.ts +99 -0
  45. package/src/ui.ts +371 -41
  46. package/src/utils/constants.ts +3 -1
package/dist/index.js CHANGED
@@ -1,22 +1,22 @@
1
- var If=Object.defineProperty;var _s=(e,t)=>()=>(e&&(t=e(e=0)),t);var bu=(e,t)=>{for(var n in t)If(e,n,{get:t[n],enumerable:!0})};var xu={};bu(xu,{DOMPurify:()=>Wf,Marked:()=>Rf});import{Marked as Rf}from"marked";import Wf from"dompurify";var vu=_s(()=>{"use strict"});var ys,tl=_s(()=>{"use strict";ys=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 Zh(e){return e.replace(/\/+$/,"")}async function ey(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 za,fm=_s(()=>{"use strict";tl();za=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 ys(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=`${Zh(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 ey(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 Va,hm=_s(()=>{"use strict";Va=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 ym={};bu(ym,{FallbackSpeechEngine:()=>Va,RuntypeSpeechEngine:()=>za});var bm=_s(()=>{"use strict";fm();hm()});import{Marked as Hf}from"marked";import Bf from"dompurify";var wu=null,ps=null,ds=null;var Cu=e=>{ps=e},Au=()=>ps?Promise.resolve(ps):ds||(wu?(ds=wu().then(e=>(ps=e,e)),ds):(ds=Promise.resolve().then(()=>(vu(),xu)).then(e=>(ps=e,e)),ds)),No=()=>ps;Cu({Marked:Hf,DOMPurify:Bf});var Df=e=>{if(e)return e},ka=e=>{let t=null;return n=>{var o,s;let r=No();if(!r)return Vr(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=Df(e==null?void 0:e.renderer);d&&t.use({renderer:d})}return t.parse(n)}},us=e=>e?ka({markedOptions:e.options,renderer:e.renderer}):ka(),Nf=ka(),Tu=e=>Nf(e),Vr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Eu=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Su=e=>`%%FORM_PLACEHOLDER_${e}%%`,Mu=(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=Su(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=Su(t.length);return t.push({token:s,type:o}),s}),n},Of=e=>{let t=us(e);return n=>{let r=[],o=Mu(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="${Eu(i)}"></div>`;s=s.replace(d,p)}),s}},Ff=e=>{let t=[],n=Mu(e,t),r=Tu(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="${Eu(s)}"></div>`;r=r.replace(a,d)}),r};var _f={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"]},$f=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,ku=()=>{let e=null;return t=>{let n=No();if(!n)return Vr(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:")&&!$f.test(a)&&(s.attrValue="",s.keepAttr=!1)}})}return e.sanitize(t,_f)}},$s=e=>e===!1?null:typeof e=="function"?e:ku();var Lu=/^\s*\|?[\s:|-]*-[\s:|-]*$/,Pu=e=>e.includes("|"),Iu=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())},jf=e=>`| ${e.join(" | ")} |`,Uf=e=>`| ${Array.from({length:e},()=>"---").join(" | ")} |`,qf=(e,t)=>e.length>=t?e.slice(0,t):e.concat(Array.from({length:t-e.length},()=>"")),Ru=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(!Pu(o)||Lu.test(o)||!Lu.test(s))continue;let a=Iu(o).length;if(a<1)continue;let i=Uf(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()===""||!Pu(l))break;let p=jf(qf(Iu(l),a));t[d]!==p&&(t[d]=p,n=!0)}r=d-1}return n?t.join(`
3
- `):e};var Rr="webmcp:",Fi=new Map,Wu=e=>{var t;Fi.clear();for(let n of e){let r=(t=n.title)==null?void 0:t.trim();r&&Fi.set(n.name,r)}},Us=e=>Fi.get(_i(e)),La={warn(e,...t){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[Persona/WebMCP] ${e}`,...t)}},Hu=null;function Du(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}:${zf(t.join(""))}`}function Bu(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 zf(e){let t=Bu(e,0).toString(36),n=Bu(e,2654435761).toString(36);return`${t}.${n}`}var js=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 La.warn("getTools() threw: shipping an empty WebMCP snapshot.",o),[]}Wu(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=Kf(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 v=typeof document!="undefined"&&!!document.modelContext;return gr(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=_i(t),a;try{a=await o.getTools()}catch(v){let x=v instanceof Error?v.message:String(v);return gr(`Failed to read WebMCP registry: ${x}`)}Wu(a);let i=a.find(v=>v.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=Us(s),l={toolName:s,args:n,description:i.description,...d?{title:d}:{},reason:"gate"};if(!await this.requestConfirm(l))return gr("User declined the tool call.");if(r!=null&&r.aborted)return gr("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,Qf(n),{signal:p.signal});return Gf(v)}catch(v){if(u)return gr(`WebMCP tool '${s}' timed out after ${this.timeoutMs}ms`);if(r!=null&&r.aborted)return gr("Aborted by cancel()");let x=v instanceof Error?v.message:String(v);return gr(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}(Hu?await Hu():await import("@mcp-b/webmcp-polyfill")).initializeWebMCPPolyfill(),this.installed=!0}catch(t){La.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,La.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:Jf;try{return await n(t)}catch(o){return La.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=>Vf(t,r))}},_i=e=>e.startsWith(Rr)?e.slice(Rr.length):e,Oo=e=>e.startsWith(Rr),Vf=(e,t)=>{if(t==="*")return!0;let n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+n.replace(/\*/g,".*")+"$").test(e)},Kf=e=>{if(!(e===void 0||e===""))try{let t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}},Gf=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:Yf(t)}]}},gr=e=>({isError:!0,content:[{type:"text",text:e}]}),Jf=async e=>{if(typeof window=="undefined"||typeof window.confirm!="function")return!1;let t=Xf(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)},Xf=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)}},Qf=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Yf=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Zf="agent_",eh="flow_";function Nu(e){return e.startsWith(Zf)?{kind:"agentId",agentId:e}:e.startsWith(eh)?{kind:"flowId",flowId:e}:null}function Ou(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=Nu(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=Nu(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 th,ARR as nh,OBJ as rh,STR as oh}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 St=(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},qs=(...e)=>e.filter(Boolean).join(" ");var Pa="ask_user_question",zs=8,ms="data-persona-ask-sheet-for",sh="Other",ah="Other\u2026",_u="Type your own answer here",$u="Send",ih="Next",lh="Back",ch="Submit all",dh="Skip",ph=3,$i="data-ask-current-index",ji="data-ask-question-count",ju="data-ask-answers",Ui="data-ask-grouped",Uu="data-ask-layout",uh=e=>e.layout==="pills"?"pills":"rows",mh=e=>e.getAttribute(Uu)==="pills"?"pills":"rows",Fu=!1,qu=e=>e.replace(/["\\]/g,"\\$&"),po=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Pa,Ia=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},uo=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=th(o,oh|rh|nh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Vs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>zs&&!Fu&&(Fu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${zs}.`)),t.slice(0,zs)},gh=e=>{var t;return(t=Vs(e)[0])!=null?t:null},fh=(e,t)=>{var n;return(n=Vs(e)[t])!=null?n:null},zu=(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))},Vu=(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},hh=(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=Vu(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},yh=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},bh=(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(yh(r));return s}if(d.forEach((f,v)=>{s.appendChild(hh(f,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let f=r==="rows"?sh:ah;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:_u,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=Vu(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},Ku=(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:_u,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:$u,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},xh=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:$u,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},vh=(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:lh,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:dh,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:ch:(g=n.nextLabel)!=null?g:ih,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Fo=e=>{let t=e.getAttribute(ju);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Gu=(e,t)=>{e.setAttribute(ju,JSON.stringify(t))},or=e=>{var n;let t=Number((n=e.getAttribute($i))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},wh=(e,t)=>{e.setAttribute($i,String(Math.max(0,Math.floor(t))))},gs=e=>{var n;let t=Number((n=e.getAttribute(ji))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},mo=e=>e.getAttribute(Ui)==="true",Ch=(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},Ah=(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)))},Ra=(e,t)=>{let{payload:n}=uo(t),r=Vs(n),o=Fo(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},Ju=e=>{let t=Fo(e),n=or(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=""},Xu=e=>{if(!mo(e))return;let t=Fo(e),n=or(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=Ia(n),o=mh(e),{payload:s,complete:a}=uo(t),i=mo(e),d=or(e),l=gs(e),p=i?fh(s,d):gh(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=bh(p,r,a,o);x.replaceWith(L)}if(o!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Ku(r,o))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!E?e.appendChild(xh(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=vh(d,l,r);T?T.replaceWith(L):e.appendChild(L)}else T&&T.remove();Ju(e),Xu(e)},Sh=(e,t,n)=>{let r=Ia(t),o=uh(r),s=e.toolCall.id,a=Vs(n),i=Math.max(1,a.length),d=i>1,l=Ch(e,a),p=d?Ah(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(ms,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(ji,String(i)),u.setAttribute($i,String(p)),u.setAttribute(Ui,d?"true":"false"),u.setAttribute(Uu,o),Gu(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`),zu(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(Ku(r,o)),qi(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Th=(e,t,n)=>{let{payload:r}=uo(t),o=Math.max(1,Vs(r).length);o>gs(e)&&(e.setAttribute(ji,String(o)),o>1&&!mo(e)&&e.setAttribute(Ui,"true")),qi(e,t,n)},Eh=(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=Ia(t);zu(n,r);let o=y("span","persona-ask-stub-label"),{complete:s}=uo(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},Ks=(e,t,n)=>{if(!n||!po(e)||Ia(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${ms}]`).forEach(l=>{l.getAttribute(ms)!==o&&l.remove()});let a=n.querySelector(`[${ms}="${qu(o)}"]`);if(a){Th(a,e,t);return}let{payload:i}=uo(e),d=Sh(e,t,i);n.appendChild(d)},_o=(e,t)=>{if(!e)return;let n=t?`[${ms}="${qu(t)}"]`:`[${ms}]`;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)})},zi=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),go=(e,t)=>{let n=Fo(e),r=or(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Gu(e,n),Ju(e),Xu(e)},Wa=(e,t,n,r)=>{let o=gs(e),s=Math.max(0,Math.min(o-1,r));wh(e,s),qi(e,t,n)};var Hr="suggest_replies";var Qu={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},Vi={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:Qu,origin:"sdk",annotations:{readOnlyHint:!0}},Ki=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ha=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Hr},Yu=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},Gi=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!Ha(r))continue;let o=Yu((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},Zu=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 em={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},tm={name:Pa,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:em,origin:"sdk",annotations:{readOnlyHint:!0}},Ba=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(tm),Zu(e)&&t.push(Vi),t};import{parse as nm,STR as rm,OBJ as om}from"partial-json";var Da=e=>e.replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),fo=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)}},Mh=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`},sm=e=>e.status==="complete"?Mh(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 am=e=>e.status==="complete"?kh(e):"Using tool...",Na=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Js=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 Na(t)},Oa=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 Na(t)},Ji=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=Js(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Fa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&Gs(r,n.slice(s,a.index),[]),a[1]!==void 0?Gs(r,a[1],["bold"]):a[2]!==void 0?Gs(r,a[2],["italic"]):a[3]!==void 0&&Gs(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Gs(r,n.slice(s),[]),r},Gs=(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})},Lh=()=>{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()=>{}}},Xs=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Xi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Qi=()=>{var t;let e=Lh();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)}},Yi=()=>{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=nm(n,rm|om);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Da(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Da(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Ph=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Da(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Da(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=nm(s,rm|om),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Zi=()=>{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 im="4.4.2";var fr=im;var Rh="https://api.runtype.com/v1/dispatch",_a="https://api.runtype.com";function Wh(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 el=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 Hh(e){switch(e){case"json":return Yi;case"regex-json":return Qi;case"xml":return Zi;default:return Xi}}var lm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Bh(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=lm(n);if(!lm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=Xs(e);return Xs(t)!==null&&a===null?t:e}var fs=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:Rh,this.headers={"Content-Type":"application/json","X-Persona-Version":fr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Hh(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 js(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=Ou(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$/,""))||_a}/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":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$/,""))||_a}/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 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(el).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?Du(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":fr},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$/,""))||_a}/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(/\/+$/,""))||_a}/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(el).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=[...Ba(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(el).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=[...Ba(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 xt,hn,yr,br;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,Te=A.toolCall?{...A.toolCall,chunks:A.toolCall.chunks?[...A.toolCall.chunks]:void 0}:void 0,De=A.tools?A.tools.map(Pe=>({...Pe,chunks:Pe.chunks?[...Pe.chunks]:void 0})):void 0;return{...A,reasoning:te,toolCall:Te,tools:De}},u=A=>{if(A.role!=="assistant"||A.variant)return!0;let te=Array.isArray(A.contentParts)&&A.contentParts.length>0,Te=typeof A.rawContent=="string"&&A.rawContent.trim()!=="";return typeof A.content=="string"&&A.content.trim()!==""||te||Te||!!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},W=A=>{if(A==null)return null;try{return String(A)}catch{return null}},O=A=>{var te,Te,De,Pe,Ne;return W((Ne=(Pe=(De=(Te=(te=A.stepId)!=null?te:A.step_id)!=null?Te:A.step)!=null?De:A.parentId)!=null?Pe:A.flowStepId)!=null?Ne:A.flow_step_id)},N=A=>{var te,Te,De,Pe,Ne,Ge,it;return W((it=(Ge=(Ne=(Pe=(De=(Te=(te=A.callId)!=null?te:A.call_id)!=null?Te:A.requestId)!=null?De:A.request_id)!=null?Pe:A.toolCallId)!=null?Ne:A.tool_call_id)!=null?Ge:A.stepId)!=null?it:A.step_id)},Y=r,Ee=!1,de=()=>{if(f)return f;let A,te=T;return!Ee&&Y?(A=Y,Ee=!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)},Ce=(A,te)=>{var Ne;let Te=(Ne=A.reasoningId)!=null?Ne:A.id,De=O(A);if(Te){let Ge=String(Te);return Z(De,Ge),Ge}if(De){let Ge=F.byStep.get(De);if(Ge)return F.lastId=Ge,Ge}if(F.lastId&&!te)return F.lastId;if(!te)return null;let Pe=`reason-${l()}`;return Z(De,Pe),Pe},ke=A=>{let te=C.get(A);if(te)return te;let Te={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,Te),g(Te),Te},re=(A,te)=>{j.lastId=te,A&&j.byCall.set(A,te)},we=new Set,le=new Map,se=new Set,oe=new Map,be=A=>{if(!A)return!1;let te=A.replace(/_+/g,"_").replace(/^_|_$/g,"");return te==="emit_artifact_markdown"||te==="emit_artifact_component"},He=(A,te)=>{var Ne;let Te=(Ne=A.toolId)!=null?Ne:A.id,De=N(A);if(Te){let Ge=String(Te);return re(De,Ge),Ge}if(De){let Ge=j.byCall.get(De);if(Ge)return j.lastId=Ge,Ge}if(j.lastId&&!te)return j.lastId;if(!te)return null;let Pe=`tool-${l()}`;return re(De,Pe),Pe},V=A=>{let te=R.get(A);if(te)return te;let Te={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,Te),g(Te),Te},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 Te=Date.parse(A);if(!Number.isNaN(Te))return Te}return Date.now()},We=A=>{if(typeof A=="string")return A;if(A==null)return"";try{return JSON.stringify(A)}catch{return String(A)}},K=new Map,pe=new Map,$e=new Map,ge=(A,te,Te)=>{var it;let De=$e.get(A);De||(De=[],$e.set(A,De));let Pe=0,Ne=De.length;for(;Pe<Ne;){let It=Pe+Ne>>>1;De[It].seq<te?Pe=It+1:Ne=It}((it=De[Pe])==null?void 0:it.seq)===te?De[Pe]={seq:te,text:Te}:De.splice(Pe,0,{seq:te,text:Te});let Ge="";for(let It=0;It<De.length;It++)Ge+=De[It].text;return Ge},Ve=(A,te)=>{let Te=We(te),De=pe.get(A.id),Pe=Bh(De,Te);A.rawContent=Pe;let Ne=K.get(A.id),Ge=he=>{var vt;let Fe=(vt=A.content)!=null?vt:"";he.trim()!==""&&(Fe.trim().length===0||he.startsWith(Fe)||he.trimStart().startsWith(Fe.trim()))&&(A.content=he)},it=()=>{var he;if(Ne){let Fe=(he=Ne.close)==null?void 0:he.call(Ne);Fe instanceof Promise&&Fe.catch(()=>{})}K.delete(A.id),pe.delete(A.id),A.streaming=!1,g(A)};if(!Ne){Ge(Te),it();return}let It=Xs(Pe);if(It!==null&&It.trim()!==""){Ge(It),it();return}let ce=he=>{var Ye;let Fe=typeof he=="string"?he:(Ye=he==null?void 0:he.text)!=null?Ye:null;if(Fe!==null&&Fe.trim()!=="")return Fe;let vt=Ne.getExtractedText();return vt!==null&&vt.trim()!==""?vt:Te},H;try{H=Ne.processChunk(Pe)}catch{Ge(Te),it();return}if(H instanceof Promise){H.then(he=>{Ge(ce(he)),it()}).catch(()=>{Ge(Te),it()});return}Ge(ce(H)),it()},et=null,$t=(A,te,Te,De)=>{var It;A.rawContent=te,K.has(A.id)||K.set(A.id,this.createStreamParser());let Pe=K.get(A.id),Ne=te.trim().startsWith("{")||te.trim().startsWith("[");if(Ne&&pe.set(A.id,te),Pe.__isPlainTextParser===!0){A.content=De!==void 0?te:A.content+Te,pe.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A);return}let it=Pe.processChunk(te);if(it instanceof Promise)it.then(ce=>{var he;let H=typeof ce=="string"?ce:(he=ce==null?void 0:ce.text)!=null?he:null;H!==null&&H.trim()!==""?(A.content=H,g(A)):!Ne&&!te.trim().startsWith("<")&&(A.content=De!==void 0?te:A.content+Te,pe.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A))}).catch(()=>{A.content=De!==void 0?te:A.content+Te,pe.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A)});else{let ce=typeof it=="string"?it:(It=it==null?void 0:it.text)!=null?It:null;ce!==null&&ce.trim()!==""?(A.content=ce,g(A)):!Ne&&!te.trim().startsWith("<")&&(A.content=De!==void 0?te:A.content+Te,pe.delete(A.id),K.delete(A.id),A.rawContent=void 0,g(A))}},Xe=(A,te)=>{var It,ce;let Te=te!=null?te:A.content;if(Te==null||Te===""){A.streaming=!1,g(A);return}let De=pe.get(A.id),Pe=De!=null?De:We(Te);A.rawContent=Pe;let Ne=K.get(A.id),Ge=null,it=!1;if(Ne&&(Ge=Ne.getExtractedText(),Ge===null&&(Ge=Xs(Pe)),Ge===null)){let H=Ne.processChunk(Pe);H instanceof Promise?(it=!0,H.then(he=>{var vt;let Fe=typeof he=="string"?he:(vt=he==null?void 0:he.text)!=null?vt:null;Fe!==null&&(A.content=Fe,A.streaming=!1,K.delete(A.id),pe.delete(A.id),g(A))}).catch(()=>{})):Ge=typeof H=="string"?H:(It=H==null?void 0:H.text)!=null?It:null}if(!it){Ge!==null&&Ge.trim()!==""?A.content=Ge:pe.has(A.id)||(A.content=We(Te));let H=K.get(A.id);if(H){let he=(ce=H.close)==null?void 0:ce.call(H);he instanceof Promise&&he.catch(()=>{}),K.delete(A.id)}pe.delete(A.id),A.streaming=!1,g(A)}},fe=(A,te,Te)=>{let De=M.get(A);if(De)return De;let Pe={id:`nested-${te}-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Te?{variant:Te}:{},...Te==="reasoning"?{reasoning:{id:A,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:te}};return M.set(A,Pe),g(Pe),Pe},J=[],dt,qe=new Map,Ae=0,Me="agent",nt=!1,Pt=null,ee=null,je=new Map,Cn=(xt=this.config.iterationDisplay)!=null?xt:"separate";for(dt=()=>{var A,te,Te,De,Pe,Ne,Ge,it,It,ce,H,he,Fe,vt,Ye,Ht,Tt,ht,Lt,Qt,Ft,Hn,jt,Bn,Gn,yn,kn,Jn,Xr,wt,xr,vr,Dr,lr,ut,Co,wr,Ao,Ln,Xo,Qr,Nr,Yr,Zr,So,To,eo,bt,Dn,Nn,An,Ct,Xn,Qn,On,to,Or,no,Fn,Rt,Sn,Yn,ro,Fr,oo,xe,Pn,Cr,mt,rn,on,Ar,ks,_r,Eo,Sr,$,Qo,Tr,Er,$r,Mr,cr,Yo,xa,_n,$n,dr,pr,Mo,jr,bn,kr,Zo,ko,es,va,ts,wa,ns,pt,Ls,Zn,In,Ca;for(let rs=0;rs<J.length;rs++){let tt=J[rs].payloadType,w=J[rs].payload;if(!nt&&Me!=="flow"&&typeof w.stepType=="string"&&(Me="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),fe(z,U,"reasoning");continue}let G=(A=Ce(w,!0))!=null?A:`reason-${l()}`,ye=ke(G);ye.reasoning=(te=ye.reasoning)!=null?te:{id:G,status:"streaming",chunks:[]},ye.reasoning.startedAt=(De=ye.reasoning.startedAt)!=null?De:X((Te=w.startedAt)!=null?Te:w.timestamp),ye.reasoning.completedAt=void 0,ye.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(ye.reasoning.scope=w.scope),ye.streaming=!0,ye.reasoning.status="streaming",g(ye)}else if(tt==="reasoning_delta"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let _e=M.get(z),gt=(Ge=(Ne=(Pe=w.reasoningText)!=null?Pe:w.text)!=null?Ne:w.delta)!=null?Ge:"";gt&&w.hidden!==!0&&_e.reasoning&&(_e.reasoning.chunks.push(String(gt)),g(_e));continue}let U=(It=(it=Ce(w,!1))!=null?it:Ce(w,!0))!=null?It:`reason-${l()}`,G=ke(U);G.reasoning=(ce=G.reasoning)!=null?ce:{id:U,status:"streaming",chunks:[]},G.reasoning.startedAt=(he=G.reasoning.startedAt)!=null?he:X((H=w.startedAt)!=null?H:w.timestamp);let ye=(Ye=(vt=(Fe=w.reasoningText)!=null?Fe:w.text)!=null?vt:w.delta)!=null?Ye:"";if(ye&&w.hidden!==!0){let _e=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(_e!==void 0){let gt=ge(U,_e,String(ye));G.reasoning.chunks=[gt]}else G.reasoning.chunks.push(String(ye))}if(G.reasoning.status=w.done?"complete":"streaming",w.done){G.reasoning.completedAt=X((Ht=w.completedAt)!=null?Ht:w.timestamp);let _e=(Tt=G.reasoning.startedAt)!=null?Tt:Date.now();G.reasoning.durationMs=Math.max(0,((ht=G.reasoning.completedAt)!=null?ht:Date.now())-_e)}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 gt=M.get(z);if(gt.reasoning){let st=typeof w.text=="string"?w.text:"";st&&gt.reasoning.chunks.length===0&&gt.reasoning.chunks.push(st),gt.reasoning.status="complete",gt.streaming=!1,g(gt)}k.delete(z),M.delete(z);continue}let U=(Qt=(Lt=Ce(w,!1))!=null?Lt:Ce(w,!0))!=null?Qt:`reason-${l()}`,G=typeof w.text=="string"?w.text:"";!C.get(U)&&(G||w.scope==="loop")&&ke(U);let ye=C.get(U);if(ye!=null&&ye.reasoning){(w.scope==="loop"||w.scope==="turn")&&(ye.reasoning.scope=w.scope),G&&ye.reasoning.chunks.length===0&&ye.reasoning.chunks.push(G),ye.reasoning.status="complete",ye.reasoning.completedAt=X((Ft=w.completedAt)!=null?Ft:w.timestamp);let gt=(Hn=ye.reasoning.startedAt)!=null?Hn:Date.now();ye.reasoning.durationMs=Math.max(0,((jt=ye.reasoning.completedAt)!=null?jt:Date.now())-gt),ye.streaming=!1,g(ye)}let _e=O(w);_e&&F.byStep.delete(_e)}else if(tt==="tool_start"){f&&(f.streaming=!1,g(f),f=null),typeof w.iteration=="number"&&(Ae=w.iteration);let z=(Gn=(Bn=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Bn:He(w,!0))!=null?Gn:`tool-${l()}`,U=(yn=w.toolName)!=null?yn:w.name;if(be(U)){we.add(z);continue}re(N(w),z);let G=V(z),ye=(kn=G.toolCall)!=null?kn:{id:z,status:"pending"};ye.name=U!=null?U:ye.name,ye.status="running",w.parameters!==void 0?ye.args=w.parameters:w.args!==void 0&&(ye.args=w.args),ye.startedAt=(Xr=ye.startedAt)!=null?Xr:X((Jn=w.startedAt)!=null?Jn:w.timestamp),ye.completedAt=void 0,ye.durationMs=void 0,G.toolCall=ye,G.streaming=!0,w.executionId&&(G.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(G)}else if(tt==="tool_output_delta"){let z=(xr=(wt=He(w,!1))!=null?wt:He(w,!0))!=null?xr:`tool-${l()}`;if(we.has(z))continue;let U=V(z),G=(vr=U.toolCall)!=null?vr:{id:z,status:"running"};G.startedAt=(lr=G.startedAt)!=null?lr:X((Dr=w.startedAt)!=null?Dr:w.timestamp);let ye=(wr=(Co=(ut=w.text)!=null?ut:w.delta)!=null?Co:w.message)!=null?wr:"";ye&&(G.chunks=(Ao=G.chunks)!=null?Ao:[],G.chunks.push(String(ye))),G.status="running",U.toolCall=G,U.streaming=!0;let _e=w.agentContext;(_e||w.executionId)&&(U.agentMetadata=(Qr=U.agentMetadata)!=null?Qr:{executionId:(Ln=_e==null?void 0:_e.executionId)!=null?Ln:w.executionId,iteration:(Xo=_e==null?void 0:_e.iteration)!=null?Xo:w.iteration}),g(U)}else if(tt==="tool_complete"){let z=(Yr=(Nr=He(w,!1))!=null?Nr:He(w,!0))!=null?Yr:`tool-${l()}`;if(we.has(z)){we.delete(z);continue}let U=V(z),G=(Zr=U.toolCall)!=null?Zr:{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((So=w.completedAt)!=null?So:w.timestamp);let ye=(To=w.duration)!=null?To:w.executionTime;if(typeof ye=="number")G.durationMs=ye;else{let st=(eo=G.startedAt)!=null?eo:Date.now();G.durationMs=Math.max(0,((bt=G.completedAt)!=null?bt:Date.now())-st)}U.toolCall=G,U.streaming=!1;let _e=w.agentContext;(_e||w.executionId)&&(U.agentMetadata=(An=U.agentMetadata)!=null?An:{executionId:(Dn=_e==null?void 0:_e.executionId)!=null?Dn:w.executionId,iteration:(Nn=_e==null?void 0:_e.iteration)!=null?Nn:w.iteration}),g(U);let gt=N(w);gt&&j.byCall.delete(gt)}else if(tt==="await"&&w.toolName){let z=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,U=(Ct=z!=null?z:w.toolId)!=null?Ct:`local-${l()}`,G=V(U),ye=w.toolName,_e=w.origin==="webmcp"&&!Oo(ye)?`webmcp:${ye}`:ye,gt=Oo(_e),st=(Xn=G.toolCall)!=null?Xn:{id:U,status:"pending"};st.name=_e,st.args=w.parameters,st.status=gt?"running":"complete",st.chunks=(Qn=st.chunks)!=null?Qn:[],st.startedAt=(Or=st.startedAt)!=null?Or:X((to=(On=w.startedAt)!=null?On:w.timestamp)!=null?to:w.awaitedAt),gt?(st.completedAt=void 0,st.duration=void 0,st.durationMs=void 0):st.completedAt=(no=st.completedAt)!=null?no:st.startedAt,G.toolCall=st,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(Rt=w.executionId)!=null?Rt:(Fn=G.agentMetadata)==null?void 0:Fn.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&&(Me==="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 ye=typeof w.delta=="string"?w.delta:"",_e=((Sn=P.get(z))!=null?Sn:"")+ye;if(P.set(z,_e),_e.trim()==="")continue;let gt=fe(z,U);gt.agentMetadata={...gt.agentMetadata,executionId:w.executionId,parentToolId:U},$t(gt,_e,ye,void 0);continue}if(T=typeof w.id=="string"?w.id:T,Me==="flow"){let ye=typeof w.delta=="string"?w.delta:"";if(L+=ye,L.trim()==="")continue;let _e=de();_e.agentMetadata={executionId:w.executionId,iteration:w.iteration},$t(_e,L,ye,void 0),v=_e;continue}let G=de();G.content+=(Yn=w.delta)!=null?Yn:"",G.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Pt!=null?Pt: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&&(Me==="flow"?(Xe(U),et=U):(((ro=U.content)!=null?ro:"")===""&&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,ye=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&"message"in G?String((Fr=G.message)!=null?Fr:"Step failed"):"Step failed";n({type:"error",error:new Error(ye)});let _e=f;_e&&_e.streaming&&(_e.streaming=!1,g(_e)),n({type:"status",status:"idle"});continue}{let G=et;et=null;let ye=w.stopReason,_e=(oo=w.result)==null?void 0:oo.response;if(G)ye&&(G.stopReason=ye),_e!=null?Ve(G,_e):G.streaming!==!1&&(K.delete(G.id),pe.delete(G.id),G.streaming=!1,g(G));else{let gt=_e!=null&&_e!=="";if(gt||ye){let st=de();ye&&(st.stopReason=ye),gt?Xe(st,_e):(st.streaming=!1,g(st))}}continue}}else if(tt==="execution_start")Me=w.kind==="flow"?"flow":"agent",nt=!0,Me==="agent"&&(ee={executionId:w.executionId,agentId:(xe=w.agentId)!=null?xe:"virtual",agentName:(Pn=w.agentName)!=null?Pn:"",status:"running",currentIteration:0,maxTurns:(Cr=w.maxTurns)!=null?Cr:1,startedAt:X(w.startedAt)});else if(tt==="turn_start"){let z=typeof w.iteration=="number"?w.iteration:Ae;if(z!==Ae){if(ee&&(ee.currentIteration=z),Cn==="separate"&&z>1){let U=f;U&&(U.streaming=!1,g(U),je.set(z-1,U),f=null)}Ae=z}Pt=typeof w.id=="string"?w.id:null,v=null}else if(tt==="tool_input_delta"){let z=(mt=w.toolCallId)!=null?mt:j.lastId;if(z){let U=R.get(z);U!=null&&U.toolCall&&(U.toolCall.chunks=(rn=U.toolCall.chunks)!=null?rn:[],U.toolCall.chunks.push((on=w.delta)!=null?on:""),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||((Ar=U.agentMetadata)==null?void 0:Ar.turnId)===G)&&(U.stopReason=z,g(U))}Pt===w.id&&(Pt=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=(_r=(ks=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?ks:U==null?void 0:U.mediaType)!=null?_r:"application/octet-stream",ye=typeof w.data=="string"?w.data:void 0,_e=typeof w.url=="string"?w.url:U&&U.parts.length>0?U.parts.join(""):void 0,gt=null;if(ye)gt={type:"media",data:ye,mediaType:G};else if(_e){let dn=G.toLowerCase();gt={type:dn==="image"||dn.startsWith("image/")?"image-url":"file-url",url:_e,mediaType:G}}let st=(Eo=w.toolCallId)!=null?Eo:U==null?void 0:U.toolCallId,Ps=gt?[gt]:[],Rn=[];for(let dn of Ps){if(!dn||typeof dn!="object")continue;let pn=dn,Lo=typeof pn.type=="string"?pn.type:void 0,Ur=typeof pn.mediaType=="string"?pn.mediaType.toLowerCase():"",Tn=null,fn="";if(Lo==="media"){let jn=typeof pn.data=="string"?pn.data:void 0;if(!jn)continue;fn=Ur.length>0?Ur:"application/octet-stream",Tn=`data:${fn};base64,${jn}`}else if(Lo==="image-url"){let jn=typeof pn.url=="string"?pn.url:void 0;if(!jn)continue;fn=Ur,Tn=jn}else if(Lo==="file-url"){let jn=typeof pn.url=="string"?pn.url:void 0;if(!jn)continue;fn=Ur,Tn=jn}else continue;if(Tn)if(Lo==="image-url"||fn.startsWith("image/"))Rn.push({type:"image",image:Tn,...fn.includes("/")?{mimeType:fn}:{}});else if(fn.startsWith("audio/"))Rn.push({type:"audio",audio:Tn,mimeType:fn});else if(fn.startsWith("video/"))Rn.push({type:"video",video:Tn,mimeType:fn});else{let jn=fn||"application/octet-stream";Rn.push({type:"file",data:Tn,mimeType:jn,filename:Wh(jn)})}}if(Rn.length>0){let dn=l(),pn=st,Ur={id:`agent-media-${typeof pn=="string"&&pn.length>0?`${pn}-${dn}`:String(dn)}`,role:"assistant",content:"",contentParts:Rn,createdAt:new Date().toISOString(),streaming:!1,sequence:dn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:Ae}};g(Ur);let Tn=f;Tn&&(Tn.streaming=!1,g(Tn)),f=null,x.current=null}}else if(tt==="execution_complete"){let z=(Sr=w.kind)!=null?Sr:Me;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:(Qo=($=w.error)==null?void 0:$.message)!=null?Qo:"Execution error";n({type:"error",error:new Error(z)})}else if(tt!=="ping"){if(tt==="approval_start"){let z=(Tr=w.approvalId)!=null?Tr:`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:(Er=ee==null?void 0:ee.agentId)!=null?Er:"virtual",executionId:(Mr=($r=w.executionId)!=null?$r:ee==null?void 0:ee.executionId)!=null?Mr:"",toolName:(cr=w.toolName)!=null?cr:"",toolType:w.toolType,description:(xa=w.description)!=null?xa:`Execute ${(Yo=w.toolName)!=null?Yo:"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=(_n=w.approvalId)!=null?_n:`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:($n=ee==null?void 0:ee.agentId)!=null?$n:"virtual",executionId:(pr=(dr=w.executionId)!=null?dr:ee==null?void 0:ee.executionId)!=null?pr:"",toolName:(Mo=w.toolName)!=null?Mo:"",toolType:w.toolType,description:(bn=w.description)!=null?bn:`Execute ${(jr=w.toolName)!=null?jr:"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:(kr=w.decision)!=null?kr:"approved",agentId:(Zo=ee==null?void 0:ee.agentId)!=null?Zo:"virtual",executionId:(es=(ko=w.executionId)!=null?ko:ee==null?void 0:ee.executionId)!=null?es:"",toolName:(va=w.toolName)!=null?va:"",description:(ts=w.description)!=null?ts:"",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}),oe.set(U,{markdown:"",title:G}),!se.has(U)){se.add(U);let ye={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"}})};le.set(U,ye),g(ye)}}else if(tt==="artifact_delta"){let z=String(w.id),U=typeof w.delta=="string"?w.delta:String((wa=w.delta)!=null?wa:"");n({type:"artifact_delta",id:z,artDelta:U});let G=oe.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=le.get(z);if(U){U.streaming=!1;try{let G=JSON.parse((ns=U.rawContent)!=null?ns:"{}");if(G.props){G.props.status="complete";let ye=oe.get(z);ye!=null&&ye.markdown&&(G.props.markdown=ye.markdown)}U.rawContent=JSON.stringify(G)}catch{}oe.delete(z),g(U),le.delete(z)}}}else if(tt==="transcript_insert"){let z=w.message;if(!z||typeof z!="object")continue;let U=String((pt=z.id)!=null?pt:`msg-${l()}`),G=z.role,_e={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(_e),_e.rawContent)try{let gt=JSON.parse(_e.rawContent),st=(Ls=gt==null?void 0:gt.props)==null?void 0:Ls.artifactId;typeof st=="string"&&se.add(st)}catch{}f=null,x.current=null,K.delete(U),pe.delete(U)}else if(tt==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let z=typeof w.error=="string"?w.error:((Zn=w.error)==null?void 0:Zn.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=(In=w.message)!=null?In: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((Ca=U.message)!=null?Ca: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 Te=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.0";var fr=Rm;var ly="https://api.runtype.com/v1/dispatch",za="https://api.runtype.com";function cy(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var cl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function dy(e){switch(e){case"json":return il;case"regex-json":return al;case"xml":return ll;default:return sl}}var Wm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function py(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=Wm(n);if(!Wm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=sa(e);return sa(t)!==null&&a===null?t:e}var As=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=t.apiUrl)!=null?n:ly,this.headers={"Content-Type":"application/json","X-Persona-Version":fr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:dy(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Qs(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=cm(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(c=n.agentId)!=null?c:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let E=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:E}),E}let c=await this.buildPayload(t.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([E])=>E!=="sessionId"&&E!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(cl).map(E=>{var k,C,I;return{id:E.id,role:E.role,content:(I=(C=(k=E.contentParts)!=null?k:E.llmContent)!=null?C:E.rawContent)!=null?I:E.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},f=c.clientTools,g=!!(f&&f.length>0),b=g?im(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,S=g&&v&&this.lastSentClientToolsFingerprint===b,T=!1,L=null,P;for(let E=0;;E++){let C={...u,...g&&(T||!S)&&f?{clientTools:f}:{},...b?{clientToolsFingerprint:b}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),P=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":fr},body:JSON.stringify(C),signal:r.signal}),P.status===409&&E===0&&g){let I=await P.json().catch(()=>null);if((I==null?void 0:I.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}L=I!=null?I:{error:"Chat request failed"}}break}if(!P.ok){let E=L!=null?L:await P.json().catch(()=>({error:"Chat request failed"}));if(P.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(P.status===429){let C=new Error(E.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let k=new Error(E.error||"Failed to send message");throw n({type:"error",error:k}),k}if(!P.body){let E=new Error("No response body received");throw n({type:"error",error:E}),E}this.lastSentClientToolsFingerprint=b!=null?b:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(P.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&n({type:"error",error:c}),c}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||za}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var c,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||za}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(cl).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,p)=>{let u=new Date(c.createdAt).getTime(),f=new Date(p.createdAt).getTime();return u-f}).map(c=>{var p,u,f;return{role:c.role,content:(f=(u=(p=c.contentParts)!=null?p:c.llmContent)!=null?u:c.rawContent)!=null?f:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[..._a(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(c,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(cl).sort((d,c)=>{let p=new Date(d.createdAt).getTime(),u=new Date(c.createdAt).getTime();return p-u}).map(d=>{var c,p,u;return{role:d.role,content:(u=(p=(c=d.contentParts)!=null?c:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,c]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=c);let s=[..._a(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async c=>{try{let p=await c({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let c=d;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},c=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r,o){var fn,yr,br,Ue;let s=t.getReader(),a=new TextDecoder,i="",d=Date.now(),c=0,p=()=>d+c++,u=M=>{let ue=M.reasoning?{...M.reasoning,chunks:[...M.reasoning.chunks]}:void 0,Te=M.toolCall?{...M.toolCall,chunks:M.toolCall.chunks?[...M.toolCall.chunks]:void 0}:void 0,ke=M.tools?M.tools.map(He=>({...He,chunks:He.chunks?[...He.chunks]:void 0})):void 0;return{...M,reasoning:ue,toolCall:Te,tools:ke}},f=M=>{if(M.role!=="assistant"||M.variant)return!0;let ue=Array.isArray(M.contentParts)&&M.contentParts.length>0,Te=typeof M.rawContent=="string"&&M.rawContent.trim()!=="";return typeof M.content=="string"&&M.content.trim()!==""||ue||Te||!!M.stopReason},g=M=>{f(M)&&n({type:"message",message:u(M)})},b=null,v=null,S={current:null},T={current:null},L=null,P="",E=new Map,k=new Map,C=new Map,I=new Map,j=new Map,$={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},N=M=>{if(M==null)return null;try{return String(M)}catch{return null}},O=M=>{var ue,Te,ke,He,nt;return N((nt=(He=(ke=(Te=(ue=M.stepId)!=null?ue:M.step_id)!=null?Te:M.step)!=null?ke:M.parentId)!=null?He:M.flowStepId)!=null?nt:M.flow_step_id)},Z=M=>{var ue,Te,ke,He,nt,Qe,ht;return N((ht=(Qe=(nt=(He=(ke=(Te=(ue=M.callId)!=null?ue:M.call_id)!=null?Te:M.requestId)!=null?ke:M.request_id)!=null?He:M.toolCallId)!=null?nt:M.tool_call_id)!=null?Qe:M.stepId)!=null?ht:M.step_id)},Ee=r,de=!1,ee=()=>{if(b)return b;let M,ue="",Te=L;return!de&&Ee?(M=Ee,de=!0,ue=o!=null?o:""):Ee&&Te?M=`${Ee}_${Te}`:M=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:M,role:"assistant",content:ue,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},g(b),b},Le=(M,ue)=>{$.lastId=ue,M&&$.byStep.set(M,ue)},Pe=(M,ue)=>{var nt;let Te=(nt=M.reasoningId)!=null?nt:M.id,ke=O(M);if(Te){let Qe=String(Te);return Le(ke,Qe),Qe}if(ke){let Qe=$.byStep.get(ke);if(Qe)return $.lastId=Qe,Qe}if($.lastId&&!ue)return $.lastId;if(!ue)return null;let He=`reason-${p()}`;return Le(ke,He),He},ne=M=>{let ue=I.get(M);if(ue)return ue;let Te={id:`reason-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:M,status:"streaming",chunks:[]}};return I.set(M,Te),g(Te),Te},Ae=(M,ue)=>{R.lastId=ue,M&&R.byCall.set(M,ue)},re=new Set,se=new Map,ae=new Set,fe=new Map,$e=M=>{if(!M)return!1;let ue=M.replace(/_+/g,"_").replace(/^_|_$/g,"");return ue==="emit_artifact_markdown"||ue==="emit_artifact_component"},V=(M,ue)=>{var nt;let Te=(nt=M.toolId)!=null?nt:M.id,ke=Z(M);if(Te){let Qe=String(Te);return Ae(ke,Qe),Qe}if(ke){let Qe=R.byCall.get(ke);if(Qe)return R.lastId=Qe,Qe}if(R.lastId&&!ue)return R.lastId;if(!ue)return null;let He=`tool-${p()}`;return Ae(ke,He),He},Q=M=>{let ue=j.get(M);if(ue)return ue;let Te={id:`tool-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:M,status:"pending"}};return j.set(M,Te),g(Te),Te},Me=M=>{if(typeof M=="number"&&Number.isFinite(M))return M;if(typeof M=="string"){let ue=Number(M);if(!Number.isNaN(ue)&&Number.isFinite(ue))return ue;let Te=Date.parse(M);if(!Number.isNaN(Te))return Te}return Date.now()},J=M=>{if(typeof M=="string")return M;if(M==null)return"";try{return JSON.stringify(M)}catch{return String(M)}},le=new Map,Ie=new Map,he=new Map,Ke=(M,ue,Te)=>{var ht;let ke=he.get(M);ke||(ke=[],he.set(M,ke));let He=0,nt=ke.length;for(;He<nt;){let me=He+nt>>>1;ke[me].seq<ue?He=me+1:nt=me}((ht=ke[He])==null?void 0:ht.seq)===ue?ke[He]={seq:ue,text:Te}:ke.splice(He,0,{seq:ue,text:Te});let Qe="";for(let me=0;me<ke.length;me++)Qe+=ke[me].text;return Qe},gt=(M,ue)=>{let Te=J(ue),ke=Ie.get(M.id),He=py(ke,Te);M.rawContent=He;let nt=le.get(M.id),Qe=ce=>{var Je;let ft=(Je=M.content)!=null?Je:"";ce.trim()!==""&&(ft.trim().length===0||ce.startsWith(ft)||ce.trimStart().startsWith(ft.trim()))&&(M.content=ce)},ht=()=>{var ce;if(nt){let ft=(ce=nt.close)==null?void 0:ce.call(nt);ft instanceof Promise&&ft.catch(()=>{})}le.delete(M.id),Ie.delete(M.id),M.streaming=!1,g(M)};if(!nt){Qe(Te),ht();return}let me=sa(He);if(me!==null&&me.trim()!==""){Qe(me),ht();return}let B=ce=>{var Lt;let ft=typeof ce=="string"?ce:(Lt=ce==null?void 0:ce.text)!=null?Lt:null;if(ft!==null&&ft.trim()!=="")return ft;let Je=nt.getExtractedText();return Je!==null&&Je.trim()!==""?Je:Te},xe;try{xe=nt.processChunk(He)}catch{Qe(Te),ht();return}if(xe instanceof Promise){xe.then(ce=>{Qe(B(ce)),ht()}).catch(()=>{Qe(Te),ht()});return}Qe(B(xe)),ht()},Wt=null,tt=(M,ue,Te,ke)=>{var me;M.rawContent=ue,le.has(M.id)||le.set(M.id,this.createStreamParser());let He=le.get(M.id),nt=ue.trim().startsWith("{")||ue.trim().startsWith("[");if(nt&&Ie.set(M.id,ue),He.__isPlainTextParser===!0){M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M);return}let ht=He.processChunk(ue);if(ht instanceof Promise)ht.then(B=>{var ce;let xe=typeof B=="string"?B:(ce=B==null?void 0:B.text)!=null?ce:null;xe!==null&&xe.trim()!==""?(M.content=xe,g(M)):!nt&&!ue.trim().startsWith("<")&&(M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M))}).catch(()=>{M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M)});else{let B=typeof ht=="string"?ht:(me=ht==null?void 0:ht.text)!=null?me:null;B!==null&&B.trim()!==""?(M.content=B,g(M)):!nt&&!ue.trim().startsWith("<")&&(M.content=ke!==void 0?ue:M.content+Te,Ie.delete(M.id),le.delete(M.id),M.rawContent=void 0,g(M))}},ge=(M,ue)=>{var me,B;let Te=ue!=null?ue:M.content;if(Te==null||Te===""){M.streaming=!1,g(M);return}let ke=Ie.get(M.id),He=ke!=null?ke:J(Te);M.rawContent=He;let nt=le.get(M.id),Qe=null,ht=!1;if(nt&&(Qe=nt.getExtractedText(),Qe===null&&(Qe=sa(He)),Qe===null)){let xe=nt.processChunk(He);xe instanceof Promise?(ht=!0,xe.then(ce=>{var Je;let ft=typeof ce=="string"?ce:(Je=ce==null?void 0:ce.text)!=null?Je:null;ft!==null&&(M.content=ft,M.streaming=!1,le.delete(M.id),Ie.delete(M.id),g(M))}).catch(()=>{})):Qe=typeof xe=="string"?xe:(me=xe==null?void 0:xe.text)!=null?me:null}if(!ht){Qe!==null&&Qe.trim()!==""?M.content=Qe:Ie.has(M.id)||(M.content=J(Te));let xe=le.get(M.id);if(xe){let ce=(B=xe.close)==null?void 0:B.call(xe);ce instanceof Promise&&ce.catch(()=>{}),le.delete(M.id)}Ie.delete(M.id),M.streaming=!1,g(M)}},X=(M,ue,Te)=>{let ke=k.get(M);if(ke)return ke;let He={id:`nested-${ue}-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Te?{variant:Te}:{},...Te==="reasoning"?{reasoning:{id:M,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ue}};return k.set(M,He),g(He),He},it=[],Ve,Se=new Map,we=0,Ze="agent",qt=!1,be=null,pe=null,vn=new Map,Ct=(fn=this.config.iterationDisplay)!=null?fn:"separate";for(Ve=()=>{var M,ue,Te,ke,He,nt,Qe,ht,me,B,xe,ce,ft,Je,Lt,Mt,xt,Rt,Xt,Ot,en,xr,Nr,or,sr,Xr,zt,ar,Or,Hn,kn,Bn,ir,vr,Qr,zn,Yr,At,wr,Cr,Fr,lr,yt,Lo,Ar,Po,Ln,ss,Zr,_r,eo,to,Io,Ro,no,vt,Dn,Nn,wn,St,Vn,Kn,On,ro,Ce,$r,Gn,Ft,Jn,jr,Ds,as,Ns,Wo,Sr,oo,lt,rn,on,Tr,Os,Ur,Ho,Er,F,is,cr,Mr,qr,kr,dr,ls,Ma,hn,Cn,pr,An,Bo,ur,yn,Lr,cs,Do,ds,so;for(let ao=0;ao<it.length;ao++){let ot=it[ao].payloadType,w=it[ao].payload;if(!qt&&Ze!=="flow"&&typeof w.stepType=="string"&&(Ze="flow"),ot==="reasoning_start"){let z=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&q){E.set(z,q),X(z,q,"reasoning");continue}let G=(M=Pe(w,!0))!=null?M:`reason-${p()}`,K=ne(G);K.reasoning=(ue=K.reasoning)!=null?ue:{id:G,status:"streaming",chunks:[]},K.reasoning.startedAt=(ke=K.reasoning.startedAt)!=null?ke:Me((Te=w.startedAt)!=null?Te:w.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(K.reasoning.scope=w.scope),K.streaming=!0,K.reasoning.status="streaming",g(K)}else if(ot==="reasoning_delta"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)&&k.has(z)){let Ne=k.get(z),rt=(Qe=(nt=(He=w.reasoningText)!=null?He:w.text)!=null?nt:w.delta)!=null?Qe:"";rt&&w.hidden!==!0&&Ne.reasoning&&(Ne.reasoning.chunks.push(String(rt)),g(Ne));continue}let q=(me=(ht=Pe(w,!1))!=null?ht:Pe(w,!0))!=null?me:`reason-${p()}`,G=ne(q);G.reasoning=(B=G.reasoning)!=null?B:{id:q,status:"streaming",chunks:[]},G.reasoning.startedAt=(ce=G.reasoning.startedAt)!=null?ce:Me((xe=w.startedAt)!=null?xe:w.timestamp);let K=(Lt=(Je=(ft=w.reasoningText)!=null?ft:w.text)!=null?Je:w.delta)!=null?Lt:"";if(K&&w.hidden!==!0){let Ne=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Ne!==void 0){let rt=Ke(q,Ne,String(K));G.reasoning.chunks=[rt]}else G.reasoning.chunks.push(String(K))}if(G.reasoning.status=w.done?"complete":"streaming",w.done){G.reasoning.completedAt=Me((Mt=w.completedAt)!=null?Mt:w.timestamp);let Ne=(xt=G.reasoning.startedAt)!=null?xt:Date.now();G.reasoning.durationMs=Math.max(0,((Rt=G.reasoning.completedAt)!=null?Rt:Date.now())-Ne)}G.streaming=G.reasoning.status!=="complete",g(G)}else if(ot==="reasoning_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)&&k.has(z)){let rt=k.get(z);if(rt.reasoning){let ct=typeof w.text=="string"?w.text:"";ct&&rt.reasoning.chunks.length===0&&rt.reasoning.chunks.push(ct),rt.reasoning.status="complete",rt.streaming=!1,g(rt)}E.delete(z),k.delete(z);continue}let q=(Ot=(Xt=Pe(w,!1))!=null?Xt:Pe(w,!0))!=null?Ot:`reason-${p()}`,G=typeof w.text=="string"?w.text:"";!I.get(q)&&(G||w.scope==="loop")&&ne(q);let K=I.get(q);if(K!=null&&K.reasoning){(w.scope==="loop"||w.scope==="turn")&&(K.reasoning.scope=w.scope),G&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(G),K.reasoning.status="complete",K.reasoning.completedAt=Me((en=w.completedAt)!=null?en:w.timestamp);let rt=(xr=K.reasoning.startedAt)!=null?xr:Date.now();K.reasoning.durationMs=Math.max(0,((Nr=K.reasoning.completedAt)!=null?Nr:Date.now())-rt),K.streaming=!1,g(K)}let Ne=O(w);Ne&&$.byStep.delete(Ne)}else if(ot==="tool_start"){b&&(b.streaming=!1,g(b),b=null),typeof w.iteration=="number"&&(we=w.iteration);let z=(sr=(or=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?or:V(w,!0))!=null?sr:`tool-${p()}`,q=(Xr=w.toolName)!=null?Xr:w.name;if($e(q)){re.add(z);continue}Ae(Z(w),z);let G=Q(z),K=(zt=G.toolCall)!=null?zt:{id:z,status:"pending"};K.name=q!=null?q:K.name,K.status="running",w.parameters!==void 0?K.args=w.parameters:w.args!==void 0&&(K.args=w.args),K.startedAt=(Or=K.startedAt)!=null?Or:Me((ar=w.startedAt)!=null?ar:w.timestamp),K.completedAt=void 0,K.durationMs=void 0,G.toolCall=K,G.streaming=!0,w.executionId&&(G.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(G)}else if(ot==="tool_output_delta"){let z=(kn=(Hn=V(w,!1))!=null?Hn:V(w,!0))!=null?kn:`tool-${p()}`;if(re.has(z))continue;let q=Q(z),G=(Bn=q.toolCall)!=null?Bn:{id:z,status:"running"};G.startedAt=(vr=G.startedAt)!=null?vr:Me((ir=w.startedAt)!=null?ir:w.timestamp);let K=(Yr=(zn=(Qr=w.text)!=null?Qr:w.delta)!=null?zn:w.message)!=null?Yr:"";K&&(G.chunks=(At=G.chunks)!=null?At:[],G.chunks.push(String(K))),G.status="running",q.toolCall=G,q.streaming=!0;let Ne=w.agentContext;(Ne||w.executionId)&&(q.agentMetadata=(Fr=q.agentMetadata)!=null?Fr:{executionId:(wr=Ne==null?void 0:Ne.executionId)!=null?wr:w.executionId,iteration:(Cr=Ne==null?void 0:Ne.iteration)!=null?Cr:w.iteration}),g(q)}else if(ot==="tool_complete"){let z=(yt=(lr=V(w,!1))!=null?lr:V(w,!0))!=null?yt:`tool-${p()}`;if(re.has(z)){re.delete(z);continue}let q=Q(z),G=(Lo=q.toolCall)!=null?Lo:{id:z,status:"running"};G.status="complete",w.result!==void 0&&(G.result=w.result),typeof w.duration=="number"&&(G.duration=w.duration),G.completedAt=Me((Ar=w.completedAt)!=null?Ar:w.timestamp);let K=(Po=w.duration)!=null?Po:w.executionTime;if(typeof K=="number")G.durationMs=K;else{let ct=(Ln=G.startedAt)!=null?Ln:Date.now();G.durationMs=Math.max(0,((ss=G.completedAt)!=null?ss:Date.now())-ct)}q.toolCall=G,q.streaming=!1;let Ne=w.agentContext;(Ne||w.executionId)&&(q.agentMetadata=(eo=q.agentMetadata)!=null?eo:{executionId:(Zr=Ne==null?void 0:Ne.executionId)!=null?Zr:w.executionId,iteration:(_r=Ne==null?void 0:Ne.iteration)!=null?_r:w.iteration}),g(q);let rt=Z(w);rt&&R.byCall.delete(rt)}else if(ot==="await"&&w.toolName){let z=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,q=(to=z!=null?z:w.toolId)!=null?to:`local-${p()}`,G=Q(q),K=w.toolName,Ne=w.origin==="webmcp"&&!Ko(K)?`webmcp:${K}`:K,rt=Ko(Ne),ct=(Io=G.toolCall)!=null?Io:{id:q,status:"pending"};ct.name=Ne,ct.args=w.parameters,ct.status=rt?"running":"complete",ct.chunks=(Ro=ct.chunks)!=null?Ro:[],ct.startedAt=(Dn=ct.startedAt)!=null?Dn:Me((vt=(no=w.startedAt)!=null?no:w.timestamp)!=null?vt:w.awaitedAt),rt?(ct.completedAt=void 0,ct.duration=void 0,ct.durationMs=void 0):ct.completedAt=(Nn=ct.completedAt)!=null?Nn:ct.startedAt,G.toolCall=ct,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(St=w.executionId)!=null?St:(wn=G.agentMetadata)==null?void 0:wn.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},g(G)}else if(ot==="text_start"){let z=typeof w.id=="string"?w.id:null,q=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&q){E.set(z,q);continue}let G=b;G&&(Ze==="flow"?(ge(G),Wt=G):(G.streaming=!1,g(G)),b=null),L=typeof w.id=="string"?w.id:L,P=""}else if(ot==="text_delta"){let z=typeof w.id=="string"?w.id:null,q=z?E.get(z):void 0;if(z&&q){let K=typeof w.delta=="string"?w.delta:"",Ne=((Vn=C.get(z))!=null?Vn:"")+K;if(C.set(z,Ne),Ne.trim()==="")continue;let rt=X(z,q);rt.agentMetadata={...rt.agentMetadata,executionId:w.executionId,parentToolId:q},tt(rt,Ne,K,void 0);continue}if(L=typeof w.id=="string"?w.id:L,Ze==="flow"){let K=typeof w.delta=="string"?w.delta:"";if(P+=K,P.trim()==="")continue;let Ne=ee();Ne.agentMetadata={executionId:w.executionId,iteration:w.iteration},tt(Ne,P,K,void 0),v=Ne;continue}let G=ee();G.content+=(Kn=w.delta)!=null?Kn:"",G.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:be!=null?be:void 0,agentName:pe==null?void 0:pe.agentName},v=G,g(G)}else if(ot==="text_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&E.has(z)){let G=k.get(z);G&&ge(G),E.delete(z),C.delete(z),k.delete(z);continue}let q=b;q&&(Ze==="flow"?(ge(q),Wt=q):(((On=q.content)!=null?On:"")===""&&typeof w.text=="string"&&(q.content=w.text),q.streaming=!1,g(q)),b=null),L=null,P=""}else if(ot==="step_complete"){let z=w.stepType,q=w.executionType;if(z==="tool"||q==="context")continue;if(w.success===!1){let G=w.error,K=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&"message"in G?String((ro=G.message)!=null?ro:"Step failed"):"Step failed";n({type:"error",error:new Error(K)});let Ne=b;Ne&&Ne.streaming&&(Ne.streaming=!1,g(Ne)),n({type:"status",status:"idle"});continue}{let G=Wt;Wt=null;let K=w.stopReason,Ne=(Ce=w.result)==null?void 0:Ce.response;if(G)K&&(G.stopReason=K),Ne!=null?gt(G,Ne):G.streaming!==!1&&(le.delete(G.id),Ie.delete(G.id),G.streaming=!1,g(G));else{let rt=Ne!=null&&Ne!=="";if(rt||K){let ct=ee();K&&(ct.stopReason=K),rt?ge(ct,Ne):(ct.streaming=!1,g(ct))}}continue}}else if(ot==="execution_start")Ze=w.kind==="flow"?"flow":"agent",qt=!0,Ze==="agent"&&(pe={executionId:w.executionId,agentId:($r=w.agentId)!=null?$r:"virtual",agentName:(Gn=w.agentName)!=null?Gn:"",status:"running",currentIteration:0,maxTurns:(Ft=w.maxTurns)!=null?Ft:1,startedAt:Me(w.startedAt)});else if(ot==="turn_start"){let z=typeof w.iteration=="number"?w.iteration:we;if(z!==we){if(pe&&(pe.currentIteration=z),Ct==="separate"&&z>1){let q=b;q&&(q.streaming=!1,g(q),vn.set(z-1,q),b=null)}we=z}be=typeof w.id=="string"?w.id:null,v=null}else if(ot==="tool_input_delta"){let z=(Jn=w.toolCallId)!=null?Jn:R.lastId;if(z){let q=j.get(z);q!=null&&q.toolCall&&(q.toolCall.chunks=(jr=q.toolCall.chunks)!=null?jr:[],q.toolCall.chunks.push((Ds=w.delta)!=null?Ds:""),g(q))}}else{if(ot==="tool_input_complete")continue;if(ot==="turn_complete"){let z=w.stopReason,q=b!=null?b:v;if(z&&q!==null){let G=w.id;(!G||((as=q.agentMetadata)==null?void 0:as.turnId)===G)&&(q.stopReason=z,g(q))}be===w.id&&(be=null)}else if(ot==="media_start"){let z=String(w.id);Se.set(z,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(ot==="media_delta"){let z=Se.get(String(w.id));z&&typeof w.delta=="string"&&z.parts.push(w.delta)}else if(ot==="media_complete"){let z=String(w.id),q=Se.get(z);Se.delete(z);let G=(Wo=(Ns=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Ns:q==null?void 0:q.mediaType)!=null?Wo:"application/octet-stream",K=typeof w.data=="string"?w.data:void 0,Ne=typeof w.url=="string"?w.url:q&&q.parts.length>0?q.parts.join(""):void 0,rt=null;if(K)rt={type:"media",data:K,mediaType:G};else if(Ne){let Pn=G.toLowerCase();rt={type:Pn==="image"||Pn.startsWith("image/")?"image-url":"file-url",url:Ne,mediaType:G}}let ct=(Sr=w.toolCallId)!=null?Sr:q==null?void 0:q.toolCallId,Di=rt?[rt]:[],io=[];for(let Pn of Di){if(!Pn||typeof Pn!="object")continue;let Qt=Pn,lo=typeof Qt.type=="string"?Qt.type:void 0,Xn=typeof Qt.mediaType=="string"?Qt.mediaType.toLowerCase():"",Sn=null,In="";if(lo==="media"){let Tn=typeof Qt.data=="string"?Qt.data:void 0;if(!Tn)continue;In=Xn.length>0?Xn:"application/octet-stream",Sn=`data:${In};base64,${Tn}`}else if(lo==="image-url"){let Tn=typeof Qt.url=="string"?Qt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else if(lo==="file-url"){let Tn=typeof Qt.url=="string"?Qt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else continue;if(Sn)if(lo==="image-url"||In.startsWith("image/"))io.push({type:"image",image:Sn,...In.includes("/")?{mimeType:In}:{}});else if(In.startsWith("audio/"))io.push({type:"audio",audio:Sn,mimeType:In});else if(In.startsWith("video/"))io.push({type:"video",video:Sn,mimeType:In});else{let Tn=In||"application/octet-stream";io.push({type:"file",data:Sn,mimeType:Tn,filename:cy(Tn)})}}if(io.length>0){let Pn=p(),Qt=ct,Xn={id:`agent-media-${typeof Qt=="string"&&Qt.length>0?`${Qt}-${Pn}`:String(Pn)}`,role:"assistant",content:"",contentParts:io,createdAt:new Date().toISOString(),streaming:!1,sequence:Pn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:we}};g(Xn);let Sn=b;Sn&&(Sn.streaming=!1,g(Sn)),b=null,S.current=null}}else if(ot==="execution_complete"){let z=(oo=w.kind)!=null?oo:Ze;z==="agent"&&pe&&(pe.status=w.success?"complete":"error",pe.completedAt=Me(w.completedAt),pe.stopReason=w.stopReason);let q=b;q&&(z==="flow"&&q.streaming!==!1?ge(q):(q.streaming=!1,g(q)),b=null),L=null,P="",Wt=null,n({type:"status",status:"idle",terminal:!0})}else if(ot==="execution_error"){let z=typeof w.error=="string"?w.error:(rn=(lt=w.error)==null?void 0:lt.message)!=null?rn:"Execution error";n({type:"error",error:new Error(z)})}else if(ot!=="ping"){if(ot==="approval_start"){let z=(on=w.approvalId)!=null?on:`approval-${p()}`,q={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:"pending",agentId:(Tr=pe==null?void 0:pe.agentId)!=null?Tr:"virtual",executionId:(Ur=(Os=w.executionId)!=null?Os:pe==null?void 0:pe.executionId)!=null?Ur:"",toolName:(Ho=w.toolName)!=null?Ho:"",toolType:w.toolType,description:(F=w.description)!=null?F:`Execute ${(Er=w.toolName)!=null?Er:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(ot==="step_await"&&w.awaitReason==="approval_required"){let z=(is=w.approvalId)!=null?is:`approval-${p()}`,q={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:"pending",agentId:(cr=pe==null?void 0:pe.agentId)!=null?cr:"virtual",executionId:(qr=(Mr=w.executionId)!=null?Mr:pe==null?void 0:pe.executionId)!=null?qr:"",toolName:(kr=w.toolName)!=null?kr:"",toolType:w.toolType,description:(ls=w.description)!=null?ls:`Execute ${(dr=w.toolName)!=null?dr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(q)}else if(ot==="approval_complete"){let z=w.approvalId;if(z){let G={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:z,status:(Ma=w.decision)!=null?Ma:"approved",agentId:(hn=pe==null?void 0:pe.agentId)!=null?hn:"virtual",executionId:(pr=(Cn=w.executionId)!=null?Cn:pe==null?void 0:pe.executionId)!=null?pr:"",toolName:(An=w.toolName)!=null?An:"",description:(Bo=w.description)!=null?Bo:"",resolvedAt:Date.now()}};g(G)}}else if(ot==="artifact_start"||ot==="artifact_delta"||ot==="artifact_update"||ot==="artifact_complete"){if(ot==="artifact_start"){let z=w.artifactType,q=String(w.id),G=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:q,artifactType:z,title:G,component:typeof w.component=="string"?w.component:void 0}),fe.set(q,{markdown:"",title:G}),!ae.has(q)){ae.add(q);let K={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:G,artifactType:z,status:"streaming"}})};se.set(q,K),g(K)}}else if(ot==="artifact_delta"){let z=String(w.id),q=typeof w.delta=="string"?w.delta:String((ur=w.delta)!=null?ur:"");n({type:"artifact_delta",id:z,artDelta:q});let G=fe.get(z);G&&(G.markdown+=q)}else if(ot==="artifact_update"){let z=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:z,component:typeof w.component=="string"?w.component:void 0})}else if(ot==="artifact_complete"){let z=String(w.id);n({type:"artifact_complete",id:z});let q=se.get(z);if(q){q.streaming=!1;try{let G=JSON.parse((yn=q.rawContent)!=null?yn:"{}");if(G.props){G.props.status="complete";let K=fe.get(z);K!=null&&K.markdown&&(G.props.markdown=K.markdown)}q.rawContent=JSON.stringify(G)}catch{}fe.delete(z),g(q),se.delete(z)}}}else if(ot==="transcript_insert"){let z=w.message;if(!z||typeof z!="object")continue;let q=String((Lr=z.id)!=null?Lr:`msg-${p()}`),G=z.role,Ne={id:q,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:p()};if(g(Ne),Ne.rawContent)try{let rt=JSON.parse(Ne.rawContent),ct=(cs=rt==null?void 0:rt.props)==null?void 0:cs.artifactId;typeof ct=="string"&&ae.add(ct)}catch{}b=null,S.current=null,le.delete(q),Ie.delete(q)}else if(ot==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let z=typeof w.error=="string"?w.error:((Do=w.error)==null?void 0:Do.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(z)});let q=b;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}else if(ot==="step_error"||ot==="dispatch_error"||ot==="flow_error"){let z=null;if(w.error instanceof Error)z=w.error;else if(ot==="dispatch_error"){let q=(ds=w.message)!=null?ds:w.error;q!=null&&q!==""&&(z=new Error(String(q)))}else{let q=w.error;typeof q=="string"&&q!==""?z=new Error(q):q!=null&&typeof q=="object"&&"message"in q&&(z=new Error(String((so=q.message)!=null?so:q)))}if(z){n({type:"error",error:z});let q=b;q&&q.streaming&&(q.streaming=!1,g(q)),n({type:"status",status:"idle"})}}}}}it.length=0};;){let{done:M,value:ue}=await s.read();if(M)break;i+=a.decode(ue,{stream:!0});let Te=i.split(`
12
12
 
13
- `);a=(hn=Te.pop())!=null?hn:"";for(let De of Te){let Pe=De.split(`
14
- `),Ne="message",Ge="";for(let ce of Pe)ce.startsWith("event:")?Ne=ce.replace("event:","").trim():ce.startsWith("data:")&&(Ge+=ce.replace("data:","").trim());if(!Ge)continue;let it;try{it=JSON.parse(Ge)}catch(ce){n({type:"error",error:ce instanceof Error?ce:new Error("Failed to parse chat stream payload")});continue}let It=Ne!=="message"?Ne:(yr=it.type)!=null?yr:"message";if((br=this.onSSEEvent)==null||br.call(this,It,it),this.parseSSEEvent){x.current=f;let ce=await this.handleCustomSSEEvent(it,n,x,g,l,E);if(x.current&&x.current!==f&&(f=x.current),ce)continue}J.push({payloadType:It,payload:it}),dt()}}dt()}};function Dh(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Qs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function hs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var $a="[Image]";function Nh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Oh(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Fh(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function _h(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function ja(e){return{type:"text",text:e}}function $h(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 jh(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 Uh(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 cm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],qh=["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"],Kr=[...cm,...qh];function zh(e){return cm.includes(e)||e.startsWith("image/")}function Ua(e){return zh(e.type)}async function dm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ua(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 pm(e,t=Kr,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 Vh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function um(e,t){let n=Vh(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"}tl();var mm=16e3,Kh=24e3,Gh=4096,Jh=1380533830;function Xh(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Jh?new Uint8Array(e,44):new Uint8Array(e)}function Qh(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 Ys=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:mm,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:mm});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new ys(Kh);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=`${Qh(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(Gh,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=Xh(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 $o=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="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 jo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ys(e.runtype);case"browser":if(!$o.isSupported())throw new Error("Browser speech recognition not supported");return new $o(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function nl(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return jo({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return jo({type:"runtype",runtype:e.runtype});if($o.isSupported())return jo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function qa(e){try{return nl(e),!0}catch{return!1}}function Zs(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 Uo=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):Zs(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 bs=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 rl(e){if(!e)return"";let t=Yh(e);return gm(t!==null?t:e)}function Yh(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 gm(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 xm=null;var ol=()=>xm?xm():Promise.resolve().then(()=>(bm(),ym));var ty=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function ny(e,t){return ty.some(n=>e[n]!==t[n])}function vm(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 ea=e=>({isError:!0,content:[{type:"text",text:e}]}),wm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Cm=e=>Oo(e)||e===Hr,ta=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 bs(()=>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)&&(Oo(g.name)||g.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&&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 fs(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||ol().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 qa((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=Uo.isSupported()?new Uo({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 ol().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=jo(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(!ny(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 fs(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"?Qs():n==="assistant"?hs():`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"?Qs():o==="assistant"?hs():`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=Qs(),s=hs(),a={id:o,role:"user",content:r||$a,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=vm(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=hs();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=vm(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 W=C[j],O=Array.isArray(W)?W.join(", "):typeof W=="string"?W:"";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)!==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,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,W,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===Hr)return{dedupeKey:x,resumeKey:T,output:Ki(),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=(W=this.callbacks).onError)==null||O.call(W,N instanceof Error?N:new Error(String(N))),this.markWebMcpToolComplete(g,ea(Y?"Aborted by cancel()":wm(N)),E),this.webMcpInflightKeys.delete(x),null}return L.signal.aborted?(this.markWebMcpToolComplete(g,ea("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)===Hr?{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,ea("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 W=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(W)||this.webMcpResolvedKeys.has(W))return;this.webMcpInflightKeys.add(W);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(W)}catch(O){(M=(k=this.callbacks).onError)==null||M.call(k,O instanceof Error?O:new Error(String(O)))}finally{this.webMcpInflightKeys.delete(W)}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===Hr,p=(P=t.toolCall)==null?void 0:P.args,u=l?null:this.client.executeWebMcpToolCall(r,p,d),g="execute",f=a;try{let W;if(l?W=Ki():u?W=await u:W={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ea("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,W,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,W,a,f,l?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(W){let O=W instanceof Error&&(W.name==="AbortError"||W.message.includes("aborted")||W.message.includes("abort"));(g==="execute"||O||d.aborted)&&this.markWebMcpToolComplete(t,ea(O||d.aborted?"Aborted by cancel()":wm(W)),a),O||(j=(F=this.callbacks).onError)==null||j.call(F,W instanceof Error?W:new Error(String(W)))}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=rl(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Zs(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let r=rl(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,W=n.approval;a.approval={...j,...W,executionId:W.executionId||j.executionId,toolName:W.toolName||j.toolName,description:W.description||j.description,toolType:(f=W.toolType)!=null?f:j.toolType,reason:(v=W.reason)!=null?v:j.reason,parameters:(x=W.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&&Cm(i)&&d&&l&&((k=n.agentMetadata)==null?void 0:k.awaitingLocalTool)===!0){let j=`${d}:${l}`,W=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&&Cm(N)&&((R=o.toolCall)==null?void 0:R.status)==="complete";(W||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 ry,ArrowDown as oy,ArrowUp as sy,ArrowUpRight as ay,Bot as iy,ChevronDown as ly,ChevronUp as cy,ChevronRight as dy,ChevronLeft as py,Check as uy,Clipboard as my,ClipboardCopy as gy,Copy as fy,File as hy,FileCode as yy,FileSpreadsheet as by,FileText as xy,ImagePlus as vy,Loader as wy,LoaderCircle as Cy,Mic as Ay,Paperclip as Sy,RefreshCw as Ty,Search as Ey,Send as My,ShieldAlert as ky,ShieldCheck as Ly,ShieldX as Py,Square as Iy,ThumbsDown as Ry,ThumbsUp as Wy,Upload as Hy,Volume2 as By,X as Dy,User as Ny,Mail as Oy,Phone as Fy,Calendar as _y,Clock as $y,Building as jy,MapPin as Uy,Lock as qy,Key as zy,CreditCard as Vy,AtSign as Ky,Hash as Gy,Globe as Jy,Link as Xy,CircleCheck as Qy,CircleX as Yy,TriangleAlert as Zy,Info as eb,Ban as tb,Shield as nb,ArrowLeft as rb,ArrowRight as ob,ExternalLink as sb,Ellipsis as ab,EllipsisVertical as ib,Menu as lb,House as cb,Plus as db,Minus as pb,Pencil as ub,Trash as mb,Trash2 as gb,Save as fb,Download as hb,Share as yb,Funnel as bb,Settings as xb,RotateCw as vb,Maximize as wb,Minimize as Cb,ShoppingCart as Ab,ShoppingBag as Sb,Package as Tb,Truck as Eb,Tag as Mb,Gift as kb,Receipt as Lb,Wallet as Pb,Store as Ib,DollarSign as Rb,Percent as Wb,Play as Hb,Pause as Bb,VolumeX as Db,Camera as Nb,Image as Ob,Film as Fb,Headphones as _b,MessageCircle as $b,MessageSquare as jb,Bell as Ub,Heart as qb,Star as zb,Eye as Vb,EyeOff as Kb,Bookmark as Gb,CalendarDays as Jb,History as Xb,Timer as Qb,Folder as Yb,FolderOpen as Zb,Files as ex,Sparkles as tx,Zap as nx,Sun as rx,Moon as ox,Flag as sx,Monitor as ax,Smartphone as ix}from"lucide";var lx={activity:ry,"arrow-down":oy,"arrow-up":sy,"arrow-up-right":ay,bot:iy,"chevron-down":ly,"chevron-up":cy,"chevron-right":dy,"chevron-left":py,check:uy,clipboard:my,"clipboard-copy":gy,copy:fy,file:hy,"file-code":yy,"file-spreadsheet":by,"file-text":xy,"image-plus":vy,loader:wy,"loader-circle":Cy,mic:Ay,paperclip:Sy,"refresh-cw":Ty,search:Ey,send:My,"shield-alert":ky,"shield-check":Ly,"shield-x":Py,square:Iy,"thumbs-down":Ry,"thumbs-up":Wy,upload:Hy,"volume-2":By,x:Dy,user:Ny,mail:Oy,phone:Fy,calendar:_y,clock:$y,building:jy,"map-pin":Uy,lock:qy,key:zy,"credit-card":Vy,"at-sign":Ky,hash:Gy,globe:Jy,link:Xy,"circle-check":Qy,"circle-x":Yy,"triangle-alert":Zy,info:eb,ban:tb,shield:nb,"arrow-left":rb,"arrow-right":ob,"external-link":sb,ellipsis:ab,"ellipsis-vertical":ib,menu:lb,house:cb,plus:db,minus:pb,pencil:ub,trash:mb,"trash-2":gb,save:fb,download:hb,share:yb,funnel:bb,settings:xb,"rotate-cw":vb,maximize:wb,minimize:Cb,"shopping-cart":Ab,"shopping-bag":Sb,package:Tb,truck:Eb,tag:Mb,gift:kb,receipt:Lb,wallet:Pb,store:Ib,"dollar-sign":Rb,percent:Wb,play:Hb,pause:Bb,"volume-x":Db,camera:Nb,image:Ob,film:Fb,headphones:_b,"message-circle":$b,"message-square":jb,bell:Ub,heart:qb,star:zb,eye:Vb,"eye-off":Kb,bookmark:Gb,"calendar-days":Jb,history:Xb,timer:Qb,folder:Yb,"folder-open":Zb,files:ex,sparkles:tx,zap:nx,sun:rx,moon:ox,flag:sx,monitor:ax,smartphone:ix},me=(e,t=24,n="currentColor",r=2)=>{let o=lx[e];return o?cx(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 cx(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 Ka={allowedTypes:Kr,maxFileSize:10*1024*1024,maxFiles:4};function dx(){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 xs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ka.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Ka.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Ka.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:Ka.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=pm(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 dm(l),g=Ua(l)?URL.createObjectURL(l):null,f={id:dx(),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=Ua(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=me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=y("span");l.textContent=um(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=me("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 Am=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function na(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];Am(s)&&Am(o)?n[r]=na(s,o):n[r]=o}return n}var sr="min(440px, calc(100vw - 24px))",sl="440px",ux={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:sr,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)"},Ot={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:ux,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Sm(e,t){if(!(!e&&!t))return e?t?na(e,t):e:t}function al(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?{...Ot,...e,theme:Sm(Ot.theme,e.theme),darkTheme:Sm(Ot.darkTheme,e.darkTheme),launcher:{...Ot.launcher,...e.launcher,dock:{...(t=Ot.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Ot.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Ot.copy,...e.copy},sendButton:{...Ot.sendButton,...e.sendButton},statusIndicator:{...Ot.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ot.voiceRecognition,...e.voiceRecognition},features:(()=>{var le,se,oe,be,He,V,X,We,K,pe;let C=(le=Ot.features)==null?void 0:le.artifacts,R=(se=e.features)==null?void 0:se.artifacts,F=(oe=Ot.features)==null?void 0:oe.scrollToBottom,j=(be=e.features)==null?void 0:be.scrollToBottom,W=(He=Ot.features)==null?void 0:He.scrollBehavior,O=(V=e.features)==null?void 0:V.scrollBehavior,N=(X=Ot.features)==null?void 0:X.streamAnimation,Y=(We=e.features)==null?void 0:We.streamAnimation,Ee=(K=Ot.features)==null?void 0:K.askUserQuestion,de=(pe=e.features)==null?void 0:pe.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}},Ce=F===void 0&&j===void 0?void 0:{...F,...j},ke=W===void 0&&O===void 0?void 0:{...W,...O},re=N===void 0&&Y===void 0?void 0:{...N,...Y},we=Ee===void 0&&de===void 0?void 0:{...Ee,...de,styles:{...Ee==null?void 0:Ee.styles,...de==null?void 0:de.styles}};return{...Ot.features,...e.features,...Ce!==void 0?{scrollToBottom:Ce}:{},...ke!==void 0?{scrollBehavior:ke}:{},...Z!==void 0?{artifacts:Z}:{},...re!==void 0?{streamAnimation:re}:{},...we!==void 0?{askUserQuestion:we}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Ot.suggestionChips,suggestionChipsConfig:{...Ot.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ot.layout,...e.layout,header:{...(a=Ot.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Ot.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(p=Ot.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=Ot.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=Ot.layout)==null?void 0:L.slots,...(k=e.layout)==null?void 0:k.slots}},markdown:{...Ot.markdown,...e.markdown,options:{...(M=Ot.markdown)==null?void 0:M.options,...(P=e.markdown)==null?void 0:P.options}},messageActions:{...Ot.messageActions,...e.messageActions}}:Ot}var Tm={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"}},Em={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"}},Mm={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:sr,maxWidth:sl,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function vs(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."))?vs(e,r):r}function il(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=vs(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 km(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 Lm(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]=Lm(s,o):n[r]=o}return n}function mx(e,t){return t?Lm(e,t):e}function ra(e,t={}){var o,s,a,i,d,l,p,u,g,f,v,x,E;let n={palette:Tm,semantic:Em,components:Mm},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:mx(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=km(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 ll(e){var x,E,T,L,k,M,P,C,R,F,j,W,O,N,Y,Ee,de,Z,Ce,ke,re,we,le,se,oe,be,He,V,X,We,K,pe,$e,ge,Ve,et,$t,Xe,fe,J,dt,qe,Ae,Me,nt,Pt,ee,je,Cn,xt,hn,yr,br,A,te,Te,De,Pe,Ne,Ge,it,It,ce,H,he,Fe,vt,Ye,Ht,Tt,ht,Lt,Qt,Ft,Hn,jt,Bn,Gn,yn,kn,Jn,Xr,wt,xr,vr,Dr,lr,ut,Co,wr,Ao,Ln,Xo,Qr,Nr,Yr,Zr,So,To,eo,bt,Dn,Nn,An,Ct,Xn,Qn,On,to,Or,no,Fn,Rt,Sn,Yn,ro,Fr,oo;let t=il(e),n={};for(let[xe,Pn]of Object.entries(t)){let Cr=xe.replace(/\./g,"-");n[`--persona-${Cr}`]=Pn.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"]=(W=n["--persona-components-voice-recording-indicator"])!=null?W: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"]=(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"]=(Z=n["--persona-components-approval-requested-text"])!=null?Z:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Ce=n["--persona-components-approval-requested-shadow"])!=null?Ce:"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"]=(ke=n["--persona-components-approval-approve-background"])!=null?ke:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(re=n["--persona-components-approval-deny-background"])!=null?re:n["--persona-container"],n["--persona-attachment-image-bg"]=(we=n["--persona-components-attachment-image-background"])!=null?we:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(le=n["--persona-components-attachment-image-border"])!=null?le: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"]=(oe=n["--persona-semantic-typography-fontSize"])!=null?oe:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(be=n["--persona-semantic-typography-fontWeight"])!=null?be:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(He=n["--persona-semantic-typography-lineHeight"])!=null?He:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(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"]=(We=n["--persona-palette-radius-lg"])!=null?We:"0.5rem",n["--persona-radius-xl"]=(K=n["--persona-palette-radius-xl"])!=null?K:"0.75rem",n["--persona-radius-full"]=(pe=n["--persona-palette-radius-full"])!=null?pe:"9999px",n["--persona-launcher-radius"]=(ge=($e=n["--persona-components-launcher-borderRadius"])!=null?$e:n["--persona-palette-radius-full"])!=null?ge:"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"]=($t=n["--persona-components-launcher-border"])!=null?$t: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"]=(fe=n["--persona-components-button-primary-foreground"])!=null?fe: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"]=(Ae=(qe=n["--persona-components-panel-borderRadius"])!=null?qe:n["--persona-radius-xl"])!=null?Ae:"0.75rem",n["--persona-panel-border"]=(Me=n["--persona-components-panel-border"])!=null?Me:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Pt=(nt=n["--persona-components-panel-shadow"])!=null?nt:n["--persona-palette-shadows-xl"])!=null?Pt:"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"]=(Cn=(je=n["--persona-components-input-borderRadius"])!=null?je:n["--persona-radius-lg"])!=null?Cn:"0.5rem",n["--persona-message-user-radius"]=(hn=(xt=n["--persona-components-message-user-borderRadius"])!=null?xt:n["--persona-radius-lg"])!=null?hn:"0.5rem",n["--persona-message-assistant-radius"]=(br=(yr=n["--persona-components-message-assistant-borderRadius"])!=null?yr:n["--persona-radius-lg"])!=null?br:"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"]=(Te=n["--persona-components-header-iconBackground"])!=null?Te:n["--persona-primary"],n["--persona-header-icon-fg"]=(De=n["--persona-components-header-iconForeground"])!=null?De:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Pe=n["--persona-components-header-titleForeground"])!=null?Pe:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Ne=n["--persona-components-header-subtitleForeground"])!=null?Ne:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Ge=n["--persona-components-header-actionIconForeground"])!=null?Ge:n["--persona-muted"];let r=(it=e.components)==null?void 0:it.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(It=e.components)==null?void 0:It.introCard;n["--persona-intro-card-bg"]=(ce=n["--persona-components-introCard-background"])!=null?ce:n["--persona-surface"],n["--persona-intro-card-radius"]=(H=n["--persona-components-introCard-borderRadius"])!=null?H:"1rem",n["--persona-intro-card-padding"]=(he=n["--persona-components-introCard-padding"])!=null?he:"1.5rem",n["--persona-intro-card-shadow"]=(vt=(Fe=o==null?void 0:o.shadow)!=null?Fe:n["--persona-components-introCard-shadow"])!=null?vt:"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"]=(Ht=n["--persona-components-input-placeholder"])!=null?Ht:n["--persona-text-muted"],n["--persona-message-user-bg"]=(Tt=n["--persona-components-message-user-background"])!=null?Tt: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"]=(Lt=n["--persona-components-message-user-shadow"])!=null?Lt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Qt=n["--persona-components-message-assistant-background"])!=null?Qt: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"]=(Hn=n["--persona-components-message-assistant-border"])!=null?Hn:n["--persona-border"],n["--persona-message-assistant-shadow"]=(jt=n["--persona-components-message-assistant-shadow"])!=null?jt:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Gn=(Bn=n["--persona-components-scrollToBottom-background"])!=null?Bn:n["--persona-button-primary-bg"])!=null?Gn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(kn=(yn=n["--persona-components-scrollToBottom-foreground"])!=null?yn:n["--persona-button-primary-fg"])!=null?kn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Jn=n["--persona-components-scrollToBottom-border"])!=null?Jn:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(Xr=n["--persona-components-scrollToBottom-size"])!=null?Xr:"40px",n["--persona-scroll-to-bottom-radius"]=(vr=(xr=(wt=n["--persona-components-scrollToBottom-borderRadius"])!=null?wt:n["--persona-button-radius"])!=null?xr:n["--persona-radius-full"])!=null?vr:"9999px",n["--persona-scroll-to-bottom-shadow"]=(lr=(Dr=n["--persona-components-scrollToBottom-shadow"])!=null?Dr:n["--persona-palette-shadows-sm"])!=null?lr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(ut=n["--persona-components-scrollToBottom-padding"])!=null?ut:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Co=n["--persona-components-scrollToBottom-gap"])!=null?Co:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Ao=(wr=n["--persona-components-scrollToBottom-fontSize"])!=null?wr:n["--persona-palette-typography-fontSize-sm"])!=null?Ao:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Ln=n["--persona-components-scrollToBottom-iconSize"])!=null?Ln:"14px",n["--persona-tool-bubble-shadow"]=(Xo=n["--persona-components-toolBubble-shadow"])!=null?Xo:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Qr=n["--persona-components-reasoningBubble-shadow"])!=null?Qr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Nr=n["--persona-components-composer-shadow"])!=null?Nr:"none",n["--persona-md-inline-code-bg"]=(Yr=n["--persona-components-markdown-inlineCode-background"])!=null?Yr:n["--persona-container"],n["--persona-md-inline-code-color"]=(Zr=n["--persona-components-markdown-inlineCode-foreground"])!=null?Zr:n["--persona-text"],n["--persona-md-link-color"]=(To=(So=n["--persona-components-markdown-link-foreground"])!=null?So:n["--persona-accent"])!=null?To:"#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"]=(eo=n["--persona-components-markdown-codeBlock-background"])!=null?eo:n["--persona-container"],n["--persona-md-code-block-border-color"]=(bt=n["--persona-components-markdown-codeBlock-borderColor"])!=null?bt:n["--persona-border"],n["--persona-md-code-block-text-color"]=(Dn=n["--persona-components-markdown-codeBlock-textColor"])!=null?Dn:"inherit",n["--persona-md-table-header-bg"]=(Nn=n["--persona-components-markdown-table-headerBackground"])!=null?Nn:n["--persona-container"],n["--persona-md-table-border-color"]=(An=n["--persona-components-markdown-table-borderColor"])!=null?An:n["--persona-border"],n["--persona-md-hr-color"]=(Ct=n["--persona-components-markdown-hr-color"])!=null?Ct:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Xn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Xn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Qn=n["--persona-components-markdown-blockquote-background"])!=null?Qn:"transparent",n["--persona-md-blockquote-text-color"]=(On=n["--persona-components-markdown-blockquote-textColor"])!=null?On:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(to=n["--persona-components-collapsibleWidget-container"])!=null?to:n["--persona-surface"],n["--cw-surface"]=(Or=n["--persona-components-collapsibleWidget-surface"])!=null?Or:n["--persona-surface"],n["--cw-border"]=(no=n["--persona-components-collapsibleWidget-border"])!=null?no:n["--persona-border"],n["--persona-message-border"]=(Fn=n["--persona-components-message-border"])!=null?Fn: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 xe=v.toolbar;xe.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,n["--persona-dropdown-bg"]=(Rt=n["--persona-dropdown-bg"])!=null?Rt:xe.copyMenuBackground),xe.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,n["--persona-dropdown-border"]=(Sn=n["--persona-dropdown-border"])!=null?Sn:xe.copyMenuBorder),xe.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,n["--persona-dropdown-shadow"]=(Yn=n["--persona-dropdown-shadow"])!=null?Yn:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(ro=n["--persona-dropdown-radius"])!=null?ro:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Fr=n["--persona-dropdown-item-hover-bg"])!=null?Fr:xe.copyMenuItemHoverBackground),xe.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(v!=null&&v.tab){let xe=v.tab;xe.background&&(n["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(n["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(n["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(n["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(n["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(n["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(n["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(v!=null&&v.pane){let xe=v.pane;if(xe.toolbarBackground){let Pn=(oo=vs(e,xe.toolbarBackground))!=null?oo:xe.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Pn}}return n}var gx={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 fx={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"}}},Pm=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ga=()=>{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"},hx=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Ga()},Im=e=>hx(e),yx=e=>ra(e),bx=e=>{var n;let t=ra(void 0,{validate:!1});return ra({...e,palette:{...t.palette,colors:{...fx.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},oa=e=>{let t=Im(e),n=Pm(e==null?void 0:e.theme),r=Pm(e==null?void 0:e.darkTheme);return t==="dark"?bx(na(n!=null?n:{},r!=null?r:{})):yx(n)},xx=e=>ll(e),qo=(e,t)=>{let n=oa(t),r=xx(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},cl=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Ga())});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(Ga());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 vx}from"idiomorph";var Ja=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;vx.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 Rm=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Xa={index:-1,draft:""};function Wm(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:{...Xa}}}function Hm(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,W,O,N,Y,Ee,de,Z,Ce,ke,re,we,le,se,oe;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=(W=e.reasoning)==null?void 0:W.chunks)==null?void 0:O.length)!=null?N:0,(Z=(de=(Ee=(Y=e.reasoning)==null?void 0:Y.chunks)==null?void 0:Ee[e.reasoning.chunks.length-1])==null?void 0:de.length)!=null?Z:0,(we=(re=(ke=(Ce=e.reasoning)==null?void 0:Ce.chunks)==null?void 0:ke[e.reasoning.chunks.length-1])==null?void 0:re.slice(-32))!=null?we:"",(se=(le=e.contentParts)==null?void 0:le.length)!=null?se:0,(oe=e.stopReason)!=null?oe:"",t].join("\0")}function Bm(){return new Map}function Dm(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Nm(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Om(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Qa(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Gr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function zo(e,t){return Gr(e)-e.scrollTop<=t}function Ya(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 Za(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 Fm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function _m(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 $m(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var vn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},wn=1e5,ho=wn+1;var sa={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},wx=["pre","code","a","script","style"],ei=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:sa.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:sa.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:sa.speed,duration:(o=e==null?void 0:e.duration)!=null?o:sa.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:sa.buffer}},Um=[{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"}],aa=new Map;for(let e of Um)aa.set(e.name,e);var Cx=e=>{aa.set(e.name,e)},Ax=e=>{Um.some(t=>t.name===e)||aa.delete(e)},Sx=()=>Array.from(aa.keys()),ia=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=aa.get(e))!=null?r:null},ti=(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},Tx=(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},Ex=(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},dl=/\s/,Mx=(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(dl.test(s[i])){let l=i;for(;l<s.length&&dl.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&&!dl.test(s[p]);)l.appendChild(Tx(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,e)},Lx=(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(Ex(r,l,t,n.value)),n.value+=1));o.replaceChild(a,e)},la=(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:wx).map(f=>f.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Mx(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:Lx;for(let f of i)p(f,n,l);return o.innerHTML},ni=(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},ca=(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},jm=new WeakMap,Px=(e,t)=>{var s;if(!e.styles)return;let n=jm.get(t);if(n||(n=new Set,jm.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},pl=new WeakMap,Ix=(e,t)=>{if(!e.onAttach)return;let n=pl.get(t);if(n||(n=new Map,pl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},qm=e=>{let t=pl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},ul=(e,t)=>{Px(e,t),Ix(e,t)};function ml(e,t=wn){let n=e.style.position,r=e.style.zIndex,o=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=o}}var da=0,yo=null;function gl(e=document){var n;if(da++,da===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;yo={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,da=Math.max(0,da-1),da===0&&yo)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=yo.originalOverflow,o.style.position=yo.originalPosition,o.style.top=yo.originalTop,o.style.width=yo.originalWidth,s.scrollTo(0,yo.scrollY),yo=null}}}var pa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},cn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},bo=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},ar=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:pa.side,width:(o=t==null?void 0:t.width)!=null?o:pa.width,animate:(s=t==null?void 0:t.animate)!=null?s:pa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:pa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:pa.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 Rx="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ri=(e,t={})=>{var E,T,L,k,M,P;let{showClose:n=!0,wrapperClassName:r=Rx,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=St("button",{className:qs("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=me(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,W=j.body;if(!W)return;C=Wr(j,"div","persona-clear-chat-tooltip"),C.textContent=l;let O=Wr(j,"div");O.className="persona-clear-chat-tooltip-arrow",C.appendChild(O);let N=v.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(ho),C.style.left=`${N.left+N.width/2}px`,C.style.top=`${N.top-8}px`,C.style.transform="translate(-50%, -100%)",W.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}},Wx="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",oi=(e,t={})=>{var C,R,F,j,W,O,N,Y,Ee,de,Z,Ce,ke;let{wrapperClassName:n=Wx,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=(W=a.iconColor)!=null?W:"",p=(O=a.backgroundColor)!=null?O:"",u=(N=a.borderWidth)!=null?N:"",g=(Y=a.borderColor)!=null?Y:"",f=(Ee=a.borderRadius)!=null?Ee:"",v=(de=a.paddingX)!=null?de:"",x=(Z=a.paddingY)!=null?Z:"",E=(Ce=a.tooltipText)!=null?Ce:"Clear chat",T=(ke=a.showTooltip)!=null?ke:!0,L=y("div",n),k=!!(u||g),M=St("button",{className:qs("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=me(d,o,"currentColor",1);if(P&&(P.style.display="block",M.appendChild(P)),L.appendChild(M),T&&E){let re=null,we=()=>{if(re)return;let se=M.ownerDocument,oe=se.body;if(!oe)return;re=Wr(se,"div","persona-clear-chat-tooltip"),re.textContent=E;let be=Wr(se,"div");be.className="persona-clear-chat-tooltip-arrow",re.appendChild(be);let He=M.getBoundingClientRect();re.style.position="fixed",re.style.zIndex=String(ho),re.style.left=`${He.left+He.width/2}px`,re.style.top=`${He.top-8}px`,re.style.transform="translate(-50%, -100%)",oe.appendChild(re)},le=()=>{re&&re.parentNode&&(re.parentNode.removeChild(re),re=null)};L.addEventListener("mouseenter",we),L.addEventListener("mouseleave",le),M.addEventListener("focus",we),M.addEventListener("blur",le),L._cleanupTooltip=()=>{le(),L.removeEventListener("mouseenter",we),L.removeEventListener("mouseleave",le),M.removeEventListener("focus",we),M.removeEventListener("blur",le)}}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))"},xo=e=>{var P,C,R,F,j,W,O,N,Y,Ee,de,Z,Ce,ke,re,we;let{config:t,showClose:n=!0}=e,r=St("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=St("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 le=parseFloat(s)||24,se=me(d,le*.6,"currentColor",1);se?l.replaceChildren(se):l.textContent=(W=(j=t==null?void 0:t.launcher)==null?void 0:j.agentIconText)!=null?W:"\u{1F4AC}"}else if((O=t==null?void 0:t.launcher)!=null&&O.iconUrl){let le=y("img");le.src=t.launcher.iconUrl,le.alt="",le.className="persona-rounded-xl persona-object-cover",le.style.height=s,le.style.width=s,l.replaceChildren(le)}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=St("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}}),g=St("span",{className:"persona-text-xs",text:(Ce=(Z=t==null?void 0:t.launcher)==null?void 0:Z.subtitle)!=null?Ce:"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=(ke=o.clearChat)!=null?ke:{},v=(re=f.enabled)!=null?re:!0,x=(we=f.placement)!=null?we:"inline",E=null,T=null;if(v){let se=oi(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=se.button,T=se.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}=ri(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}},ws=(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 Vo(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(ho)):(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=me(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 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 l=me(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 si(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=me(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 ai(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 l(p){a=p,d()}return{element:s,setSelected:l}}function fl(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=me(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=Vo({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 zm=e=>{var r;let t=xo({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 Hx(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=me(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=Vo({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 Vm=e=>{var L,k,M,P,C,R,F,j,W;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=fl({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),Hx(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=(W=a.closeButtonIconName)!=null?W:"x",x=me(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}},hl={default:zm,minimal:Vm},Km=e=>{var t;return(t=hl[e])!=null?t:hl.default},ua=(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=Km(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 ii=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}},li=e=>{var P,C,R,F,j,W,O,N,Y,Ee,de,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=(W=t.stopTooltipText)!=null?W:"Stop generating",d=(N=(O=e==null?void 0:e.copy)==null?void 0:O.sendButtonLabel)!=null?N:"Send",l=(Ee=(Y=e==null?void 0:e.copy)==null?void 0:Y.stopButtonLabel)!=null?Ee:"Stop",p=(de=t.showTooltip)!=null?de:!1,u=(Z=t.size)!=null?Z:"40px",g=t.backgroundColor,f=t.textColor,v=y("div","persona-send-button-wrapper"),x=St("button",{className:qs("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 Ce=parseFloat(u)||24,ke=(f==null?void 0:f.trim())||"currentColor";o?(E=me(o,Ce,ke,2),E?x.appendChild(E):x.textContent=r):x.textContent=r,T=me(s,Ce,ke,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:Ce=>{if(Ce===k)return;k=Ce;let ke=Ce==="stop"?i:a;if(x.setAttribute("aria-label",ke),L&&(L.textContent=ke),n){if(E&&T){let re=Ce==="stop"?T:E;x.replaceChildren(re)}}else x.textContent=Ce==="stop"?l:d}}},ci=e=>{var L,k,M,P,C,R,F,j,W,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:(W=e==null?void 0:e.sendButton)==null?void 0:W.textColor,g=y("div","persona-send-button-wrapper"),f=St("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=me(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 Ee=y("div","persona-send-button-tooltip");Ee.textContent=E,g.appendChild(Ee)}return{button:f,wrapper:g}},di=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:Kr).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=St("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=me(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}},pi=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},ui=()=>St("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ma=e=>{var v,x,E,T,L,k;let{config:t}=e,n=St("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=ui(),o=St("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}=ii(t);a();let i=li(t),d=ci(t),l=di(t),p=pi(t);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let u=St("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 Gm=()=>{let e=St("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=me("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=me("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},Jm=e=>{var v,x,E,T,L,k;let{config:t}=e,n=St("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=ui();r.style.display="none";let o=pi(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=ii(t);s.style.maxHeight="100px",a();let i=li(t),d=ci(t),l=di(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=St("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 Xm=e=>{var p,u,g,f,v,x,E,T,L,k,M,P,C,R,F,j,W;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=cn(e);if(bo(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:wn);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 Ee=y("div","persona-widget-pill-root");return Ee.setAttribute("data-persona-composer-bar",""),Ee.dataset.state="collapsed",Ee.dataset.expandedSize=(T=O.expandedSize)!=null?T:"anchored",Ee.style.zIndex=String((k=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?k:wn),{wrapper:N,panel:Y,pillRoot:Ee}}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&&hr[o.position]?hr[o.position]:hr["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:wn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(W=(j=e==null?void 0:e.launcher)==null?void 0:j.width)!=null?W:e==null?void 0:e.launcherWidth,l=d!=null?d:sr;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Bx=(e,t)=>{var M,P,C,R,F,j,W,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}=ri(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=oi(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=St("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=St("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=St("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=St("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(W=(j=e==null?void 0:e.copy)==null?void 0:j.welcomeSubtitle)!=null?W:"Ask anything about your account or products."}),g=St("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=St("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=Jm({config:e}),{root:L,textNode:k}=Gm();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}},Qm=(e,t=!0)=>{var E,T,L,k,M,P,C,R,F;if(bo(e))return Bx(e,t);let n=St("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?ua(e,r,{showClose:t}):xo({config:e,showClose:t}),a=St("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=St("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=St("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=St("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:cn(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=ma({config:e}),v=((F=e==null?void 0:e.layout)==null?void 0:F.showFooter)!==!1;o?ws(n,s,e):(s.header.style.display="none",ws(n,s,e)),n.append(a);let x=St("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 yl=(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-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 ea=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,W,O,N,Y,Ee,de;let a=(k=s.launcher)!=null?k:{},i=cn(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 Ce=parseFloat(Z)||24,ke=me(a.agentIconName,Ce*.6,"var(--persona-text-inverse, #ffffff)",2);ke?(u.appendChild(ke),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=(W=a.callToActionIconSize)!=null?W:"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 Ce=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,Ce=(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 ke=parseFloat(Z)||24,re=Math.max(ke-Ce,8),we=me(a.callToActionIconName,re,"currentColor",2);we?f.appendChild(we):f.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else f.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}let v=a.position&&hr[a.position]?hr[a.position]:hr["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:wn));let T="1px solid var(--persona-border, #e5e7eb)",L="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(Ee=a.border)!=null?Ee:T,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:L,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(de=a.collapsedMaxWidth)!=null?de:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:o}};var Ym=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:o}=Xm(e),s=Qm(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}}},bl=({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:()=>yl(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=yl(e,n);return{instance:o,element:o.element}};var Dx=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}},Nx=(e,t)=>{if(!e)return null;let n=Dx(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},Ox=(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},Fx=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},xl=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(":"))},vl=320,eg=320,_x=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),$x=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),jx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Ux=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),qx=(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=`${vl}px`,l.style.maxHeight=`${eg}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}),Fx(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}},zx=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(!xl(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=`${vl}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Vx=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(!xl(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=`${vl}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}},Kx=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(!xl(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}},Cs=()=>{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},tg=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Cs};if(t){let o=t(r);if(o!==null)return o}return Cs()},Gx=(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},Zm=(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},Jx=(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},ng=(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=Gt({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},ga=(e,t,n,r,o,s)=>{var le,se,oe,be,He,V,X,We,K,pe,$e,ge,Ve,et,$t,Xe,fe;let a=n!=null?n:{},i=(le=a.layout)!=null?le:"bubble",d=a.avatar,l=a.timestamp,p=(se=d==null?void 0:d.show)!=null?se:!1,u=(oe=l==null?void 0:l.show)!=null?oe:!1,g=(be=d==null?void 0:d.position)!=null?be:"left",f=(He=l==null?void 0:l.position)!=null?He:"below",v=Jx(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=_x(e),T=(X=(V=e.content)==null?void 0:V.trim())!=null?X:"",k=E.length>0&&T===$a,M=ei((K=(We=s==null?void 0:s.widgetConfig)==null?void 0:We.features)==null?void 0:K.streamAnimation),P=(ge=($e=(pe=s==null?void 0:s.widgetConfig)==null?void 0:pe.features)==null?void 0:$e.streamAnimation)==null?void 0:ge.plugins,C=e.role==="assistant"&&M.type!=="none"?ia(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 W=F?ti((et=e.content)!=null?et:"",M.buffer,C,e,!!e.streaming):($t=e.content)!=null?$t:"",O=t({text:W,message:e,streaming:!!e.streaming,raw:e.rawContent}),N=O;F&&(C==null?void 0:C.wrap)==="char"?N=la(O,"char",e.id,{skipTags:C.skipTags}):F&&(C==null?void 0:C.wrap)==="word"&&(N=la(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=ni(),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 Ae=j.lastElementChild;Ae?Ae.appendChild(J):j.appendChild(J)}}if(u&&f==="inline"&&e.createdAt){let J=Zm(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=qx(E,!k&&!!T,()=>{k&&Y&&(Y.style.display="")});J?x.appendChild(J):k&&Y&&(Y.style.display="")}let Ee=$x(e);if(Ee.length>0){let J=zx(Ee);J&&x.appendChild(J)}let de=jx(e);if(de.length>0){let J=Vx(de);J&&x.appendChild(J)}let Z=Ux(e);if(Z.length>0){let J=Kx(Z);J&&x.appendChild(J)}if(x.appendChild(j),u&&f==="below"&&e.createdAt){let J=Zm(e,l);J.classList.add("persona-mt-1"),x.appendChild(J)}let Ce=e.role==="assistant"?Nx(e.stopReason,(fe=(Xe=s==null?void 0:s.widgetConfig)==null?void 0:Xe.copy)==null?void 0:fe.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let J=!!(W&&W.trim()),dt=M.placeholder==="skeleton",qe=dt&&M.buffer==="line"&&J;if(J)qe&&x.appendChild(ca());else if(dt)x.appendChild(ca());else{let Ae=tg("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Ae&&x.appendChild(Ae)}}if(Ce&&e.stopReason&&!e.streaming&&(T||(j.style.display="none"),x.appendChild(Ox(e.stopReason,Ce))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let J=ng(e,r,o);x.appendChild(J)}if(!p||e.role==="system")return x;let re=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),we=Gx(d,e.role);return g==="right"||g==="left"&&e.role==="user"?re.append(x,we):re.append(we,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),re},Xx=(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}):ga(e,t,n,r,o,s)};var As=new Set,Qx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Yx=(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
- `):""},rg=(e,t)=>{let n=As.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=me(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")},wl=(e,t)=>{var de,Z,Ce,ke,re,we,le,se,oe,be,He;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=(de=t==null?void 0:t.features)==null?void 0:de.reasoningDisplay)!=null?Z:{},s=o.expandable!==!1,a=s&&As.has(e.id),i=n.status!=="complete",d=Yx(e,(Ce=o.previewMaxLines)!=null?Ce: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=(ke=t==null?void 0:t.reasoning)!=null?ke:{},v=String((re=n.startedAt)!=null?re:Date.now()),x=()=>{let V=y("span","");return V.setAttribute("data-tool-elapsed",v),V.textContent=Oa(n),V},E=(we=f.renderCollapsedSummary)==null?void 0:we.call(f,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Oa(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=sm(n),p.appendChild(T);let L=(le=o.loadingAnimation)!=null?le:"none",k=f.activeTextTemplate,M=f.completeTextTemplate,P=i?k:M,C=E instanceof HTMLElement,R=(V,X,We)=>{let K=We;for(let pe of X){let $e=y("span","persona-tool-char");$e.style.setProperty("--char-index",String(K)),$e.textContent=pe===" "?"\xA0":pe,V.appendChild($e),K++}return K},F=(V,X)=>{u.textContent="";let We=Fa(V,""),K=0;for(let pe of We){let $e=pe.styles.length>0?(()=>{let ge=y("span",pe.styles.map(Ve=>`persona-tool-text-${Ve}`).join(" "));return u.appendChild(ge),ge})():u;if(pe.isDuration&&i)$e.appendChild(x());else{let ge=pe.isDuration?Oa(n):pe.text;X?K=R($e,ge,K):$e.appendChild(document.createTextNode(ge))}}};if(!C&&P)if(T.style.display="none",u.style.display="",i&&L!=="none"){let V=(se=f.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`),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=(oe=f.loadingAnimationDuration)!=null?oe: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=me(a?"chevron-up":"chevron-down",16,"currentColor",2);X?j.appendChild(X):j.textContent=a?"Hide":"Show";let We=y("div","persona-flex persona-items-center persona-ml-auto");We.append(j),l.append(p,We)}else l.append(p);let W=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(W.setAttribute("data-persona-collapsed-preview","reasoning"),W.style.display="none",W.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let V=(He=(be=t==null?void 0:t.reasoning)==null?void 0:be.renderCollapsedPreview)==null?void 0:He.call(be,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Qx(W,V)||(W.textContent=d),W.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(l,W),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=me(a?"chevron-up":"chevron-down",16,"currentColor",2);X?j.appendChild(X):j.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",W.style.display=a?"none":W.textContent||W.childNodes.length?"":"none"})(),r.append(l,W,O),r};var Ss=new Set,Zx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ev=(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=fo(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
30
- `):""},Cl=(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)"},tv=(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=ev(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?am(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=Ji(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Ji(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},og=(e,t,n)=>{var p;let r=Ss.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=me(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")},Al=(e,t)=>{var N,Y,Ee,de,Z,Ce,ke,re,we;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=(Ee=(Y=t==null?void 0:t.features)==null?void 0:Y.toolCallDisplay)!=null?Ee:{},a=s.expandable!==!1,i=a&&Ss.has(e.id),{summary:d,previewText:l,isActive:p}=tv(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((de=n.startedAt)!=null?de:Date.now()),x=()=>{let le=y("span","");return le.setAttribute("data-tool-elapsed",v),le.textContent=Js(n),le},E=(Ce=r.renderCollapsedSummary)==null?void 0:Ce.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:Js(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=(ke=s.loadingAnimation)!=null?ke:"none",L=r.activeTextTemplate,k=r.completeTextTemplate,M=p?L:k,P=E instanceof HTMLElement,C=(le,se,oe)=>{let be=oe;for(let He of se){let V=y("span","persona-tool-char");V.style.setProperty("--char-index",String(be)),V.textContent=He===" "?"\xA0":He,le.appendChild(V),be++}return be},R=(le,se)=>{var V;f.textContent="";let oe=((V=n.name)==null?void 0:V.trim())||"tool",be=Fa(le,oe),He=0;for(let X of be){let We=X.styles.length>0?(()=>{let K=y("span",X.styles.map(pe=>`persona-tool-text-${pe}`).join(" "));return f.appendChild(K),K})():f;if(X.isDuration&&p)We.appendChild(x());else{let K=X.isDuration?Js(n):X.text;se?He=C(We,K,He):We.appendChild(document.createTextNode(K))}}};if(!P)if(p&&T!=="none"){let le=(re=r.loadingAnimationDuration)!=null?re:2e3;if(f.setAttribute("data-preserve-animation","true"),T==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${le}ms`),M&&R(M,!1);else if(f.classList.add(`persona-tool-loading-${T}`),f.style.setProperty("--persona-tool-anim-duration",`${le}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 se=f.textContent||d;f.textContent="",C(f,se,0)}}else M&&R(M,!1);let F=null;if(a){F=y("div","persona-flex persona-items-center");let le=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=me(i?"chevron-up":"chevron-down",16,le,2);se?F.appendChild(se):F.textContent=i?"Hide":"Show";let oe=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");oe.append(F),u.append(g,oe)}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 le=(we=r.renderCollapsedPreview)==null?void 0:we.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});Zx(j,le)||(j.textContent=l),j.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,j),o;let W=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(W.style.display=i?"":"none",r.contentBackgroundColor&&(W.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(W.style.color=r.contentTextColor),r.contentPaddingX&&(W.style.paddingLeft=r.contentPaddingX,W.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(W.style.paddingTop=r.contentPaddingY,W.style.paddingBottom=r.contentPaddingY),n.name){let le=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?le.style.color=r.contentTextColor:r.headerTextColor&&(le.style.color=r.headerTextColor),le.textContent=n.name,W.appendChild(le)}if(n.args!==void 0){let le=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 oe=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");oe.style.fontSize="0.75rem",oe.style.lineHeight="1rem",Cl(oe,r),oe.textContent=fo(n.args),le.append(se,oe),W.appendChild(le)}if(n.chunks&&n.chunks.length){let le=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 oe=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");oe.style.fontSize="0.75rem",oe.style.lineHeight="1rem",Cl(oe,r),oe.textContent=n.chunks.join(""),le.append(se,oe),W.appendChild(le)}if(n.status==="complete"&&n.result!==void 0){let le=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 oe=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");oe.style.fontSize="0.75rem",oe.style.lineHeight="1rem",Cl(oe,r),oe.textContent=fo(n.result),le.append(se,oe),W.appendChild(le)}if(n.status==="complete"&&typeof n.duration=="number"){let le=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(le.style.color=r.contentTextColor),le.textContent=`Duration: ${n.duration}ms`,W.appendChild(le)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),F){F.innerHTML="";let le=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",se=me(i?"chevron-up":"chevron-down",16,le,2);se?F.appendChild(se):F.textContent=i?"Hide":"Show"}W.style.display=i?"":"none",j.style.display=i?"none":j.textContent||j.childNodes.length?"":"none"})(),o.append(u,j,W),o};var Ko=new Map,mi=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)},sg=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,ag=(e,t)=>{var r,o,s;let n=(o=(r=sg(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Ko.get(e))!=null?s:n==="expanded"},ig=(e,t,n)=>{var a,i;let r=sg(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=me(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},lg=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=ag(e,n);ig(r,s,n),o.style.display=s?"":"none"};var gi=(e,t)=>{var R,F,j,W,O,N,Y,Ee,de,Z,Ce,ke,re,we,le;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=me(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=(W=r==null?void 0:r.title)!=null?W:"Approval Required",g.appendChild(f),!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"),g.appendChild(se)}u.appendChild(g);let x=n.toolType==="webmcp"||n.toolName.startsWith(Rr)?Us(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:mi(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 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 oe=y("span","persona-font-medium");oe.textContent=`${(N=r==null?void 0:r.reasonLabel)!=null?N:"Agent's stated reason:"} `,se.appendChild(oe),se.appendChild(document.createTextNode(n.reason)),u.appendChild(se)}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 se=ag(e.id,t),oe=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");oe.type="button",oe.setAttribute("data-expand-header","true"),oe.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(oe.style.color=r.descriptionColor);let be=y("span");be.setAttribute("data-approval-details-label","true");let He=y("span","persona-inline-flex persona-items-center");He.setAttribute("data-approval-details-chevron","true"),oe.append(be,He),ig(oe,se,t),u.appendChild(oe);let V=y("div");if(V.setAttribute("data-approval-details","true"),V.style.display=se?"":"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=fo(n.parameters),V.appendChild(X)}u.appendChild(V)}if(o){let se=y("div","persona-flex persona-gap-2 persona-mt-2");se.setAttribute("data-approval-buttons","true");let oe=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");oe.type="button",oe.style.backgroundColor=(Ee=r==null?void 0:r.approveButtonColor)!=null?Ee:"var(--persona-approval-approve-bg, #22c55e)",oe.style.color=(de=r==null?void 0:r.approveButtonTextColor)!=null?de:"#ffffff",oe.setAttribute("data-approval-action","approve");let be=me("shield-check",14,(Z=r==null?void 0:r.approveButtonTextColor)!=null?Z:"#ffffff",2);be&&(be.style.marginRight="4px",oe.appendChild(be));let He=document.createTextNode((Ce=r==null?void 0:r.approveLabel)!=null?Ce:"Approve");oe.appendChild(He);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=(ke=r==null?void 0:r.denyButtonColor)!=null?ke:"transparent",V.style.color=(re=r==null?void 0:r.denyButtonTextColor)!=null?re:"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=me("shield-x",14,(we=r==null?void 0:r.denyButtonTextColor)!=null?we:"var(--persona-feedback-error, #dc2626)",2);X&&(X.style.marginRight="4px",V.appendChild(X));let We=document.createTextNode((le=r==null?void 0:r.denyLabel)!=null?le:"Deny");V.appendChild(We),se.append(oe,V),u.appendChild(se)}return a.append(i,u),s.appendChild(a),s};function nv(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 cg(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:nv(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 dg(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var rv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),pg=(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))},Go=(e,t)=>{pg(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)},ov=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=Ko.get(e))!=null?o:n==="expanded"},Sl=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},av=(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(Rr)?Us(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:mi(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},iv=e=>{let t=y("div","persona-approval-resolved"),n=me("ban",15,"currentColor",2);n&&t.appendChild(n);let r=y("span","persona-approval-resolved-name");return r.textContent=e.toolName?mi(e.toolName):"Tool",t.append(r,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},lv=(e,t,n,r,o,s,a)=>{var F,j,W,O,N,Y,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=(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=(W=r==null?void 0:r.hideDetailsLabel)!=null?W:"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=me("shield-check",16,"currentColor",2);T&&E.appendChild(T),x.appendChild(E);let L=av(n,r);if(u){let de=y("span","persona-approval-toggle");de.setAttribute("aria-hidden","true");let Z=me("chevron-down",14,"currentColor",2);Z&&de.appendChild(Z),L.append(" "),L.appendChild(de)}x.appendChild(L),i.appendChild(x);let k=y("div","persona-approval-body");if(u){let de=y("div","persona-approval-details");if(de.setAttribute("data-role","params"),de.hidden=!g,l){let Z=y("p","persona-approval-desc");r!=null&&r.descriptionColor&&(Z.style.color=r.descriptionColor),Z.textContent=n.description,de.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=fo(n.parameters),de.appendChild(Z)}k.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 Z=y("span","persona-approval-reason-label");Z.textContent=`${(O=r==null?void 0:r.reasonLabel)!=null?O:"Agent's stated reason:"} `,de.append(Z,document.createTextNode(n.reason)),k.appendChild(de)}let M=y("div","persona-approval-actions"),P=null,C=de=>{r!=null&&r.approveButtonColor&&(de.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(de.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 de=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",Sl("\u23CE"));let Ce=y("button","persona-approval-caret");Ce.type="button",Ce.setAttribute("data-action","toggle-menu"),Ce.setAttribute("aria-label","More options"),C(Ce);let ke=me("chevron-down",15,"currentColor",2);ke&&Ce.appendChild(ke),de.append(Z,Ce),M.append(de,R),R.append(Sl("Esc"));let re=y("div","persona-approval-menu"),we=y("button","persona-approval-menu-item");we.type="button",we.append("Allow once",Sl("\u2318\u23CE")),re.appendChild(we),P=cg({anchor:de,content:re,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,P),we.addEventListener("click",()=>{Go(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"),M.append(de,R)}return k.appendChild(M),i.appendChild(k),i.addEventListener("click",de=>{let Z=de.target instanceof Element?de.target.closest("[data-action]"):null;if(!Z)return;let Ce=Z.getAttribute("data-action");if(Ce==="toggle-params"){let ke=i.querySelector('[data-role="params"]');if(ke){let re=ke.hidden;ke.hidden=!re,x.setAttribute("aria-expanded",re?"true":"false"),x.setAttribute("aria-label",re?v:f),Ko.set(t.id,re)}return}if(Ce==="toggle-menu"){P==null||P.toggle();return}if(Ce==="always"){Go(e,t.id),o({remember:!0});return}if(Ce==="allow"){Go(e,t.id),o();return}if(Ce==="deny"){Go(e,t.id),s();return}}),i},ug=()=>{let e=rv();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=ov(a);if(i.status!=="pending"){if(Go(e,r.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return iv(i)}pg(e,r.id);let l=(d==null?void 0:d.enableAlwaysAllow)===!0,p=lv(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=>{dg(g)||r.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),Go(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()])Go(e,r);e.latestPendingApprovalId=null}}};var mg=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 fa=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 ha=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 cv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),dv=new Set(["step_start","execution_start"]),pv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),uv=new Set(["step_complete","agent_turn_complete"]),mv=new Set(["flow_complete","agent_complete"]),gg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),hg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Kn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Jo=(e,t)=>{let n=e[t];return hg(n)?n:void 0};function Tl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function fi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function gv(e,t){return typeof t.type=="string"?t.type:e}function fv(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 hv(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 fg(e){var r,o,s,a,i;let t=Jo(e,"result"),n=[Jo(e,"tokens"),Jo(e,"totalTokens"),t?Jo(t,"tokens"):void 0,Jo(e,"usage"),t?Jo(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(o=(r=Kn(d.output))!=null?r:Kn(d.outputTokens))!=null?o:Kn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Kn(e.outputTokens))!=null?s:Kn(e.completionTokens))!=null?i:t?(a=Kn(t.outputTokens))!=null?a:Kn(t.completionTokens):void 0}function yv(e){var n,r,o,s,a;let t=Jo(e,"result");return(a=(o=(r=(n=Kn(e.executionTime))!=null?n:Kn(e.executionTimeMs))!=null?r:Kn(e.execution_time))!=null?o:Kn(e.duration))!=null?a:t?(s=Kn(t.executionTime))!=null?s:Kn(t.executionTimeMs):void 0}function bv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ya=class{constructor(t=bv){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:fi(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(!hg(n)){gg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=gv(t,n),o=this.now();if(cv.has(r)){this.startRun(o);return}if(dv.has(r)){this.run||this.startRun(o);return}if(pv.has(r)){if(!hv(r,n))return;let a=fv(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+Tl(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:fi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(uv.has(r)){if(!this.run)return;let a=this.run,i=fg(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Tl(a.visibleCharCount),p=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:fi(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(mv.has(r)){if(!this.run)return;let a=this.run,i=fg(n),d=i!=null?i:a.exactOutputTokens+Tl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:fi(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(gg.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=yv(n);return s!=null?s:r-t.startedAt}};function Ts(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var xv={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)"}},vv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},wv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Cv=100;function Av(e,t){let n={...xv,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return vv}function Sv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Tv(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 Ev(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 Mv(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 Lv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Pv(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 Iv(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 El(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");Ts(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=me(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"?Sv(e.timestamp,n):Tv(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=Av(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:wv,R=Ev(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"),W=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=me("clipboard","12px","currentColor",1.5);return O&&W.appendChild(O),W.addEventListener("click",async Ee=>{Ee.stopPropagation(),await Mv(kv(e)),W.innerHTML="";let de=me("check","12px","currentColor",1.5);de&&W.appendChild(de),setTimeout(()=>{W.innerHTML="";let Z=me("clipboard","12px","currentColor",1.5);Z&&W.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(W),f.appendChild(v),d&&f.appendChild(Iv(e,a,i)),f}}function yg(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");Ts(M,k==null?void 0:k.panel);let P=[],C="",R="",F=null,j=[],W={},O=0,N=Qa(),Y=0,Ee=0,de=!1,Z=null,Ce=!1,ke=0,re=new Set,we=new Map,le="",se="",oe=null,be,He,V,X,We=null,K=null,pe=null;function $e(){let ce=y("div","persona-event-toolbar persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),H=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(Ts(H,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",We=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"),We.textContent="-- tok/s",pe=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"),pe.style.display="none",pe.style.pointerEvents="none";let Ft=K,Hn=pe,jt=()=>{if(!Hn.textContent)return;let Gn=Ft.getBoundingClientRect(),yn=ce.getBoundingClientRect();Hn.style.left=`${Gn.left-yn.left}px`,Hn.style.top=`${Gn.bottom-yn.top+4}px`,Hn.style.display="block"},Bn=()=>{Hn.style.display="none"};K.addEventListener("mouseenter",jt),K.addEventListener("mouseleave",Bn),K.appendChild(We)}let he=y("div","persona-flex-1");be=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 Fe=y("option","");Fe.value="",Fe.textContent="All events (0)",be.appendChild(Fe),He=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"),He.type="button",He.title="Copy All";let Ye=me("clipboard-copy","12px","currentColor",1.5);Ye&&He.appendChild(Ye);let Ht=y("span","persona-event-copy-all persona-text-xs");Ht.textContent="Copy All",He.appendChild(Ht),K&&H.appendChild(K),H.appendChild(he),H.appendChild(be),H.appendChild(He);let Tt=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ts(Tt,k==null?void 0:k.searchBar);let ht=me("search","14px","var(--persona-muted, #9ca3af)",1.5),Lt=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&&Lt.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"),Ts(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 Qt=me("x","12px","currentColor",2);return Qt&&X.appendChild(Qt),Tt.appendChild(Lt),Tt.appendChild(V),Tt.appendChild(X),ce.appendChild(H),ce.appendChild(Tt),pe&&ce.appendChild(pe),ce}let ge,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:H=>{C=H,ee(),xt()},onSearchChange:H=>{R=H,ee(),xt()}});ge=ce!=null?ce:$e()}else ge=$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 $t(){if(!a||!We||!K)return;let ce=a(),H=Lv(ce);We.textContent=H;let he=Pv(ce);pe&&(pe.textContent=he,he||(pe.style.display="none")),K.setAttribute("aria-label",he?`Throughput: ${H}, ${he}`:`Throughput: ${H}`)}let Xe=y("div","persona-flex-1 persona-min-h-0 persona-relative"),fe=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");fe.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");Ts(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=me(l,"14px","currentColor",2);dt&&J.appendChild(dt);let qe=y("span","");qe.textContent=p,J.appendChild(qe);let Ae=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ae.style.display="none",Xe.appendChild(fe),Xe.appendChild(Ae),Xe.appendChild(J),M.setAttribute("tabindex","0"),M.appendChild(ge),M.appendChild(et),M.appendChild(Xe);function Me(){let ce=t.getAll(),H={};for(let Tt of ce)H[Tt.type]=(H[Tt.type]||0)+1;let he=Object.keys(H).sort(),Fe=he.length!==j.length||!he.every((Tt,ht)=>Tt===j[ht]),vt=!Fe&&he.some(Tt=>H[Tt]!==W[Tt]),Ye=ce.length!==Object.values(W).reduce((Tt,ht)=>Tt+ht,0);if(!Fe&&!vt&&!Ye||(j=he,W=H,!be))return;let Ht=be.value;if(be.options[0].textContent=`All events (${ce.length})`,Fe){for(;be.options.length>1;)be.remove(1);for(let Tt of he){let ht=y("option","");ht.value=Tt,ht.textContent=`${Tt} (${H[Tt]||0})`,be.appendChild(ht)}Ht&&he.includes(Ht)?be.value=Ht:Ht&&(be.value="",C="")}else for(let Tt=1;Tt<be.options.length;Tt++){let ht=be.options[Tt];ht.textContent=`${ht.value} (${H[ht.value]||0})`}}function nt(){let ce=t.getAll();if(C&&(ce=ce.filter(H=>H.type===C)),R){let H=R.toLowerCase();ce=ce.filter(he=>he.type.toLowerCase().includes(H)||he.payload.toLowerCase().includes(H))}return ce}function Pt(){return C!==""||R!==""}function ee(){O=0,Y=0,N.resume(),J.style.display="none"}function je(ce){re.has(ce)?re.delete(ce):re.add(ce),oe=ce;let H=fe.scrollTop,he=N.isFollowing();Ce=!0,N.pause(),xt(),fe.scrollTop=H,he&&N.resume(),Ce=!1}function Cn(){return zo(fe,50)}function xt(){Ee=Date.now(),de=!1,$t(),Me();let ce=t.getEvictedCount();ce>0?(et.textContent=`${ce.toLocaleString()} older events truncated`,et.style.display=""):et.style.display="none",P=nt();let H=P.length,he=t.getSize()>0;H===0&&he&&Pt()?(Ae.textContent=R?`No events matching '${R}'`:"No events matching filter",Ae.style.display="",fe.style.display="none"):(Ae.style.display="none",fe.style.display=""),He&&(He.title=Pt()?`Copy Filtered (${H})`:"Copy All"),d&&!N.isFollowing()&&H>O&&(Y+=H-O,qe.textContent=p?`${p}${Y>0?` (${Y})`:""}`:"",J.style.display=""),O=H;let Fe=t.getAll(),vt=Fe.length>0?Fe[0].timestamp:0,Ye=new Set(P.map(ht=>ht.id));for(let ht of re)Ye.has(ht)||re.delete(ht);let Ht=C!==le||R!==se,Tt=we.size===0&&P.length>0;if(Ht||Tt||P.length===0){fe.innerHTML="",we.clear();let ht=document.createDocumentFragment();for(let Lt=0;Lt<P.length;Lt++){let Qt=El(P[Lt],Lt,vt,u,re,je,s,o);we.set(P[Lt].id,Qt),ht.appendChild(Qt)}fe.appendChild(ht),le=C,se=R,oe=null}else{if(oe!==null){let Lt=we.get(oe);if(Lt&&Lt.parentNode===fe){let Qt=P.findIndex(Ft=>Ft.id===oe);if(Qt>=0){let Ft=El(P[Qt],Qt,vt,u,re,je,s,o);fe.insertBefore(Ft,Lt),Lt.remove(),we.set(oe,Ft)}}oe=null}let ht=new Set(P.map(Lt=>Lt.id));for(let[Lt,Qt]of we)ht.has(Lt)||(Qt.remove(),we.delete(Lt));for(let Lt=0;Lt<P.length;Lt++){let Qt=P[Lt];if(!we.has(Qt.id)){let Ft=El(Qt,Lt,vt,u,re,je,s,o);we.set(Qt.id,Ft),fe.appendChild(Ft)}}}N.isFollowing()&&(fe.scrollTop=fe.scrollHeight)}function hn(){if(Date.now()-Ee>=Cv){Z!==null&&(cancelAnimationFrame(Z),Z=null),xt();return}de||(de=!0,Z=requestAnimationFrame(()=>{Z=null,xt()}))}let yr=(ce,H)=>{if(!He)return;He.innerHTML="";let he=me(ce,"12px","currentColor",1.5);he&&He.appendChild(he);let Fe=y("span","persona-text-xs");Fe.textContent="Copy All",He.appendChild(Fe),setTimeout(()=>{He.innerHTML="";let vt=me("clipboard-copy","12px","currentColor",1.5);vt&&He.appendChild(vt);let Ye=y("span","persona-text-xs");Ye.textContent="Copy All",He.appendChild(Ye),He.disabled=!1},H)},br=async()=>{if(He){He.disabled=!0;try{let ce;Pt()?ce=P:n?(ce=await n(),ce.length===0&&(ce=t.getAll())):ce=t.getAll();let H=ce.map(he=>{try{return JSON.parse(he.payload)}catch{return he.payload}});await navigator.clipboard.writeText(JSON.stringify(H,null,2)),yr("check",1500)}catch{yr("x",1500)}}},A=()=>{be&&(C=be.value,ee(),xt())},te=()=>{!V||!X||(X.style.display=V.value?"":"none",F&&clearTimeout(F),F=setTimeout(()=>{R=V.value,ee(),xt()},150))},Te=()=>{!V||!X||(V.value="",R="",X.style.display="none",F&&clearTimeout(F),ee(),xt())},De=()=>{if(Ce)return;let ce=fe.scrollTop,{action:H,nextLastScrollTop:he}=Ya({following:N.isFollowing(),currentScrollTop:ce,lastScrollTop:ke,nearBottom:Cn(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ke=he,H==="resume"?(N.resume(),Y=0,J.style.display="none"):H==="pause"&&(N.pause(),d&&(qe.textContent=p,J.style.display=""))},Pe=ce=>{let H=Za({following:N.isFollowing(),deltaY:ce.deltaY,nearBottom:Cn(),resumeWhenNearBottom:!0});H==="pause"?(N.pause(),d&&(qe.textContent=p,J.style.display="")):H==="resume"&&(N.resume(),Y=0,J.style.display="none")},Ne=()=>{d&&(fe.scrollTop=fe.scrollHeight,N.resume(),Y=0,J.style.display="none")},Ge=ce=>{let H=ce.target;if(!H||H.closest("button"))return;let he=H.closest("[data-event-id]");if(!he)return;let Fe=he.getAttribute("data-event-id");Fe&&je(Fe)},it=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?(Te(),V.blur(),M.focus()):r&&r())};He&&He.addEventListener("click",br),be&&be.addEventListener("change",A),V&&V.addEventListener("input",te),X&&X.addEventListener("click",Te),fe.addEventListener("scroll",De),fe.addEventListener("wheel",Pe,{passive:!0}),fe.addEventListener("click",Ge),J.addEventListener("click",Ne),M.addEventListener("keydown",it);function It(){F&&clearTimeout(F),Z!==null&&(cancelAnimationFrame(Z),Z=null),de=!1,we.clear(),He&&He.removeEventListener("click",br),be&&be.removeEventListener("change",A),V&&V.removeEventListener("input",te),X&&X.removeEventListener("click",Te),fe.removeEventListener("scroll",De),fe.removeEventListener("wheel",Pe),fe.removeEventListener("click",Ge),J.removeEventListener("click",Ne),M.removeEventListener("keydown",it)}return{element:M,update:hn,destroy:It}}}function bg(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 xg=(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:()=>bg(e,t)});if(p)return p}return bg(e,t)};var Ml=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)})}},vo=new Ml;vo.register("PersonaArtifactCard",xg);function Rv(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 He,V,X,We;let n=(V=(He=e.features)==null?void 0:He.artifacts)==null?void 0:V.layout,o=((X=n==null?void 0:n.toolbarPreset)!=null?X:"default")==="document",s=(We=n==null?void 0:n.panePadding)==null?void 0:We.trim(),a=e.markdown?us(e.markdown):null,i=$s(e.sanitize),d=K=>{let pe=a?a(K):Vr(K);return i?i(pe):pe},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?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"}),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,W=null,O=null;if(o&&(M||P)&&!R){if(j=M?si({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let K=me("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?si({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W=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"}}),F.append(j,W)):o?j=Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):j=Gt({icon:"copy",label:"Copy"});let N=o?Gt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"refresh-cw",label:"Refresh"}),Y=o?Gt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"x",label:"Close"}),Ee=()=>{var Ve,et,$t;let K=(Ve=we.find(Xe=>Xe.id===le))!=null?Ve:we[we.length-1],pe=(et=K==null?void 0:K.id)!=null?et:null,$e=(K==null?void 0:K.artifactType)==="markdown"&&($t=K.markdown)!=null?$t:"",ge=K?JSON.stringify({component:K.component,props:K.props},null,2):"";return{markdown:$e,jsonPayload:ge,id:pe}},de=async()=>{var Ve;let{markdown:K,jsonPayload:pe}=Ee(),$e=(Ve=we.find(et=>et.id===le))!=null?Ve:we[we.length-1],ge=($e==null?void 0:$e.artifactType)==="markdown"?K:$e?pe:"";try{await navigator.clipboard.writeText(ge)}catch{}};if(j.addEventListener("click",async()=>{let K=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(K&&R){let{markdown:pe,jsonPayload:$e,id:ge}=Ee();try{await K({actionId:"primary",artifactId:ge,markdown:pe,jsonPayload:$e})}catch{}return}await de()}),W&&(C!=null&&C.length)){let K=()=>{var $e;return($e=u.closest("[data-persona-root]"))!=null?$e:document.body},pe=()=>{O=Vo({items:C.map($e=>({id:$e.id,label:$e.label})),onSelect:async $e=>{let{markdown:ge,jsonPayload:Ve,id:et}=Ee(),$t=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{$t?await $t({actionId:$e,artifactId:et,markdown:ge,jsonPayload:Ve}):$e==="markdown"||$e==="md"?await navigator.clipboard.writeText(ge):$e==="json"||$e==="source"?await navigator.clipboard.writeText(Ve):await navigator.clipboard.writeText(ge||Ve)}catch{}},anchor:F!=null?F:W,position:"bottom-right",portal:K()})};u.isConnected?pe():requestAnimationFrame(pe),W.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{}oe()}),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(),oe()}),L.addEventListener("click",()=>{x="source",Z(),oe()});let Ce=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,Ce,k),Z()):(g.appendChild(f),g.appendChild(v)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let ke=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"),re=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(ke.style.paddingLeft=s,ke.style.paddingRight=s,re.style.padding=s),u.appendChild(g),u.appendChild(ke),u.appendChild(re);let we=[],le=null,se=!1,oe=()=>{var ge,Ve,et,$t;let K=o&&we.length<=1;ke.classList.toggle("persona-hidden",K),ke.replaceChildren();for(let Xe of we){let fe=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");fe.type="button",fe.textContent=Xe.title||Xe.id.slice(0,8),Xe.id===le&&fe.classList.add("persona-bg-persona-container","persona-border-persona-border"),fe.addEventListener("click",()=>t.onSelect(Xe.id)),ke.appendChild(fe)}re.replaceChildren();let pe=le&&we.find(Xe=>Xe.id===le)||we[we.length-1];if(!pe)return;if(o){let Xe=pe.artifactType==="markdown"?"MD":(ge=pe.component)!=null?ge:"Component",J=(pe.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Ce.textContent=`${J} \xB7 ${Xe}`}else f.textContent="Artifacts";if(pe.artifactType==="markdown"){if(o&&x==="source"){let fe=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");fe.textContent=(Ve=pe.markdown)!=null?Ve:"",re.appendChild(fe);return}let Xe=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Xe.innerHTML=d((et=pe.markdown)!=null?et:""),re.appendChild(Xe);return}let $e=pe.component?vo.get(pe.component):void 0;if($e){let fe={message:{id:pe.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let J=$e(($t=pe.props)!=null?$t:{},fe);if(J){re.appendChild(J);return}}catch{}}re.appendChild(Rv(pe))},be=()=>{var pe;let K=we.length>0;if(u.classList.toggle("persona-hidden",!K),l){let $e=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ve=((pe=$e==null?void 0:$e.classList.contains("persona-artifact-narrow-host"))!=null?pe:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;K&&Ve&&se?(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 pe,$e,ge;we=K.artifacts,le=(ge=($e=K.selectedId)!=null?$e:(pe=K.artifacts[K.artifacts.length-1])==null?void 0:pe.id)!=null?ge:null,we.length>0&&(se=!0),oe(),be()},setMobileOpen(K){se=K,!K&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):be()}}}function ir(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 wg(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"),!ir(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 Wv(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 hi(e,t){var d,l,p,u,g,f,v,x,E,T;if(!ir(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"),Wv(e),wg(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"),wg(e,t)}var Cg=["panel","seamless"];function yi(e,t){var i,d,l,p,u,g;for(let f of Cg)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"),!ir(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=Cg.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 Ag(e,t){var n,r,o;return!t||!ir(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Hv(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 Bv(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 Dv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Nv(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function Sg(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 Tg(e,t,n,r,o,s){let a=Hv(o,200),i=Nv(t,n,r,200);i=Math.max(a,i);let d=Bv(s);return d!==null&&(i=Math.min(i,d)),Dv(e,a,i)}var Eg={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"}},kl=(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=Eg[a])!=null?x:Eg.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 Ll=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()}},bi=new Ll;var Mg=()=>{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 Ov=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Fv=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},xi=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Ov(e),n=Fv(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}},Pl=e=>typeof e=="string"?e:e==null?"":String(e),Es={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Pl(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=Pl(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:Pl(n.text)}}},kg=e=>Array.isArray(e)?e.map(t=>String(t)):[],vi=e=>{let t=new Set(kg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(kg(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 _v=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}},$v=e=>e.map(t=>({...t,streaming:!1})),jv=e=>e.map(t=>({...t,status:"complete"})),Il=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?_v(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?$v(n.messages):void 0,artifacts:n.artifacts?jv(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 Uv,STR as qv,OBJ as zv}from"partial-json";function Vv(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Kv(e,t){if(!Vv(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 Rl(){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=Uv(n,qv|zv),s=Kv(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Gv(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Wl(e,t){let{config:n,message:r,onPropsUpdate:o}=t,s=vo.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 Jv(){let e=Rl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Lg(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 Hl(e){let t=Lg(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 Bl(e){let t=Lg(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 Xv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Dl(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=Xv}=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 W=j<C;F.classList.toggle("selected",W),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 Nl(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,Ee)=>{Y.classList.toggle("selected",Ee===O),Y.setAttribute("aria-checked",Ee===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 W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(g===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let O=(R==null?void 0:R.value.trim())||void 0;await t(g,O),u.remove()}catch(O){W.disabled=!1,W.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),F.appendChild(j),F.appendChild(W),f.appendChild(F),u.appendChild(f),u}var Ms="persona-chat-history",Qv=30*1e3,Yv={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function Zv(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=Yv[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 wi(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 ew(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 tw(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Ol=e=>!e||typeof e!="object"?{}:{...e},Pg=e=>e.map(t=>({...t,streaming:!1})),Ig=(e,t,n)=>{let r=e!=null&&e.markdown?us(e.markdown):null,o=$s(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=No()!==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?Ru(a):a,v=r(f);l=o&&d?o(v):v}else l=Vr(a);return l}};function Rg(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=me(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 Fl=(e,t,n)=>{var Ac,Sc,Tc,Ec,Mc,kc,Lc,Pc,Ic,Rc,Wc,Hc,Bc,Dc,Nc,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;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=al(t),o=bi.getForInstance(r.plugins),{plugin:s,teardown:a}=ug();r.components&&vo.registerAll(r.components);let i=Mg(),l=r.persistState===!1?null:(Ac=r.storageAdapter)!=null?Ac:Il(),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=Ol(h.metadata)),(Sc=h.messages)!=null&&Sc.length&&(r={...r,initialMessages:h.messages}),(Tc=h.artifacts)!=null&&Tc.length&&(r={...r,initialArtifacts:h.artifacts,initialSelectedArtifactId:(Ec=h.selectedArtifactId)!=null?Ec: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:{}});(Mc=c.messages)!=null&&Mc.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:{},tt()},E=r.actionParsers&&r.actionParsers.length?r.actionParsers:[xi],T=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Es.message,Es.messageAndClick],L=vi({parsers:E,handlers:T,getSessionMetadata:v,updateSessionMetadata:x,emit:i.emit,documentRef:typeof document!="undefined"?document:null});L.syncFromMetadata();let k=(Lc=(kc=r.launcher)==null?void 0:kc.enabled)!=null?Lc:!0,M=(Ic=(Pc=r.launcher)==null?void 0:Pc.autoExpand)!=null?Ic:!1,P=(Rc=r.autoFocusInput)!=null?Rc:!1,C=M,R=k,F=(Hc=(Wc=r.layout)==null?void 0:Wc.header)==null?void 0:Hc.layout,j=!1,W=()=>bo(r),O=()=>k||W(),N=W()?!1:k?M:!0,Y=!1,Ee=null,de=()=>{Y=!0,Ee&&clearTimeout(Ee),Ee=setTimeout(()=>{Y&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Y=!1)},1e4)},Z=Ig(r,L,de),Ce=(Dc=(Bc=r.features)==null?void 0:Bc.showReasoning)!=null?Dc:!0,ke=(Oc=(Nc=r.features)==null?void 0:Nc.showToolCalls)!=null?Oc:!0,re=(_c=(Fc=r.features)==null?void 0:Fc.showEventStreamToggle)!=null?_c:!1,we=(jc=($c=r.features)==null?void 0:$c.scrollToBottom)!=null?jc:{},le=(qc=(Uc=r.features)==null?void 0:Uc.scrollBehavior)!=null?qc:{},oe=`${(Vc=typeof r.persistState=="object"?(zc=r.persistState)==null?void 0:zc.keyPrefix:void 0)!=null?Vc:"persona-"}event-stream`,be=re?new ha(oe):null,He=(Jc=(Gc=(Kc=r.features)==null?void 0:Kc.eventStream)==null?void 0:Gc.maxEvents)!=null?Jc:2e3,V=re?new fa(He,be):null,X=re?new ya:null,We=null,K=!1,pe=null,$e=0;be==null||be.open().then(()=>V==null?void 0:V.restore()).catch(c=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",c)});let ge={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=(Xc=r.statusIndicator)!=null?Xc:{},et=c=>{var m,h,b,S;return c==="idle"?(m=Ve.idleText)!=null?m:vn.idle:c==="connecting"?(h=Ve.connectingText)!=null?h:vn.connecting:c==="connected"?(b=Ve.connectedText)!=null?b:vn.connected:c==="error"?(S=Ve.errorText)!=null?S:vn.error:vn[c]};function $t(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=Ym({config:r,showClose:O()}),{wrapper:fe,panel:J,pillRoot:dt}=Xe.shell,qe=Xe.panelElements,{container:Ae,body:Me,messagesWrapper:nt,suggestions:Pt,textarea:ee,sendButton:je,sendButtonWrapper:Cn,composerForm:xt,statusText:hn,introTitle:yr,introSubtitle:br,closeButton:A,iconHolder:te,headerTitle:Te,headerSubtitle:De,header:Pe,footer:Ne,actionsRow:Ge,leftActions:it,rightActions:It}=qe,ce=qe.setSendButtonMode,H=qe.micButton,he=qe.micButtonWrapper,Fe=qe.attachmentButton,vt=qe.attachmentButtonWrapper,Ye=qe.attachmentInput,Ht=qe.attachmentPreviewsContainer;Ae.classList.add("persona-relative"),Me.classList.add("persona-relative");let Tt=12,ht=()=>{var c;return(c=we.label)!=null?c:""},Lt=()=>{var c;return(c=we.iconName)!=null?c:"arrow-down"},Qt=()=>we.enabled!==!1,Ft=()=>{var c;return(c=le.mode)!=null?c:"follow"},Hn=()=>{var c;return(c=le.anchorTopOffset)!=null?c:16},jt=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");jt.type="button",jt.style.display="none",jt.setAttribute("data-persona-scroll-to-bottom","true");let Bn=y("span","persona-flex persona-items-center"),Gn=y("span",""),yn=y("span","");yn.setAttribute("data-persona-scroll-to-bottom-count",""),yn.style.display="none",jt.append(Bn,Gn,yn),Ae.appendChild(jt);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",Me.appendChild(kn);let Jn=()=>{let m=Ne.style.display==="none"?0:Ne.offsetHeight;jt.style.bottom=`${m+Tt}px`};Jn();let Xr=()=>{let c=!!ht();jt.setAttribute("aria-label",ht()||"Jump to latest"),jt.title=ht(),jt.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false"),Bn.innerHTML="";let m=me(Lt(),"14px","currentColor",2);m?(Bn.appendChild(m),Bn.style.display=""):Bn.style.display="none",Gn.textContent=ht(),Gn.style.display=c?"":"none"};Xr();let wt=null,xr=null,vr=o.find(c=>c.renderHeader);if(vr!=null&&vr.renderHeader){let c=vr.renderHeader({config:r,defaultRenderer:()=>{let m=xo({config:r,showClose:O()});return ws(Ae,m,r),m.header},onClose:()=>Ut(!1,"user")});if(c){let m=Ae.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(c),Pe=c,Xe.header.element=c)}}let Dr=()=>{var m,h,b,S;if(!V)return;if(K=!0,!We&&V&&(We=yg({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>lr(),config:r,plugins:o,getThroughput:()=>{var B;return(B=X==null?void 0:X.getMetric())!=null?B:{status:"idle"}}})),We&&(Me.style.display="none",(m=Ne.parentNode)==null||m.insertBefore(We.element,Ne),We.update()),ut){ut.style.boxShadow=`inset 0 0 0 1.5px ${Mn.actionIconColor}`;let B=(S=(b=(h=r.features)==null?void 0:h.eventStream)==null?void 0:b.classNames)==null?void 0:S.toggleButtonActive;B&&B.split(/\s+/).forEach(q=>q&&ut.classList.add(q))}let c=()=>{if(!K)return;let B=Date.now();B-$e>=200&&(We==null||We.update(),$e=B),pe=requestAnimationFrame(c)};$e=0,pe=requestAnimationFrame(c),st(),i.emit("eventStream:opened",{timestamp:Date.now()})},lr=()=>{var c,m,h;if(K){if(K=!1,We&&We.element.remove(),Me.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))}pe!==null&&(cancelAnimationFrame(pe),pe=null),st(),i.emit("eventStream:closed",{timestamp:Date.now()})}},ut=null;if(re){let c=(Yc=(Qc=r.features)==null?void 0:Qc.eventStream)==null?void 0:Yc.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=me("activity","18px","currentColor",1.5);h&&ut.appendChild(h);let b=qe.clearChatButtonWrapper,S=qe.closeButtonWrapper,B=b||S;B&&B.parentNode===Pe?Pe.insertBefore(ut,B):Pe.appendChild(ut),ut.addEventListener("click",()=>{K?lr():Dr()})}let Co=c=>{var S,B,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 ae=c.querySelector("[data-persona-composer-form]");ae!=null&&ae.parentNode?ae.parentNode.insertBefore(h,ae):c.insertBefore(h,c.firstChild)}if(!((B=c.querySelector("[data-persona-composer-attachment-input]"))!=null?B:c.querySelector('input[type="file"]'))){let ae=y("input");ae.type="file",ae.setAttribute("data-persona-composer-attachment-input",""),ae.accept=((q=m.allowedTypes)!=null?q:Kr).join(","),ae.multiple=((_=m.maxFiles)!=null?_:4)>1,ae.style.display="none",ae.setAttribute("aria-label",(D=m.buttonTooltipText)!=null?D:"Attach files"),c.appendChild(ae)}},wr=o.find(c=>c.renderComposer);if(wr!=null&&wr.renderComposer){let c=r.composer,m=wr.renderComposer({config:r,defaultRenderer:()=>ma({config:r}).footer,onSubmit:h=>{var q;if(!$||$.isStreaming())return;let b=h.trim(),S=(q=wt==null?void 0:wt.hasAttachments())!=null?q:!1;if(!b&&!S)return;ec();let B;S&&(B=[],B.push(...wt.getContentParts()),b&&B.push(ja(b))),$.sendMessage(b,{contentParts:B}),S&&wt.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:((Zc=r.voiceRecognition)==null?void 0:Zc.enabled)===!0?()=>{xr==null||xr()}:void 0});m&&(Xe.replaceComposer(m),Ne=Xe.composer.footer)}let Ao=c=>{let m=(...ie)=>{for(let Q of ie){let ve=c.querySelector(Q);if(ve)return ve}return null},h=c.querySelector("[data-persona-composer-form]"),b=c.querySelector("[data-persona-composer-input]"),S=c.querySelector("[data-persona-composer-submit]"),B=c.querySelector("[data-persona-composer-mic]"),q=c.querySelector("[data-persona-composer-status]");h&&(xt=h),b&&(ee=b),S&&(je=S),B&&(H=B,he=B.parentElement),q&&(hn=q);let _=m("[data-persona-composer-suggestions]",".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");_&&(Pt=_);let D=m("[data-persona-composer-attachment-button]",".persona-attachment-button");D&&(Fe=D,vt=D.parentElement),Ye=m("[data-persona-composer-attachment-input]",'input[type="file"]'),Ht=m("[data-persona-composer-attachment-previews]",".persona-attachment-previews");let ae=m("[data-persona-composer-actions]",".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");ae&&(Ge=ae)};Co(Ne),Ao(Ne);let Ln=(od=(ed=r.layout)==null?void 0:ed.contentMaxWidth)!=null?od:W()?(rd=(nd=(td=r.launcher)==null?void 0:td.composerBar)==null?void 0:nd.contentMaxWidth)!=null?rd:"720px":void 0;if(Ln&&(nt.style.maxWidth=Ln,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%"),Ln&&xt&&!W()&&(xt.style.maxWidth=Ln,xt.style.marginLeft="auto",xt.style.marginRight="auto"),Ln&&Pt&&!W()&&(Pt.style.maxWidth=Ln,Pt.style.marginLeft="auto",Pt.style.marginRight="auto"),Ln&&Ht&&!W()&&(Ht.style.maxWidth=Ln,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),(sd=r.attachments)!=null&&sd.enabled&&Ye&&Ht){wt=xs.fromConfig(r.attachments),wt.setPreviewsContainer(Ht),Ye.addEventListener("change",h=>{let b=h.target;wt==null||wt.handleFileSelect(b.files),b.value=""});let c=r.attachments.dropOverlay,m=Rg(c);Ae.appendChild(m)}(()=>{var b,S;let c=(S=(b=r.layout)==null?void 0:b.slots)!=null?S:{},m=B=>{switch(B){case"body-top":return Ae.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return nt;case"footer-top":return Pt;case"composer":return xt;case"footer-bottom":return hn;default:return null}},h=(B,q)=>{var _;switch(B){case"header-left":case"header-center":case"header-right":if(B==="header-left")Pe.insertBefore(q,Pe.firstChild);else if(B==="header-right")Pe.appendChild(q);else{let D=Pe.querySelector(".persona-flex-col");D?(_=D.parentNode)==null||_.insertBefore(q,D.nextSibling):Pe.appendChild(q)}break;case"body-top":{let D=Me.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith(q):Me.insertBefore(q,Me.firstChild);break}case"body-bottom":Me.appendChild(q);break;case"footer-top":Pt.replaceWith(q);break;case"footer-bottom":hn.replaceWith(q);break;default:break}};for(let[B,q]of Object.entries(c))if(q)try{let _=q({config:r,defaultContent:()=>m(B)});_&&h(B,_)}catch(_){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${B}":`,_)}})();let Qr=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 B=h.getAttribute("data-bubble-type");if(B==="reasoning")As.has(S)?As.delete(S):As.add(S),rg(S,b);else if(B==="tool")Ss.has(S)?Ss.delete(S):Ss.add(S),og(S,b,r);else if(B==="approval"){let D=r.approval!==!1?r.approval:void 0,ae=((q=D==null?void 0:D.detailsDisplay)!=null?q:"collapsed")==="expanded",ie=(_=Ko.get(S))!=null?_:ae;Ko.set(S,!ie),lg(S,b,r)}Er.delete(S)};nt.addEventListener("pointerdown",c=>{c.target.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Qr(c))}),nt.addEventListener("keydown",c=>{let m=c.target;(c.key==="Enter"||c.key===" ")&&m.closest('button[data-expand-header="true"]')&&(c.preventDefault(),Qr(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(),B=Rm(S);!B||B===S||(m.setData("text/plain",B),c.preventDefault())});let Nr=new Map,Yr=null,Zr="idle",So={idle:{icon:"volume-2",label:"Read aloud"},loading:{icon:"loader-circle",label:"Loading\u2026"},playing:{icon:"pause",label:"Pause"},paused:{icon:"play",label:"Resume"}},To=(c,m)=>{let{icon:h,label:b}=So[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=me(h,14,"currentColor",2);S&&(c.innerHTML="",c.appendChild(S))},eo=()=>{nt.querySelectorAll('[data-action="read-aloud"]').forEach(m=>{var B;let h=m.closest("[data-actions-for]"),b=(B=h==null?void 0:h.getAttribute("data-actions-for"))!=null?B:null;To(m,b&&b===Yr?Zr:"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 B=h.getAttribute("data-action");if(B==="copy"){let D=$.getMessages().find(ae=>ae.id===S);if(D&&ge.onCopy){let ae=D.content||"";navigator.clipboard.writeText(ae).then(()=>{h.classList.add("persona-message-action-success");let ie=me("check",14,"currentColor",2);ie&&(h.innerHTML="",h.appendChild(ie)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Q=me("copy",14,"currentColor",2);Q&&(h.innerHTML="",h.appendChild(Q))},2e3)}).catch(ie=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ie)}),ge.onCopy(D)}}else if(B==="read-aloud")$.toggleReadAloud(S);else if(B==="upvote"||B==="downvote"){let D=((q=Nr.get(S))!=null?q:null)===B,ae=B==="upvote"?"thumbs-up":"thumbs-down";if(D){Nr.delete(S),h.classList.remove("persona-message-action-active");let ie=me(ae,14,"currentColor",2);ie&&(h.innerHTML="",h.appendChild(ie))}else{let ie=B==="upvote"?"downvote":"upvote",Q=b.querySelector(`[data-action="${ie}"]`);if(Q){Q.classList.remove("persona-message-action-active");let Ue=me(ie==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ue&&(Q.innerHTML="",Q.appendChild(Ue))}Nr.set(S,B),h.classList.add("persona-message-action-active");let ve=me(ae,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 Se=$.getMessages().find(Ze=>Ze.id===S);Se&&ge.onFeedback&&ge.onFeedback({type:B,messageId:Se.id,message:Se})}}}),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 B=h.getAttribute("data-approval-action");if(!B)return;let q=B==="approve"?"approved":"denied",D=$.getMessages().find(ie=>ie.id===S);if(!(D!=null&&D.approval))return;let ae=b.querySelector("[data-approval-buttons]");ae&&ae.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 bt=null,Dn=null,Nn={artifacts:[],selectedId:null},An=!1,Ct={current:null};nt.addEventListener("click",c=>{var Q,ve,Oe,Se,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||((Oe=(ve=(Q=r.features)==null?void 0:Q.artifacts)==null?void 0:ve.onArtifactAction)==null?void 0:Oe.call(ve,{type:"download",artifactId:b}))===!0)return;let B=$.getArtifactById(b),q=B==null?void 0:B.markdown,_=(B==null?void 0:B.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 Le=$.getMessages().find(ze=>ze.id===rt);if(Le!=null&&Le.rawContent)try{let ze=JSON.parse(Le.rawContent);q=(Se=ze==null?void 0:ze.props)==null?void 0:Se.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"}),ae=URL.createObjectURL(D),ie=document.createElement("a");ie.href=ae,ie.download=`${_}.md`,ie.click(),URL.revokeObjectURL(ae)}),nt.addEventListener("click",c=>{var B,q,_;let h=c.target.closest("[data-open-artifact]");if(!h)return;let b=h.getAttribute("data-open-artifact");!b||((_=(q=(B=r.features)==null?void 0:B.artifacts)==null?void 0:q.onArtifactAction)==null?void 0:_.call(q,{type:"open",artifactId:b}))===!0||(c.preventDefault(),c.stopPropagation(),An=!1,$.selectArtifact(b),Pn())}),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 Xn=qe.composerOverlay,Qn=(c,m,h)=>{var _,D,ae,ie;let b=m.trim();if(!b||!Ct.current)return;let S=(_=c.getAttribute("data-tool-call-id"))!=null?_:"",B=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:B,source:h.source},bubbles:!0,composed:!0})),_o(Xn,S);let q=Ct.current.getMessages().find(Q=>{var ve;return((ve=Q.toolCall)==null?void 0:ve.id)===S});(ae=q==null?void 0:q.agentMetadata)!=null&&ae.awaitingLocalTool?Ct.current.resolveAskUserQuestion(q,(ie=h.structured)!=null?ie:b):Ct.current.sendMessage(b)},On=c=>{var S;let m=Ct.current;if(!m)return;let h=(S=c.getAttribute("data-tool-call-id"))!=null?S:"",b=m.getMessages().find(B=>{var q;return((q=B.toolCall)==null?void 0:q.id)===h});b&&m.persistAskUserQuestionProgress(b,{answers:Ra(c,b),currentIndex:or(c)})},to=c=>Object.entries(c).map(([m,h])=>`${m}: ${Array.isArray(h)?h.join(", "):h}`).join(" | "),Or=c=>{var S,B,q;if(((B=(S=r.features)==null?void 0:S.askUserQuestion)==null?void 0:B.groupedAutoAdvance)===!1)return;let m=or(c),h=gs(c);if(m>=h-1)return;let b=(q=Ct.current)==null?void 0:q.getMessages().find(_=>{var D;return((D=_.toolCall)==null?void 0:D.id)===c.getAttribute("data-tool-call-id")});b&&(Wa(c,b,r,m+1),On(c))};Xn.addEventListener("click",c=>{var B,q,_,D,ae,ie,Q,ve,Oe,Se,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 Ie=(B=b.getAttribute("data-tool-call-id"))!=null?B:"";e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),_o(Xn,Ie);let Le=(q=Ct.current)==null?void 0:q.getMessages().find(ze=>{var Ke;return((Ke=ze.toolCall)==null?void 0:Ke.id)===Ie});(_=Le==null?void 0:Le.agentMetadata)!=null&&_.awaitingLocalTool&&((D=Ct.current)==null||D.markAskUserQuestionResolved(Le),(ae=Ct.current)==null||ae.resolveAskUserQuestion(Le,"(dismissed)"));return}if(S==="pick"){let Ie=h.getAttribute("data-option-label");if(!Ie)return;let Le=b.getAttribute("data-multi-select")==="true",ze=mo(b);if(ze&&Le){let Ke=Fo(b)[or(b)],ft=new Set(Array.isArray(Ke)?Ke:[]);ft.has(Ie)?ft.delete(Ie):ft.add(Ie),go(b,Array.from(ft)),On(b);return}if(ze){go(b,Ie),On(b),Or(b);return}if(Le){let Ke=h.getAttribute("aria-pressed")==="true";h.setAttribute("aria-pressed",Ke?"false":"true"),h.classList.toggle("persona-ask-pill-selected",!Ke);let ft=b.querySelector('[data-ask-user-action="submit-multi"]');ft&&(ft.disabled=zi(b).length===0);return}Qn(b,Ie,{source:"pick",values:[Ie]});return}if(S==="submit-multi"){let Ie=zi(b);if(Ie.length===0)return;Qn(b,Ie.join(", "),{source:"multi",values:Ie});return}if(S==="open-free-text"){let Ie=b.querySelector('[data-ask-free-text-row="true"]');if(Ie){Ie.classList.remove("persona-hidden");let Le=Ie.querySelector('[data-ask-free-text-input="true"]');Le==null||Le.focus()}return}if(S==="focus-free-text"){let Ie=b.querySelector('[data-ask-free-text-input="true"]');Ie==null||Ie.focus();return}if(S==="submit-free-text"){let Ie=b.querySelector('[data-ask-free-text-input="true"]'),Le=(ie=Ie==null?void 0:Ie.value)!=null?ie:"";if(!Le.trim())return;if(mo(b)){go(b,Le.trim()),On(b),Or(b);return}Qn(b,Le,{source:"free-text"});return}if(S==="next"||S==="back"){if(!Ct.current)return;let Ie=(Q=b.getAttribute("data-tool-call-id"))!=null?Q:"",Le=Ct.current.getMessages().find(Be=>{var Re;return((Re=Be.toolCall)==null?void 0:Re.id)===Ie});if(!Le)return;let ze=b.querySelector('[data-ask-free-text-input="true"]'),Ke=(Oe=(ve=ze==null?void 0:ze.value)==null?void 0:ve.trim())!=null?Oe:"";if(Ke){let Be=Fo(b)[or(b)];(typeof Be!="string"||Be!==Ke)&&go(b,Ke)}let ft=S==="next"?1:-1,I=or(b)+ft;Wa(b,Le,r,I),On(b);return}if(S==="submit-all"){if(!Ct.current)return;let Ie=(Se=b.getAttribute("data-tool-call-id"))!=null?Se:"",Le=Ct.current.getMessages().find(Be=>{var Re;return((Re=Be.toolCall)==null?void 0:Re.id)===Ie});if(!Le)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&&go(b,Ke);let ft=Ra(b,Le);Ct.current.persistAskUserQuestionProgress(Le,{answers:ft,currentIndex:or(b)});let I=to(ft);Qn(b,I||"(submitted)",{source:"submit-all",structured:ft});return}if(S==="skip"){if(!Ct.current)return;let Ie=(ct=b.getAttribute("data-tool-call-id"))!=null?ct:"",Le=Ct.current.getMessages().find(Re=>{var ue;return((ue=Re.toolCall)==null?void 0:ue.id)===Ie});if(!Le)return;let ze=mo(b),Ke=or(b),ft=gs(b),I=Ke>=ft-1;if(!ze){e.dispatchEvent(new CustomEvent("persona:askUserQuestion:dismissed",{detail:{toolUseId:Ie},bubbles:!0,composed:!0})),_o(Xn,Ie),(rt=Le.agentMetadata)!=null&&rt.awaitingLocalTool&&(Ct.current.markAskUserQuestionResolved(Le),Ct.current.resolveAskUserQuestion(Le,"(dismissed)"));return}go(b,"");let Be=b.querySelector('[data-ask-free-text-input="true"]');if(Be&&(Be.value=""),I){let Re=Ra(b,Le),ue=to(Re);Qn(b,ue||"(skipped)",{source:"submit-all",structured:Re});return}Wa(b,Le,r,Ke+1),On(b);return}}),Xn.addEventListener("keydown",c=>{var B;if(c.key!=="Enter")return;let h=c.target;if(!((B=h.matches)!=null&&B.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(mo(b)){go(b,S.trim()),On(b),Or(b);return}Qn(b,S,{source:"free-text"})}});let no=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=Xn.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),B=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];B&&(c.preventDefault(),B.click())};document.addEventListener("keydown",no);let Fn=null,Rt=null,Sn=null,Yn=null,ro=()=>{};function Fr(){Yn==null||Yn(),Yn=null}let oo=()=>{var q;if(!Fn||!Rt)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){Rt.style.removeProperty("position"),Rt.style.removeProperty("left"),Rt.style.removeProperty("top"),Rt.style.removeProperty("bottom"),Rt.style.removeProperty("width"),Rt.style.removeProperty("z-index");return}let b=Fn.firstElementChild;if(!b||b===Rt)return;let S=10;Rt.style.position="absolute",Rt.style.top="0",Rt.style.bottom="0",Rt.style.width=`${S}px`,Rt.style.zIndex="5";let B=b.offsetWidth-S/2;Rt.style.left=`${Math.max(0,B)}px`},xe=()=>{},Pn=()=>{var h,b,S,B,q;if(!bt||!ir(r))return;hi(e,r),yi(e,r),xe();let c=(B=(S=(b=(h=r.features)==null?void 0:h.artifacts)==null?void 0:b.layout)==null?void 0:S.narrowHostMaxWidth)!=null?B:520,m=J.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=c),bt.update(Nn),An?(bt.setMobileOpen(!1),bt.element.classList.add("persona-hidden"),(q=bt.backdrop)==null||q.classList.add("persona-hidden")):Nn.artifacts.length>0&&(bt.element.classList.remove("persona-hidden"),bt.setMobileOpen(!0)),ro()};if(ir(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(Ae),bt=vg(r,{onSelect:h=>{var b;return(b=Ct.current)==null?void 0:b.selectArtifact(h)},onDismiss:()=>{An=!0,Pn()}}),bt.element.classList.add("persona-hidden"),Fn=m,m.appendChild(c),m.appendChild(bt.element),bt.backdrop&&J.appendChild(bt.backdrop),J.appendChild(m),ro=()=>{var b,S,B,q;if(!Fn||!bt)return;if(!(((B=(S=(b=r.features)==null?void 0:b.artifacts)==null?void 0:S.layout)==null?void 0:B.resizable)===!0)){Sn==null||Sn(),Sn=null,Fr(),Rt&&(Rt.remove(),Rt=null),bt.element.style.removeProperty("width"),bt.element.style.removeProperty("maxWidth");return}if(!Rt){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,ae=(q=D.defaultView)!=null?q:window,ie=Q=>{var ct,rt;if(!bt||Q.button!==0||e.classList.contains("persona-artifact-narrow-host")||ae.innerWidth<=640)return;Q.preventDefault(),Fr();let ve=Q.clientX,Oe=bt.element.getBoundingClientRect().width,Se=(rt=(ct=r.features)==null?void 0:ct.artifacts)==null?void 0:rt.layout,Ze=Ie=>{let Le=Fn.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),Ke=ze?0:Sg(Fn,ae),ft=ze?0:_.getBoundingClientRect().width||6,I=Oe-(Ie.clientX-ve),Be=Tg(I,Le,Ke,ft,Se==null?void 0:Se.resizableMinWidth,Se==null?void 0:Se.resizableMaxWidth);bt.element.style.width=`${Be}px`,bt.element.style.maxWidth="none",oo()},Ue=()=>{D.removeEventListener("pointermove",Ze),D.removeEventListener("pointerup",Ue),D.removeEventListener("pointercancel",Ue),Yn=null;try{_.releasePointerCapture(Q.pointerId)}catch{}};Yn=Ue,D.addEventListener("pointermove",Ze),D.addEventListener("pointerup",Ue),D.addEventListener("pointercancel",Ue);try{_.setPointerCapture(Q.pointerId)}catch{}};_.addEventListener("pointerdown",ie),Rt=_,Fn.insertBefore(_,bt.element),Sn=()=>{_.removeEventListener("pointerdown",ie)}}if(Rt){let _=Nn.artifacts.length>0&&!An;Rt.classList.toggle("persona-hidden",!_),oo()}},xe=()=>{var ae,ie,Q,ve,Oe,Se,Ze,Ue,ct,rt,Ie,Le,ze,Ke;if(!k||!bt||((ie=(ae=r.launcher)==null?void 0:ae.sidebarMode)!=null?ie:!1)||cn(r)&&ar(r).reveal==="emerge")return;let b=(Q=e.ownerDocument.defaultView)!=null?Q:window,S=(Oe=(ve=r.launcher)==null?void 0:ve.mobileFullscreen)!=null?Oe:!0,B=(Ze=(Se=r.launcher)==null?void 0:Se.mobileBreakpoint)!=null?Ze:640;if(S&&b.innerWidth<=B||!Ag(r,k))return;let q=(rt=(ct=(Ue=r.launcher)==null?void 0:Ue.width)!=null?ct:r.launcherWidth)!=null?rt:sr,_=(Ke=(ze=(Le=(Ie=r.features)==null?void 0:Ie.artifacts)==null?void 0:Le.layout)==null?void 0:ze.expandedPanelWidth)!=null?Ke:"min(720px, calc(100vw - 24px))";Nn.artifacts.length>0&&!An?(J.style.width=_,J.style.maxWidth=_):(J.style.width=q,J.style.maxWidth=q)},typeof ResizeObserver!="undefined"&&(Dn=new ResizeObserver(()=>{Pn()}),Dn.observe(J))}else J.appendChild(Ae),W()&&dt&&(qe.peekBanner&&dt.appendChild(qe.peekBanner),dt.appendChild(Ne));e.appendChild(fe),dt&&e.appendChild(dt);let Cr=()=>{var Be,Re,ue,Bt,Wt,Kt,yt,qt,Un,en,Je,Et,nn,nr,qn,Io,Ro,ls,cs,Jt,Wo,io,lo,zr,Ho,ur,Pr,Qe;if(W()){J.style.width="100%",J.style.maxWidth="100%";let Dt=(Re=(Be=r.launcher)==null?void 0:Be.composerBar)!=null?Re:{},Vt=fe.dataset.state==="expanded",Nt=(ue=Dt.expandedSize)!=null?ue:"anchored";if(!(Vt&&Nt!=="fullscreen")){Ae.style.background="",Ae.style.border="",Ae.style.borderRadius="",Ae.style.overflow="",Ae.style.boxShadow="";return}let Mt=(Wt=(Bt=r.theme)==null?void 0:Bt.components)==null?void 0:Wt.panel,_t=oa(r),un=(gn,rr)=>{var co;return gn==null||gn===""?rr:(co=vs(_t,gn))!=null?co:gn},zn="1px solid var(--persona-border)",Ir="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))";Ae.style.background="var(--persona-surface, #ffffff)",Ae.style.border=un(Mt==null?void 0:Mt.border,zn),Ae.style.borderRadius=un(Mt==null?void 0:Mt.borderRadius,mn),Ae.style.boxShadow=un(Mt==null?void 0:Mt.shadow,Ir),Ae.style.overflow="hidden";return}let c=cn(r),m=(yt=(Kt=r.launcher)==null?void 0:Kt.sidebarMode)!=null?yt:!1,h=c||m||((Un=(qt=r.launcher)==null?void 0:qt.fullHeight)!=null?Un:!1),b=((en=r.launcher)==null?void 0:en.enabled)===!1,S=(Et=(Je=r.theme)==null?void 0:Je.components)==null?void 0:Et.panel,B=oa(r),q=(Dt,Vt)=>{var Nt;return Dt==null||Dt===""?Vt:(Nt=vs(B,Dt))!=null?Nt:Dt},_=(nn=e.ownerDocument.defaultView)!=null?nn:window,D=(qn=(nr=r.launcher)==null?void 0:nr.mobileFullscreen)!=null?qn:!0,ae=(Ro=(Io=r.launcher)==null?void 0:Io.mobileBreakpoint)!=null?Ro:640,ie=_.innerWidth<=ae,Q=D&&ie&&k,ve=(cs=(ls=r.launcher)==null?void 0:ls.position)!=null?cs:"bottom-left",Oe=ve==="bottom-left"||ve==="top-left",Se=(Wo=(Jt=r.launcher)==null?void 0:Jt.zIndex)!=null?Wo:wn,Ze=m||Q?"none":"1px solid var(--persona-border)",Ue=Q?"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))";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),Ie=q(S==null?void 0:S.shadow,Ue),Le=q(S==null?void 0:S.borderRadius,ct),ze=Me.scrollTop;e.style.cssText="",fe.style.cssText="",J.style.cssText="",Ae.style.cssText="",Me.style.cssText="",Ne.style.cssText="",K&&(Me.style.display="none");let Ke=()=>{var Vt;if(ze<=0)return;((Vt=Me.ownerDocument.defaultView)!=null?Vt:window).requestAnimationFrame(()=>{if(Me.scrollTop===ze)return;let Nt=Me.scrollHeight-Me.clientHeight;Nt<=0||(Me.scrollTop=Math.min(ze,Nt))})};if(Q){fe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),fe.style.cssText=`
34
+ `,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 ea=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: ${Se} !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;
@@ -56,7 +56,7 @@ _Details: ${n.message}_`:r}var ea=e=>({isError:!0,content:[{type:"text",text:e}]
56
56
  padding: 0 !important;
57
57
  box-shadow: none !important;
58
58
  border-radius: 0 !important;
59
- `,Ae.style.cssText=`
59
+ `,Se.style.cssText=`
60
60
  display: flex !important;
61
61
  flex-direction: column !important;
62
62
  flex: 1 1 0% !important;
@@ -67,20 +67,20 @@ _Details: ${n.message}_`:r}var ea=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
- `,Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.overflowY="auto",Ne.style.flexShrink="0",j=!0,Ke();return}let ft=(lo=(io=r==null?void 0:r.launcher)==null?void 0:io.width)!=null?lo:r==null?void 0:r.launcherWidth,I=ft!=null?ft:sr;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(ar(r).reveal==="emerge"){let Vt=ar(r).width;J.style.width=Vt,J.style.maxWidth=Vt}else J.style.width="100%",J.style.maxWidth="100%";if(xe(),J.style.boxShadow=Ie,J.style.borderRadius=Le,Ae.style.border=rt,Ae.style.borderRadius=Le,c&&!Q&&(S==null?void 0:S.border)===void 0&&(Ae.style.border="none",ar(r).side==="right"?Ae.style.borderLeft="1px solid var(--persona-border)":Ae.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%"),fe.style.display="flex",fe.style.flexDirection="column",fe.style.flex="1 1 0%",fe.style.minHeight="0",fe.style.maxHeight="100%",fe.style.height="100%",b&&(fe.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",Ae.style.display="flex",Ae.style.flexDirection="column",Ae.style.flex="1 1 0%",Ae.style.minHeight="0",Ae.style.maxHeight="100%",Ae.style.overflow="hidden",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.overflowY="auto",Ne.style.flexShrink="0"),fe.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!m&&!b&&!c&&((zr=hr[ve])!=null?zr:hr["bottom-right"]).split(" ").forEach(Vt=>fe.classList.add(Vt)),m){let Dt=(ur=(Ho=r.launcher)==null?void 0:Ho.sidebarWidth)!=null?ur:"420px";fe.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: ${Dt} !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: ${Se} !important;
81
+ z-index: ${Fe} !important;
82
82
  ${Oe?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
83
- `,J.style.cssText=`
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 ea=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: ${Ie} !important;
95
- border-radius: ${Le} !important;
96
- `,J.style.setProperty("width","100%","important"),J.style.setProperty("max-width","100%","important"),Ae.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 ea=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: ${Le} !important;
106
- border: ${rt} !important;
107
- `,Ne.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 Dt="max-height: -moz-available !important; max-height: stretch !important;",Vt=m?"":"padding-top: 1.25em !important;",Nt=m?"":`z-index: ${(Qe=(Pr=r.launcher)==null?void 0:Pr.zIndex)!=null?Qe:wn} !important;`;fe.style.cssText+=Dt+Vt+Nt}Ke()};Cr(),qo(e,r),hi(e,r),yi(e,r);let mt=[];mt.push(()=>{document.removeEventListener("keydown",no)});let rn=null,on=null;mt.push(()=>{rn==null||rn(),rn=null,on==null||on(),on=null}),Dn&&mt.push(()=>{Dn==null||Dn.disconnect(),Dn=null}),mt.push(()=>{Sn==null||Sn(),Sn=null,Fr(),Rt&&(Rt.remove(),Rt=null),bt==null||bt.element.style.removeProperty("width"),bt==null||bt.element.style.removeProperty("maxWidth")}),re&&mt.push(()=>{pe!==null&&(cancelAnimationFrame(pe),pe=null),We==null||We.destroy(),We=null,V==null||V.destroy(),V=null,be=null});let Ar=null,ks=()=>{Ar&&(Ar(),Ar=null),r.colorScheme==="auto"&&(Ar=cl(()=>{qo(e,r)}))};ks(),mt.push(()=>{Ar&&(Ar(),Ar=null)}),mt.push(a);let _r=(ad=r.features)==null?void 0:ad.streamAnimation;if(_r!=null&&_r.type&&_r.type!=="none"){let c=ia(_r.type,_r.plugins);c&&(ul(c,e),mt.push(()=>qm(e)))}let Eo=mg(Pt),Sr=null,$,Qo=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?Gi(m):null;h?Eo.render(h,$,ee,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(B=>B.role==="user")?Eo.render([],$,ee,m):Eo.render(r.suggestionChips,$,ee,m,r.suggestionChipsConfig)},Tr=!1,Er=Bm(),$r=new Map,Mr=new Map,cr=new Map,Yo=0,xa=No()!==null,_n=Qa(),$n=0,dr=null,pr=!1,Mo=!1,jr=0,bn=null,kr=null,Zo=!1,ko=!1,es=null,va=4,ts=24,wa=80,ns=new Map,pt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ls=(ld=(id=r.voiceRecognition)==null?void 0:id.autoResume)!=null?ld:!1,Zn=c=>{i.emit("voice:state",{active:pt.active,source:c,timestamp:Date.now()})},In=()=>{x(c=>({...c,voiceState:{active:pt.active,timestamp:Date.now(),manuallyDeactivated:pt.manuallyDeactivated}}))},Ca=()=>{var b,S;if(((b=r.voiceRecognition)==null?void 0:b.enabled)===!1)return;let c=Ol(p.voiceState),m=!!c.active,h=Number((S=c.timestamp)!=null?S:0);pt.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-h<Qv&&setTimeout(()=>{var B,q;pt.active||(pt.manuallyDeactivated=!1,((q=(B=r.voiceRecognition)==null?void 0:B.provider)==null?void 0:q.type)==="runtype"?$.toggleVoice().then(()=>{pt.active=$.isVoiceActive(),Zn("restore"),$.isVoiceActive()&&as()}):Sa("restore"))},1e3)},rs=()=>$?Pg($.getMessages()).filter(c=>!c.__skipPersist):[];function tt(c){if(!(l!=null&&l.save))return;let h={messages:c?Pg(c):$?rs():[],metadata:p,artifacts:Nn.artifacts,selectedArtifactId:Nn.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 w=null,z=()=>fe.querySelector("#persona-scroll-container")||Me,U=()=>{w!==null&&(cancelAnimationFrame(w),w=null),pr=!1},G=()=>{dr!==null&&(cancelAnimationFrame(dr),dr=null),Mo=!1,U()},ye=()=>{jr>0?(yn.textContent=String(jr),yn.style.display="",jt.setAttribute("aria-label",`${ht()||"Jump to latest"} (${jr} new)`)):(yn.textContent="",yn.style.display="none",jt.setAttribute("aria-label",ht()||"Jump to latest"))},_e=()=>{jr!==0&&(jr=0,ye())},gt=()=>Ft()==="follow"?!_n.isFollowing():!zo(Me,ts),st=()=>{if(!Qt()||K){jt.parentNode&&jt.remove(),jt.style.display="none";return}jt.parentNode!==Ae&&Ae.appendChild(jt),Jn();let m=Gr(Me)>0&&gt();m||_e(),jt.style.display=m?"":"none"},Ps=()=>{_n.pause()&&(G(),st())},Rn=()=>{_n.resume(),_e(),st()},dn=(c=!1)=>{Ft()==="follow"&&_n.isFollowing()&&(!c&&!Tr||(dr!==null&&(cancelAnimationFrame(dr),dr=null),Mo=!0,dr=requestAnimationFrame(()=>{dr=null,Mo=!1,_n.isFollowing()&&Lo(z(),c?220:140)})))},pn=(c,m,h,b=()=>!0)=>{let S=c.scrollTop,B=m(),q=B-S;U();let _=performance.now();pr=!0;let D=ie=>1-Math.pow(1-ie,3),ae=ie=>{if(!b()){U();return}let Q=m();Q!==B&&(B=Q,q=B-S);let ve=ie-_,Oe=Math.min(ve/h,1),Se=D(Oe),Ze=S+q*Se;c.scrollTop=Ze,$n=c.scrollTop,Oe<1?w=requestAnimationFrame(ae):(c.scrollTop=B,$n=c.scrollTop,w=null,pr=!1)};w=requestAnimationFrame(ae)},Lo=(c,m=500)=>{let h=Gr(c)-c.scrollTop;if(Math.abs(h)<1){$n=c.scrollTop;return}if(Math.abs(h)>=wa){U(),pr=!0,c.scrollTop=Gr(c),$n=c.scrollTop,pr=!1;return}pn(c,()=>Gr(c),m,()=>_n.isFollowing())},Ur=()=>{let c=z();pr=!0,c.scrollTop=Gr(c),$n=c.scrollTop,pr=!1,st()},Tn=c=>{kn.style.height=`${Math.max(0,Math.round(c))}px`,bn&&(bn.spacerHeight=Math.max(0,c))},fn=()=>{kr!==null&&(cancelAnimationFrame(kr),kr=null),U(),bn=null,kn.style.height="0px"},jn=c=>{kr!==null&&cancelAnimationFrame(kr),kr=requestAnimationFrame(()=>{var ae;kr=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),h=Me.querySelector(`[data-message-id="${m}"]`);if(!h)return;let b=0,S=h;for(;S&&S!==Me;)b+=S.offsetTop,S=S.offsetParent;let B=(ae=bn==null?void 0:bn.spacerHeight)!=null?ae:0,q=Me.scrollHeight-B,{targetScrollTop:_,spacerHeight:D}=_m({anchorOffsetTop:b,topOffset:Hn(),viewportHeight:Me.clientHeight,contentHeight:q});bn={initialSpacerHeight:D,contentHeightAtAnchor:q,spacerHeight:D},Tn(D),pn(Me,()=>_,220)})},mf=()=>{if(Ft()==="follow"){if(!_n.isFollowing()||zo(Me,1))return;dn(!Tr);return}if(bn&&bn.initialSpacerHeight>0){let c=Me.scrollHeight-bn.spacerHeight,m=$m({initialSpacerHeight:bn.initialSpacerHeight,contentHeightAtAnchor:bn.contentHeightAtAnchor,currentContentHeight:c});m!==bn.spacerHeight&&Tn(m)}st()},gf=c=>{let m=Ft();m==="follow"?(Rn(),dn(!0)):m==="anchor-top"&&jn(c)},ff=c=>{let m=new Map;c.forEach(h=>{let b=ns.get(h.id);m.set(h.id,{streaming:h.streaming,role:h.role}),!b&&h.role==="assistant"&&(i.emit("assistant:message",h),!ko&&Ft()!=="anchor-top"&&gt()&&(jr+=1,ye(),st())),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}))}),ns.clear(),m.forEach((h,b)=>{ns.set(b,h)})},hf=(c,m,h)=>{var rt,Ie,Le,ze,Ke,ft;let b=document.createElement("div"),B=(()=>{var Be;let I=o.find(Re=>Re.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((Be=r.loadingIndicator)!=null&&Be.render)return r.loadingIndicator.render})(),q=(I,Be)=>Be==null?!1:typeof Be=="string"?(I.textContent=Be,!0):(I.appendChild(Be),!0),_=new Set,D=new Set,ae=o.some(I=>I.renderAskUserQuestion),ie=[],Q=[],ve=r.enableComponentStreaming!==!1,Oe=r.approval!==!1,Se=[];if(m.forEach(I=>{var Je,Et,nn,nr,qn,Io,Ro,ls,cs,Jt,Wo,io,lo,zr,Ho,ur,Pr;_.add(I.id);let Be=ae&&po(I),Re=Oe&&I.variant==="approval"&&!!I.approval,ue=!Be&&I.role==="assistant"&&!I.variant&&ve&&Hl(I);if(!Re&&cr.has(I.id)){let Qe=c.querySelector(`#wrapper-${I.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime"),cr.delete(I.id)}if(!ue&&Mr.has(I.id)){let Qe=c.querySelector(`#wrapper-${I.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime"),Mr.delete(I.id)}let Bt=po(I)?`:${(Je=I.agentMetadata)!=null&&Je.askUserQuestionAnswered?"a":"u"}:${(Et=I.agentMetadata)!=null&&Et.askUserQuestionAnswers?Object.keys(I.agentMetadata.askUserQuestionAnswers).length:0}`:"",Wt=Hm(I,Yo)+Bt,Kt=Be||Re||ue?null:Dm(Er,I.id,Wt);if(Kt){b.appendChild(Kt.cloneNode(!0)),po(I)&&((nn=I.toolCall)!=null&&nn.id)&&((nr=I.agentMetadata)==null?void 0:nr.awaitingLocalTool)===!0&&!((qn=I.agentMetadata)!=null&&qn.askUserQuestionAnswered)&&(D.add(I.toolCall.id),Ks(I,r,qe.composerOverlay));return}let yt=null,qt=o.find(Qe=>!!(I.variant==="reasoning"&&Qe.renderReasoning||I.variant==="tool"&&Qe.renderToolCall||!I.variant&&Qe.renderMessage)),Un=(Io=r.layout)==null?void 0:Io.messages;if(po(I)&&((Ro=I.agentMetadata)==null?void 0:Ro.askUserQuestionAnswered)===!0){$r.delete(I.id);let Qe=c.querySelector(`#wrapper-${I.id}`);Qe==null||Qe.removeAttribute("data-preserve-runtime");return}if(Ha(I)&&((cs=(ls=r.features)==null?void 0:ls.suggestReplies)==null?void 0:cs.enabled)!==!1)return;if(po(I)&&((Wo=(Jt=r.features)==null?void 0:Jt.askUserQuestion)==null?void 0:Wo.enabled)!==!1){let Qe=o.find(Dt=>typeof Dt.renderAskUserQuestion=="function");if(Qe&&Ct.current){let Dt=$r.get(I.id),Vt=Dt!==Wt,Nt=null;if(Vt){let{payload:_t,complete:un}=uo(I),zn=I.id,Ir=()=>{var mn;return(mn=Ct.current)==null?void 0:mn.getMessages().find(gn=>gn.id===zn)};Nt=Qe.renderAskUserQuestion({message:I,payload:_t,complete:un,resolve:mn=>{var rr;let gn=Ir();gn&&((rr=Ct.current)==null||rr.resolveAskUserQuestion(gn,mn))},dismiss:()=>{var gn,rr,co;let mn=Ir();(gn=mn==null?void 0:mn.agentMetadata)!=null&&gn.awaitingLocalTool&&((rr=Ct.current)==null||rr.markAskUserQuestionResolved(mn),(co=Ct.current)==null||co.resolveAskUserQuestion(mn,"(dismissed)"))},config:r})}let Xt=Dt!=null;if(Vt&&Nt===null&&!Xt){((io=I.agentMetadata)==null?void 0:io.awaitingLocalTool)===!0&&!((lo=I.agentMetadata)!=null&&lo.askUserQuestionAnswered)&&(D.add(I.toolCall.id),Ks(I,r,qe.composerOverlay));return}let Mt=document.createElement("div");Mt.className="persona-flex",Mt.id=`wrapper-${I.id}`,Mt.setAttribute("data-wrapper-id",I.id),Mt.setAttribute("data-ask-plugin-stub","true"),Mt.setAttribute("data-preserve-runtime","true"),b.appendChild(Mt),ie.push({messageId:I.id,fingerprint:Wt,bubble:Nt});return}else{((zr=I.agentMetadata)==null?void 0:zr.awaitingLocalTool)===!0&&!((Ho=I.agentMetadata)!=null&&Ho.askUserQuestionAnswered)&&(D.add(I.toolCall.id),Ks(I,r,qe.composerOverlay));return}}else if(Re){let Qe=(ur=o.find(Xt=>typeof Xt.renderApproval=="function"))!=null?ur:s,Vt=cr.get(I.id)!==Wt,Nt=null;if(Vt&&(Qe!=null&&Qe.renderApproval)){let Xt=I.id,Mt=(_t,un)=>{var Ir,mn,gn;let zn=(Ir=Ct.current)==null?void 0:Ir.getMessages().find(rr=>rr.id===Xt);zn!=null&&zn.approval&&(zn.approval.toolType==="webmcp"?(mn=Ct.current)==null||mn.resolveWebMcpApproval(zn.id,_t):(gn=Ct.current)==null||gn.resolveApproval(zn.approval,_t,un))};Nt=Qe.renderApproval({message:I,defaultRenderer:()=>gi(I,r),config:r,approve:_t=>Mt("approved",_t),deny:_t=>Mt("denied",_t)})}if(Vt&&Nt===null){let Xt=c.querySelector(`#wrapper-${I.id}`);Xt==null||Xt.removeAttribute("data-preserve-runtime"),cr.delete(I.id),yt=gi(I,r)}else{let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${I.id}`,Xt.setAttribute("data-wrapper-id",I.id),Xt.setAttribute("data-approval-plugin-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),b.appendChild(Xt),Se.push({messageId:I.id,fingerprint:Wt,bubble:Nt});return}}else if(qt)if(I.variant==="reasoning"&&I.reasoning&&qt.renderReasoning){if(!Ce)return;yt=qt.renderReasoning({message:I,defaultRenderer:()=>wl(I,r),config:r})}else if(I.variant==="tool"&&I.toolCall&&qt.renderToolCall){if(!ke)return;yt=qt.renderToolCall({message:I,defaultRenderer:()=>Al(I,r),config:r})}else qt.renderMessage&&(yt=qt.renderMessage({message:I,defaultRenderer:()=>{let Qe=ga(I,h,Un,r.messageActions,ge,{loadingIndicatorRenderer:B,widgetConfig:r});return I.role!=="user"&&kl(Qe,I,r,$),Qe},config:r}));if(!yt&&ue){let Qe=Bl(I);if(Qe){let Dt=Mr.get(I.id),Vt=Dt!==Wt,Nt=r.wrapComponentDirectiveInBubble!==!1,Xt=null;if(Vt){let Mt=Wl(Qe,{config:r,message:I,transform:h});if(Mt)if(Nt){let _t=document.createElement("div");if(_t.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(" "),_t.id=`bubble-${I.id}`,_t.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}),_t.appendChild(un)}_t.appendChild(Mt),Xt=_t}else{let _t=document.createElement("div");if(_t.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",_t.id=`bubble-${I.id}`,_t.setAttribute("data-message-id",I.id),_t.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}),_t.appendChild(un)}_t.appendChild(Mt),Xt=_t}}if(Xt||Dt!=null){let Mt=document.createElement("div");Mt.className="persona-flex",Mt.id=`wrapper-${I.id}`,Mt.setAttribute("data-wrapper-id",I.id),Mt.setAttribute("data-component-directive-stub","true"),Mt.setAttribute("data-preserve-runtime","true"),Nt||Mt.classList.add("persona-w-full"),b.appendChild(Mt),Q.push({messageId:I.id,fingerprint:Wt,bubble:Xt});return}}}if(!yt)if(I.variant==="reasoning"&&I.reasoning){if(!Ce)return;yt=wl(I,r)}else if(I.variant==="tool"&&I.toolCall){if(!ke)return;yt=Al(I,r)}else if(I.variant==="approval"&&I.approval){if(r.approval===!1)return;yt=gi(I,r)}else{let Qe=(Pr=r.layout)==null?void 0:Pr.messages;Qe!=null&&Qe.renderUserMessage&&I.role==="user"?yt=Qe.renderUserMessage({message:I,config:r,streaming:!!I.streaming}):Qe!=null&&Qe.renderAssistantMessage&&I.role==="assistant"?yt=Qe.renderAssistantMessage({message:I,config:r,streaming:!!I.streaming}):yt=ga(I,h,Qe,r.messageActions,ge,{loadingIndicatorRenderer:B,widgetConfig:r}),I.role!=="user"&&yt&&kl(yt,I,r,$)}let en=document.createElement("div");en.className="persona-flex",en.id=`wrapper-${I.id}`,en.setAttribute("data-wrapper-id",I.id),I.role==="user"&&en.classList.add("persona-justify-end"),(yt==null?void 0:yt.getAttribute("data-persona-component-directive"))==="true"&&en.classList.add("persona-w-full"),en.appendChild(yt),Nm(Er,I.id,Wt,en),b.appendChild(en)}),qe.composerOverlay&&qe.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let Re=Be.getAttribute("data-persona-ask-sheet-for");Re&&!D.has(Re)&&_o(qe.composerOverlay,Re)}),(Ie=(rt=r.features)==null?void 0:rt.toolCallDisplay)!=null&&Ie.grouped){let I=[],Be=[];m.forEach(Re=>{if(Re.variant==="tool"&&Re.toolCall&&ke){Be.push(Re);return}Be.length>1&&I.push(Be),Be=[]}),Be.length>1&&I.push(Be),I.forEach((Re,ue)=>{var Je,Et;let Bt=Re.map(nn=>Array.from(b.children).find(nr=>nr instanceof HTMLElement&&nr.getAttribute("data-wrapper-id")===nn.id)).filter(nn=>!!nn);if(Bt.length<2)return;let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id=`wrapper-tool-group-${ue}-${Re[0].id}`,Wt.setAttribute("data-wrapper-id",`tool-group-${ue}-${Re[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 yt=document.createElement("div");yt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let qt=`Called ${Re.length} tools`,Un=(Et=(Je=r.toolCall)==null?void 0:Je.renderGroupedSummary)==null?void 0:Et.call(Je,{messages:Re,toolCalls:Re.map(nn=>nn.toolCall).filter(nn=>!!nn),defaultSummary:qt,config:r});q(yt,Un)||(yt.textContent=qt);let en=document.createElement("div");en.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(yt,en),Wt.appendChild(Kt),Bt[0].before(Wt),Bt.forEach((nn,nr)=>{let qn=document.createElement("div");qn.className="persona-tool-group-item persona-relative",qn.setAttribute("data-persona-tool-group-item","true"),nr<Bt.length-1&&qn.setAttribute("data-persona-tool-group-connector","true"),qn.appendChild(nn),en.appendChild(qn)})})}Om(Er,_);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(Tr&&m.some(I=>I.role==="user")&&!Ze&&!ct){let I={config:r,streaming:!0,location:"standalone",defaultRenderer:Cs},Be=o.find(ue=>ue.renderLoadingIndicator),Re=null;if(Be!=null&&Be.renderLoadingIndicator&&(Re=Be.renderLoadingIndicator(I)),Re===null&&((Le=r.loadingIndicator)!=null&&Le.render)&&(Re=r.loadingIndicator.render(I)),Re===null&&(Re=Cs()),Re){let ue=document.createElement("div"),Bt=((ze=r.loadingIndicator)==null?void 0:ze.showBubble)!==!1;ue.className=Bt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ue.setAttribute("data-typing-indicator","true"),ue.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ue.appendChild(Re);let Wt=document.createElement("div");Wt.className="persona-flex",Wt.id="wrapper-typing-indicator",Wt.setAttribute("data-wrapper-id","typing-indicator"),Wt.appendChild(ue),b.appendChild(Wt)}}if(!Tr&&m.length>0){let I=m[m.length-1],Be={config:r,lastMessage:I,messageCount:m.length},Re=o.find(Bt=>Bt.renderIdleIndicator),ue=null;if(Re!=null&&Re.renderIdleIndicator&&(ue=Re.renderIdleIndicator(Be)),ue===null&&((Ke=r.loadingIndicator)!=null&&Ke.renderIdle)&&(ue=r.loadingIndicator.renderIdle(Be)),ue){let Bt=document.createElement("div"),Wt=((ft=r.loadingIndicator)==null?void 0:ft.showBubble)!==!1;Bt.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-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(" "),Bt.setAttribute("data-idle-indicator","true"),Bt.appendChild(ue);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-idle-indicator",Kt.setAttribute("data-wrapper-id","idle-indicator"),Kt.appendChild(Bt),b.appendChild(Kt)}}if(Ja(c,b),ie.length>0)for(let{messageId:I,fingerprint:Be,bubble:Re}of ie){let ue=c.querySelector(`#wrapper-${I}`);ue&&Re!==null&&(ue.replaceChildren(Re),ue.setAttribute("data-bubble-fp",Be),$r.set(I,Be))}if($r.size>0)for(let I of $r.keys())_.has(I)||$r.delete(I);if(Q.length>0)for(let{messageId:I,fingerprint:Be,bubble:Re}of Q){let ue=c.querySelector(`#wrapper-${I}`);ue&&Re!==null&&(ue.replaceChildren(Re),ue.setAttribute("data-bubble-fp",Be),Mr.set(I,Be))}if(Mr.size>0)for(let I of Mr.keys())_.has(I)||Mr.delete(I);if(Se.length>0)for(let{messageId:I,fingerprint:Be,bubble:Re}of Se){let ue=c.querySelector(`#wrapper-${I}`);ue&&Re!==null&&(ue.replaceChildren(Re),ue.setAttribute("data-bubble-fp",Be),cr.set(I,Be))}if(cr.size>0)for(let I of cr.keys())_.has(I)||cr.delete(I)},Is=(c,m,h)=>{hf(c,m,h),eo()},Rs=null,yf=()=>{var h;if(Rs)return;let c=b=>{let S=b.composedPath();S.includes(fe)||dt&&S.includes(dt)||Ut(!1,"user")};Rs=c,((h=e.ownerDocument)!=null?h:document).addEventListener("pointerdown",c,!0)},Xl=()=>{var m;if(!Rs)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",Rs,!0),Rs=null};mt.push(()=>Xl());let Ws=null,bf=()=>{var h;if(Ws)return;let c=b=>{b.key==="Escape"&&(b.isComposing||Ut(!1,"user"))};Ws=c,((h=e.ownerDocument)!=null?h:document).addEventListener("keydown",c,!0)},Ql=()=>{var m;if(!Ws)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",Ws,!0),Ws=null};mt.push(()=>Ql());let Hs=!1,Yl=new Set,xf=()=>{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)},os=()=>{var ct,rt,Ie,Le;if(!W())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,B=!!b.streaming,q=xf(),_=ei(q),D=_.type!=="none"?ia(_.type,q==null?void 0:q.plugins):null,ae=((rt=D==null?void 0:D.isAnimating)==null?void 0:rt.call(D,b))===!0,ie=D!==null&&(B||ae);ie&&D&&!Yl.has(D.name)&&(ul(D,e),Yl.add(D.name));let Q=ie&&(D!=null&&D.containerClass)?D.containerClass:null,ve=(Ie=m.dataset.personaPeekStreamClass)!=null?Ie:null;ve&&ve!==Q&&(m.classList.remove(ve),delete m.dataset.personaPeekStreamClass),Q&&ve!==Q&&(m.classList.add(Q),m.dataset.personaPeekStreamClass=Q),ie?(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=ie?ti(S,_.buffer,D,b,B):S;if(ie&&_.placeholder==="skeleton"&&B&&(!Oe||!Oe.trim())){let ze=document.createElement("div"),Ke=ca();Ke.classList.add("persona-pill-peek__skeleton"),ze.appendChild(Ke),Ja(m,ze)}else{let ze=Math.max(0,Oe.length-100),Ke=Oe.length>100?Oe.slice(-100):Oe,ft=Vr(Ke);if(!ie||!D){let I=Oe.length>100?`\u2026${Ke}`:Ke;m.textContent!==I&&(m.textContent=I)}else{let I=ft;(D.wrap==="char"||D.wrap==="word")&&(I=la(ft,D.wrap,`peek-${b.id}`,{skipTags:D.skipTags,startIndex:ze}));let Be=document.createElement("div");if(Be.innerHTML=I,D.useCaret&&Ke.length>0){let Re=ni(),ue=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),Bt=ue[ue.length-1];Bt!=null&&Bt.parentNode?Bt.parentNode.insertBefore(Re,Bt.nextSibling):Be.appendChild(Re)}Ja(m,Be),(Le=D.onAfterRender)==null||Le.call(D,{container:m,bubble:c,messageId:b.id,message:b,speed:_.speed,duration:_.duration})}}let Ue=Tr||Hs;c.classList.toggle("persona-pill-peek--visible",Ue)};if(W()){let c=qe.peekBanner;if(c){let b=S=>{S.preventDefault(),S.stopPropagation(),Ut(!0,"user")};c.addEventListener("pointerdown",b),mt.push(()=>{c.removeEventListener("pointerdown",b)})}let m=()=>{Hs||(Hs=!0,os())},h=()=>{Hs&&(Hs=!1,os())};J.addEventListener("pointerenter",m),J.addEventListener("pointerleave",h),mt.push(()=>{J.removeEventListener("pointerenter",m),J.removeEventListener("pointerleave",h)}),dt&&(dt.addEventListener("pointerenter",m),dt.addEventListener("pointerleave",h),mt.push(()=>{dt.removeEventListener("pointerenter",m),dt.removeEventListener("pointerleave",h)}))}let vf=c=>{var ve,Oe,Se,Ze,Ue,ct,rt,Ie;let m=(Oe=(ve=r.launcher)==null?void 0:ve.composerBar)!=null?Oe:{},h=(Se=m.expandedSize)!=null?Se:"anchored",b=(Ze=m.bottomOffset)!=null?Ze:"16px",S=m.collapsedMaxWidth,B=(Ue=m.expandedMaxWidth)!=null?Ue:"880px",q=(ct=m.expandedTopOffset)!=null?ct:"5vh",_=(rt=m.modalMaxWidth)!=null?rt:"880px",D=(Ie=m.modalMaxHeight)!=null?Ie:"min(90vh, 800px)",ae="calc(100vw - 32px)",ie="var(--persona-pill-area-height, 80px)",Q=fe.style;if(Q.left="",Q.right="",Q.top="",Q.bottom="",Q.transform="",Q.width="",Q.maxWidth="",Q.height="",Q.maxHeight="",dt){let Le=dt.style;Le.bottom=b,Le.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=ae,Q.maxHeight=D,Q.height=D;return}Q.left="50%",Q.transform="translateX(-50%)",Q.bottom=`calc(${b} + ${ie})`,Q.top=q,Q.width=B,Q.maxWidth=ae}},Bs=()=>{var D,ae,ie,Q,ve,Oe,Se,Ze;if(!O())return;if(W()){let ct=(ie=((ae=(D=r.launcher)==null?void 0:D.composerBar)!=null?ae:{}).expandedSize)!=null?ie:"anchored",rt=N?"expanded":"collapsed";fe.dataset.state=rt,fe.dataset.expandedSize=ct,dt&&(dt.dataset.state=rt,dt.dataset.expandedSize=ct),fe.style.removeProperty("display"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),vf(N),Ae.style.display=N?"flex":"none",Cr(),N?(yf(),bf()):(Xl(),Ql()),os();return}let c=cn(r),m=(Q=e.ownerDocument.defaultView)!=null?Q:window,h=(Oe=(ve=r.launcher)==null?void 0:ve.mobileBreakpoint)!=null?Oe:640,b=(Ze=(Se=r.launcher)==null?void 0:Se.mobileFullscreen)!=null?Ze:!0,S=m.innerWidth<=h,B=b&&S&&k,q=ar(r).reveal;N?(fe.style.removeProperty("display"),fe.style.display=c?"flex":"",fe.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"),Zt?Zt.element.style.display="none":sn&&(sn.style.display="none")):(c?c&&(q==="overlay"||q==="push")&&!B?(fe.style.removeProperty("display"),fe.style.display="flex",fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.setProperty("display","none","important"),fe.classList.remove("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(fe.style.display="",fe.classList.add("persona-pointer-events-none","persona-opacity-0"),J.classList.remove("persona-scale-100","persona-opacity-100"),J.classList.add("persona-scale-95","persona-opacity-0")),Zt?Zt.element.style.display=c?"none":"":sn&&(sn.style.display=c?"none":""))},Ut=(c,m="user")=>{var B,q;if(!O()||N===c)return;let h=N;N=c,Bs();let b=(()=>{var Se,Ze,Ue,ct,rt,Ie,Le,ze,Ke,ft;let _=(Ze=(Se=r.launcher)==null?void 0:Se.sidebarMode)!=null?Ze:!1,D=(Ue=e.ownerDocument.defaultView)!=null?Ue:window,ae=(rt=(ct=r.launcher)==null?void 0:ct.mobileFullscreen)!=null?rt:!0,ie=(Le=(Ie=r.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Le:640,Q=D.innerWidth<=ie,ve=cn(r)&&ae&&Q,Oe=W()&&((ft=(Ke=(ze=r.launcher)==null?void 0:ze.composerBar)==null?void 0:Ke.expandedSize)!=null?ft:"fullscreen")==="fullscreen";return _||ae&&Q&&k||ve||Oe})();if(N&&b){if(!rn){let _=e.getRootNode(),D=_ instanceof ShadowRoot?_.host:e.closest(".persona-host");D&&(rn=ml(D,(q=(B=r.launcher)==null?void 0:B.zIndex)!=null?q:wn))}on||(on=gl(e.ownerDocument))}else N||(rn==null||rn(),rn=null,on==null||on(),on=null);N&&(Ds(),Ft()==="follow"?dn(!0):Ur());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:pt.active,streaming:$.isStreaming()})},Pi=c=>{ce(c?"stop":"send"),H&&(H.disabled=c),Eo.buttons.forEach(m=>{m.disabled=c}),Ne.dataset.personaComposerStreaming=c?"true":"false",Ne.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},Ii=()=>{pt.active||ee&&ee.focus()};i.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>Ii(),200)});let Zl=()=>{var h,b,S,B,q,_,D,ae,ie,Q,ve;yr.textContent=(b=(h=r.copy)==null?void 0:h.welcomeTitle)!=null?b:"Hello \u{1F44B}",br.textContent=(B=(S=r.copy)==null?void 0:S.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",ee.placeholder=(_=(q=r.copy)==null?void 0:q.inputPlaceholder)!=null?_:"How can I help...";let c=Me.querySelector("[data-persona-intro-card]");if(c){let Oe=((D=r.copy)==null?void 0:D.showWelcomeCard)!==!1;c.style.display=Oe?"":"none",Oe?(Me.classList.remove("persona-gap-3"),Me.classList.add("persona-gap-6")):(Me.classList.remove("persona-gap-6"),Me.classList.add("persona-gap-3"))}!((ie=(ae=r.sendButton)==null?void 0:ae.useIcon)!=null&&ie)&&!($!=null&&$.isStreaming())&&(je.textContent=(ve=(Q=r.copy)==null?void 0:Q.sendButtonLabel)!=null?ve:"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 Po=null,wf=()=>{Po==null&&(Po=setInterval(()=>{let c=nt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Po),Po=null;return}let m=Date.now();c.forEach(h=>{let b=Number(h.getAttribute("data-tool-elapsed"));b&&(h.textContent=Na(m-b))})},100))};$=new ta(r,{onMessagesChanged(c){var b;Is(nt,c,Z),wf(),Qo(c),dn(!Tr),ff(c);let m=[...c].reverse().find(S=>S.role==="user");c.length===0&&fn(),!Zo||ko?(Zo=!0,es=(b=m==null?void 0:m.id)!=null?b:null):m&&m.id!==es&&(es=m.id,gf(m.id));let h=pt.lastUserMessageId;m&&m.id!==h&&(pt.lastUserMessageId=m.id,i.emit("user:message",m)),pt.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),tt(c),os()},onStatusChanged(c){var b;let m=(b=r.statusIndicator)!=null?b:{};$t(hn,(S=>{var B,q,_,D;return S==="idle"?(B=m.idleText)!=null?B:vn.idle:S==="connecting"?(q=m.connectingText)!=null?q:vn.connecting:S==="connected"?(_=m.connectedText)!=null?_:vn.connected:S==="error"?(D=m.errorText)!=null?D:vn.error:vn[S]})(c),m,c)},onStreamingChanged(c){Tr=c,Pi(c),$&&Is(nt,$.getMessages(),Z),c||dn(!0),os()},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":qr(),as();break;case"processing":qr(),Ef();break;case"speaking":qr(),Mf();break;default:c==="idle"&&$.isBargeInActive()?(qr(),as(),H==null||H.setAttribute("aria-label","End voice session")):(pt.active=!1,qr(),Zn("system"),In());break}},onArtifactsState(c){Nn=c,Pn(),tt()}}),Ct.current=$;let Ri=null;if($.onReadAloudChange((c,m)=>{var S;Yr=c,Zr=m,eo();let h=c!=null?c:Ri;c&&(Ri=c);let b=h&&(S=$.getMessages().find(B=>B.id===h))!=null?S:null;i.emit("message:read-aloud",{messageId:h,message:b,state:m,timestamp:Date.now()}),m==="idle"&&(Ri=null)}),Zo=!0,((dd=(cd=r.voiceRecognition)==null?void 0:cd.provider)==null?void 0:dd.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=Ol(c.metadata),L.syncFromMetadata()),(m=c.messages)!=null&&m.length){ko=!0;try{$.hydrateMessages(c.messages)}finally{ko=!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 ec=()=>{var m,h,b;!W()||N||!((b=(h=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:h.expandOnSubmit)==null||b)||Ut(!0,"auto")},tc=c=>{var S;if(c.preventDefault(),$.isStreaming()){$.cancel(),X==null||X.reset(),We==null||We.update();return}let m=ee.value.trim(),h=(S=wt==null?void 0:wt.hasAttachments())!=null?S:!1;if(!m&&!h)return;ec();let b;h&&(b=[],b.push(...wt.getContentParts()),m&&b.push(ja(m))),ee.value="",ee.style.height="auto",Aa(),$.sendMessage(m,{contentParts:b}),h&&wt.clearAttachments()},Cf=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},Wi={...Xa},Hi=!1,Aa=()=>{Wi={...Xa}},Af=()=>$.getMessages().filter(c=>c.role==="user").map(c=>{var m;return(m=c.content)!=null?m:""}).filter(c=>c.length>0),Sf=c=>{if(!ee)return;Hi=!0,ee.value=c,ee.dispatchEvent(new Event("input",{bubbles:!0})),Hi=!1;let m=ee.value.length;ee.setSelectionRange(m,m)},nc=()=>{Hi||Aa()},rc=c=>{if(ee){if(Cf()&&(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=Wm({direction:c.key==="ArrowUp"?"up":"down",history:Af(),currentValue:ee.value,atStart:m,state:Wi});if(Wi=h.state,h.handled){c.preventDefault(),h.value!==void 0&&Sf(h.value);return}}if(c.key==="Enter"&&!c.shiftKey){if($.isStreaming()){c.preventDefault();return}Aa(),c.preventDefault(),je.click()}}},oc=c=>{c.key!=="Escape"||c.isComposing||$.isStreaming()&&c.composedPath().includes(Ae)&&($.cancel(),X==null||X.reset(),We==null||We.update(),Aa(),c.preventDefault(),c.stopImmediatePropagation())},sc=async c=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!wt)return;let m=Zv(c.clipboardData);m.length!==0&&(c.preventDefault(),await wt.handleFiles(m))},er=null,Lr=!1,ss=null,lt=null,ac=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Sa=(c="user")=>{var B,q,_,D,ae,ie,Q;if(Lr||$.isStreaming())return;let m=ac();if(!m)return;er=new m;let b=(q=((B=r.voiceRecognition)!=null?B:{}).pauseDuration)!=null?q:2e3;er.continuous=!0,er.interimResults=!0,er.lang="en-US";let S=ee.value;er.onresult=ve=>{let Oe="",Se="";for(let Ue=0;Ue<ve.results.length;Ue++){let ct=ve.results[Ue],rt=ct[0].transcript;ct.isFinal?Oe+=rt+" ":Se=rt}let Ze=S+Oe+Se;ee.value=Ze,ss&&clearTimeout(ss),(Oe||Se)&&(ss=window.setTimeout(()=>{let Ue=ee.value.trim();Ue&&er&&Lr&&(so(),ee.value="",ee.style.height="auto",$.sendMessage(Ue,{viaVoice:!0}))},b))},er.onerror=ve=>{ve.error!=="no-speech"&&so()},er.onend=()=>{if(Lr){let ve=ee.value.trim();ve&&ve!==S.trim()&&(ee.value="",ee.style.height="auto",$.sendMessage(ve,{viaVoice:!0})),so()}};try{if(er.start(),Lr=!0,pt.active=!0,c!=="system"&&(pt.manuallyDeactivated=!1),Zn(c),In(),H){let ve=(_=r.voiceRecognition)!=null?_:{};lt={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(D=ve.iconName)!=null?D:"mic",iconSize:parseFloat((Q=(ie=ve.iconSize)!=null?ie:(ae=r.sendButton)==null?void 0:ae.size)!=null?Q:"40")||24};let Oe=ve.recordingBackgroundColor,Se=ve.recordingIconColor,Ze=ve.recordingBorderColor;if(H.classList.add("persona-voice-recording"),H.style.backgroundColor=Oe!=null?Oe:"var(--persona-voice-recording-bg, #ef4444)",H.style.color=Se!=null?Se:"var(--persona-voice-recording-indicator, #ffffff)",Se){let Ue=H.querySelector("svg");Ue&&Ue.setAttribute("stroke",Se)}Ze&&(H.style.borderColor=Ze),H.setAttribute("aria-label","Stop voice recognition")}}catch{so("system")}},so=(c="user")=>{if(Lr){if(Lr=!1,ss&&(clearTimeout(ss),ss=null),er){try{er.stop()}catch{}er=null}if(pt.active=!1,Zn(c),In(),H){if(H.classList.remove("persona-voice-recording"),lt){H.style.backgroundColor=lt.backgroundColor,H.style.color=lt.color,H.style.borderColor=lt.borderColor;let m=H.querySelector("svg");m&&m.setAttribute("stroke",lt.color||"currentColor"),lt=null}H.setAttribute("aria-label","Start voice recognition")}}},Tf=(c,m)=>{var rt,Ie,Le,ze,Ke,ft,I,Be,Re;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=((Ie=c==null?void 0:c.provider)==null?void 0:Ie.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=(Le=c==null?void 0:c.iconName)!=null?Le:"mic",ae=(ze=m==null?void 0:m.size)!=null?ze:"40px",ie=(Ke=c==null?void 0:c.iconSize)!=null?Ke:ae,Q=parseFloat(ie)||24,ve=(ft=c==null?void 0:c.backgroundColor)!=null?ft:m==null?void 0:m.backgroundColor,Oe=(I=c==null?void 0:c.iconColor)!=null?I:m==null?void 0:m.textColor;_.style.width=ie,_.style.height=ie,_.style.minWidth=ie,_.style.minHeight=ie,_.style.fontSize="18px",_.style.lineHeight="1",Oe?_.style.color=Oe:_.style.color="var(--persona-text, #111827)";let Ze=me(D,Q,Oe||"currentColor",1.5);Ze?_.appendChild(Ze):_.textContent="\u{1F3A4}",ve?_.style.backgroundColor=ve:_.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=(Be=c==null?void 0:c.tooltipText)!=null?Be:"Start voice recognition";if(((Re=c==null?void 0:c.showTooltip)!=null?Re:!1)&&Ue){let ue=y("div","persona-send-button-tooltip");ue.textContent=Ue,q.appendChild(ue)}return{micButton:_,micButtonWrapper:q}},Bi=()=>{var m,h,b,S,B;if(!H||lt)return;let c=(m=r.voiceRecognition)!=null?m:{};lt={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(h=c.iconName)!=null?h:"mic",iconSize:parseFloat((B=(S=c.iconSize)!=null?S:(b=r.sendButton)==null?void 0:b.size)!=null?B:"40")||24}},Di=(c,m)=>{var B,q,_,D,ae;if(!H)return;let h=H.querySelector("svg");h&&h.remove();let b=(ae=lt==null?void 0:lt.iconSize)!=null?ae:parseFloat((D=(_=(B=r.voiceRecognition)==null?void 0:B.iconSize)!=null?_:(q=r.sendButton)==null?void 0:q.size)!=null?D:"40")||24,S=me(c,b,m,1.5);S&&H.appendChild(S)},Ta=()=>{H&&H.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},as=()=>{var S;if(!H)return;Bi();let c=(S=r.voiceRecognition)!=null?S:{},m=c.recordingBackgroundColor,h=c.recordingIconColor,b=c.recordingBorderColor;if(Ta(),H.classList.add("persona-voice-recording"),H.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",H.style.color=h!=null?h:"var(--persona-voice-recording-indicator, #ffffff)",h){let B=H.querySelector("svg");B&&B.setAttribute("stroke",h)}b&&(H.style.borderColor=b),H.setAttribute("aria-label","Stop voice recognition")},Ef=()=>{var _,D,ae,ie,Q,ve,Oe,Se;if(!H)return;Bi();let c=(_=r.voiceRecognition)!=null?_:{},m=$.getVoiceInterruptionMode(),h=(D=c.processingIconName)!=null?D:"loader",b=(ie=(ae=c.processingIconColor)!=null?ae:lt==null?void 0:lt.color)!=null?ie:"",S=(ve=(Q=c.processingBackgroundColor)!=null?Q:lt==null?void 0:lt.backgroundColor)!=null?ve:"",B=(Se=(Oe=c.processingBorderColor)!=null?Oe:lt==null?void 0:lt.borderColor)!=null?Se:"";Ta(),H.classList.add("persona-voice-processing"),H.style.backgroundColor=S,H.style.borderColor=B;let q=b||"currentColor";H.style.color=q,Di(h,q),H.setAttribute("aria-label","Processing voice input"),m==="none"&&(H.style.cursor="default")},Mf=()=>{var ae,ie,Q,ve,Oe,Se,Ze,Ue,ct,rt,Ie,Le;if(!H)return;Bi();let c=(ae=r.voiceRecognition)!=null?ae:{},m=$.getVoiceInterruptionMode(),h=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",b=(ie=c.speakingIconName)!=null?ie:h,S=(Se=c.speakingIconColor)!=null?Se:m==="barge-in"?(ve=(Q=c.recordingIconColor)!=null?Q:lt==null?void 0:lt.color)!=null?ve:"":(Oe=lt==null?void 0:lt.color)!=null?Oe:"",B=(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=(Le=c.speakingBorderColor)!=null?Le:m==="barge-in"?(rt=c.recordingBorderColor)!=null?rt:"":(Ie=lt==null?void 0:lt.borderColor)!=null?Ie:"";Ta(),H.classList.add("persona-voice-speaking"),H.style.backgroundColor=B,H.style.borderColor=q;let _=S||"currentColor";H.style.color=_,Di(b,_);let D=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";H.setAttribute("aria-label",D),m==="none"&&(H.style.cursor="default"),m==="barge-in"&&H.classList.add("persona-voice-recording")},qr=()=>{var c,m,h;H&&(Ta(),lt&&(H.style.backgroundColor=(c=lt.backgroundColor)!=null?c:"",H.style.color=(m=lt.color)!=null?m:"",H.style.borderColor=(h=lt.borderColor)!=null?h:"",Di(lt.iconName,lt.color||"currentColor"),lt=null),H.style.cursor="",H.setAttribute("aria-label","Start voice recognition"))},Ea=()=>{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(()=>{pt.active=!1,pt.manuallyDeactivated=!0,In(),Zn("user"),qr()});return}$.toggleVoice().then(()=>{pt.active=$.isVoiceActive(),pt.manuallyDeactivated=!$.isVoiceActive(),In(),Zn("user"),$.isVoiceActive()?as():qr()});return}if(Lr){let h=ee.value.trim();pt.manuallyDeactivated=!0,In(),so("user"),h&&(ee.value="",ee.style.height="auto",$.sendMessage(h))}else pt.manuallyDeactivated=!1,In(),Sa("user")};xr=Ea,H&&(H.addEventListener("click",Ea),mt.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),qr()):so("system"),H&&H.removeEventListener("click",Ea)}));let kf=i.on("assistant:complete",()=>{Ls&&(pt.active||pt.manuallyDeactivated||Ls==="assistant"&&!pt.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!pt.active&&!pt.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?$.toggleVoice().then(()=>{pt.active=$.isVoiceActive(),Zn("auto"),$.isVoiceActive()&&as()}):Sa("auto"))},600))});mt.push(kf);let Lf=i.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});mt.push(Lf);let ic=()=>{Ut(!N,"user")},Zt=null,sn=null;if(k&&!W()){let{instance:c,element:m}=bl({config:r,plugins:o,onToggle:ic});Zt=c,c||(sn=m)}Zt?e.appendChild(Zt.element):sn&&e.appendChild(sn),Bs(),Qo(),Zl(),Pi($.isStreaming()),Ft()==="follow"?dn(!0):Ur(),Ca(),P&&(!k||W()?setTimeout(()=>Ii(),0):N&&setTimeout(()=>Ii(),200));let Ds=()=>{var D,ae,ie,Q,ve,Oe,Se,Ze,Ue,ct,rt,Ie,Le,ze,Ke,ft,I,Be,Re,ue,Bt,Wt;if(W()){Jn(),Bs();return}let c=cn(r),m=(ae=(D=r.launcher)==null?void 0:D.sidebarMode)!=null?ae:!1,h=c||m||((Q=(ie=r.launcher)==null?void 0:ie.fullHeight)!=null?Q:!1),b=(ve=e.ownerDocument.defaultView)!=null?ve:window,S=(Se=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?Se:!0,B=(Ue=(Ze=r.launcher)==null?void 0:Ze.mobileBreakpoint)!=null?Ue:640,q=b.innerWidth<=B,_=S&&q&&k;try{if(_){Cr(),qo(e,r);return}if(j&&(j=!1,Cr(),qo(e,r)),!k&&!c){J.style.height="",J.style.width="";return}if(!m&&!c){let Kt=(rt=(ct=r==null?void 0:r.launcher)==null?void 0:ct.width)!=null?rt:r==null?void 0:r.launcherWidth,yt=Kt!=null?Kt:sr;J.style.width=yt,J.style.maxWidth=yt}if(xe(),!h){let Kt=b.innerHeight,yt=64,qt=(Le=(Ie=r.launcher)==null?void 0:Ie.heightOffset)!=null?Le:0,Un=Math.max(200,Kt-yt),en=Math.min(640,Un),Je=Math.max(200,en-qt);J.style.height=`${Je}px`}}finally{if(Jn(),Bs(),N&&k){let yt=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((ft=(Ke=r.launcher)==null?void 0:Ke.mobileBreakpoint)!=null?ft:640),qt=(Be=(I=r.launcher)==null?void 0:I.sidebarMode)!=null?Be:!1,Un=(ue=(Re=r.launcher)==null?void 0:Re.mobileFullscreen)!=null?ue:!0,en=cn(r)&&Un&&yt,Je=qt||Un&&yt&&k||en;if(Je&&!on){let Et=e.getRootNode(),nn=Et instanceof ShadowRoot?Et.host:e.closest(".persona-host");nn&&!rn&&(rn=ml(nn,(Wt=(Bt=r.launcher)==null?void 0:Bt.zIndex)!=null?Wt:wn)),on=gl(e.ownerDocument)}else Je||(rn==null||rn(),rn=null,on==null||on(),on=null)}}};Ds();let lc=(pd=e.ownerDocument.defaultView)!=null?pd:window;if(lc.addEventListener("resize",Ds),mt.push(()=>lc.removeEventListener("resize",Ds)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Jn()});c.observe(Ne),mt.push(()=>c.disconnect())}$n=Me.scrollTop;let cc=Gr(Me),Pf=()=>{let c=Me.getRootNode(),m=typeof c.getSelection=="function"?c.getSelection():null;return m!=null?m:Me.ownerDocument.getSelection()},Ni=()=>Fm(Pf(),Me),dc=()=>{let c=Me.scrollTop,m=Gr(Me),h=m<cc;if(cc=m,Ft()!=="follow"){$n=c,st();return}let{action:b,nextLastScrollTop:S}=Ya({following:_n.isFollowing(),currentScrollTop:c,lastScrollTop:$n,nearBottom:zo(Me,ts),userScrollThreshold:va,isAutoScrolling:pr||Mo||h,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if($n=S,b==="resume"){Ni()||Rn();return}b==="pause"&&Ps()};if(Me.addEventListener("scroll",dc,{passive:!0}),mt.push(()=>Me.removeEventListener("scroll",dc)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{mf()});c.observe(nt),c.observe(Me),mt.push(()=>c.disconnect())}let pc=()=>{Ft()==="follow"&&_n.isFollowing()&&Ni()&&Ps()},uc=Me.ownerDocument;uc.addEventListener("selectionchange",pc),mt.push(()=>{uc.removeEventListener("selectionchange",pc)});let mc=c=>{if(Ft()!=="follow")return;let m=Za({following:_n.isFollowing(),deltaY:c.deltaY,nearBottom:zo(Me,ts),resumeWhenNearBottom:!0});m==="pause"?Ps():m==="resume"&&!Ni()&&Rn()};Me.addEventListener("wheel",mc,{passive:!0}),mt.push(()=>Me.removeEventListener("wheel",mc)),jt.addEventListener("click",()=>{fn(),Me.scrollTop=Me.scrollHeight,$n=Me.scrollTop,Rn(),dn(!0),st()}),mt.push(()=>jt.remove()),mt.push(()=>{G(),fn()});let gc=()=>{A&&(Sr&&(A.removeEventListener("click",Sr),Sr=null),O()?(A.style.display="",Sr=()=>{Ut(!1,"user")},A.addEventListener("click",Sr)):A.style.display="none")};gc(),(()=>{let{clearChatButton:c}=qe;c&&c.addEventListener("click",()=>{$.clearMessages(),Er.clear(),Rn(),_o(qe.composerOverlay);try{localStorage.removeItem(Ms),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ms}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ms)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(),We==null||We.update()})})(),xt&&xt.addEventListener("submit",tc),ee==null||ee.addEventListener("keydown",rc),ee==null||ee.addEventListener("input",nc),ee==null||ee.addEventListener("paste",sc);let fc=(ud=e.ownerDocument)!=null?ud:document;fc.addEventListener("keydown",oc,!0);let hc="persona-attachment-drop-active",Ns=0,Oi=()=>{Ns=0,Ae.classList.remove(hc)},is=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&wt!==null},yc=c=>{!wi(c.dataTransfer)||!is()||(Ns++,Ns===1&&Ae.classList.add(hc))},bc=c=>{!wi(c.dataTransfer)||!is()||(Ns--,Ns<=0&&Oi())},xc=c=>{!wi(c.dataTransfer)||!is()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},vc=c=>{var h;if(!wi(c.dataTransfer)||!is())return;c.preventDefault(),c.stopPropagation(),Oi();let m=Array.from((h=c.dataTransfer.files)!=null?h:[]);m.length!==0&&wt.handleFiles(m)},ao=!0;Ae.addEventListener("dragenter",yc,ao),Ae.addEventListener("dragleave",bc,ao),e.addEventListener("dragover",xc,ao),e.addEventListener("drop",vc,ao);let Ma=e.ownerDocument,wc=c=>{is()&&c.preventDefault()},Cc=c=>{is()&&c.preventDefault()};Ma.addEventListener("dragover",wc),Ma.addEventListener("drop",Cc),mt.push(()=>{xt&&xt.removeEventListener("submit",tc),ee==null||ee.removeEventListener("keydown",rc),ee==null||ee.removeEventListener("input",nc),ee==null||ee.removeEventListener("paste",sc),fc.removeEventListener("keydown",oc,!0)}),mt.push(()=>{Ae.removeEventListener("dragenter",yc,ao),Ae.removeEventListener("dragleave",bc,ao),e.removeEventListener("dragover",xc,ao),e.removeEventListener("drop",vc,ao),Ma.removeEventListener("dragover",wc),Ma.removeEventListener("drop",Cc),Oi()}),mt.push(()=>{$.cancel()}),Zt?mt.push(()=>{Zt==null||Zt.destroy()}):sn&&mt.push(()=>{sn==null||sn.remove()});let tn={update(c){var _t,un,zn,Ir,mn,gn,rr,co,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Rd,Wd,Hd,Bd,Dd,Nd,Od,Fd,_d,$d,jd,Ud,qd,zd,Vd,Kd,Gd,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;let m=r.toolCall,h=r.messageActions,b=(_t=r.layout)==null?void 0:_t.messages,S=r.colorScheme,B=r.loadingIndicator,q=r.iterationDisplay,_=(un=r.features)==null?void 0:un.showReasoning,D=(zn=r.features)==null?void 0:zn.showToolCalls,ae=(Ir=r.features)==null?void 0:Ir.toolCallDisplay,ie=(mn=r.features)==null?void 0:mn.reasoningDisplay;r={...r,...c},Cr(),qo(e,r),hi(e,r),yi(e,r),Pn(),r.colorScheme!==S&&ks();let Q=bi.getForInstance(r.plugins);o.length=0,o.push(...Q),k=(rr=(gn=r.launcher)==null?void 0:gn.enabled)!=null?rr:!0,M=(xd=(co=r.launcher)==null?void 0:co.autoExpand)!=null?xd:!1,Ce=(wd=(vd=r.features)==null?void 0:vd.showReasoning)!=null?wd:!0,ke=(Ad=(Cd=r.features)==null?void 0:Cd.showToolCalls)!=null?Ad:!0,we=(Td=(Sd=r.features)==null?void 0:Sd.scrollToBottom)!=null?Td:{};let ve=Ft();le=(Md=(Ed=r.features)==null?void 0:Ed.scrollBehavior)!=null?Md:{},ve!==Ft()&&(fn(),Rn()),Xr(),st();let Oe=re;if(re=(Ld=(kd=r.features)==null?void 0:kd.showEventStreamToggle)!=null?Ld:!1,re&&!Oe){if(V||(be=new ha(oe),V=new fa(He,be),X=X!=null?X:new ya,be.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),$.setSSEEventCallback((ne,At)=>{var zt;(zt=r.onSSEEvent)==null||zt.call(r,ne,At),X==null||X.processEvent(ne,At),V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:ne,timestamp:Date.now(),payload:JSON.stringify(At)})})),!ut&&Pe){let ne=(Id=(Pd=r.features)==null?void 0:Pd.eventStream)==null?void 0:Id.classNames,At="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",At),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 zt=me("activity","18px","currentColor",1.5);zt&&ut.appendChild(zt);let ot=qe.clearChatButtonWrapper,kt=qe.closeButtonWrapper,an=ot||kt;an&&an.parentNode===Pe?Pe.insertBefore(ut,an):Pe.appendChild(ut),ut.addEventListener("click",()=>{K?lr():Dr()})}}else!re&&Oe&&(lr(),ut&&(ut.remove(),ut=null),V==null||V.clear(),be==null||be.destroy(),V=null,be=null,X==null||X.reset(),X=null);if(((Rd=r.launcher)==null?void 0:Rd.enabled)===!1&&Zt&&(Zt.destroy(),Zt=null),((Wd=r.launcher)==null?void 0:Wd.enabled)===!1&&sn&&(sn.remove(),sn=null),((Hd=r.launcher)==null?void 0:Hd.enabled)!==!1&&!Zt&&!sn){let{instance:ne,element:At}=bl({config:r,plugins:o,onToggle:ic});Zt=ne,ne||(sn=At),e.appendChild(At)}Zt&&Zt.update(r),Te&&((Bd=r.launcher)==null?void 0:Bd.title)!==void 0&&(Te.textContent=r.launcher.title),De&&((Dd=r.launcher)==null?void 0:Dd.subtitle)!==void 0&&(De.textContent=r.launcher.subtitle);let Se=(Nd=r.layout)==null?void 0:Nd.header;if((Se==null?void 0:Se.layout)!==F&&Pe){let ne=Se?ua(r,Se,{showClose:O(),onClose:()=>Ut(!1,"user")}):xo({config:r,showClose:O(),onClose:()=>Ut(!1,"user")});Xe.replaceHeader(ne),Pe=Xe.header.element,te=Xe.header.iconHolder,Te=Xe.header.headerTitle,De=Xe.header.headerSubtitle,A=Xe.header.closeButton,F=Se==null?void 0:Se.layout}else if(Se&&(te&&(te.style.display=Se.showIcon===!1?"none":""),Te&&(Te.style.display=Se.showTitle===!1?"none":""),De&&(De.style.display=Se.showSubtitle===!1?"none":""),A&&(A.style.display=Se.showCloseButton===!1?"none":""),qe.clearChatButtonWrapper)){let ne=Se.showClearChat;if(ne!==void 0){qe.clearChatButtonWrapper.style.display=ne?"":"none";let{closeButtonWrapper:At}=qe;At&&!At.classList.contains("persona-absolute")&&(ne?At.classList.remove("persona-ml-auto"):At.classList.add("persona-ml-auto"))}}let Ue=((Od=r.layout)==null?void 0:Od.showHeader)!==!1;Pe&&(Pe.style.display=Ue?"":"none");let ct=((Fd=r.layout)==null?void 0:Fd.showFooter)!==!1;Ne&&(Ne.style.display=ct?"":"none"),Jn(),st(),k!==R?k?Ut(M,"auto"):(N=!0,Bs()):M!==C&&Ut(M,"auto"),C=M,R=k,Ds(),gc();let Le=JSON.stringify(c.toolCall)!==JSON.stringify(m),ze=JSON.stringify(r.messageActions)!==JSON.stringify(h),Ke=JSON.stringify((_d=r.layout)==null?void 0:_d.messages)!==JSON.stringify(b),ft=(($d=r.loadingIndicator)==null?void 0:$d.render)!==(B==null?void 0:B.render)||((jd=r.loadingIndicator)==null?void 0:jd.renderIdle)!==(B==null?void 0:B.renderIdle)||((Ud=r.loadingIndicator)==null?void 0:Ud.showBubble)!==(B==null?void 0:B.showBubble),I=r.iterationDisplay!==q,Be=((zd=(qd=r.features)==null?void 0:qd.showReasoning)!=null?zd:!0)!==(_!=null?_:!0)||((Kd=(Vd=r.features)==null?void 0:Vd.showToolCalls)!=null?Kd:!0)!==(D!=null?D:!0)||JSON.stringify((Gd=r.features)==null?void 0:Gd.toolCallDisplay)!==JSON.stringify(ae)||JSON.stringify((Jd=r.features)==null?void 0:Jd.reasoningDisplay)!==JSON.stringify(ie);(Le||ze||Ke||ft||I||Be)&&$&&(Yo++,Is(nt,$.getMessages(),Z));let ue=(Xd=r.launcher)!=null?Xd:{},Bt=(Qd=ue.headerIconHidden)!=null?Qd:!1,Wt=(Zd=(Yd=r.layout)==null?void 0:Yd.header)==null?void 0:Zd.showIcon,Kt=Bt||Wt===!1,yt=ue.headerIconName,qt=(ep=ue.headerIconSize)!=null?ep:"48px";if(te){let ne=Ae.querySelector(".persona-border-b-persona-divider"),At=ne==null?void 0:ne.querySelector(".persona-flex-col");if(Kt)te.style.display="none",ne&&At&&!ne.contains(At)&&ne.insertBefore(At,ne.firstChild);else{if(te.style.display="",te.style.height=qt,te.style.width=qt,ne&&At&&(ne.contains(te)?te.nextSibling!==At&&(te.remove(),ne.insertBefore(te,At)):ne.insertBefore(te,At)),yt){let ot=parseFloat(qt)||24,kt=me(yt,ot*.6,"currentColor",1);kt?te.replaceChildren(kt):te.textContent=(tp=ue.agentIconText)!=null?tp:"\u{1F4AC}"}else if(ue.iconUrl){let ot=te.querySelector("img");if(ot)ot.src=ue.iconUrl,ot.style.height=qt,ot.style.width=qt;else{let kt=document.createElement("img");kt.src=ue.iconUrl,kt.alt="",kt.className="persona-rounded-xl persona-object-cover",kt.style.height=qt,kt.style.width=qt,te.replaceChildren(kt)}}else{let ot=te.querySelector("svg"),kt=te.querySelector("img");(ot||kt)&&te.replaceChildren(),te.textContent=(np=ue.agentIconText)!=null?np:"\u{1F4AC}"}let zt=te.querySelector("img");zt&&(zt.style.height=qt,zt.style.width=qt)}}let Un=(op=(rp=r.layout)==null?void 0:rp.header)==null?void 0:op.showTitle,en=(ap=(sp=r.layout)==null?void 0:sp.header)==null?void 0:ap.showSubtitle;if(Te&&(Te.style.display=Un===!1?"none":""),De&&(De.style.display=en===!1?"none":""),A){((lp=(ip=r.layout)==null?void 0:ip.header)==null?void 0:lp.showCloseButton)===!1?A.style.display="none":A.style.display="";let At=(cp=ue.closeButtonSize)!=null?cp:"32px",zt=(dp=ue.closeButtonPlacement)!=null?dp:"inline";A.style.height=At,A.style.width=At;let{closeButtonWrapper:ot}=qe,kt=zt==="top-right",an=ot==null?void 0:ot.classList.contains("persona-absolute");if(ot&&kt!==an)if(ot.remove(),kt)ot.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Ae.style.position="relative",Ae.appendChild(ot);else{let at=(up=(pp=ue.clearChat)==null?void 0:pp.placement)!=null?up:"inline",ln=(gp=(mp=ue.clearChat)==null?void 0:mp.enabled)!=null?gp:!0;ot.className=ln&&at==="inline"?"":"persona-ml-auto";let Wn=Ae.querySelector(".persona-border-b-persona-divider");Wn&&Wn.appendChild(ot)}if(A.style.color=ue.closeButtonColor||Mn.actionIconColor,ue.closeButtonBackgroundColor?(A.style.backgroundColor=ue.closeButtonBackgroundColor,A.classList.remove("hover:persona-bg-gray-100")):(A.style.backgroundColor="",A.classList.add("hover:persona-bg-gray-100")),ue.closeButtonBorderWidth||ue.closeButtonBorderColor){let at=ue.closeButtonBorderWidth||"0px",ln=ue.closeButtonBorderColor||"transparent";A.style.border=`${at} solid ${ln}`,A.classList.remove("persona-border-none")}else A.style.border="",A.classList.add("persona-border-none");ue.closeButtonBorderRadius?(A.style.borderRadius=ue.closeButtonBorderRadius,A.classList.remove("persona-rounded-full")):(A.style.borderRadius="",A.classList.add("persona-rounded-full")),ue.closeButtonPaddingX?(A.style.paddingLeft=ue.closeButtonPaddingX,A.style.paddingRight=ue.closeButtonPaddingX):(A.style.paddingLeft="",A.style.paddingRight=""),ue.closeButtonPaddingY?(A.style.paddingTop=ue.closeButtonPaddingY,A.style.paddingBottom=ue.closeButtonPaddingY):(A.style.paddingTop="",A.style.paddingBottom="");let xn=(fp=ue.closeButtonIconName)!=null?fp:"x",mr=(hp=ue.closeButtonIconText)!=null?hp:"\xD7";A.innerHTML="";let En=me(xn,"28px","currentColor",1);En?A.appendChild(En):A.textContent=mr;let Yt=(yp=ue.closeButtonTooltipText)!=null?yp:"Close chat",Vn=(bp=ue.closeButtonShowTooltip)!=null?bp:!0;if(A.setAttribute("aria-label",Yt),ot&&(ot._cleanupTooltip&&(ot._cleanupTooltip(),delete ot._cleanupTooltip),Vn&&Yt)){let at=null,ln=()=>{if(at||!A)return;let Bo=A.ownerDocument,Os=Bo.body;if(!Os)return;at=Wr(Bo,"div","persona-clear-chat-tooltip"),at.textContent=Yt;let Fs=Wr(Bo,"div");Fs.className="persona-clear-chat-tooltip-arrow",at.appendChild(Fs);let Do=A.getBoundingClientRect();at.style.position="fixed",at.style.zIndex=String(ho),at.style.left=`${Do.left+Do.width/2}px`,at.style.top=`${Do.top-8}px`,at.style.transform="translate(-50%, -100%)",Os.appendChild(at)},Wn=()=>{at&&at.parentNode&&(at.parentNode.removeChild(at),at=null)};ot.addEventListener("mouseenter",ln),ot.addEventListener("mouseleave",Wn),A.addEventListener("focus",ln),A.addEventListener("blur",Wn),ot._cleanupTooltip=()=>{Wn(),ot&&(ot.removeEventListener("mouseenter",ln),ot.removeEventListener("mouseleave",Wn)),A&&(A.removeEventListener("focus",ln),A.removeEventListener("blur",Wn))}}}let{clearChatButton:Je,clearChatButtonWrapper:Et}=qe;if(Je){let ne=(xp=ue.clearChat)!=null?xp:{},At=(vp=ne.enabled)!=null?vp:!0,zt=(Cp=(wp=r.layout)==null?void 0:wp.header)==null?void 0:Cp.showClearChat,ot=zt!==void 0?zt:At,kt=(Ap=ne.placement)!=null?Ap:"inline";if(Et){Et.style.display=ot?"":"none";let{closeButtonWrapper:an}=qe;!W()&&an&&!an.classList.contains("persona-absolute")&&(ot?an.classList.remove("persona-ml-auto"):an.classList.add("persona-ml-auto"));let xn=kt==="top-right",mr=Et.classList.contains("persona-absolute");if(!W()&&xn!==mr&&ot){if(Et.remove(),xn)Et.className="persona-absolute persona-top-4 persona-z-50",Et.style.right="48px",Ae.style.position="relative",Ae.appendChild(Et);else{Et.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Et.style.right="";let Yt=Ae.querySelector(".persona-border-b-persona-divider"),Vn=qe.closeButtonWrapper;Yt&&Vn&&Vn.parentElement===Yt?Yt.insertBefore(Et,Vn):Yt&&Yt.appendChild(Et)}let En=qe.closeButtonWrapper;En&&!En.classList.contains("persona-absolute")&&(xn?En.classList.add("persona-ml-auto"):En.classList.remove("persona-ml-auto"))}}if(ot){if(!W()){let at=(Sp=ne.size)!=null?Sp:"32px";Je.style.height=at,Je.style.width=at}let an=(Tp=ne.iconName)!=null?Tp:"refresh-cw",xn=(Ep=ne.iconColor)!=null?Ep:"";Je.style.color=xn||Mn.actionIconColor,Je.innerHTML="";let mr=W()?"14px":"20px",En=me(an,mr,"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 at=ne.borderWidth||"0px",ln=ne.borderColor||"transparent";Je.style.border=`${at} solid ${ln}`,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 Yt=(Mp=ne.tooltipText)!=null?Mp:"Clear chat",Vn=(kp=ne.showTooltip)!=null?kp:!0;if(Je.setAttribute("aria-label",Yt),Et&&(Et._cleanupTooltip&&(Et._cleanupTooltip(),delete Et._cleanupTooltip),Vn&&Yt)){let at=null,ln=()=>{if(at||!Je)return;let Bo=Je.ownerDocument,Os=Bo.body;if(!Os)return;at=Wr(Bo,"div","persona-clear-chat-tooltip"),at.textContent=Yt;let Fs=Wr(Bo,"div");Fs.className="persona-clear-chat-tooltip-arrow",at.appendChild(Fs);let Do=Je.getBoundingClientRect();at.style.position="fixed",at.style.zIndex=String(ho),at.style.left=`${Do.left+Do.width/2}px`,at.style.top=`${Do.top-8}px`,at.style.transform="translate(-50%, -100%)",Os.appendChild(at)},Wn=()=>{at&&at.parentNode&&(at.parentNode.removeChild(at),at=null)};Et.addEventListener("mouseenter",ln),Et.addEventListener("mouseleave",Wn),Je.addEventListener("focus",ln),Je.addEventListener("blur",Wn),Et._cleanupTooltip=()=>{Wn(),Et&&(Et.removeEventListener("mouseenter",ln),Et.removeEventListener("mouseleave",Wn)),Je&&(Je.removeEventListener("focus",ln),Je.removeEventListener("blur",Wn))}}}}let nn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[xi],nr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[Es.message,Es.messageAndClick];L=vi({parsers:nn,handlers:nr,getSessionMetadata:v,updateSessionMetadata:x,emit:i.emit,documentRef:typeof document!="undefined"?document:null}),Z=Ig(r,L,de),$.updateConfig(r),Is(nt,$.getMessages(),Z),Qo(),Zl(),Pi($.isStreaming());let qn=((Lp=r.voiceRecognition)==null?void 0:Lp.enabled)===!0,Io=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ro=((Ip=(Pp=r.voiceRecognition)==null?void 0:Pp.provider)==null?void 0:Ip.type)==="runtype";if(qn&&(Io||Ro))if(!H||!he){let ne=Tf(r.voiceRecognition,r.sendButton);ne&&(H=ne.micButton,he=ne.micButtonWrapper,It.insertBefore(he,Cn),H.addEventListener("click",Ea),H.disabled=$.isStreaming())}else{let ne=(Rp=r.voiceRecognition)!=null?Rp:{},At=(Wp=r.sendButton)!=null?Wp:{},zt=(Hp=ne.iconName)!=null?Hp:"mic",ot=(Bp=At.size)!=null?Bp:"40px",kt=(Dp=ne.iconSize)!=null?Dp:ot,an=parseFloat(kt)||24;H.style.width=kt,H.style.height=kt,H.style.minWidth=kt,H.style.minHeight=kt;let xn=(Op=(Np=ne.iconColor)!=null?Np:At.textColor)!=null?Op:"currentColor";H.innerHTML="";let mr=me(zt,an,xn,2);mr?H.appendChild(mr):H.textContent="\u{1F3A4}";let En=(Fp=ne.backgroundColor)!=null?Fp:At.backgroundColor;En?H.style.backgroundColor=En:H.style.backgroundColor="",xn?H.style.color=xn:H.style.color="var(--persona-text, #111827)",ne.borderWidth?(H.style.borderWidth=ne.borderWidth,H.style.borderStyle="solid"):(H.style.borderWidth="",H.style.borderStyle=""),ne.borderColor?H.style.borderColor=ne.borderColor:H.style.borderColor="",ne.paddingX?(H.style.paddingLeft=ne.paddingX,H.style.paddingRight=ne.paddingX):(H.style.paddingLeft="",H.style.paddingRight=""),ne.paddingY?(H.style.paddingTop=ne.paddingY,H.style.paddingBottom=ne.paddingY):(H.style.paddingTop="",H.style.paddingBottom="");let Yt=he==null?void 0:he.querySelector(".persona-send-button-tooltip"),Vn=(_p=ne.tooltipText)!=null?_p:"Start voice recognition";if((($p=ne.showTooltip)!=null?$p:!1)&&Vn)if(Yt)Yt.textContent=Vn,Yt.style.display="";else{let ln=document.createElement("div");ln.className="persona-send-button-tooltip",ln.textContent=Vn,he==null||he.insertBefore(ln,H)}else Yt&&(Yt.style.display="none");he.style.display="",H.disabled=$.isStreaming()}else H&&he&&(he.style.display="none",((Up=(jp=r.voiceRecognition)==null?void 0:jp.provider)==null?void 0:Up.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():Lr&&so());if(((qp=r.attachments)==null?void 0:qp.enabled)===!0)if(!vt||!Fe){let ne=(zp=r.attachments)!=null?zp:{},zt=(Kp=((Vp=r.sendButton)!=null?Vp:{}).size)!=null?Kp:"40px";Ht||(Ht=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ht.style.display="none",xt.insertBefore(Ht,ee)),Ye||(Ye=document.createElement("input"),Ye.type="file",Ye.accept=((Gp=ne.allowedTypes)!=null?Gp:Kr).join(","),Ye.multiple=((Jp=ne.maxFiles)!=null?Jp:4)>1,Ye.style.display="none",Ye.setAttribute("aria-label","Attach files"),xt.insertBefore(Ye,ee)),vt=y("div","persona-send-button-wrapper"),Fe=y("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Fe.type="button",Fe.setAttribute("aria-label",(Xp=ne.buttonTooltipText)!=null?Xp:"Attach file");let ot=(Qp=ne.buttonIconName)!=null?Qp:"paperclip",kt=zt,an=parseFloat(kt)||40,xn=Math.round(an*.6);Fe.style.width=kt,Fe.style.height=kt,Fe.style.minWidth=kt,Fe.style.minHeight=kt,Fe.style.fontSize="18px",Fe.style.lineHeight="1",Fe.style.backgroundColor="transparent",Fe.style.color="var(--persona-primary, #111827)",Fe.style.border="none",Fe.style.borderRadius="6px",Fe.style.transition="background-color 0.15s ease",Fe.addEventListener("mouseenter",()=>{Fe.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Fe.addEventListener("mouseleave",()=>{Fe.style.backgroundColor="transparent"});let mr=me(ot,xn,"currentColor",1.5);mr?Fe.appendChild(mr):Fe.textContent="\u{1F4CE}",Fe.addEventListener("click",Vn=>{Vn.preventDefault(),Ye==null||Ye.click()}),vt.appendChild(Fe);let En=(Yp=ne.buttonTooltipText)!=null?Yp:"Attach file",Yt=y("div","persona-send-button-tooltip");Yt.textContent=En,vt.appendChild(Yt),it.append(vt),!wt&&Ye&&Ht&&(wt=xs.fromConfig(ne),wt.setPreviewsContainer(Ht),Ye.addEventListener("change",async()=>{wt&&(Ye!=null&&Ye.files)&&(await wt.handleFileSelect(Ye.files),Ye.value="")})),Ae.querySelector(".persona-attachment-drop-overlay")||Ae.appendChild(Rg(ne.dropOverlay))}else{vt.style.display="";let ne=(Zp=r.attachments)!=null?Zp:{};Ye&&(Ye.accept=((eu=ne.allowedTypes)!=null?eu:Kr).join(","),Ye.multiple=((tu=ne.maxFiles)!=null?tu:4)>1),wt&&wt.updateConfig({allowedTypes:ne.allowedTypes,maxFileSize:ne.maxFileSize,maxFiles:ne.maxFiles})}else vt&&(vt.style.display="none"),wt&&wt.clearAttachments(),(nu=Ae.querySelector(".persona-attachment-drop-overlay"))==null||nu.remove();let Jt=(ru=r.sendButton)!=null?ru:{},Wo=(ou=Jt.useIcon)!=null?ou:!1,io=(su=Jt.iconText)!=null?su:"\u2191",lo=Jt.iconName,zr=(au=Jt.tooltipText)!=null?au:"Send message",Ho=(iu=Jt.showTooltip)!=null?iu:!1,ur=(lu=Jt.size)!=null?lu:"40px",Pr=Jt.backgroundColor,Qe=Jt.textColor;if(Wo){if(je.style.width=ur,je.style.height=ur,je.style.minWidth=ur,je.style.minHeight=ur,je.style.fontSize="18px",je.style.lineHeight="1",je.innerHTML="",Qe?je.style.color=Qe:je.style.color="var(--persona-button-primary-fg, #ffffff)",lo){let ne=parseFloat(ur)||24,At=(Qe==null?void 0:Qe.trim())||"currentColor",zt=me(lo,ne,At,2);zt?je.appendChild(zt):je.textContent=io}else je.textContent=io;je.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Pr?(je.style.backgroundColor=Pr,je.classList.remove("persona-bg-persona-primary")):(je.style.backgroundColor="",je.classList.add("persona-bg-persona-primary"))}else je.textContent=(du=(cu=r.copy)==null?void 0:cu.sendButtonLabel)!=null?du:"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",Pr?(je.style.backgroundColor=Pr,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");Jt.borderWidth?(je.style.borderWidth=Jt.borderWidth,je.style.borderStyle="solid"):(je.style.borderWidth="",je.style.borderStyle=""),Jt.borderColor?je.style.borderColor=Jt.borderColor:je.style.borderColor="",Jt.paddingX?(je.style.paddingLeft=Jt.paddingX,je.style.paddingRight=Jt.paddingX):(je.style.paddingLeft="",je.style.paddingRight=""),Jt.paddingY?(je.style.paddingTop=Jt.paddingY,je.style.paddingBottom=Jt.paddingY):(je.style.paddingTop="",je.style.paddingBottom="");let Dt=Cn==null?void 0:Cn.querySelector(".persona-send-button-tooltip");if(Ho&&zr)if(Dt)Dt.textContent=zr,Dt.style.display="";else{let ne=document.createElement("div");ne.className="persona-send-button-tooltip",ne.textContent=zr,Cn==null||Cn.insertBefore(ne,je)}else Dt&&(Dt.style.display="none");let Vt=(fu=(pu=r.layout)==null?void 0:pu.contentMaxWidth)!=null?fu:W()?(gu=(mu=(uu=r.launcher)==null?void 0:uu.composerBar)==null?void 0:mu.contentMaxWidth)!=null?gu:"720px":void 0;Vt?(nt.style.maxWidth=Vt,nt.style.marginLeft="auto",nt.style.marginRight="auto",nt.style.width="100%",xt&&(xt.style.maxWidth=Vt,xt.style.marginLeft="auto",xt.style.marginRight="auto"),Pt&&(Pt.style.maxWidth=Vt,Pt.style.marginLeft="auto",Pt.style.marginRight="auto")):(nt.style.maxWidth="",nt.style.marginLeft="",nt.style.marginRight="",nt.style.width="",xt&&(xt.style.maxWidth="",xt.style.marginLeft="",xt.style.marginRight=""),Pt&&(Pt.style.maxWidth="",Pt.style.marginLeft="",Pt.style.marginRight=""));let Nt=(hu=r.statusIndicator)!=null?hu:{},Xt=(yu=Nt.visible)!=null?yu:!0;if(hn.style.display=Xt?"":"none",$){let ne=$.getStatus();$t(hn,(zt=>{var ot,kt,an,xn;return zt==="idle"?(ot=Nt.idleText)!=null?ot:vn.idle:zt==="connecting"?(kt=Nt.connectingText)!=null?kt:vn.connecting:zt==="connected"?(an=Nt.connectedText)!=null?an:vn.connected:zt==="error"?(xn=Nt.errorText)!=null?xn:vn.error:vn[zt]})(ne),Nt,ne)}hn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Mt=Nt.align==="left"?"persona-text-left":Nt.align==="center"?"persona-text-center":"persona-text-right";hn.classList.add(Mt)},open(){O()&&Ut(!0,"api")},close(){O()&&Ut(!1,"api")},toggle(){O()&&Ut(!N,"api")},clearChat(){An=!1,$.clearMessages(),Er.clear(),Rn();try{localStorage.removeItem(Ms),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ms}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Ms)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(),We==null||We.update()},setMessage(c){return!ee||$.isStreaming()?!1:(!N&&O()&&Ut(!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()&&Ut(!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()&&Ut(!0,"system"),pt.manuallyDeactivated=!1,In(),$.toggleVoice().then(()=>{pt.active=$.isVoiceActive(),Zn("user"),$.isVoiceActive()&&as()})),!0):Lr?!0:ac()?(!N&&O()&&Ut(!0,"system"),pt.manuallyDeactivated=!1,In(),Sa("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(()=>{pt.active=!1,pt.manuallyDeactivated=!0,In(),Zn("user"),qr()}),!0):!1:Lr?(pt.manuallyDeactivated=!0,In(),so("user"),!0):!1},injectMessage(c){return!N&&O()&&Ut(!0,"system"),$.injectMessage(c)},injectAssistantMessage(c){!N&&O()&&Ut(!0,"system");let m=$.injectAssistantMessage(c);return Y&&(Y=!1,Ee&&(clearTimeout(Ee),Ee=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),m},injectUserMessage(c){return!N&&O()&&Ut(!0,"system"),$.injectUserMessage(c)},injectSystemMessage(c){return!N&&O()&&Ut(!0,"system"),$.injectSystemMessage(c)},injectMessageBatch(c){return!N&&O()&&Ut(!0,"system"),$.injectMessageBatch(c)},injectComponentDirective(c){return!N&&O()&&Ut(!0,"system"),$.injectComponentDirective(c)},injectTestMessage(c){!N&&O()&&Ut(!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(){!re||!V||Dr()},hideEventStream(){K&&lr()},isEventStreamVisible(){return K},showArtifacts(){ir(r)&&(An=!1,Pn(),bt==null||bt.setMobileOpen(!0))},hideArtifacts(){ir(r)&&(An=!0,Pn())},upsertArtifact(c){return ir(r)?(An=!1,$.upsertArtifact(c)):null},selectArtifact(c){ir(r)&&$.selectArtifact(c)},clearArtifacts(){ir(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&&!W()||!ee?!1:(ee.focus(),!0)},async resolveApproval(c,m,h){let S=$.getMessages().find(B=>{var q;return B.variant==="approval"&&((q=B.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 pt.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:pt.active,streaming:$.isStreaming()}},showCSATFeedback(c){!N&&O()&&Ut(!0,"system");let m=nt.querySelector(".persona-feedback-container");m&&m.remove();let h=Dl({onSubmit:async(b,S)=>{var B;$.isClientTokenMode()&&await $.submitCSATFeedback(b,S),(B=c==null?void 0:c.onSubmit)==null||B.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()&&Ut(!0,"system");let m=nt.querySelector(".persona-feedback-container");m&&m.remove();let h=Nl({onSubmit:async(b,S)=>{var B;$.isClientTokenMode()&&await $.submitNPSFeedback(b,S),(B=c==null?void 0:c.onSubmit)==null||B.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(){Po!=null&&(clearInterval(Po),Po=null),mt.forEach(c=>c()),fe.remove(),dt==null||dt.remove(),Zt==null||Zt.destroy(),sn==null||sn.remove(),Sr&&A.removeEventListener("click",Sr)}};if((((md=n==null?void 0:n.debugTools)!=null?md:!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,mt.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),mt.push(()=>{window.removeEventListener("persona:focusInput",m)}),re){let _=ae=>{let ie=ae.detail;(!(ie!=null&&ie.instanceId)||ie.instanceId===c)&&tn.showEventStream()},D=ae=>{let ie=ae.detail;(!(ie!=null&&ie.instanceId)||ie.instanceId===c)&&tn.hideEventStream()};window.addEventListener("persona:showEventStream",_),window.addEventListener("persona:hideEventStream",D),mt.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)},B=_=>{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",B),window.addEventListener("persona:clearArtifacts",q),mt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",b),window.removeEventListener("persona:upsertArtifact",S),window.removeEventListener("persona:selectArtifact",B),window.removeEventListener("persona:clearArtifacts",q)})}let tr=ew(r.persistState);if(tr&&O()){let c=tw(tr.storage),m=`${tr.keyPrefix}widget-open`,h=`${tr.keyPrefix}widget-voice`,b=`${tr.keyPrefix}widget-voice-mode`;if(c){let S=((gd=tr.persist)==null?void 0:gd.openState)&&c.getItem(m)==="true",B=((fd=tr.persist)==null?void 0:fd.voiceState)&&c.getItem(h)==="true",q=((hd=tr.persist)==null?void 0:hd.voiceState)&&c.getItem(b)==="true";if(S&&setTimeout(()=>{tn.open(),setTimeout(()=>{var _;if(B||q)tn.startVoiceRecognition();else if((_=tr.persist)!=null&&_.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(yd=tr.persist)!=null&&yd.openState&&(i.on("widget:opened",()=>{c.setItem(m,"true")}),i.on("widget:closed",()=>{c.setItem(m,"false")})),(bd=tr.persist)!=null&&bd.voiceState&&(i.on("voice:state",_=>{c.setItem(h,_.active?"true":"false")}),i.on("user:message",_=>{c.setItem(b,_.viaVoice?"true":"false")})),tr.clearOnChatClear){let _=()=>{c.removeItem(m),c.removeItem(h),c.removeItem(b)},D=()=>_();window.addEventListener("persona:clear-chat",D),mt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return g&&O()&&setTimeout(()=>{tn.open()},0),os(),xa||Au().then(()=>{$&&(Yo++,Er.clear(),Is(nt,$.getMessages(),Z))}).catch(()=>{}),tn};var nw=(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},rw=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},ow=(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.")},Wg=(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"},Ul=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=""},Hg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",Ul(e)},_l=e=>{e.style.transition=""},$l=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"},Ci=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},aw=(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))},iw=(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)},Bg=(e,t,n,r,o,s,a)=>{var v,x,E,T,L,k;let i=ar(s),d=i.reveal==="push";aw(e,t,n,r,d),iw(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"),$l(t),_l(r),Hg(r),jl(n),Ci(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:wn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Hg(r),rw(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",$l(t),_l(r),jl(n),Ci(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",_l(r),Ul(r),Ci(o,r);let M=nw(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="",$l(t),Ul(r),jl(n),Ci(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",ow(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")}},lw=(e,t)=>{let n=e.ownerDocument.createElement("div");return Wg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Wg(n,r)},destroy(){n.remove()}}},cw=(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(),ar(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(g=new ResizeObserver(()=>{Bg(a,i,d,l,p,t,u)}),g.observe(a))},x=!1,E=()=>{Bg(a,i,d,l,p,t,u),v(),u&&!x&&a.dataset.personaDockMobileFullscreen!=="true"&&(x=!0,sw(a,ar(t)))},T=a.ownerDocument.defaultView,L=()=>{E()};return T==null||T.addEventListener("resize",L),ar(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()}}},Ai=(e,t)=>cn(t)?cw(e,t):lw(e,t);var ql={},dw=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},Dg=(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)}},Ng=e=>{var E;let t=dw(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=Ai(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)||cn(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),Dg(F,r)}else T.appendChild(P),Dg(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=Fl(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=Ai(t,T),o=T,u()},v={update(T){var R,F,j,W,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:{...(W=(j=o==null?void 0:o.launcher)==null?void 0:j.dock)!=null?W:{},...(N=(O=T==null?void 0:T.launcher)==null?void 0:O.dock)!=null?N:{}}}},k=cn(o),M=cn(L),P=bo(o),C=bo(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 jg=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),uw=new Set(["button","a","input","select","textarea","details","summary"]),mw=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),zl=/\b(product|card|item|listing|result)\b/i,Kl=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,gw=3e3,fw=100;function Ug(e){let t=typeof e.className=="string"?e.className:"";if(zl.test(t)||e.id&&zl.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&zl.test(r.value))return!0}return!1}function qg(e){var t;return Kl.test(((t=e.textContent)!=null?t:"").trim())}function zg(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 hw(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Og(e){let t=e.match(Kl);return t?t[0]:null}function Fg(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 yw(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 bw="commerce-card",xw="result-card";function _g(e){return!Ug(e)||!qg(e)||!zg(e)&&!hw(e)?0:5200}function $g(e){var r;return!Ug(e)||qg(e)||!zg(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 Vg=[{id:bw,scoreElement(e){return _g(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||Kl.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(_g(e)===0)return null;let{title:n,href:r}=Fg(e),o=(p=(l=Og(((d=e.textContent)!=null?d:"").trim()))!=null?l:Og(t.text))!=null?p:"",s=yw(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:xw,scoreElement(e){return $g(e)},formatSummary(e,t){if($g(e)===0)return null;let{title:n,href:r}=Fg(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
113
- `)}}];function vw(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function ww(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:Vg;return i==="simple"&&e.rules&&e.rules.length>0?(vw(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function Vl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Cw=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Aw(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"||uw.has(t)||n&&mw.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Kg(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 Sw(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 Gg(e){let t=e.tagName.toLowerCase();if(e.id){let o=`#${Vl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of Cw){let s=e.getAttribute(o);if(s){let a=`${t}[${o}="${Vl(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=>Vl(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 Tw(e){return e==="static"?fw:gw}function Jg(e,t){var o;let n=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,t);return{selector:Gg(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:Aw(e),attributes:Sw(e)}}function Ew(e,t,n,r){let o=Tw(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 Mw(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(jg.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Kg(l)){i=a.nextNode();continue}let u=Jg(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}=Ew(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;Mw(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 Lw(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(jg.has(l)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!Kg(d)){s=o.nextNode();continue}let p=Jg(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 Pw(e={}){var r;let t=ww(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?Lw(t,n):kw(t,n):[]}var Si=100;function Iw(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,Si)}" (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,Si)}" (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,Si)}" (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,Si)}"`);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 Rw(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function Ww(){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 Hw(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:Br(e.colors.primary,.95),100:Br(e.colors.primary,.9),200:Br(e.colors.primary,.8),300:Br(e.colors.primary,.7),400:Br(e.colors.primary,.6),500:e.colors.primary,600:Br(e.colors.primary,.8),700:Br(e.colors.primary,.7),800:Br(e.colors.primary,.6),900:Br(e.colors.primary,.5),950:Br(e.colors.primary,.45)}}),{...t,palette:n}}}}function Bw(){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 Dw(){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 Br(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 Nw(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Ow={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"}}},Xg={components:{panel:{borderRadius:"0",shadow:"none"}}},Qg={id:"shop",label:"Shopping Assistant",config:{theme:Ow,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:sr},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?"]}},Yg={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Xg}},Zg={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Xg}},ef={shop:Qg,minimal:Yg,fullscreen:Zg};function Fw(e){return ef[e]}var _w=Ng;function Jr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function $w(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 tf=`({ 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
- }`,nf=`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
- }`,rf=`(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
- }`,of=`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
- }`,jw=`(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
- }`,Uw=`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 qw(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 Ti(e){var t,n;return(n=(t=e.parserType)!=null?t:qw(e.streamParser))!=null?n:"plain"}function Ei(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 Mi(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 ki(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 Li(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 Gl(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 sf(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}: {`),sf(e,o,`${n} `),e.push(`${n}},`);return}e.push(`${n}${r}: ${JSON.stringify(o)},`)}})}function wo(e,t,n,r){n&&(e.push(`${r}${t}: {`),sf(e,n,`${r} `),e.push(`${r}},`))}function ba(e){var t;return((t=e==null?void 0:e.target)!=null?t:"body").replace(/\\/g,"\\\\").replace(/'/g,"\\'")}function zw(e,t="esm",n){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let o=n?{...n,hooks:$w(n.hooks)}:void 0;return t==="esm"?Vw(r,o):t==="script-installer"?Jw(r,o):t==="script-advanced"?Qw(r,o):t==="react-component"?Kw(r,o):t==="react-advanced"?Gw(r,o):Xw(r,o)}function Vw(e,t){let n=t==null?void 0:t.hooks,r=Ti(e),o=r!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({",` target: '${ba(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&&wo(s,"theme",e.theme," "),e.launcher&&wo(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(...Ei(e," ")),s.push(...Mi(e," ",n)),s.push(...ki(e," ")),s.push(...Li(e," ")),s.push(...Gl(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 Kw(e,t){let n=t==null?void 0:t.hooks,r=Ti(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: '${ba(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&&wo(s,"theme",e.theme," "),e.launcher&&wo(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(...Ei(e," ")),s.push(...Mi(e," ",n)),s.push(...ki(e," ")),s.push(...Li(e," ")),s.push(...Gl(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 Gw(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: '${ba(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&&wo(r,"theme",e.theme," "),e.launcher&&wo(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(...Ei(e," ")),r.push(...Mi(e," ",n)),r.push(...ki(e," ")),r.push(...Li(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(${jw}),`)),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(` ${tf}`),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(` ${tf}`),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(` ${rf}`),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(` ${rf}`),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 af(e){var o;let t=Ti(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 Jw(e,t){let n=af(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 Xw(e,t){let n=t==null?void 0:t.hooks,r=Ti(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: '${ba(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&&wo(s,"theme",e.theme," "),e.launcher&&wo(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(...Ei(e," ")),s.push(...Mi(e," ",n)),s.push(...ki(e," ")),s.push(...Li(e," ")),s.push(...Gl(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 Qw(e,t){let n=t==null?void 0:t.hooks,r=af(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@${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(${Uw});`),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(` ${nf}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${nf}`),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(` ${of}`),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(` ${of}`),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: '${ba(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 lf={desktop:{w:1280,h:800},mobile:{w:390,h:844}},cf=.1,df=.15,pf=1.5,Jl=24,uf=40,Yw=`
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: ${Jl}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 Zw(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Yw,document.head.appendChild(e)}function eC(e,t){let n=e.clientWidth-Jl*2-uf,r=e.clientHeight-Jl*2-uf;return n<=0||r<=0?1:Math.min(n/t.w,r/t.h,1)}function tC(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 nC(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");Zw();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=Gt({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=me("chevron-down",12,"currentColor",2);j&&F.appendChild(j),C.append(R,F);let W=y("div","persona-dc-dropdown");W.setAttribute("role","listbox"),W.style.display="none";let O=!1;function N(){W.innerHTML="";for(let ge=0;ge<n.length;ge++){let Ve=n[ge],et=y("button","persona-dc-dropdown-item");et.type="button",et.setAttribute("role","option"),et.setAttribute("aria-current",ge===p?"true":"false");let $t=y("span");if($t.textContent=Ve.title,et.appendChild($t),Ve.description){let Xe=y("span","persona-dc-dropdown-desc");Xe.textContent=Ve.description,et.appendChild(Xe)}et.addEventListener("click",()=>{Ee(),We(ge)}),W.appendChild(et)}}function Y(){O=!O,W.style.display=O?"":"none",C.setAttribute("aria-expanded",O?"true":"false"),O&&N()}function Ee(){O&&(O=!1,W.style.display="none",C.setAttribute("aria-expanded","false"))}C.addEventListener("click",ge=>{ge.stopPropagation(),Y()});let de=()=>Ee();document.addEventListener("click",de),P.append(C,W);let Z=Gt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>X(1)}),Ce=y("span","persona-dc-counter");L.append(M,P,Z,Ce);let ke=null;i&&(ke=ai({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:ge=>{u=ge,oe.dataset.device=u,f=null,K()}}),k.appendChild(ke.element));let re=null;if(a){let ge=y("div","persona-dc-zoom-controls"),Ve=Gt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let Xe=f!=null?f:v;f=Math.max(df,Xe-cf),K()}});re=y("span","persona-dc-zoom-level"),re.title="Reset to 100%",re.style.cursor="pointer",re.addEventListener("click",()=>{f=1,K()});let et=Gt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let Xe=f!=null?f:v;f=Math.min(pf,Xe+cf),K()}}),$t=Gt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{f=null,K()}});ge.append(Ve,re,et,$t),k.appendChild(ge)}if(d){let ge=y("div","persona-dc-separator");k.appendChild(ge);let Ve=ai({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:g,onSelect:et=>{g=et,oe.dataset.colorScheme=g,He()}});k.appendChild(Ve.element)}let we=y("div","persona-dc-separator");k.appendChild(we);let le=Gt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(n[p].url,"_blank")}});k.appendChild(le),T.append(L,k);let se=y("div","persona-dc-stage"),oe=y("div","persona-dc-iframe-wrapper");oe.dataset.device=u,oe.dataset.colorScheme=g;let be=y("iframe","persona-dc-iframe");be.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),be.setAttribute("loading","lazy"),be.title=n[p].title,oe.appendChild(be),se.appendChild(oe),E.append(T,se),e.appendChild(E);function He(){var ge;try{let Ve=(ge=be.contentDocument)==null?void 0:ge.body;if(!Ve)return;g==="dark"?Ve.classList.add("theme-dark"):Ve.classList.remove("theme-dark")}catch{}}be.addEventListener("load",()=>He());function V(){let ge=n[p];R.textContent=ge.title,Ce.textContent=`${p+1} / ${n.length}`,be.title=ge.title}function X(ge){let Ve=((p+ge)%n.length+n.length)%n.length;We(Ve)}function We(ge){ge<0||ge>=n.length||(p=ge,be.src=n[p].url,V(),l==null||l(p,n[p]))}function K(){var et;if(x)return;let ge=(et=lf[u])!=null?et:lf.desktop;v=eC(se,ge);let Ve=Math.max(df,Math.min(pf,f!=null?f:v));tC(oe,be,ge,Ve,u),re&&(re.textContent=`${Math.round(Ve*100)}%`)}let pe=new ResizeObserver(()=>K());pe.observe(se),V(),be.src=n[p].url,requestAnimationFrame(()=>K());function $e(){x||(x=!0,pe.disconnect(),document.removeEventListener("click",de),E.remove())}return{element:E,goTo:We,next:()=>X(1),prev:()=>X(-1),getIndex:()=>p,setDevice(ge){u=ge,oe.dataset.device=ge,ke==null||ke.setSelected(ge),f=null,K()},setColorScheme(ge){g=ge,oe.dataset.colorScheme=ge},setZoom(ge){f=ge,K()},destroy:$e}}export{tm as ASK_USER_QUESTION_CLIENT_TOOL,em as ASK_USER_QUESTION_PARAMETERS_SCHEMA,Pa as ASK_USER_QUESTION_TOOL_NAME,fs as AgentWidgetClient,ta as AgentWidgetSession,xs as AttachmentManager,Uo as BrowserSpeechEngine,Mm as DEFAULT_COMPONENTS,sl as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,sr as DEFAULT_FLOATING_LAUNCHER_WIDTH,Tm as DEFAULT_PALETTE,Em as DEFAULT_SEMANTIC,Ot as DEFAULT_WIDGET_CONFIG,ef as PRESETS,Zg as PRESET_FULLSCREEN,Yg as PRESET_MINIMAL,Qg as PRESET_SHOP,bs as ReadAloudController,Vi as SUGGEST_REPLIES_CLIENT_TOOL,Qu as SUGGEST_REPLIES_PARAMETERS_SCHEMA,Hr as SUGGEST_REPLIES_TOOL_NAME,gx as THEME_ZONES,fr as VERSION,Rr as WEBMCP_TOOL_PREFIX,js as WebMcpBridge,Rw as accessibilityPlugin,Ww as animationsPlugin,qo as applyThemeVariables,ws as attachHeaderToContainer,Hw as brandPlugin,ma as buildComposer,zm as buildDefaultHeader,xo as buildHeader,ua as buildHeaderWithLayout,Vm as buildMinimalHeader,Ba as builtInClientToolsForDispatch,Pw as collectEnrichedPageContext,vo as componentRegistry,vi as createActionManager,Fl as createAgentExperience,Eh as createAskUserQuestionBubble,nl as createBestAvailableVoiceProvider,Xx as createBubbleWithLayout,Dl as createCSATFeedback,fl as createComboButton,Jv as createComponentMiddleware,Rl as createComponentStreamParser,ku as createDefaultSanitizer,nC as createDemoCarousel,Of as createDirectivePostprocessor,Vo as createDropdownMenu,Ph as createFlexibleJsonStreamParser,Gt as createIconButton,$h as createImagePart,Yi as createJsonStreamParser,si as createLabelButton,Il as createLocalStorageAdapter,ka as createMarkdownProcessor,us as createMarkdownProcessorFromConfig,ng as createMessageActions,Nl as createNPSFeedback,Xi as createPlainTextParser,Nw as createPlugin,Qi as createRegexJsonParser,ga as createStandardBubble,ja as createTextPart,ra as createTheme,cl as createThemeObserver,ai as createToggleGroup,Cs as createTypingIndicator,jo as createVoiceProvider,Ai as createWidgetHostLayout,Zi as createXmlParser,_w as default,Es as defaultActionHandlers,xi as defaultJsonActionParser,Vg as defaultParseRules,Ga as detectColorScheme,Ff as directivePostprocessor,Ks as ensureAskUserQuestionSheet,Vr as escapeHtml,Bl as extractComponentDirectiveFromMessage,jh as fileToImagePart,Iw as formatEnrichedContext,hs as generateAssistantMessageId,zw as generateCodeSnippet,Dh as generateMessageId,Gg as generateStableSelector,Qs as generateUserMessageId,oa as getActiveTheme,Im as getColorScheme,Oh as getDisplayText,Km as getHeaderLayout,_h as getImageParts,Fw as getPreset,Hl as hasComponentDirective,Fh as hasImages,hl as headerLayouts,Dw as highContrastPlugin,Ng as initAgentWidget,po as isAskUserQuestionMessage,Gv as isComponentDirectiveType,cn as isDockedMountMode,Ha as isSuggestRepliesMessage,qa as isVoiceSupported,Oo as isWebMcpToolName,Gi as latestAgentSuggestions,Sx as listRegisteredStreamAnimations,Tu as markdownPostprocessor,al as mergeWithDefaults,Nh as normalizeContent,uo as parseAskUserQuestionPayload,Yu as parseSuggestRepliesPayload,Zs as pickBestVoice,bi as pluginRegistry,Bw as reducedMotionPlugin,Cx as registerStreamAnimationPlugin,_o as removeAskUserQuestionSheet,Wl as renderComponentDirective,tg as renderLoadingIndicatorWithFallback,me as renderLucideIcon,ar as resolveDockConfig,$s as resolveSanitizer,il as resolveTokens,_i as stripWebMcpPrefix,ll as themeToCssVariables,Ax as unregisterStreamAnimationPlugin,Uh as validateImageFile,km 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