@runtypelabs/persona 3.14.0 → 3.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import{Marked as sp}from"marked";var ap=e=>{if(e)return e},ss=e=>{var s,o;let r=e==null?void 0:e.markedOptions,t=new sp({gfm:(s=r==null?void 0:r.gfm)!=null?s:!0,breaks:(o=r==null?void 0:r.breaks)!=null?o:!0,pedantic:r==null?void 0:r.pedantic,silent:r==null?void 0:r.silent}),n=ap(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),a=>t.parse(a)},Gr=e=>e?ss({markedOptions:e.options,renderer:e.renderer}):ss(),ip=ss(),wc=e=>ip(e),Eo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Sc=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Cc=e=>`%%FORM_PLACEHOLDER_${e}%%`,Ac=(e,r)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=Cc(r.length);return r.push({token:a,type:String(o.type)}),a}}catch{return n}return n}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,s)=>{let o=Cc(r.length);return r.push({token:o,type:s}),o}),t},lp=e=>{let r=Gr(e);return t=>{let n=[],s=Ac(t,n),o=r(s);return n.forEach(({token:a,type:i})=>{let u=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Sc(i)}"></div>`;o=o.replace(u,p)}),o}},cp=e=>{let r=[],t=Ac(e,r),n=wc(t);return r.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${Sc(o)}"></div>`;n=n.replace(a,u)}),n};import dp from"dompurify";var pp={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"]},up=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ec=()=>{let e=dp(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(r,t)=>{if(t.attrName==="src"||t.attrName==="href"){let n=t.attrValue;n.toLowerCase().startsWith("data:")&&!up.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,pp)},To=e=>e===!1?null:typeof e=="function"?e:Ec();import{parse as Tc,STR as Mc,OBJ as kc}from"partial-json";var as=e=>e.replace(/\\n/g,`
2
2
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Kr=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)}},mp=e=>{var a,i;let r=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:r,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,r-t))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Lc=e=>e.status==="complete"?mp(e):e.status==="pending"?"Waiting":"",gp=e=>{var s,o,a;let t=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((s=e.completedAt)!=null?s:Date.now())-((a=(o=e.startedAt)!=null?o:e.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var Ic=e=>e.status==="complete"?gp(e):"Using tool...",is=e=>{let r=e/1e3;return r<.1?"<0.1s":r>=10?`${Math.round(r)}s`:`${r.toFixed(1).replace(/\.0$/,"")}s`},ko=e=>{var t,n,s;let r=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(n=e.startedAt)!=null?n:e.completedAt)!=null?s:Date.now()));return is(r)},ls=e=>{var t,n,s;let r=e.durationMs!==void 0?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(n=e.startedAt)!=null?n:e.completedAt)!=null?s:Date.now()));return is(r)},js=(e,r,t)=>{var o;if(!r)return t;let n=((o=e.name)==null?void 0:o.trim())||"tool",s=ko(e);return r.replace(/\{toolName\}/g,n).replace(/\{duration\}/g,s)},cs=(e,r)=>{let t=e.replace(/\{toolName\}/g,r),n=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(t))!==null;)a.index>o&&Mo(n,t.slice(o,a.index),[]),a[1]!==void 0?Mo(n,a[1],["bold"]):a[2]!==void 0?Mo(n,a[2],["italic"]):a[3]!==void 0&&Mo(n,a[3],["dim"]),o=a.index+a[0].length;return o<t.length&&Mo(n,t.slice(o),[]),n},Mo=(e,r,t)=>{let n=r.split("{duration}");for(let s=0;s<n.length;s++)n[s]&&e.push({text:n[s],styles:t}),s<n.length-1&&e.push({text:"{duration}",styles:t,isDuration:!0})},fp=()=>{let e=null,r=0,t=n=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=n.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
3
3
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=n.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
4
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=r)return e!==null?{text:e,raw:n}:null;let s=n.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(n);return o!==null&&(e=o),r=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},Nr=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},zs=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},qs=()=>{var r;let e=fp();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(r=e.close)==null?void 0:r.bind(e)}},Us=()=>{let e=null,r=0;return{getExtractedText:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=Tc(t,Mc|kc);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?as(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=as(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},hp=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?as(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?as(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>r,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return r!==null?{text:r,raw:o}:null;try{let i=Tc(o,Mc|kc),u=s(i);u!==null&&(r=u)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},Vs=()=>{let e=null;return{processChunk:r=>{if(!r.trim().startsWith("<"))return null;let n=r.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:r}):null},getExtractedText:()=>e}};var yp="https://api.runtype.com/v1/dispatch",Js="https://api.runtype.com",Ys=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 bp(e){switch(e){case"json":return Us;case"regex-json":return qs;case"xml":return Vs;default:return zs}}var Pc=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function xp(e,r){if(!e)return r;let t=e.trim(),n=r.trim();if(t.length===0)return r;if(n.length===0)return e;let s=Pc(t);if(!Pc(n))return e;if(!s||n===t||n.startsWith(t))return r;let a=Nr(e);return Nr(r)!==null&&a===null?r:e}var Xr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:yp,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:bp(r.parserType),this.contextProviders=(s=r.contextProviders)!=null?s:[],this.requestMiddleware=r.requestMiddleware,this.customFetch=r.customFetch,this.parseSSEEvent=r.parseSSEEvent,this.getHeaders=r.getHeaders}setSSEEventCallback(r){this.onSSEEvent=r}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(r){var n;let t=((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Js;return r==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var r,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let n=await this.sessionInitPromise;return this.clientSession=n,(t=(r=this.config).onSessionInit)==null||t.call(r,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let r=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...r&&{sessionId:r}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await n.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Js}/v1/client/feedback`}async sendFeedback(r){var o,a;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(r.type)&&!r.messageId)throw new Error(`messageId is required for ${r.type} feedback type`);if(r.type==="csat"&&(r.rating===void 0||r.rating<1||r.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(r.type==="nps"&&(r.rating===void 0||r.rating<0||r.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",r);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:r,comment:t})}async submitNPSFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:r,comment:t})}async dispatch(r,t){return this.isAgentMode()?this.dispatchAgent(r,t):this.isClientTokenMode()?this.dispatchClientToken(r,t):this.dispatchProxy(r,t)}async dispatchClientToken(r,t){var s,o,a,i;let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});try{let u=await this.initSession();if(new Date>=new Date(u.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let g=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:g}),g}let c=await this.buildPayload(r.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([g])=>g!=="sessionId"&&g!=="session_id")):void 0,d={sessionId:u.sessionId,messages:r.messages.filter(Ys).map(g=>{var v,M,C;return{id:g.id,role:g.role,content:(C=(M=(v=g.contentParts)!=null?v:g.llmContent)!=null?M:g.rawContent)!=null?C:g.content}}),...r.assistantMessageId&&{assistantMessageId:r.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}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),signal:n.signal});if(!f.ok){let g=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let M=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:M}),M}if(f.status===429){let M=new Error(g.hint||"Message limit reached for this session.");throw t({type:"error",error:M}),M}let v=new Error(g.error||"Failed to send message");throw t({type:"error",error:v}),v}if(!f.body){let g=new Error("No response body received");throw t({type:"error",error:g}),g}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(u){let c=u instanceof Error?u:new Error(String(u));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...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:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...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:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(r,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Js}/v1/agents/${r.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:r.executionId,approvalId:r.approvalId,decision:t,streamResponse:!0})})}async buildAgentPayload(r){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=r.slice().filter(Ys).filter(s=>s.role==="user"||s.role==="assistant"||s.role==="system").filter(s=>!s.variant||s.variant==="assistant").sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),n={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}return n}async buildPayload(r){let n={messages:r.slice().filter(Ys).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(r,t,n,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let u=p=>{let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return n.current=d,s(d),d},c=p=>n.current?n.current:u(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,s(n.current)),u(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,s(p)}return i.done&&(n.current&&(n.current.streaming=!1,s(n.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(r,t,n){var q,de,_e,ee,le,Lt,ct,Dt,Xt,je,me,Ne,Pt,Wt,ot,st,nn,tn,rn,z,He,ye,ht,$e,ce,Se,Oe,Ct,jt,dt,zt,yt,Ze,bt,De,qt,Gn,nr,$n,et,Tr,Kn,Mr,Wn,jr,ur,rr,at,An,_n,dn,mr,En,At,pn,Rn,gr,or,fr,Xn,Tn,Zn,wt,Nt,Ot,Mn,hr,jn,kn,D,zn,Hn,yr,fn,hn,ie,Ln,sr,qo,co,Uo,zr,Qe,po,Bn,yn,Vo,Jo,uo,ar,Yo,kr,mo,ir,go,br,xr,Go,Ko,Os,Lr,Ir,Rt,qr,Ur,fo,Qn,Xo,ho,yo,bo,un,In,lr,qe,xo,Pr,qn,Zo,Vr,Jr,Wr;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),u=0,c=()=>i+u++,p=X=>{let Ve=X.reasoning?{...X.reasoning,chunks:[...X.reasoning.chunks]}:void 0,tt=X.toolCall?{...X.toolCall,chunks:X.toolCall.chunks?[...X.toolCall.chunks]:void 0}:void 0,xt=X.tools?X.tools.map(lt=>({...lt,chunks:lt.chunks?[...lt.chunks]:void 0})):void 0;return{...X,reasoning:Ve,toolCall:tt,tools:xt}},d=X=>{t({type:"message",message:p(X)})},f=null,g={current:null},v={current:null},M=!1,C=new Map,S=new Map,k={lastId:null,byStep:new Map},H={lastId:null,byCall:new Map},w=X=>{if(X==null)return null;try{return String(X)}catch{return null}},L=X=>{var Ve,tt,xt,lt,Et;return w((Et=(lt=(xt=(tt=(Ve=X.stepId)!=null?Ve:X.step_id)!=null?tt:X.step)!=null?xt:X.parentId)!=null?lt:X.flowStepId)!=null?Et:X.flow_step_id)},P=X=>{var Ve,tt,xt,lt,Et,ut,b;return w((b=(ut=(Et=(lt=(xt=(tt=(Ve=X.callId)!=null?Ve:X.call_id)!=null?tt:X.requestId)!=null?xt:X.request_id)!=null?lt:X.toolCallId)!=null?Et:X.tool_call_id)!=null?ut:X.stepId)!=null?b:X.step_id)},E=n,Y=!1,Q=()=>{if(f)return f;let X;return!Y&&E?(X=E,Y=!0):E&&v.current?X=`${E}_${v.current}`:X=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:X,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},d(f),f},G=(X,Ve)=>{k.lastId=Ve,X&&k.byStep.set(X,Ve)},O=(X,Ve)=>{var Et;let tt=(Et=X.reasoningId)!=null?Et:X.id,xt=L(X);if(tt){let ut=String(tt);return G(xt,ut),ut}if(xt){let ut=k.byStep.get(xt);if(ut)return k.lastId=ut,ut}if(k.lastId&&!Ve)return k.lastId;if(!Ve)return null;let lt=`reason-${c()}`;return G(xt,lt),lt},re=X=>{let Ve=C.get(X);if(Ve)return Ve;let tt={id:`reason-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:X,status:"streaming",chunks:[]}};return C.set(X,tt),d(tt),tt},we=(X,Ve)=>{H.lastId=Ve,X&&H.byCall.set(X,Ve)},oe=new Set,ve=new Map,We=new Set,ge=new Map,ke=X=>{if(!X)return!1;let Ve=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ve==="emit_artifact_markdown"||Ve==="emit_artifact_component"},Le=(X,Ve)=>{var Et;let tt=(Et=X.toolId)!=null?Et:X.id,xt=P(X);if(tt){let ut=String(tt);return we(xt,ut),ut}if(xt){let ut=H.byCall.get(xt);if(ut)return H.lastId=ut,ut}if(H.lastId&&!Ve)return H.lastId;if(!Ve)return null;let lt=`tool-${c()}`;return we(xt,lt),lt},se=X=>{let Ve=S.get(X);if(Ve)return Ve;let tt={id:`tool-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:X,status:"pending"}};return S.set(X,tt),d(tt),tt},K=X=>{if(typeof X=="number"&&Number.isFinite(X))return X;if(typeof X=="string"){let Ve=Number(X);if(!Number.isNaN(Ve)&&Number.isFinite(Ve))return Ve;let tt=Date.parse(X);if(!Number.isNaN(tt))return tt}return Date.now()},ue=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},U=new Map,te=new Map,fe=new Map,pe=new Map;function Re(X,Ve,tt,xt){let lt=X.get(Ve);lt||(lt=[],X.set(Ve,lt));let Et=0,ut=lt.length;for(;Et<ut;){let ne=Et+ut>>>1;lt[ne].seq<tt?Et=ne+1:ut=ne}lt.splice(Et,0,{seq:tt,text:xt});let b="";for(let ne=0;ne<lt.length;ne++)b+=lt[ne].text;return b}let Xe=null,j=(X,Ve)=>{let tt=ue(Ve),xt=te.get(X.id),lt=xp(xt,tt);X.rawContent=lt;let Et=U.get(X.id),ut=Z=>{var he;let F=(he=X.content)!=null?he:"";Z.trim()!==""&&(F.trim().length===0||Z.startsWith(F)||Z.trimStart().startsWith(F.trim()))&&(X.content=Z)},b=()=>{var Z;if(Et){let F=(Z=Et.close)==null?void 0:Z.call(Et);F instanceof Promise&&F.catch(()=>{})}U.delete(X.id),te.delete(X.id),X.streaming=!1,d(X)};if(!Et){ut(tt),b();return}let ne=Nr(lt);if(ne!==null&&ne.trim()!==""){ut(ne),b();return}let T=Z=>{var Ue;let F=typeof Z=="string"?Z:(Ue=Z==null?void 0:Z.text)!=null?Ue:null;if(F!==null&&F.trim()!=="")return F;let he=Et.getExtractedText();return he!==null&&he.trim()!==""?he:tt},x;try{x=Et.processChunk(lt)}catch{ut(tt),b();return}if(x instanceof Promise){x.then(Z=>{ut(T(Z)),b()}).catch(()=>{ut(tt),b()});return}ut(T(x)),b()},W=null,ae=new Map,$=(q=this.config.iterationDisplay)!=null?q:"separate";for(;;){let{done:X,value:Ve}=await s.read();if(X)break;a+=o.decode(Ve,{stream:!0});let tt=a.split(`
4
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=r)return e!==null?{text:e,raw:n}:null;let s=n.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(n);return o!==null&&(e=o),r=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},Nr=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},zs=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},qs=()=>{var r;let e=fp();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(r=e.close)==null?void 0:r.bind(e)}},Us=()=>{let e=null,r=0;return{getExtractedText:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=Tc(t,Mc|kc);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?as(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=as(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},hp=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?as(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?as(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>r,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return r!==null?{text:r,raw:o}:null;try{let i=Tc(o,Mc|kc),u=s(i);u!==null&&(r=u)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},Vs=()=>{let e=null;return{processChunk:r=>{if(!r.trim().startsWith("<"))return null;let n=r.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:r}):null},getExtractedText:()=>e}};var yp="https://api.runtype.com/v1/dispatch",Js="https://api.runtype.com",Ys=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 bp(e){switch(e){case"json":return Us;case"regex-json":return qs;case"xml":return Vs;default:return zs}}var Pc=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function xp(e,r){if(!e)return r;let t=e.trim(),n=r.trim();if(t.length===0)return r;if(n.length===0)return e;let s=Pc(t);if(!Pc(n))return e;if(!s||n===t||n.startsWith(t))return r;let a=Nr(e);return Nr(r)!==null&&a===null?r:e}var Xr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:yp,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:bp(r.parserType),this.contextProviders=(s=r.contextProviders)!=null?s:[],this.requestMiddleware=r.requestMiddleware,this.customFetch=r.customFetch,this.parseSSEEvent=r.parseSSEEvent,this.getHeaders=r.getHeaders}setSSEEventCallback(r){this.onSSEEvent=r}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(r){var n;let t=((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Js;return r==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var r,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let n=await this.sessionInitPromise;return this.clientSession=n,(t=(r=this.config).onSessionInit)==null||t.call(r,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let r=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...r&&{sessionId:r}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await n.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Js}/v1/client/feedback`}async sendFeedback(r){var o,a;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(r.type)&&!r.messageId)throw new Error(`messageId is required for ${r.type} feedback type`);if(r.type==="csat"&&(r.rating===void 0||r.rating<1||r.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(r.type==="nps"&&(r.rating===void 0||r.rating<0||r.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",r);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:r,comment:t})}async submitNPSFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:r,comment:t})}async dispatch(r,t){return this.isAgentMode()?this.dispatchAgent(r,t):this.isClientTokenMode()?this.dispatchClientToken(r,t):this.dispatchProxy(r,t)}async dispatchClientToken(r,t){var s,o,a,i;let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});try{let u=await this.initSession();if(new Date>=new Date(u.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let g=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:g}),g}let c=await this.buildPayload(r.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([g])=>g!=="sessionId"&&g!=="session_id")):void 0,d={sessionId:u.sessionId,messages:r.messages.filter(Ys).map(g=>{var v,M,C;return{id:g.id,role:g.role,content:(C=(M=(v=g.contentParts)!=null?v:g.llmContent)!=null?M:g.rawContent)!=null?C:g.content}}),...r.assistantMessageId&&{assistantMessageId:r.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}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),signal:n.signal});if(!f.ok){let g=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let M=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:M}),M}if(f.status===429){let M=new Error(g.hint||"Message limit reached for this session.");throw t({type:"error",error:M}),M}let v=new Error(g.error||"Failed to send message");throw t({type:"error",error:v}),v}if(!f.body){let g=new Error("No response body received");throw t({type:"error",error:g}),g}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(u){let c=u instanceof Error?u:new Error(String(u));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...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:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...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:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(r,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Js}/v1/agents/${r.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:r.executionId,approvalId:r.approvalId,decision:t,streamResponse:!0})})}async buildAgentPayload(r){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=r.slice().filter(Ys).filter(s=>s.role==="user"||s.role==="assistant"||s.role==="system").filter(s=>!s.variant||s.variant==="assistant").sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),n={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}return n}async buildPayload(r){let n={messages:r.slice().filter(Ys).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(r,t,n,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let u=p=>{let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return n.current=d,s(d),d},c=p=>n.current?n.current:u(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,s(n.current)),u(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,s(p)}return i.done&&(n.current&&(n.current.streaming=!1,s(n.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(r,t,n){var q,de,_e,ee,le,It,dt,Dt,Xt,je,me,Ne,Wt,Rt,ot,st,nn,tn,rn,z,He,ye,ht,$e,ce,Se,Oe,Ct,jt,pt,zt,yt,Ze,bt,De,qt,Gn,nr,$n,et,Tr,Kn,Mr,Wn,jr,ur,rr,at,An,_n,dn,mr,En,At,pn,Rn,gr,or,fr,Xn,Tn,Zn,wt,Nt,Ot,Mn,hr,jn,kn,D,zn,Hn,yr,fn,hn,ie,Ln,sr,qo,co,Uo,zr,Qe,po,Bn,yn,Vo,Jo,uo,ar,Yo,kr,mo,ir,go,br,xr,Go,Ko,Os,Lr,Ir,Ht,qr,Ur,fo,Qn,Xo,ho,yo,bo,un,In,lr,qe,xo,Pr,qn,Zo,Vr,Jr,Wr;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),u=0,c=()=>i+u++,p=X=>{let Ve=X.reasoning?{...X.reasoning,chunks:[...X.reasoning.chunks]}:void 0,tt=X.toolCall?{...X.toolCall,chunks:X.toolCall.chunks?[...X.toolCall.chunks]:void 0}:void 0,xt=X.tools?X.tools.map(lt=>({...lt,chunks:lt.chunks?[...lt.chunks]:void 0})):void 0;return{...X,reasoning:Ve,toolCall:tt,tools:xt}},d=X=>{t({type:"message",message:p(X)})},f=null,g={current:null},v={current:null},M=!1,C=new Map,S=new Map,k={lastId:null,byStep:new Map},H={lastId:null,byCall:new Map},w=X=>{if(X==null)return null;try{return String(X)}catch{return null}},L=X=>{var Ve,tt,xt,lt,Et;return w((Et=(lt=(xt=(tt=(Ve=X.stepId)!=null?Ve:X.step_id)!=null?tt:X.step)!=null?xt:X.parentId)!=null?lt:X.flowStepId)!=null?Et:X.flow_step_id)},P=X=>{var Ve,tt,xt,lt,Et,ut,b;return w((b=(ut=(Et=(lt=(xt=(tt=(Ve=X.callId)!=null?Ve:X.call_id)!=null?tt:X.requestId)!=null?xt:X.request_id)!=null?lt:X.toolCallId)!=null?Et:X.tool_call_id)!=null?ut:X.stepId)!=null?b:X.step_id)},E=n,Y=!1,Q=()=>{if(f)return f;let X;return!Y&&E?(X=E,Y=!0):E&&v.current?X=`${E}_${v.current}`:X=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:X,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},d(f),f},G=(X,Ve)=>{k.lastId=Ve,X&&k.byStep.set(X,Ve)},O=(X,Ve)=>{var Et;let tt=(Et=X.reasoningId)!=null?Et:X.id,xt=L(X);if(tt){let ut=String(tt);return G(xt,ut),ut}if(xt){let ut=k.byStep.get(xt);if(ut)return k.lastId=ut,ut}if(k.lastId&&!Ve)return k.lastId;if(!Ve)return null;let lt=`reason-${c()}`;return G(xt,lt),lt},re=X=>{let Ve=C.get(X);if(Ve)return Ve;let tt={id:`reason-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:X,status:"streaming",chunks:[]}};return C.set(X,tt),d(tt),tt},we=(X,Ve)=>{H.lastId=Ve,X&&H.byCall.set(X,Ve)},oe=new Set,ve=new Map,We=new Set,ge=new Map,ke=X=>{if(!X)return!1;let Ve=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ve==="emit_artifact_markdown"||Ve==="emit_artifact_component"},Le=(X,Ve)=>{var Et;let tt=(Et=X.toolId)!=null?Et:X.id,xt=P(X);if(tt){let ut=String(tt);return we(xt,ut),ut}if(xt){let ut=H.byCall.get(xt);if(ut)return H.lastId=ut,ut}if(H.lastId&&!Ve)return H.lastId;if(!Ve)return null;let lt=`tool-${c()}`;return we(xt,lt),lt},se=X=>{let Ve=S.get(X);if(Ve)return Ve;let tt={id:`tool-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:X,status:"pending"}};return S.set(X,tt),d(tt),tt},K=X=>{if(typeof X=="number"&&Number.isFinite(X))return X;if(typeof X=="string"){let Ve=Number(X);if(!Number.isNaN(Ve)&&Number.isFinite(Ve))return Ve;let tt=Date.parse(X);if(!Number.isNaN(tt))return tt}return Date.now()},ue=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},U=new Map,te=new Map,fe=new Map,pe=new Map;function Re(X,Ve,tt,xt){let lt=X.get(Ve);lt||(lt=[],X.set(Ve,lt));let Et=0,ut=lt.length;for(;Et<ut;){let ne=Et+ut>>>1;lt[ne].seq<tt?Et=ne+1:ut=ne}lt.splice(Et,0,{seq:tt,text:xt});let b="";for(let ne=0;ne<lt.length;ne++)b+=lt[ne].text;return b}let Xe=null,j=(X,Ve)=>{let tt=ue(Ve),xt=te.get(X.id),lt=xp(xt,tt);X.rawContent=lt;let Et=U.get(X.id),ut=Z=>{var he;let F=(he=X.content)!=null?he:"";Z.trim()!==""&&(F.trim().length===0||Z.startsWith(F)||Z.trimStart().startsWith(F.trim()))&&(X.content=Z)},b=()=>{var Z;if(Et){let F=(Z=Et.close)==null?void 0:Z.call(Et);F instanceof Promise&&F.catch(()=>{})}U.delete(X.id),te.delete(X.id),X.streaming=!1,d(X)};if(!Et){ut(tt),b();return}let ne=Nr(lt);if(ne!==null&&ne.trim()!==""){ut(ne),b();return}let T=Z=>{var Ue;let F=typeof Z=="string"?Z:(Ue=Z==null?void 0:Z.text)!=null?Ue:null;if(F!==null&&F.trim()!=="")return F;let he=Et.getExtractedText();return he!==null&&he.trim()!==""?he:tt},x;try{x=Et.processChunk(lt)}catch{ut(tt),b();return}if(x instanceof Promise){x.then(Z=>{ut(T(Z)),b()}).catch(()=>{ut(tt),b()});return}ut(T(x)),b()},W=null,ae=new Map,$=(q=this.config.iterationDisplay)!=null?q:"separate";for(;;){let{done:X,value:Ve}=await s.read();if(X)break;a+=o.decode(Ve,{stream:!0});let tt=a.split(`
5
5
 
6
6
  `);a=(de=tt.pop())!=null?de:"";for(let xt of tt){let lt=xt.split(`
7
- `),Et="message",ut="";for(let T of lt)T.startsWith("event:")?Et=T.replace("event:","").trim():T.startsWith("data:")&&(ut+=T.replace("data:","").trim());if(!ut)continue;let b;try{b=JSON.parse(ut)}catch(T){t({type:"error",error:T instanceof Error?T:new Error("Failed to parse chat stream payload")});continue}let ne=Et!=="message"?Et:(_e=b.type)!=null?_e:"message";if((ee=this.onSSEEvent)==null||ee.call(this,ne,b),this.parseSSEEvent){g.current=f;let T=await this.handleCustomSSEEvent(b,t,g,d,c,v);if(g.current&&g.current!==f&&(f=g.current),T)continue}if(ne==="reason_start"){let T=(le=O(b,!0))!=null?le:`reason-${c()}`,x=re(T);x.reasoning=(Lt=x.reasoning)!=null?Lt:{id:T,status:"streaming",chunks:[]},x.reasoning.startedAt=(Dt=x.reasoning.startedAt)!=null?Dt:K((ct=b.startedAt)!=null?ct:b.timestamp),x.reasoning.completedAt=void 0,x.reasoning.durationMs=void 0,x.streaming=!0,x.reasoning.status="streaming",d(x)}else if(ne==="reason_delta"||ne==="reason_chunk"){let T=(je=(Xt=O(b,!1))!=null?Xt:O(b,!0))!=null?je:`reason-${c()}`,x=re(T);x.reasoning=(me=x.reasoning)!=null?me:{id:T,status:"streaming",chunks:[]},x.reasoning.startedAt=(Pt=x.reasoning.startedAt)!=null?Pt:K((Ne=b.startedAt)!=null?Ne:b.timestamp);let Z=(st=(ot=(Wt=b.reasoningText)!=null?Wt:b.text)!=null?ot:b.delta)!=null?st:"";if(Z&&b.hidden!==!0){let F=typeof b.sequenceIndex=="number"?b.sequenceIndex:void 0;if(F!==void 0){let he=Re(pe,T,F,String(Z));x.reasoning.chunks=[he]}else x.reasoning.chunks.push(String(Z))}if(x.reasoning.status=b.done?"complete":"streaming",b.done){x.reasoning.completedAt=K((nn=b.completedAt)!=null?nn:b.timestamp);let F=(tn=x.reasoning.startedAt)!=null?tn:Date.now();x.reasoning.durationMs=Math.max(0,((rn=x.reasoning.completedAt)!=null?rn:Date.now())-F),pe.delete(T)}x.streaming=x.reasoning.status!=="complete",d(x)}else if(ne==="reason_complete"){let T=(He=(z=O(b,!1))!=null?z:O(b,!0))!=null?He:`reason-${c()}`,x=C.get(T);if(x!=null&&x.reasoning){x.reasoning.status="complete",x.reasoning.completedAt=K((ye=b.completedAt)!=null?ye:b.timestamp);let F=(ht=x.reasoning.startedAt)!=null?ht:Date.now();x.reasoning.durationMs=Math.max(0,(($e=x.reasoning.completedAt)!=null?$e:Date.now())-F),x.streaming=!1,pe.delete(T),d(x)}let Z=L(b);Z&&k.byStep.delete(Z)}else if(ne==="tool_start"){let T=(ce=Le(b,!0))!=null?ce:`tool-${c()}`,x=(Se=b.toolName)!=null?Se:b.name;if(ke(x)){oe.add(T);continue}let Z=se(T),F=(Oe=Z.toolCall)!=null?Oe:{id:T,status:"pending"};F.name=x!=null?x:F.name,F.status="running",b.args!==void 0?F.args=b.args:b.parameters!==void 0&&(F.args=b.parameters),F.startedAt=(jt=F.startedAt)!=null?jt:K((Ct=b.startedAt)!=null?Ct:b.timestamp),F.completedAt=void 0,F.durationMs=void 0,Z.toolCall=F,Z.streaming=!0;let he=b.agentContext;(he||b.executionId)&&(Z.agentMetadata={executionId:(dt=he==null?void 0:he.executionId)!=null?dt:b.executionId,iteration:(zt=he==null?void 0:he.iteration)!=null?zt:b.iteration}),d(Z)}else if(ne==="tool_chunk"||ne==="tool_delta"){let T=(Ze=(yt=Le(b,!1))!=null?yt:Le(b,!0))!=null?Ze:`tool-${c()}`;if(oe.has(T))continue;let x=se(T),Z=(bt=x.toolCall)!=null?bt:{id:T,status:"running"};Z.startedAt=(qt=Z.startedAt)!=null?qt:K((De=b.startedAt)!=null?De:b.timestamp);let F=($n=(nr=(Gn=b.text)!=null?Gn:b.delta)!=null?nr:b.message)!=null?$n:"";F&&(Z.chunks=(et=Z.chunks)!=null?et:[],Z.chunks.push(String(F))),Z.status="running",x.toolCall=Z,x.streaming=!0;let he=b.agentContext;(he||b.executionId)&&(x.agentMetadata=(Mr=x.agentMetadata)!=null?Mr:{executionId:(Tr=he==null?void 0:he.executionId)!=null?Tr:b.executionId,iteration:(Kn=he==null?void 0:he.iteration)!=null?Kn:b.iteration}),d(x)}else if(ne==="tool_complete"){let T=(jr=(Wn=Le(b,!1))!=null?Wn:Le(b,!0))!=null?jr:`tool-${c()}`;if(oe.has(T)){oe.delete(T);continue}let x=se(T),Z=(ur=x.toolCall)!=null?ur:{id:T,status:"running"};Z.status="complete",b.result!==void 0&&(Z.result=b.result),typeof b.duration=="number"&&(Z.duration=b.duration),Z.completedAt=K((rr=b.completedAt)!=null?rr:b.timestamp);let F=(at=b.duration)!=null?at:b.executionTime;if(typeof F=="number")Z.durationMs=F;else{let it=(An=Z.startedAt)!=null?An:Date.now();Z.durationMs=Math.max(0,((_n=Z.completedAt)!=null?_n:Date.now())-it)}x.toolCall=Z,x.streaming=!1;let he=b.agentContext;(he||b.executionId)&&(x.agentMetadata=(En=x.agentMetadata)!=null?En:{executionId:(dn=he==null?void 0:he.executionId)!=null?dn:b.executionId,iteration:(mr=he==null?void 0:he.iteration)!=null?mr:b.iteration}),d(x);let Ue=P(b);Ue&&H.byCall.delete(Ue)}else if(ne==="text_start"){let T=b.partId;if(T!==void 0&&v.current!==null&&T!==v.current){let x=f;x&&(x.streaming=!1,d(x),Xe=x,f=null,M=!0)}T!==void 0&&(v.current=T)}else if(ne==="text_end"){let T=f;T&&(T.streaming=!1,d(T),Xe=T,f=null,M=!0)}else if(ne==="step_chunk"||ne==="step_delta"){let T=b.stepType,x=b.executionType;if(T==="tool"||x==="context")continue;let Z=b.partId;if(Z!==void 0&&v.current!==null&&Z!==v.current){let Ue=f;Ue&&(Ue.streaming=!1,d(Ue),Xe=Ue,f=null,M=!0)}Z!==void 0&&(v.current=Z);let F=Q();Z!==void 0&&!F.partId&&(F.partId=Z);let he=(gr=(Rn=(pn=(At=b.text)!=null?At:b.delta)!=null?pn:b.content)!=null?Rn:b.chunk)!=null?gr:"";if(he){let Ue=typeof b.seq=="number"?b.seq:void 0,it;Ue!==void 0?it=Re(fe,F.id,Ue,he):it=((or=te.get(F.id))!=null?or:"")+he,F.rawContent=it,U.has(F.id)||U.set(F.id,this.createStreamParser());let $t=U.get(F.id),Vt=it.trim().startsWith("{")||it.trim().startsWith("[");if(Vt&&te.set(F.id,it),$t.__isPlainTextParser===!0){Ue!==void 0?F.content=it:F.content+=he,te.delete(F.id),U.delete(F.id),F.rawContent=void 0,d(F);continue}let Ft=$t.processChunk(it);if(Ft instanceof Promise)Ft.then(Ge=>{var Zt;let kt=typeof Ge=="string"?Ge:(Zt=Ge==null?void 0:Ge.text)!=null?Zt:null;if(kt!==null&&kt.trim()!=="")F.content=kt,d(F);else if(!Vt&&!it.trim().startsWith("<")){let on=f;on&&on.id===F.id&&(Ue!==void 0?on.content=it:on.content+=he,te.delete(on.id),U.delete(on.id),on.rawContent=void 0,d(on))}}).catch(()=>{Ue!==void 0?F.content=it:F.content+=he,te.delete(F.id),U.delete(F.id),F.rawContent=void 0,d(F)});else{let Ge=typeof Ft=="string"?Ft:(fr=Ft==null?void 0:Ft.text)!=null?fr:null;Ge!==null&&Ge.trim()!==""?(F.content=Ge,d(F)):!Vt&&!it.trim().startsWith("<")&&(Ue!==void 0?F.content=it:F.content+=he,te.delete(F.id),U.delete(F.id),F.rawContent=void 0,d(F))}}if(b.isComplete){let Ue=(Tn=(Xn=b.result)==null?void 0:Xn.response)!=null?Tn:F.content;if(Ue){let it=te.get(F.id),$t=it!=null?it:ue(Ue);F.rawContent=$t;let Vt=U.get(F.id),Jt=null,Ft=!1;if(Vt&&(Jt=Vt.getExtractedText(),Jt===null&&(Jt=Nr($t)),Jt===null)){let Ge=Vt.processChunk($t);Ge instanceof Promise?(Ft=!0,Ge.then(kt=>{var on;let Zt=typeof kt=="string"?kt:(on=kt==null?void 0:kt.text)!=null?on:null;if(Zt!==null){let Tt=f;Tt&&Tt.id===F.id&&(Tt.content=Zt,Tt.streaming=!1,U.delete(Tt.id),te.delete(Tt.id),fe.delete(Tt.id),d(Tt))}})):Jt=typeof Ge=="string"?Ge:(Zn=Ge==null?void 0:Ge.text)!=null?Zn:null}if(!Ft){Jt!==null&&Jt.trim()!==""?F.content=Jt:te.has(F.id)||(F.content=ue(Ue));let Ge=U.get(F.id);if(Ge){let kt=(wt=Ge.close)==null?void 0:wt.call(Ge);kt instanceof Promise&&kt.catch(()=>{}),U.delete(F.id)}te.delete(F.id),fe.delete(F.id),F.streaming=!1,d(F)}}}}else if(ne==="step_complete"){let T=b.stepType,x=b.executionType;if(T==="tool"||x==="context")continue;if(M){if(f!==null){let it=f;U.delete(it.id),te.delete(it.id),fe.delete(it.id),it.streaming!==!1&&(it.streaming=!1,d(it))}let he=(Nt=b.result)==null?void 0:Nt.response,Ue=Xe;Ue&&(he!=null?j(Ue,he):(U.delete(Ue.id),te.delete(Ue.id))),Xe=null;continue}let Z=(Ot=b.result)==null?void 0:Ot.response,F=Q();if(Z!=null){let he=U.get(F.id),Ue=!1,it=!1;if(he){let $t=he.getExtractedText(),Vt=te.get(F.id),Jt=Vt!=null?Vt:ue(Z);if(F.rawContent=Jt,$t!==null&&$t.trim()!=="")F.content=$t,Ue=!0;else{let Ft=Nr(Jt);if(Ft!==null)F.content=Ft,Ue=!0;else{let Ge=he.processChunk(Jt);if(Ge instanceof Promise)it=!0,Ge.then(kt=>{var on;let Zt=typeof kt=="string"?kt:(on=kt==null?void 0:kt.text)!=null?on:null;if(Zt!==null&&Zt.trim()!==""){let Tt=f;Tt&&Tt.id===F.id&&(Tt.content=Zt,Tt.streaming=!1,U.delete(Tt.id),te.delete(Tt.id),fe.delete(Tt.id),d(Tt))}else{let Tt=he.getExtractedText(),mn=f;mn&&mn.id===F.id&&(Tt!==null&&Tt.trim()!==""?mn.content=Tt:te.has(mn.id)||(mn.content=ue(Z)),mn.streaming=!1,U.delete(mn.id),te.delete(mn.id),fe.delete(mn.id),d(mn))}});else{let kt=typeof Ge=="string"?Ge:(Mn=Ge==null?void 0:Ge.text)!=null?Mn:null;if(kt!==null&&kt.trim()!=="")F.content=kt,Ue=!0;else{let Zt=he.getExtractedText();Zt!==null&&Zt.trim()!==""&&(F.content=Zt,Ue=!0)}}}}}if(!it){if(!F.rawContent){let $t=te.get(F.id);F.rawContent=$t!=null?$t:ue(Z)}if(!Ue&&!te.has(F.id)&&(F.content=ue(Z)),he){let $t=(hr=he.close)==null?void 0:hr.call(he);$t instanceof Promise&&$t.catch(()=>{})}U.delete(F.id),te.delete(F.id),fe.delete(F.id),F.streaming=!1,d(F)}}else U.delete(F.id),te.delete(F.id),fe.delete(F.id),F.streaming=!1,d(F)}else if(ne==="flow_complete"){let T=(jn=b.result)==null?void 0:jn.response;if(M){if(f!==null){let x=f;U.delete(x.id),te.delete(x.id),fe.delete(x.id),x.streaming!==!1&&(x.streaming=!1,d(x))}}else if(T!=null){let x=Q(),Z=te.get(x.id),F=Z!=null?Z:ue(T);x.rawContent=F;let he=ue(T),Ue=U.get(x.id);if(Ue){let Vt=Nr(F);if(Vt!==null)he=Vt;else{let Jt=Ue.processChunk(F);Jt instanceof Promise&&Jt.then(Ge=>{var Zt;let kt=typeof Ge=="string"?Ge:(Zt=Ge==null?void 0:Ge.text)!=null?Zt:null;kt!==null&&(x.content=kt,x.streaming=!1,d(x))});let Ft=Ue.getExtractedText();Ft!==null&&(he=Ft)}}U.delete(x.id),te.delete(x.id),fe.delete(x.id);let it=he!==x.content,$t=x.streaming!==!1;it&&(x.content=he),x.streaming=!1,(it||$t)&&d(x)}else if(f!==null){let x=f;U.delete(x.id),te.delete(x.id),fe.delete(x.id),x.streaming!==!1&&(x.streaming=!1,d(x))}t({type:"status",status:"idle"})}else if(ne==="agent_start")W={executionId:b.executionId,agentId:(kn=b.agentId)!=null?kn:"virtual",agentName:(D=b.agentName)!=null?D:"",status:"running",currentIteration:0,maxTurns:(zn=b.maxTurns)!=null?zn:1,startedAt:K(b.startedAt)};else if(ne==="agent_iteration_start"){if(W&&(W.currentIteration=b.iteration),$==="separate"&&b.iteration>1){let T=f;T&&(T.streaming=!1,d(T),ae.set(b.iteration-1,T),f=null)}}else if(ne!=="agent_turn_start"){if(ne==="agent_turn_delta"){if(b.contentType==="text"){let T=Q();T.content+=(Hn=b.delta)!=null?Hn:"",T.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId,agentName:W==null?void 0:W.agentName},d(T)}else if(b.contentType==="thinking"){let T=(yr=b.turnId)!=null?yr:`agent-think-${b.iteration}`,x=re(T);x.reasoning=(fn=x.reasoning)!=null?fn:{id:T,status:"streaming",chunks:[]},x.reasoning.chunks.push((hn=b.delta)!=null?hn:""),x.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId},d(x)}else if(b.contentType==="tool_input"){let T=(ie=b.toolCallId)!=null?ie:H.lastId;if(T){let x=S.get(T);x!=null&&x.toolCall&&(x.toolCall.chunks=(Ln=x.toolCall.chunks)!=null?Ln:[],x.toolCall.chunks.push((sr=b.delta)!=null?sr:""),d(x))}}}else if(ne==="agent_turn_complete"){let T=b.turnId;if(T){let x=C.get(T);if(x!=null&&x.reasoning){x.reasoning.status="complete",x.reasoning.completedAt=K(b.completedAt);let Z=(qo=x.reasoning.startedAt)!=null?qo:Date.now();x.reasoning.durationMs=Math.max(0,((co=x.reasoning.completedAt)!=null?co:Date.now())-Z),x.streaming=!1,d(x)}}}else if(ne==="agent_tool_start"){let T=(Uo=b.toolCallId)!=null?Uo:`agent-tool-${c()}`;we(P(b),T);let x=se(T),Z=(zr=x.toolCall)!=null?zr:{id:T,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Z.name=(po=(Qe=b.toolName)!=null?Qe:b.name)!=null?po:Z.name,Z.status="running",b.parameters!==void 0&&(Z.args=b.parameters),Z.startedAt=K((Bn=b.startedAt)!=null?Bn:b.timestamp),x.toolCall=Z,x.streaming=!0,x.agentMetadata={executionId:b.executionId,iteration:b.iteration},d(x)}else if(ne==="agent_tool_delta"){let T=(yn=b.toolCallId)!=null?yn:H.lastId;if(T){let x=(Vo=S.get(T))!=null?Vo:se(T);x.toolCall&&(x.toolCall.chunks=(Jo=x.toolCall.chunks)!=null?Jo:[],x.toolCall.chunks.push((uo=b.delta)!=null?uo:""),x.toolCall.status="running",x.streaming=!0,d(x))}}else if(ne==="agent_tool_complete"){let T=(ar=b.toolCallId)!=null?ar:H.lastId;if(T){let x=(Yo=S.get(T))!=null?Yo:se(T);if(x.toolCall){x.toolCall.status="complete",b.result!==void 0&&(x.toolCall.result=b.result),typeof b.executionTime=="number"&&(x.toolCall.durationMs=b.executionTime),x.toolCall.completedAt=K((kr=b.completedAt)!=null?kr:b.timestamp),x.streaming=!1,d(x);let Z=P(b);Z&&H.byCall.delete(Z)}}}else if(ne!=="agent_iteration_complete"){if(ne==="agent_reflection"||ne==="agent_reflect"){let T=`agent-reflection-${b.executionId}-${b.iteration}`,x={id:T,role:"assistant",content:(mo=b.reflection)!=null?mo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:T,status:"complete",chunks:[(ir=b.reflection)!=null?ir:""]},agentMetadata:{executionId:b.executionId,iteration:b.iteration}};d(x)}else if(ne==="agent_complete"){W&&(W.status=b.success?"complete":"error",W.completedAt=K(b.completedAt),W.stopReason=b.stopReason);let T=f;T&&(T.streaming=!1,d(T)),t({type:"status",status:"idle"})}else if(ne==="agent_error"){let T=typeof b.error=="string"?b.error:(br=(go=b.error)==null?void 0:go.message)!=null?br:"Agent execution error";b.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",T):t({type:"error",error:new Error(T)})}else if(ne!=="agent_ping"){if(ne==="agent_approval_start"){let T=(xr=b.approvalId)!=null?xr:`approval-${c()}`,x={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:(Go=W==null?void 0:W.agentId)!=null?Go:"virtual",executionId:(Os=(Ko=b.executionId)!=null?Ko:W==null?void 0:W.executionId)!=null?Os:"",toolName:(Lr=b.toolName)!=null?Lr:"",toolType:b.toolType,description:(Rt=b.description)!=null?Rt:`Execute ${(Ir=b.toolName)!=null?Ir:"tool"}`,parameters:b.parameters}};d(x)}else if(ne==="step_await"&&b.awaitReason==="approval_required"){let T=(qr=b.approvalId)!=null?qr:`approval-${c()}`,x={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:(Ur=W==null?void 0:W.agentId)!=null?Ur:"virtual",executionId:(Qn=(fo=b.executionId)!=null?fo:W==null?void 0:W.executionId)!=null?Qn:"",toolName:(Xo=b.toolName)!=null?Xo:"",toolType:b.toolType,description:(yo=b.description)!=null?yo:`Execute ${(ho=b.toolName)!=null?ho:"tool"}`,parameters:b.parameters}};d(x)}else if(ne==="agent_approval_complete"){let T=b.approvalId;if(T){let Z={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:(bo=b.decision)!=null?bo:"approved",agentId:(un=W==null?void 0:W.agentId)!=null?un:"virtual",executionId:(lr=(In=b.executionId)!=null?In:W==null?void 0:W.executionId)!=null?lr:"",toolName:(qe=b.toolName)!=null?qe:"",description:(xo=b.description)!=null?xo:"",resolvedAt:Date.now()}};d(Z)}}else if(ne==="artifact_start"||ne==="artifact_delta"||ne==="artifact_update"||ne==="artifact_complete"){if(ne==="artifact_start"){let T=b.artifactType,x=String(b.id),Z=typeof b.title=="string"?b.title:void 0;if(t({type:"artifact_start",id:x,artifactType:T,title:Z,component:typeof b.component=="string"?b.component:void 0}),ge.set(x,{markdown:"",title:Z}),!We.has(x)){We.add(x);let F={id:`artifact-ref-${x}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:x,title:Z,artifactType:T,status:"streaming"}})};ve.set(x,F),d(F)}}else if(ne==="artifact_delta"){let T=String(b.id),x=typeof b.delta=="string"?b.delta:String((Pr=b.delta)!=null?Pr:"");t({type:"artifact_delta",id:T,artDelta:x});let Z=ge.get(T);Z&&(Z.markdown+=x)}else if(ne==="artifact_update"){let T=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};t({type:"artifact_update",id:String(b.id),props:T,component:typeof b.component=="string"?b.component:void 0})}else if(ne==="artifact_complete"){let T=String(b.id);t({type:"artifact_complete",id:T});let x=ve.get(T);if(x){x.streaming=!1;try{let Z=JSON.parse((qn=x.rawContent)!=null?qn:"{}");if(Z.props){Z.props.status="complete";let F=ge.get(T);F!=null&&F.markdown&&(Z.props.markdown=F.markdown)}x.rawContent=JSON.stringify(Z)}catch{}ge.delete(T),d(x),ve.delete(T)}}}else if(ne==="transcript_insert"){let T=b.message;if(!T||typeof T!="object")continue;let x=String((Zo=T.id)!=null?Zo:`msg-${c()}`),Z=T.role,he={id:x,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof T.content=="string"?T.content:"",rawContent:typeof T.rawContent=="string"?T.rawContent:void 0,createdAt:typeof T.createdAt=="string"?T.createdAt:new Date().toISOString(),streaming:T.streaming===!0,...typeof T.variant=="string"?{variant:T.variant}:{},sequence:c()};if(d(he),he.rawContent)try{let Ue=JSON.parse(he.rawContent),it=(Vr=Ue==null?void 0:Ue.props)==null?void 0:Vr.artifactId;typeof it=="string"&&We.add(it)}catch{}f=null,g.current=null,U.delete(x),te.delete(x),fe.delete(x)}else if(ne==="error"||ne==="step_error"||ne==="dispatch_error"||ne==="flow_error"){let T=null;if(b.error instanceof Error)T=b.error;else if(ne==="dispatch_error"){let x=(Jr=b.message)!=null?Jr:b.error;x!=null&&x!==""&&(T=new Error(String(x)))}else if(ne==="step_error"||ne==="flow_error"){let x=b.error;typeof x=="string"&&x!==""?T=new Error(x):x!=null&&typeof x=="object"&&"message"in x&&(T=new Error(String((Wr=x.message)!=null?Wr:x)))}else ne==="error"&&b.error!=null&&b.error!==""&&(T=new Error(String(b.error)));if(T){t({type:"error",error:T});let x=f;x&&x.streaming&&(x.streaming=!1,d(x)),t({type:"status",status:"idle"})}}}}}}}}};function vp(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function Lo(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function Zr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var ds="[Image]";function Cp(e){return typeof e=="string"?[{type:"text",text:e}]:e}function wp(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function Sp(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Ap(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function ps(e){return{type:"text",text:e}}function Ep(e,r){return{type:"image",image:e,...(r==null?void 0:r.mimeType)&&{mimeType:r.mimeType},...(r==null?void 0:r.alt)&&{alt:r.alt}}}async function Tp(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;r({type:"image",image:s,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Mp(e,r=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${r.join(", ")}`}}var Wc=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],kp=["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"],dr=[...Wc,...kp];function Lp(e){return Wc.includes(e)||e.startsWith("image/")}function us(e){return Lp(e.type)}async function Rc(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;us(e)?r({type:"image",image:s,mimeType:e.type,alt:e.name}):r({type:"file",data:s,mimeType:e.type,filename:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Hc(e,r=dr,t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${r.join(", ")}`}}function Ip(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function Bc(e,r){let t=Ip(r).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]||t||"FILE"}var ms=class{constructor(r=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=r}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let u=new Uint8Array(this.remainder.length+r.length);u.set(this.remainder),u.set(r,this.remainder.length),t=u,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.ensureContext(),s=this.pcmToFloat32(t),o=n.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=n.createBufferSource();a.buffer=o,a.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let u=this.activeSources.indexOf(a);u!==-1&&this.activeSources.splice(u,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let r of this.activeSources)try{r.stop(),r.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(r){this.finishedCallbacks.push(r)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),s=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);n[o]=a/32768}return n}};var gs=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,n,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=r.createMediaStreamSource(t),this.analyserNode=r.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let u=Math.sqrt(i/a.length);(n==="silence"?u<s.threshold:u>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Io=class{constructor(r){this.config=r;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new gs;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,t,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(r=this.config)==null?void 0:r.host,i=(t=this.config)==null?void 0:t.agentId,u=(n=this.config)==null?void 0:n.clientToken;if(!i||!u)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${o}//${a}/ws/agents/${i}/voice?token=${u}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,d=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,g)=>{if(!this.ws)return g(new Error("WebSocket not created"));let v=!1,M=S=>{v||(v=!0,clearTimeout(C),g(new Error(S)))},C=setTimeout(()=>M("WebSocket connection timed out."+d),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(C),f())},{once:!0}),this.ws.addEventListener("error",()=>{M("WebSocket connection failed to "+p+"."+d)},{once:!0}),this.ws.addEventListener("close",S=>{if(!S.wasClean&&!v){let k=S.code!==1006?` (code ${S.code})`:"";M("WebSocket connection failed"+k+"."+d)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(r.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new ms(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var r,t,n,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let c=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(c)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,u=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:u,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let p=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",d=new Blob(this.audioChunks,{type:p});await this.sendAudio(d),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),s=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=n,s.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let c=0;c<t.length;c++)n[c]=t.charCodeAt(c);let s=r.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([n],{type:o}),i=URL.createObjectURL(a),u=new Audio(i);this.currentAudio=u,this.currentAudioUrl=i,u.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===u&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await u.play()}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Or=class{constructor(r={}){this.config=r;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(r=>r("connected"))}async startListening(){var r,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((r=this.config)==null?void 0:r.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(u=>u[0]).map(u=>u.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(u=>u({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Qr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Io(e.runtype);case"browser":if(!Or.isSupported())throw new Error("Browser speech recognition not supported");return new Or(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Gs(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Qr({type:"runtype",runtype:e.runtype});if(Or.isSupported())return Qr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function fs(e){try{return Gs(e),!0}catch{return!1}}var Po=class e{constructor(r={},t){this.config=r;this.callbacks=t;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.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=r=>{var t,n,s,o,a,i,u;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(s=r.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(u=(i=this.callbacks).onError)==null||u.call(i,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n;this.messages=[...(n=r.initialMessages)!=null?n:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Xr(r),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return fs((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,s;try{let o=r||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Qr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",u=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var p,d,f,g,v,M;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=c.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(d=c.transcript)!=null&&d.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=c.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(g=c.text)!=null&&g.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let C=(M=this.pendingVoiceAssistantMessageId)!=null?M:(v=[...this.messages].reverse().find(S=>S.role==="assistant"))==null?void 0:v.id;C&&this.ttsSpokenMessageIds.add(C)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:u,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var p,d;this.voiceStatus=c,this.voiceActive=c==="listening",(d=(p=this.callbacks).onVoiceStatusChanged)==null||d.call(p,c)}),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(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,s,o,a,i,u,c,p;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((s=r.runtype)==null?void 0:s.clientToken)||"",host:(o=r.runtype)==null?void 0:o.host,voiceId:(a=r.runtype)==null?void 0:a.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(u=r.runtype)==null?void 0:u.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(p=r.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new Xr(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:u,streaming:c=!1,voiceProcessing:p}=r,f={id:a!=null?a:t==="user"?Lo():t==="assistant"?Zr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p}};return this.upsertMessage(f),f}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:s,content:o,llmContent:a,contentParts:i,id:u,createdAt:c,sequence:p,streaming:d=!1}=n,g={id:u!=null?u:s==="user"?Lo():s==="assistant"?Zr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:d,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(g)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(r,t){var c,p,d,f,g;let n=r.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=Lo(),o=Zr(),a={id:s,role:"user",content:n||ds,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let u=[...this.messages];try{await this.client.dispatch({messages:u,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!M){let C={id:o,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(C)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,M||(v instanceof Error?(d=(p=this.callbacks).onError)==null||d.call(p,v):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,u;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=Zr();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:r},this.handleEvent)}catch(c){let p={id:r,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(p),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(u=(i=this.callbacks).onError)==null||u.call(i,new Error(String(c)))}}async connectStream(r,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var u,c,p;let n=`approval-${r.id}`,s={...r,status:t,resolvedAt:Date.now()},o={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let d;if(i?d=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):d=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),d){let f=null;if(d instanceof Response){if(!d.ok){let g=await d.json().catch(()=>null);throw new Error((u=g==null?void 0:g.error)!=null?u:`Approval request failed: ${d.status}`)}f=d.body}else d instanceof ReadableStream&&(f=d);f?await this.connectStream(f):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(d){(p=(c=this.callbacks).onError)==null||p.call(c,d instanceof Error?d:new Error(String(d)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var s;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(s=r.props)!=null?s:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((n=s.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...r.props},r.component&&(s.component=r.component));break}case"artifact_complete":{let s=this.artifacts.get(r.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var s;return{...n,streaming:!1,sequence:(s=n.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let s=n.content;s.trim()&&this.speak(s,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let s=new SpeechSynthesisUtterance(r),o=n.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>n.speak(s),50)}static pickBestVoice(r){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 s of t){let o=r.find(a=>a.name===s);if(o)return o}return(n=r.find(s=>s.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(s=>s.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===n?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var u,c;let s=new Date(t.createdAt).getTime(),o=new Date(n.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(u=t.sequence)!=null?u:0,i=(c=n.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(n.id)})}};var h=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},er=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};import*as Pp from"lucide";var be=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=Pp[s];return o?Wp(o,r,t,n):(console.warn(`Lucide icon "${e}" not found (tried "${s}"). Available icons: https://lucide.dev/icons`),null)}catch(s){return console.warn(`Failed to render Lucide icon "${e}":`,s),null}};function Wp(e,r,t,n){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(r)),s.setAttribute("height",String(r)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(n)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let a=o[0],i=o[1];if(i){let u=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&u.setAttribute(c,String(p))}),s.appendChild(u)}}}),s}var hs={allowedTypes:dr,maxFileSize:10*1024*1024,maxFiles:4};function Rp(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Hp(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-json":"file"}var eo=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:hs.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:hs.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:hs.maxFiles,onFileRejected:r.onFileRejected,onAttachmentsChange:r.onAttachmentsChange}}setPreviewsContainer(r){this.previewsContainer=r}updateConfig(r){r.allowedTypes!==void 0&&(this.config.allowedTypes=r.allowedTypes.length>0?r.allowedTypes:hs.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,s,o,a,i,u;if(r.length){for(let c of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,c,"count");continue}let p=Hc(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let d=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,d);continue}try{let d=await Rc(c),f=us(c)?URL.createObjectURL(c):null,g={id:Rp(),file:c,previewUrl:f,contentPart:d};this.attachments.push(g),this.renderPreview(g)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(u=(i=this.config).onAttachmentsChange)==null||u.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(u=>u.id===r);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${r}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=us(r.file),n=h("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",r.id),n.style.width="48px",n.style.height="48px",t&&r.previewUrl){let a=h("img");a.src=r.previewUrl,a.alt=r.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",n.appendChild(a)}else{let a=h("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=Hp(r.file.type),u=be(i,20,"var(--persona-muted, #6b7280)",1.5);u&&a.appendChild(u);let c=h("span");c.textContent=Bc(r.file.type,r.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),n.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=be("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(r.id)}),n.appendChild(s),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(r,t){return new e({allowedTypes:r==null?void 0:r.allowedTypes,maxFileSize:r==null?void 0:r.maxFileSize,maxFiles:r==null?void 0:r.maxFiles,onFileRejected:r==null?void 0:r.onFileRejected,onAttachmentsChange:t})}};var Dc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Wo(e,r){if(!e)return r;if(!r)return e;let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];Dc(o)&&Dc(s)?t[n]=Wo(o,s):t[n]=s}return t}var Nn="min(440px, calc(100vw - 24px))",Ks="440px",It={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{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:Nn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",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)"},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:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"}},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 Fc(e,r){if(!(!e&&!r))return e?r?Wo(e,r):e:r}function Xs(e){var r,t,n,s,o,a,i,u,c,p,d,f,g,v,M,C,S,k,H,w,L;return e?{...It,...e,theme:Fc(It.theme,e.theme),darkTheme:Fc(It.darkTheme,e.darkTheme),launcher:{...It.launcher,...e.launcher,dock:{...(r=It.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=It.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...It.copy,...e.copy},sendButton:{...It.sendButton,...e.sendButton},statusIndicator:{...It.statusIndicator,...e.statusIndicator},voiceRecognition:{...It.voiceRecognition,...e.voiceRecognition},features:(()=>{var re,we,oe,ve;let P=(re=It.features)==null?void 0:re.artifacts,E=(we=e.features)==null?void 0:we.artifacts,Y=(oe=It.features)==null?void 0:oe.scrollToBottom,Q=(ve=e.features)==null?void 0:ve.scrollToBottom,G=P===void 0&&E===void 0?void 0:{...P,...E,layout:{...P==null?void 0:P.layout,...E==null?void 0:E.layout}},O=Y===void 0&&Q===void 0?void 0:{...Y,...Q};return{...It.features,...e.features,...O!==void 0?{scrollToBottom:O}:{},...G!==void 0?{artifacts:G}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:It.suggestionChips,suggestionChipsConfig:{...It.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...It.layout,...e.layout,header:{...(a=It.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(u=It.layout)==null?void 0:u.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(d=(p=It.layout)==null?void 0:p.messages)==null?void 0:d.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(M=(v=It.layout)==null?void 0:v.messages)==null?void 0:M.timestamp,...(S=(C=e.layout)==null?void 0:C.messages)==null?void 0:S.timestamp}},slots:{...(k=It.layout)==null?void 0:k.slots,...(H=e.layout)==null?void 0:H.slots}},markdown:{...It.markdown,...e.markdown,options:{...(w=It.markdown)==null?void 0:w.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...It.messageActions,...e.messageActions}}:It}var Nc={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"}},Oc={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"}},$c={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:Nn,maxWidth:Ks,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"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"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:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",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 Ro(e,r){if(!r.startsWith("palette.")&&!r.startsWith("semantic.")&&!r.startsWith("components."))return r;let t=r.split("."),n=e;for(let s of t){if(n==null)return;n=n[s]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?Ro(e,n):n}function Zs(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let u=Ro(e,a);u!==void 0&&(r[i]={path:i,value:u,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),r}function _c(e){let r=[],t=[];return e.palette||r.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:r.length===0,errors:r,warnings:t}}function jc(e,r){let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[n]=jc(o,s):t[n]=s}return t}function Bp(e,r){return r?jc(e,r):e}function Ho(e,r={}){var s,o,a,i,u,c,p,d,f,g,v,M,C;let t={palette:Nc,semantic:Oc,components:$c},n={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(u=e==null?void 0:e.palette)==null?void 0:u.borders},radius:{...t.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...t.semantic.colors.interactive,...(f=(d=e==null?void 0:e.semantic)==null?void 0:d.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(v=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(M=e==null?void 0:e.semantic)==null?void 0:M.spacing},typography:{...t.semantic.typography,...(C=e==null?void 0:e.semantic)==null?void 0:C.typography}},components:Bp(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let S=_c(n);if(!S.valid)throw new Error(`Theme validation failed: ${S.errors.map(k=>k.message).join(", ")}`)}if(r.plugins)for(let S of r.plugins)n=S.transform(n);return n}function Qs(e){var v,M,C,S,k,H,w,L,P,E,Y,Q,G,O,re,we,oe,ve,We,ge,ke,Le,se,K,ue,U,te,fe,pe,Re,Xe,j,W,ae,$,q,de,_e,ee,le,Lt,ct,Dt,Xt,je,me,Ne,Pt,Wt,ot,st,nn,tn,rn,z,He,ye,ht,$e,ce,Se,Oe,Ct,jt,dt,zt,yt,Ze,bt,De,qt,Gn,nr,$n,et,Tr,Kn,Mr,Wn,jr,ur,rr,at,An,_n,dn,mr,En,At,pn,Rn,gr,or,fr,Xn,Tn,Zn,wt,Nt,Ot,Mn,hr,jn,kn,D,zn,Hn,yr,fn,hn;let r=Zs(e),t={};for(let[ie,Ln]of Object.entries(r)){let sr=ie.replace(/\./g,"-");t[`--persona-${sr}`]=Ln.value}t["--persona-primary"]=(v=t["--persona-semantic-colors-primary"])!=null?v:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(M=t["--persona-semantic-colors-secondary"])!=null?M:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(C=t["--persona-semantic-colors-accent"])!=null?C:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(S=t["--persona-semantic-colors-surface"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(k=t["--persona-semantic-colors-background"])!=null?k:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(H=t["--persona-semantic-colors-container"])!=null?H:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(w=t["--persona-semantic-colors-text"])!=null?w:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(L=t["--persona-semantic-colors-text-muted"])!=null?L:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(P=t["--persona-semantic-colors-text-inverse"])!=null?P:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(E=t["--persona-semantic-colors-border"])!=null?E:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(Y=t["--persona-semantic-colors-divider"])!=null?Y:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(Q=t["--persona-components-voice-recording-indicator"])!=null?Q:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(G=t["--persona-components-voice-recording-background"])!=null?G:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(O=t["--persona-components-voice-processing-icon"])!=null?O:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(re=t["--persona-components-voice-speaking-icon"])!=null?re:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(we=t["--persona-components-approval-requested-background"])!=null?we:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(oe=t["--persona-components-approval-requested-border"])!=null?oe:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(ve=t["--persona-components-approval-requested-text"])!=null?ve:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(We=t["--persona-components-approval-approve-background"])!=null?We:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(ge=t["--persona-components-approval-deny-background"])!=null?ge:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(ke=t["--persona-components-attachment-image-background"])!=null?ke:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Le=t["--persona-components-attachment-image-border"])!=null?Le:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(se=t["--persona-semantic-typography-fontFamily"])!=null?se:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(K=t["--persona-semantic-typography-fontSize"])!=null?K:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(ue=t["--persona-semantic-typography-fontWeight"])!=null?ue:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(U=t["--persona-semantic-typography-lineHeight"])!=null?U:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(te=t["--persona-palette-radius-sm"])!=null?te:"0.125rem",t["--persona-radius-md"]=(fe=t["--persona-palette-radius-md"])!=null?fe:"0.375rem",t["--persona-radius-lg"]=(pe=t["--persona-palette-radius-lg"])!=null?pe:"0.5rem",t["--persona-radius-xl"]=(Re=t["--persona-palette-radius-xl"])!=null?Re:"0.75rem",t["--persona-radius-full"]=(Xe=t["--persona-palette-radius-full"])!=null?Xe:"9999px",t["--persona-launcher-radius"]=(W=(j=t["--persona-components-launcher-borderRadius"])!=null?j:t["--persona-palette-radius-full"])!=null?W:"9999px",t["--persona-launcher-bg"]=(ae=t["--persona-components-launcher-background"])!=null?ae:t["--persona-primary"],t["--persona-launcher-fg"]=($=t["--persona-components-launcher-foreground"])!=null?$:t["--persona-text-inverse"],t["--persona-launcher-border"]=(q=t["--persona-components-launcher-border"])!=null?q:t["--persona-border"],t["--persona-button-primary-bg"]=(de=t["--persona-components-button-primary-background"])!=null?de:t["--persona-primary"],t["--persona-button-primary-fg"]=(_e=t["--persona-components-button-primary-foreground"])!=null?_e:t["--persona-text-inverse"],t["--persona-button-radius"]=(le=(ee=t["--persona-components-button-primary-borderRadius"])!=null?ee:t["--persona-palette-radius-full"])!=null?le:"9999px",t["--persona-panel-radius"]=(ct=(Lt=t["--persona-components-panel-borderRadius"])!=null?Lt:t["--persona-radius-xl"])!=null?ct:"0.75rem",t["--persona-panel-border"]=(Dt=t["--persona-components-panel-border"])!=null?Dt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(je=(Xt=t["--persona-components-panel-shadow"])!=null?Xt:t["--persona-palette-shadows-xl"])!=null?je:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Ne=(me=t["--persona-components-input-borderRadius"])!=null?me:t["--persona-radius-lg"])!=null?Ne:"0.5rem",t["--persona-message-user-radius"]=(Wt=(Pt=t["--persona-components-message-user-borderRadius"])!=null?Pt:t["--persona-radius-lg"])!=null?Wt:"0.5rem",t["--persona-message-assistant-radius"]=(st=(ot=t["--persona-components-message-assistant-borderRadius"])!=null?ot:t["--persona-radius-lg"])!=null?st:"0.5rem",t["--persona-header-bg"]=(nn=t["--persona-components-header-background"])!=null?nn:t["--persona-surface"],t["--persona-header-border"]=(tn=t["--persona-components-header-border"])!=null?tn:t["--persona-divider"],t["--persona-header-icon-bg"]=(rn=t["--persona-components-header-iconBackground"])!=null?rn:t["--persona-primary"],t["--persona-header-icon-fg"]=(z=t["--persona-components-header-iconForeground"])!=null?z:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(He=t["--persona-components-header-titleForeground"])!=null?He:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(ye=t["--persona-components-header-subtitleForeground"])!=null?ye:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(ht=t["--persona-components-header-actionIconForeground"])!=null?ht:t["--persona-muted"];let n=($e=e.components)==null?void 0:$e.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-input-background"]=(ce=t["--persona-components-input-background"])!=null?ce:t["--persona-surface"],t["--persona-input-placeholder"]=(Se=t["--persona-components-input-placeholder"])!=null?Se:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Oe=t["--persona-components-message-user-background"])!=null?Oe:t["--persona-accent"],t["--persona-message-user-text"]=(Ct=t["--persona-components-message-user-text"])!=null?Ct:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(jt=t["--persona-components-message-user-shadow"])!=null?jt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(dt=t["--persona-components-message-assistant-background"])!=null?dt:t["--persona-surface"],t["--persona-message-assistant-text"]=(zt=t["--persona-components-message-assistant-text"])!=null?zt:t["--persona-text"],t["--persona-message-assistant-border"]=(yt=t["--persona-components-message-assistant-border"])!=null?yt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Ze=t["--persona-components-message-assistant-shadow"])!=null?Ze:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(De=(bt=t["--persona-components-scrollToBottom-background"])!=null?bt:t["--persona-button-primary-bg"])!=null?De:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Gn=(qt=t["--persona-components-scrollToBottom-foreground"])!=null?qt:t["--persona-button-primary-fg"])!=null?Gn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(nr=t["--persona-components-scrollToBottom-border"])!=null?nr:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=($n=t["--persona-components-scrollToBottom-size"])!=null?$n:"40px",t["--persona-scroll-to-bottom-radius"]=(Kn=(Tr=(et=t["--persona-components-scrollToBottom-borderRadius"])!=null?et:t["--persona-button-radius"])!=null?Tr:t["--persona-radius-full"])!=null?Kn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Wn=(Mr=t["--persona-components-scrollToBottom-shadow"])!=null?Mr:t["--persona-palette-shadows-sm"])!=null?Wn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(jr=t["--persona-components-scrollToBottom-padding"])!=null?jr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(ur=t["--persona-components-scrollToBottom-gap"])!=null?ur:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(at=(rr=t["--persona-components-scrollToBottom-fontSize"])!=null?rr:t["--persona-palette-typography-fontSize-sm"])!=null?at:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(An=t["--persona-components-scrollToBottom-iconSize"])!=null?An:"14px",t["--persona-tool-bubble-shadow"]=(_n=t["--persona-components-toolBubble-shadow"])!=null?_n:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(dn=t["--persona-components-reasoningBubble-shadow"])!=null?dn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(mr=t["--persona-components-composer-shadow"])!=null?mr:"none",t["--persona-md-inline-code-bg"]=(En=t["--persona-components-markdown-inlineCode-background"])!=null?En:t["--persona-container"],t["--persona-md-inline-code-color"]=(At=t["--persona-components-markdown-inlineCode-foreground"])!=null?At:t["--persona-text"],t["--persona-md-link-color"]=(Rn=(pn=t["--persona-components-markdown-link-foreground"])!=null?pn:t["--persona-accent"])!=null?Rn:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let u=t["--persona-components-markdown-prose-fontFamily"];u&&u!=="inherit"&&(t["--persona-md-prose-font-family"]=u),t["--persona-md-code-block-bg"]=(gr=t["--persona-components-markdown-codeBlock-background"])!=null?gr:t["--persona-container"],t["--persona-md-code-block-border-color"]=(or=t["--persona-components-markdown-codeBlock-borderColor"])!=null?or:t["--persona-border"],t["--persona-md-code-block-text-color"]=(fr=t["--persona-components-markdown-codeBlock-textColor"])!=null?fr:"inherit",t["--persona-md-table-header-bg"]=(Xn=t["--persona-components-markdown-table-headerBackground"])!=null?Xn:t["--persona-container"],t["--persona-md-table-border-color"]=(Tn=t["--persona-components-markdown-table-borderColor"])!=null?Tn:t["--persona-border"],t["--persona-md-hr-color"]=(Zn=t["--persona-components-markdown-hr-color"])!=null?Zn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(wt=t["--persona-components-markdown-blockquote-borderColor"])!=null?wt:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Nt=t["--persona-components-markdown-blockquote-background"])!=null?Nt:"transparent",t["--persona-md-blockquote-text-color"]=(Ot=t["--persona-components-markdown-blockquote-textColor"])!=null?Ot:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Mn=t["--persona-components-collapsibleWidget-container"])!=null?Mn:t["--persona-surface"],t["--cw-surface"]=(hr=t["--persona-components-collapsibleWidget-surface"])!=null?hr:t["--persona-surface"],t["--cw-border"]=(jn=t["--persona-components-collapsibleWidget-border"])!=null?jn:t["--persona-border"],t["--persona-message-border"]=(kn=t["--persona-components-message-border"])!=null?kn:t["--persona-border"];let c=e.components,p=c==null?void 0:c.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let d=c==null?void 0:c.labelButton;d&&(d.background&&(t["--persona-label-btn-bg"]=d.background),d.border&&(t["--persona-label-btn-border"]=d.border),d.color&&(t["--persona-label-btn-color"]=d.color),d.padding&&(t["--persona-label-btn-padding"]=d.padding),d.borderRadius&&(t["--persona-label-btn-radius"]=d.borderRadius),d.hoverBackground&&(t["--persona-label-btn-hover-bg"]=d.hoverBackground),d.fontSize&&(t["--persona-label-btn-font-size"]=d.fontSize),d.gap&&(t["--persona-label-btn-gap"]=d.gap));let f=c==null?void 0:c.toggleGroup;f&&(f.gap&&(t["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(t["--persona-toggle-group-radius"]=f.borderRadius));let g=c==null?void 0:c.artifact;if(g!=null&&g.toolbar){let ie=g.toolbar;ie.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=ie.iconHoverColor),ie.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=ie.iconHoverBackground),ie.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=ie.iconPadding),ie.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=ie.iconBorderRadius),ie.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=ie.iconBorder),ie.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=ie.toggleGroupGap),ie.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=ie.toggleBorderRadius),ie.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=ie.copyBackground),ie.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=ie.copyBorder),ie.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=ie.copyColor),ie.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=ie.copyBorderRadius),ie.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=ie.copyPadding),ie.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=ie.copyMenuBackground,t["--persona-dropdown-bg"]=(D=t["--persona-dropdown-bg"])!=null?D:ie.copyMenuBackground),ie.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ie.copyMenuBorder,t["--persona-dropdown-border"]=(zn=t["--persona-dropdown-border"])!=null?zn:ie.copyMenuBorder),ie.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ie.copyMenuShadow,t["--persona-dropdown-shadow"]=(Hn=t["--persona-dropdown-shadow"])!=null?Hn:ie.copyMenuShadow),ie.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ie.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(yr=t["--persona-dropdown-radius"])!=null?yr:ie.copyMenuBorderRadius),ie.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ie.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(fn=t["--persona-dropdown-item-hover-bg"])!=null?fn:ie.copyMenuItemHoverBackground),ie.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ie.iconBackground),ie.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ie.toolbarBorder)}if(g!=null&&g.tab){let ie=g.tab;ie.background&&(t["--persona-artifact-tab-bg"]=ie.background),ie.activeBackground&&(t["--persona-artifact-tab-active-bg"]=ie.activeBackground),ie.activeBorder&&(t["--persona-artifact-tab-active-border"]=ie.activeBorder),ie.borderRadius&&(t["--persona-artifact-tab-radius"]=ie.borderRadius),ie.textColor&&(t["--persona-artifact-tab-color"]=ie.textColor),ie.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=ie.hoverBackground),ie.listBackground&&(t["--persona-artifact-tab-list-bg"]=ie.listBackground),ie.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=ie.listBorderColor),ie.listPadding&&(t["--persona-artifact-tab-list-padding"]=ie.listPadding)}if(g!=null&&g.pane){let ie=g.pane;if(ie.toolbarBackground){let Ln=(hn=Ro(e,ie.toolbarBackground))!=null?hn:ie.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Ln}}return t}var Dp={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 Fp={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"}}},zc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ys=()=>{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"},Np=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":ys()},qc=e=>Np(e),Op=e=>Ho(e),$p=e=>{var t;let r=Ho(void 0,{validate:!1});return Ho({...e,palette:{...r.palette,colors:{...Fp.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},bs=e=>{let r=qc(e),t=zc(e==null?void 0:e.theme),n=zc(e==null?void 0:e.darkTheme);return r==="dark"?$p(Wo(t!=null?t:{},n!=null?n:{})):Op(t)},_p=e=>Qs(e),$r=(e,r)=>{var o;let t=bs(r),n=_p(t);for(let[a,i]of Object.entries(n))e.style.setProperty(a,i);let s=(o=r==null?void 0:r.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},ea=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(ys())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(ys());t.addEventListener?(t.addEventListener("change",n),r.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),r.push(()=>t.removeListener(n)))}return()=>{r.forEach(t=>t())}};import{Idiomorph as jp}from"idiomorph";var Uc=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;jp.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&n){if(s.classList.contains("persona-animate-typing"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let u=(a=s.textContent)!=null?a:"",c=(i=o.textContent)!=null?i:"";if(u!==c)return}return!1}}}}})};function Vc(e,r){var t,n,s,o,a,i,u,c,p,d,f,g,v,M,C,S,k,H,w,L,P,E,Y,Q,G,O,re,we,oe;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(u=(i=e.rawContent)==null?void 0:i.length)!=null?u:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(d=e.approval)==null?void 0:d.status)!=null?f:"",(v=(g=e.toolCall)==null?void 0:g.status)!=null?v:"",(C=(M=e.toolCall)==null?void 0:M.name)!=null?C:"",(H=(k=(S=e.toolCall)==null?void 0:S.chunks)==null?void 0:k.length)!=null?H:0,(E=(P=(L=(w=e.toolCall)==null?void 0:w.chunks)==null?void 0:L[e.toolCall.chunks.length-1])==null?void 0:P.slice(-32))!=null?E:"",typeof((Y=e.toolCall)==null?void 0:Y.args)=="string"?e.toolCall.args.length:(Q=e.toolCall)!=null&&Q.args?JSON.stringify(e.toolCall.args).length:0,(re=(O=(G=e.reasoning)==null?void 0:G.chunks)==null?void 0:O.length)!=null?re:0,(oe=(we=e.contentParts)==null?void 0:we.length)!=null?oe:0,r].join("\0")}function Jc(){return new Map}function Yc(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Gc(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Kc(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function xs(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function Bo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Do(e,r){return Bo(e)-e.scrollTop<=r}function vs(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:u=!0,resumeRequiresDownwardScroll:c=!1}=e,p=t-n;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:t}:!r&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:r&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:r&&u&&!s?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function Cs(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:s=!1}=e;return r&&t<0?"pause":!r&&s&&t>0&&n?"resume":"none"}var cn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},wn=1e5,Cr=wn+1;function ta(e,r=wn){let t=e.style.position,n=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(r),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=n,e.style.isolation=s}}var Fo=0,wr=null;function na(e=document){var t;if(Fo++,Fo===1){let n=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;wr={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:o},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${o}px`,n.style.width="100%"}let r=!1;return()=>{var n;if(!r&&(r=!0,Fo=Math.max(0,Fo-1),Fo===0&&wr)){let s=e.body,o=(n=e.defaultView)!=null?n:window;s.style.overflow=wr.originalOverflow,s.style.position=wr.originalPosition,s.style.top=wr.originalTop,s.style.width=wr.originalWidth,o.scrollTo(0,wr.scrollY),wr=null}}}var ws={side:"right",width:"420px",animate:!0,reveal:"resize"},en=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},Jn=e=>{var t,n,s,o,a;let r=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(n=r==null?void 0:r.side)!=null?n:ws.side,width:(s=r==null?void 0:r.width)!=null?s:ws.width,animate:(o=r==null?void 0:r.animate)!=null?o:ws.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:ws.reveal}};var Yn={"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 No=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
7
+ `),Et="message",ut="";for(let T of lt)T.startsWith("event:")?Et=T.replace("event:","").trim():T.startsWith("data:")&&(ut+=T.replace("data:","").trim());if(!ut)continue;let b;try{b=JSON.parse(ut)}catch(T){t({type:"error",error:T instanceof Error?T:new Error("Failed to parse chat stream payload")});continue}let ne=Et!=="message"?Et:(_e=b.type)!=null?_e:"message";if((ee=this.onSSEEvent)==null||ee.call(this,ne,b),this.parseSSEEvent){g.current=f;let T=await this.handleCustomSSEEvent(b,t,g,d,c,v);if(g.current&&g.current!==f&&(f=g.current),T)continue}if(ne==="reason_start"){let T=(le=O(b,!0))!=null?le:`reason-${c()}`,x=re(T);x.reasoning=(It=x.reasoning)!=null?It:{id:T,status:"streaming",chunks:[]},x.reasoning.startedAt=(Dt=x.reasoning.startedAt)!=null?Dt:K((dt=b.startedAt)!=null?dt:b.timestamp),x.reasoning.completedAt=void 0,x.reasoning.durationMs=void 0,x.streaming=!0,x.reasoning.status="streaming",d(x)}else if(ne==="reason_delta"||ne==="reason_chunk"){let T=(je=(Xt=O(b,!1))!=null?Xt:O(b,!0))!=null?je:`reason-${c()}`,x=re(T);x.reasoning=(me=x.reasoning)!=null?me:{id:T,status:"streaming",chunks:[]},x.reasoning.startedAt=(Wt=x.reasoning.startedAt)!=null?Wt:K((Ne=b.startedAt)!=null?Ne:b.timestamp);let Z=(st=(ot=(Rt=b.reasoningText)!=null?Rt:b.text)!=null?ot:b.delta)!=null?st:"";if(Z&&b.hidden!==!0){let F=typeof b.sequenceIndex=="number"?b.sequenceIndex:void 0;if(F!==void 0){let he=Re(pe,T,F,String(Z));x.reasoning.chunks=[he]}else x.reasoning.chunks.push(String(Z))}if(x.reasoning.status=b.done?"complete":"streaming",b.done){x.reasoning.completedAt=K((nn=b.completedAt)!=null?nn:b.timestamp);let F=(tn=x.reasoning.startedAt)!=null?tn:Date.now();x.reasoning.durationMs=Math.max(0,((rn=x.reasoning.completedAt)!=null?rn:Date.now())-F),pe.delete(T)}x.streaming=x.reasoning.status!=="complete",d(x)}else if(ne==="reason_complete"){let T=(He=(z=O(b,!1))!=null?z:O(b,!0))!=null?He:`reason-${c()}`,x=C.get(T);if(x!=null&&x.reasoning){x.reasoning.status="complete",x.reasoning.completedAt=K((ye=b.completedAt)!=null?ye:b.timestamp);let F=(ht=x.reasoning.startedAt)!=null?ht:Date.now();x.reasoning.durationMs=Math.max(0,(($e=x.reasoning.completedAt)!=null?$e:Date.now())-F),x.streaming=!1,pe.delete(T),d(x)}let Z=L(b);Z&&k.byStep.delete(Z)}else if(ne==="tool_start"){let T=(ce=Le(b,!0))!=null?ce:`tool-${c()}`,x=(Se=b.toolName)!=null?Se:b.name;if(ke(x)){oe.add(T);continue}let Z=se(T),F=(Oe=Z.toolCall)!=null?Oe:{id:T,status:"pending"};F.name=x!=null?x:F.name,F.status="running",b.args!==void 0?F.args=b.args:b.parameters!==void 0&&(F.args=b.parameters),F.startedAt=(jt=F.startedAt)!=null?jt:K((Ct=b.startedAt)!=null?Ct:b.timestamp),F.completedAt=void 0,F.durationMs=void 0,Z.toolCall=F,Z.streaming=!0;let he=b.agentContext;(he||b.executionId)&&(Z.agentMetadata={executionId:(pt=he==null?void 0:he.executionId)!=null?pt:b.executionId,iteration:(zt=he==null?void 0:he.iteration)!=null?zt:b.iteration}),d(Z)}else if(ne==="tool_chunk"||ne==="tool_delta"){let T=(Ze=(yt=Le(b,!1))!=null?yt:Le(b,!0))!=null?Ze:`tool-${c()}`;if(oe.has(T))continue;let x=se(T),Z=(bt=x.toolCall)!=null?bt:{id:T,status:"running"};Z.startedAt=(qt=Z.startedAt)!=null?qt:K((De=b.startedAt)!=null?De:b.timestamp);let F=($n=(nr=(Gn=b.text)!=null?Gn:b.delta)!=null?nr:b.message)!=null?$n:"";F&&(Z.chunks=(et=Z.chunks)!=null?et:[],Z.chunks.push(String(F))),Z.status="running",x.toolCall=Z,x.streaming=!0;let he=b.agentContext;(he||b.executionId)&&(x.agentMetadata=(Mr=x.agentMetadata)!=null?Mr:{executionId:(Tr=he==null?void 0:he.executionId)!=null?Tr:b.executionId,iteration:(Kn=he==null?void 0:he.iteration)!=null?Kn:b.iteration}),d(x)}else if(ne==="tool_complete"){let T=(jr=(Wn=Le(b,!1))!=null?Wn:Le(b,!0))!=null?jr:`tool-${c()}`;if(oe.has(T)){oe.delete(T);continue}let x=se(T),Z=(ur=x.toolCall)!=null?ur:{id:T,status:"running"};Z.status="complete",b.result!==void 0&&(Z.result=b.result),typeof b.duration=="number"&&(Z.duration=b.duration),Z.completedAt=K((rr=b.completedAt)!=null?rr:b.timestamp);let F=(at=b.duration)!=null?at:b.executionTime;if(typeof F=="number")Z.durationMs=F;else{let it=(An=Z.startedAt)!=null?An:Date.now();Z.durationMs=Math.max(0,((_n=Z.completedAt)!=null?_n:Date.now())-it)}x.toolCall=Z,x.streaming=!1;let he=b.agentContext;(he||b.executionId)&&(x.agentMetadata=(En=x.agentMetadata)!=null?En:{executionId:(dn=he==null?void 0:he.executionId)!=null?dn:b.executionId,iteration:(mr=he==null?void 0:he.iteration)!=null?mr:b.iteration}),d(x);let Ue=P(b);Ue&&H.byCall.delete(Ue)}else if(ne==="text_start"){let T=b.partId;if(T!==void 0&&v.current!==null&&T!==v.current){let x=f;x&&(x.streaming=!1,d(x),Xe=x,f=null,M=!0)}T!==void 0&&(v.current=T)}else if(ne==="text_end"){let T=f;T&&(T.streaming=!1,d(T),Xe=T,f=null,M=!0)}else if(ne==="step_chunk"||ne==="step_delta"){let T=b.stepType,x=b.executionType;if(T==="tool"||x==="context")continue;let Z=b.partId;if(Z!==void 0&&v.current!==null&&Z!==v.current){let Ue=f;Ue&&(Ue.streaming=!1,d(Ue),Xe=Ue,f=null,M=!0)}Z!==void 0&&(v.current=Z);let F=Q();Z!==void 0&&!F.partId&&(F.partId=Z);let he=(gr=(Rn=(pn=(At=b.text)!=null?At:b.delta)!=null?pn:b.content)!=null?Rn:b.chunk)!=null?gr:"";if(he){let Ue=typeof b.seq=="number"?b.seq:void 0,it;Ue!==void 0?it=Re(fe,F.id,Ue,he):it=((or=te.get(F.id))!=null?or:"")+he,F.rawContent=it,U.has(F.id)||U.set(F.id,this.createStreamParser());let $t=U.get(F.id),Vt=it.trim().startsWith("{")||it.trim().startsWith("[");if(Vt&&te.set(F.id,it),$t.__isPlainTextParser===!0){Ue!==void 0?F.content=it:F.content+=he,te.delete(F.id),U.delete(F.id),F.rawContent=void 0,d(F);continue}let Ft=$t.processChunk(it);if(Ft instanceof Promise)Ft.then(Ge=>{var Zt;let kt=typeof Ge=="string"?Ge:(Zt=Ge==null?void 0:Ge.text)!=null?Zt:null;if(kt!==null&&kt.trim()!=="")F.content=kt,d(F);else if(!Vt&&!it.trim().startsWith("<")){let on=f;on&&on.id===F.id&&(Ue!==void 0?on.content=it:on.content+=he,te.delete(on.id),U.delete(on.id),on.rawContent=void 0,d(on))}}).catch(()=>{Ue!==void 0?F.content=it:F.content+=he,te.delete(F.id),U.delete(F.id),F.rawContent=void 0,d(F)});else{let Ge=typeof Ft=="string"?Ft:(fr=Ft==null?void 0:Ft.text)!=null?fr:null;Ge!==null&&Ge.trim()!==""?(F.content=Ge,d(F)):!Vt&&!it.trim().startsWith("<")&&(Ue!==void 0?F.content=it:F.content+=he,te.delete(F.id),U.delete(F.id),F.rawContent=void 0,d(F))}}if(b.isComplete){let Ue=(Tn=(Xn=b.result)==null?void 0:Xn.response)!=null?Tn:F.content;if(Ue){let it=te.get(F.id),$t=it!=null?it:ue(Ue);F.rawContent=$t;let Vt=U.get(F.id),Jt=null,Ft=!1;if(Vt&&(Jt=Vt.getExtractedText(),Jt===null&&(Jt=Nr($t)),Jt===null)){let Ge=Vt.processChunk($t);Ge instanceof Promise?(Ft=!0,Ge.then(kt=>{var on;let Zt=typeof kt=="string"?kt:(on=kt==null?void 0:kt.text)!=null?on:null;if(Zt!==null){let Tt=f;Tt&&Tt.id===F.id&&(Tt.content=Zt,Tt.streaming=!1,U.delete(Tt.id),te.delete(Tt.id),fe.delete(Tt.id),d(Tt))}})):Jt=typeof Ge=="string"?Ge:(Zn=Ge==null?void 0:Ge.text)!=null?Zn:null}if(!Ft){Jt!==null&&Jt.trim()!==""?F.content=Jt:te.has(F.id)||(F.content=ue(Ue));let Ge=U.get(F.id);if(Ge){let kt=(wt=Ge.close)==null?void 0:wt.call(Ge);kt instanceof Promise&&kt.catch(()=>{}),U.delete(F.id)}te.delete(F.id),fe.delete(F.id),F.streaming=!1,d(F)}}}}else if(ne==="step_complete"){let T=b.stepType,x=b.executionType;if(T==="tool"||x==="context")continue;if(M){if(f!==null){let it=f;U.delete(it.id),te.delete(it.id),fe.delete(it.id),it.streaming!==!1&&(it.streaming=!1,d(it))}let he=(Nt=b.result)==null?void 0:Nt.response,Ue=Xe;Ue&&(he!=null?j(Ue,he):(U.delete(Ue.id),te.delete(Ue.id))),Xe=null;continue}let Z=(Ot=b.result)==null?void 0:Ot.response,F=Q();if(Z!=null){let he=U.get(F.id),Ue=!1,it=!1;if(he){let $t=he.getExtractedText(),Vt=te.get(F.id),Jt=Vt!=null?Vt:ue(Z);if(F.rawContent=Jt,$t!==null&&$t.trim()!=="")F.content=$t,Ue=!0;else{let Ft=Nr(Jt);if(Ft!==null)F.content=Ft,Ue=!0;else{let Ge=he.processChunk(Jt);if(Ge instanceof Promise)it=!0,Ge.then(kt=>{var on;let Zt=typeof kt=="string"?kt:(on=kt==null?void 0:kt.text)!=null?on:null;if(Zt!==null&&Zt.trim()!==""){let Tt=f;Tt&&Tt.id===F.id&&(Tt.content=Zt,Tt.streaming=!1,U.delete(Tt.id),te.delete(Tt.id),fe.delete(Tt.id),d(Tt))}else{let Tt=he.getExtractedText(),mn=f;mn&&mn.id===F.id&&(Tt!==null&&Tt.trim()!==""?mn.content=Tt:te.has(mn.id)||(mn.content=ue(Z)),mn.streaming=!1,U.delete(mn.id),te.delete(mn.id),fe.delete(mn.id),d(mn))}});else{let kt=typeof Ge=="string"?Ge:(Mn=Ge==null?void 0:Ge.text)!=null?Mn:null;if(kt!==null&&kt.trim()!=="")F.content=kt,Ue=!0;else{let Zt=he.getExtractedText();Zt!==null&&Zt.trim()!==""&&(F.content=Zt,Ue=!0)}}}}}if(!it){if(!F.rawContent){let $t=te.get(F.id);F.rawContent=$t!=null?$t:ue(Z)}if(!Ue&&!te.has(F.id)&&(F.content=ue(Z)),he){let $t=(hr=he.close)==null?void 0:hr.call(he);$t instanceof Promise&&$t.catch(()=>{})}U.delete(F.id),te.delete(F.id),fe.delete(F.id),F.streaming=!1,d(F)}}else U.delete(F.id),te.delete(F.id),fe.delete(F.id),F.streaming=!1,d(F)}else if(ne==="flow_complete"){let T=(jn=b.result)==null?void 0:jn.response;if(M){if(f!==null){let x=f;U.delete(x.id),te.delete(x.id),fe.delete(x.id),x.streaming!==!1&&(x.streaming=!1,d(x))}}else if(T!=null){let x=Q(),Z=te.get(x.id),F=Z!=null?Z:ue(T);x.rawContent=F;let he=ue(T),Ue=U.get(x.id);if(Ue){let Vt=Nr(F);if(Vt!==null)he=Vt;else{let Jt=Ue.processChunk(F);Jt instanceof Promise&&Jt.then(Ge=>{var Zt;let kt=typeof Ge=="string"?Ge:(Zt=Ge==null?void 0:Ge.text)!=null?Zt:null;kt!==null&&(x.content=kt,x.streaming=!1,d(x))});let Ft=Ue.getExtractedText();Ft!==null&&(he=Ft)}}U.delete(x.id),te.delete(x.id),fe.delete(x.id);let it=he!==x.content,$t=x.streaming!==!1;it&&(x.content=he),x.streaming=!1,(it||$t)&&d(x)}else if(f!==null){let x=f;U.delete(x.id),te.delete(x.id),fe.delete(x.id),x.streaming!==!1&&(x.streaming=!1,d(x))}t({type:"status",status:"idle"})}else if(ne==="agent_start")W={executionId:b.executionId,agentId:(kn=b.agentId)!=null?kn:"virtual",agentName:(D=b.agentName)!=null?D:"",status:"running",currentIteration:0,maxTurns:(zn=b.maxTurns)!=null?zn:1,startedAt:K(b.startedAt)};else if(ne==="agent_iteration_start"){if(W&&(W.currentIteration=b.iteration),$==="separate"&&b.iteration>1){let T=f;T&&(T.streaming=!1,d(T),ae.set(b.iteration-1,T),f=null)}}else if(ne!=="agent_turn_start"){if(ne==="agent_turn_delta"){if(b.contentType==="text"){let T=Q();T.content+=(Hn=b.delta)!=null?Hn:"",T.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId,agentName:W==null?void 0:W.agentName},d(T)}else if(b.contentType==="thinking"){let T=(yr=b.turnId)!=null?yr:`agent-think-${b.iteration}`,x=re(T);x.reasoning=(fn=x.reasoning)!=null?fn:{id:T,status:"streaming",chunks:[]},x.reasoning.chunks.push((hn=b.delta)!=null?hn:""),x.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId},d(x)}else if(b.contentType==="tool_input"){let T=(ie=b.toolCallId)!=null?ie:H.lastId;if(T){let x=S.get(T);x!=null&&x.toolCall&&(x.toolCall.chunks=(Ln=x.toolCall.chunks)!=null?Ln:[],x.toolCall.chunks.push((sr=b.delta)!=null?sr:""),d(x))}}}else if(ne==="agent_turn_complete"){let T=b.turnId;if(T){let x=C.get(T);if(x!=null&&x.reasoning){x.reasoning.status="complete",x.reasoning.completedAt=K(b.completedAt);let Z=(qo=x.reasoning.startedAt)!=null?qo:Date.now();x.reasoning.durationMs=Math.max(0,((co=x.reasoning.completedAt)!=null?co:Date.now())-Z),x.streaming=!1,d(x)}}}else if(ne==="agent_tool_start"){let T=(Uo=b.toolCallId)!=null?Uo:`agent-tool-${c()}`;we(P(b),T);let x=se(T),Z=(zr=x.toolCall)!=null?zr:{id:T,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Z.name=(po=(Qe=b.toolName)!=null?Qe:b.name)!=null?po:Z.name,Z.status="running",b.parameters!==void 0&&(Z.args=b.parameters),Z.startedAt=K((Bn=b.startedAt)!=null?Bn:b.timestamp),x.toolCall=Z,x.streaming=!0,x.agentMetadata={executionId:b.executionId,iteration:b.iteration},d(x)}else if(ne==="agent_tool_delta"){let T=(yn=b.toolCallId)!=null?yn:H.lastId;if(T){let x=(Vo=S.get(T))!=null?Vo:se(T);x.toolCall&&(x.toolCall.chunks=(Jo=x.toolCall.chunks)!=null?Jo:[],x.toolCall.chunks.push((uo=b.delta)!=null?uo:""),x.toolCall.status="running",x.streaming=!0,d(x))}}else if(ne==="agent_tool_complete"){let T=(ar=b.toolCallId)!=null?ar:H.lastId;if(T){let x=(Yo=S.get(T))!=null?Yo:se(T);if(x.toolCall){x.toolCall.status="complete",b.result!==void 0&&(x.toolCall.result=b.result),typeof b.executionTime=="number"&&(x.toolCall.durationMs=b.executionTime),x.toolCall.completedAt=K((kr=b.completedAt)!=null?kr:b.timestamp),x.streaming=!1,d(x);let Z=P(b);Z&&H.byCall.delete(Z)}}}else if(ne!=="agent_iteration_complete"){if(ne==="agent_reflection"||ne==="agent_reflect"){let T=`agent-reflection-${b.executionId}-${b.iteration}`,x={id:T,role:"assistant",content:(mo=b.reflection)!=null?mo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:T,status:"complete",chunks:[(ir=b.reflection)!=null?ir:""]},agentMetadata:{executionId:b.executionId,iteration:b.iteration}};d(x)}else if(ne==="agent_complete"){W&&(W.status=b.success?"complete":"error",W.completedAt=K(b.completedAt),W.stopReason=b.stopReason);let T=f;T&&(T.streaming=!1,d(T)),t({type:"status",status:"idle"})}else if(ne==="agent_error"){let T=typeof b.error=="string"?b.error:(br=(go=b.error)==null?void 0:go.message)!=null?br:"Agent execution error";b.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",T):t({type:"error",error:new Error(T)})}else if(ne!=="agent_ping"){if(ne==="agent_approval_start"){let T=(xr=b.approvalId)!=null?xr:`approval-${c()}`,x={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:(Go=W==null?void 0:W.agentId)!=null?Go:"virtual",executionId:(Os=(Ko=b.executionId)!=null?Ko:W==null?void 0:W.executionId)!=null?Os:"",toolName:(Lr=b.toolName)!=null?Lr:"",toolType:b.toolType,description:(Ht=b.description)!=null?Ht:`Execute ${(Ir=b.toolName)!=null?Ir:"tool"}`,parameters:b.parameters}};d(x)}else if(ne==="step_await"&&b.awaitReason==="approval_required"){let T=(qr=b.approvalId)!=null?qr:`approval-${c()}`,x={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:(Ur=W==null?void 0:W.agentId)!=null?Ur:"virtual",executionId:(Qn=(fo=b.executionId)!=null?fo:W==null?void 0:W.executionId)!=null?Qn:"",toolName:(Xo=b.toolName)!=null?Xo:"",toolType:b.toolType,description:(yo=b.description)!=null?yo:`Execute ${(ho=b.toolName)!=null?ho:"tool"}`,parameters:b.parameters}};d(x)}else if(ne==="agent_approval_complete"){let T=b.approvalId;if(T){let Z={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:(bo=b.decision)!=null?bo:"approved",agentId:(un=W==null?void 0:W.agentId)!=null?un:"virtual",executionId:(lr=(In=b.executionId)!=null?In:W==null?void 0:W.executionId)!=null?lr:"",toolName:(qe=b.toolName)!=null?qe:"",description:(xo=b.description)!=null?xo:"",resolvedAt:Date.now()}};d(Z)}}else if(ne==="artifact_start"||ne==="artifact_delta"||ne==="artifact_update"||ne==="artifact_complete"){if(ne==="artifact_start"){let T=b.artifactType,x=String(b.id),Z=typeof b.title=="string"?b.title:void 0;if(t({type:"artifact_start",id:x,artifactType:T,title:Z,component:typeof b.component=="string"?b.component:void 0}),ge.set(x,{markdown:"",title:Z}),!We.has(x)){We.add(x);let F={id:`artifact-ref-${x}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:x,title:Z,artifactType:T,status:"streaming"}})};ve.set(x,F),d(F)}}else if(ne==="artifact_delta"){let T=String(b.id),x=typeof b.delta=="string"?b.delta:String((Pr=b.delta)!=null?Pr:"");t({type:"artifact_delta",id:T,artDelta:x});let Z=ge.get(T);Z&&(Z.markdown+=x)}else if(ne==="artifact_update"){let T=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};t({type:"artifact_update",id:String(b.id),props:T,component:typeof b.component=="string"?b.component:void 0})}else if(ne==="artifact_complete"){let T=String(b.id);t({type:"artifact_complete",id:T});let x=ve.get(T);if(x){x.streaming=!1;try{let Z=JSON.parse((qn=x.rawContent)!=null?qn:"{}");if(Z.props){Z.props.status="complete";let F=ge.get(T);F!=null&&F.markdown&&(Z.props.markdown=F.markdown)}x.rawContent=JSON.stringify(Z)}catch{}ge.delete(T),d(x),ve.delete(T)}}}else if(ne==="transcript_insert"){let T=b.message;if(!T||typeof T!="object")continue;let x=String((Zo=T.id)!=null?Zo:`msg-${c()}`),Z=T.role,he={id:x,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof T.content=="string"?T.content:"",rawContent:typeof T.rawContent=="string"?T.rawContent:void 0,createdAt:typeof T.createdAt=="string"?T.createdAt:new Date().toISOString(),streaming:T.streaming===!0,...typeof T.variant=="string"?{variant:T.variant}:{},sequence:c()};if(d(he),he.rawContent)try{let Ue=JSON.parse(he.rawContent),it=(Vr=Ue==null?void 0:Ue.props)==null?void 0:Vr.artifactId;typeof it=="string"&&We.add(it)}catch{}f=null,g.current=null,U.delete(x),te.delete(x),fe.delete(x)}else if(ne==="error"||ne==="step_error"||ne==="dispatch_error"||ne==="flow_error"){let T=null;if(b.error instanceof Error)T=b.error;else if(ne==="dispatch_error"){let x=(Jr=b.message)!=null?Jr:b.error;x!=null&&x!==""&&(T=new Error(String(x)))}else if(ne==="step_error"||ne==="flow_error"){let x=b.error;typeof x=="string"&&x!==""?T=new Error(x):x!=null&&typeof x=="object"&&"message"in x&&(T=new Error(String((Wr=x.message)!=null?Wr:x)))}else ne==="error"&&b.error!=null&&b.error!==""&&(T=new Error(String(b.error)));if(T){t({type:"error",error:T});let x=f;x&&x.streaming&&(x.streaming=!1,d(x)),t({type:"status",status:"idle"})}}}}}}}}};function vp(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function Lo(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function Zr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var ds="[Image]";function Cp(e){return typeof e=="string"?[{type:"text",text:e}]:e}function wp(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function Sp(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Ap(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function ps(e){return{type:"text",text:e}}function Ep(e,r){return{type:"image",image:e,...(r==null?void 0:r.mimeType)&&{mimeType:r.mimeType},...(r==null?void 0:r.alt)&&{alt:r.alt}}}async function Tp(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;r({type:"image",image:s,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Mp(e,r=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${r.join(", ")}`}}var Wc=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],kp=["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"],dr=[...Wc,...kp];function Lp(e){return Wc.includes(e)||e.startsWith("image/")}function us(e){return Lp(e.type)}async function Rc(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;us(e)?r({type:"image",image:s,mimeType:e.type,alt:e.name}):r({type:"file",data:s,mimeType:e.type,filename:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Hc(e,r=dr,t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${r.join(", ")}`}}function Ip(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function Bc(e,r){let t=Ip(r).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]||t||"FILE"}var ms=class{constructor(r=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=r}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let u=new Uint8Array(this.remainder.length+r.length);u.set(this.remainder),u.set(r,this.remainder.length),t=u,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.ensureContext(),s=this.pcmToFloat32(t),o=n.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=n.createBufferSource();a.buffer=o,a.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let u=this.activeSources.indexOf(a);u!==-1&&this.activeSources.splice(u,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let r of this.activeSources)try{r.stop(),r.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(r){this.finishedCallbacks.push(r)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),s=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);n[o]=a/32768}return n}};var gs=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,n,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=r.createMediaStreamSource(t),this.analyserNode=r.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let u=Math.sqrt(i/a.length);(n==="silence"?u<s.threshold:u>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Io=class{constructor(r){this.config=r;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new gs;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,t,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(r=this.config)==null?void 0:r.host,i=(t=this.config)==null?void 0:t.agentId,u=(n=this.config)==null?void 0:n.clientToken;if(!i||!u)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${o}//${a}/ws/agents/${i}/voice?token=${u}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,d=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,g)=>{if(!this.ws)return g(new Error("WebSocket not created"));let v=!1,M=S=>{v||(v=!0,clearTimeout(C),g(new Error(S)))},C=setTimeout(()=>M("WebSocket connection timed out."+d),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(C),f())},{once:!0}),this.ws.addEventListener("error",()=>{M("WebSocket connection failed to "+p+"."+d)},{once:!0}),this.ws.addEventListener("close",S=>{if(!S.wasClean&&!v){let k=S.code!==1006?` (code ${S.code})`:"";M("WebSocket connection failed"+k+"."+d)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(r.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new ms(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var r,t,n,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let c=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(c)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,u=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:u,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let p=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",d=new Blob(this.audioChunks,{type:p});await this.sendAudio(d),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),s=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=n,s.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let c=0;c<t.length;c++)n[c]=t.charCodeAt(c);let s=r.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([n],{type:o}),i=URL.createObjectURL(a),u=new Audio(i);this.currentAudio=u,this.currentAudioUrl=i,u.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===u&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await u.play()}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Or=class{constructor(r={}){this.config=r;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(r=>r("connected"))}async startListening(){var r,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((r=this.config)==null?void 0:r.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(u=>u[0]).map(u=>u.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(u=>u({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Qr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Io(e.runtype);case"browser":if(!Or.isSupported())throw new Error("Browser speech recognition not supported");return new Or(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Gs(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Qr({type:"runtype",runtype:e.runtype});if(Or.isSupported())return Qr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function fs(e){try{return Gs(e),!0}catch{return!1}}var Po=class e{constructor(r={},t){this.config=r;this.callbacks=t;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.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=r=>{var t,n,s,o,a,i,u;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(s=r.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(u=(i=this.callbacks).onError)==null||u.call(i,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n;this.messages=[...(n=r.initialMessages)!=null?n:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Xr(r),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return fs((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,s;try{let o=r||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Qr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",u=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var p,d,f,g,v,M;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=c.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(d=c.transcript)!=null&&d.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=c.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(g=c.text)!=null&&g.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let C=(M=this.pendingVoiceAssistantMessageId)!=null?M:(v=[...this.messages].reverse().find(S=>S.role==="assistant"))==null?void 0:v.id;C&&this.ttsSpokenMessageIds.add(C)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:u,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var p,d;this.voiceStatus=c,this.voiceActive=c==="listening",(d=(p=this.callbacks).onVoiceStatusChanged)==null||d.call(p,c)}),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(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,s,o,a,i,u,c,p;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((s=r.runtype)==null?void 0:s.clientToken)||"",host:(o=r.runtype)==null?void 0:o.host,voiceId:(a=r.runtype)==null?void 0:a.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(u=r.runtype)==null?void 0:u.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(p=r.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new Xr(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:u,streaming:c=!1,voiceProcessing:p}=r,f={id:a!=null?a:t==="user"?Lo():t==="assistant"?Zr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p}};return this.upsertMessage(f),f}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:s,content:o,llmContent:a,contentParts:i,id:u,createdAt:c,sequence:p,streaming:d=!1}=n,g={id:u!=null?u:s==="user"?Lo():s==="assistant"?Zr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:d,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(g)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(r,t){var c,p,d,f,g;let n=r.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=Lo(),o=Zr(),a={id:s,role:"user",content:n||ds,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let u=[...this.messages];try{await this.client.dispatch({messages:u,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!M){let C={id:o,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(C)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,M||(v instanceof Error?(d=(p=this.callbacks).onError)==null||d.call(p,v):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,u;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=Zr();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:r},this.handleEvent)}catch(c){let p={id:r,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(p),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(u=(i=this.callbacks).onError)==null||u.call(i,new Error(String(c)))}}async connectStream(r,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var u,c,p;let n=`approval-${r.id}`,s={...r,status:t,resolvedAt:Date.now()},o={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let d;if(i?d=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):d=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),d){let f=null;if(d instanceof Response){if(!d.ok){let g=await d.json().catch(()=>null);throw new Error((u=g==null?void 0:g.error)!=null?u:`Approval request failed: ${d.status}`)}f=d.body}else d instanceof ReadableStream&&(f=d);f?await this.connectStream(f):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(d){(p=(c=this.callbacks).onError)==null||p.call(c,d instanceof Error?d:new Error(String(d)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var s;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(s=r.props)!=null?s:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((n=s.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...r.props},r.component&&(s.component=r.component));break}case"artifact_complete":{let s=this.artifacts.get(r.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var s;return{...n,streaming:!1,sequence:(s=n.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let s=n.content;s.trim()&&this.speak(s,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let s=new SpeechSynthesisUtterance(r),o=n.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>n.speak(s),50)}static pickBestVoice(r){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 s of t){let o=r.find(a=>a.name===s);if(o)return o}return(n=r.find(s=>s.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(s=>s.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===n?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var u,c;let s=new Date(t.createdAt).getTime(),o=new Date(n.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(u=t.sequence)!=null?u:0,i=(c=n.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(n.id)})}};var h=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},er=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};import*as Pp from"lucide";var be=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=Pp[s];return o?Wp(o,r,t,n):(console.warn(`Lucide icon "${e}" not found (tried "${s}"). Available icons: https://lucide.dev/icons`),null)}catch(s){return console.warn(`Failed to render Lucide icon "${e}":`,s),null}};function Wp(e,r,t,n){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(r)),s.setAttribute("height",String(r)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(n)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let a=o[0],i=o[1];if(i){let u=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&u.setAttribute(c,String(p))}),s.appendChild(u)}}}),s}var hs={allowedTypes:dr,maxFileSize:10*1024*1024,maxFiles:4};function Rp(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Hp(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-json":"file"}var eo=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:hs.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:hs.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:hs.maxFiles,onFileRejected:r.onFileRejected,onAttachmentsChange:r.onAttachmentsChange}}setPreviewsContainer(r){this.previewsContainer=r}updateConfig(r){r.allowedTypes!==void 0&&(this.config.allowedTypes=r.allowedTypes.length>0?r.allowedTypes:hs.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,s,o,a,i,u;if(r.length){for(let c of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,c,"count");continue}let p=Hc(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let d=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,d);continue}try{let d=await Rc(c),f=us(c)?URL.createObjectURL(c):null,g={id:Rp(),file:c,previewUrl:f,contentPart:d};this.attachments.push(g),this.renderPreview(g)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(u=(i=this.config).onAttachmentsChange)==null||u.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(u=>u.id===r);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${r}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=us(r.file),n=h("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",r.id),n.style.width="48px",n.style.height="48px",t&&r.previewUrl){let a=h("img");a.src=r.previewUrl,a.alt=r.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",n.appendChild(a)}else{let a=h("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=Hp(r.file.type),u=be(i,20,"var(--persona-muted, #6b7280)",1.5);u&&a.appendChild(u);let c=h("span");c.textContent=Bc(r.file.type,r.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),n.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=be("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(r.id)}),n.appendChild(s),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(r,t){return new e({allowedTypes:r==null?void 0:r.allowedTypes,maxFileSize:r==null?void 0:r.maxFileSize,maxFiles:r==null?void 0:r.maxFiles,onFileRejected:r==null?void 0:r.onFileRejected,onAttachmentsChange:t})}};var Dc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Wo(e,r){if(!e)return r;if(!r)return e;let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];Dc(o)&&Dc(s)?t[n]=Wo(o,s):t[n]=s}return t}var Nn="min(440px, calc(100vw - 24px))",Ks="440px",Pt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{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:Nn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",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)"},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:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"}},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 Fc(e,r){if(!(!e&&!r))return e?r?Wo(e,r):e:r}function Xs(e){var r,t,n,s,o,a,i,u,c,p,d,f,g,v,M,C,S,k,H,w,L;return e?{...Pt,...e,theme:Fc(Pt.theme,e.theme),darkTheme:Fc(Pt.darkTheme,e.darkTheme),launcher:{...Pt.launcher,...e.launcher,dock:{...(r=Pt.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=Pt.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Pt.copy,...e.copy},sendButton:{...Pt.sendButton,...e.sendButton},statusIndicator:{...Pt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Pt.voiceRecognition,...e.voiceRecognition},features:(()=>{var re,we,oe,ve;let P=(re=Pt.features)==null?void 0:re.artifacts,E=(we=e.features)==null?void 0:we.artifacts,Y=(oe=Pt.features)==null?void 0:oe.scrollToBottom,Q=(ve=e.features)==null?void 0:ve.scrollToBottom,G=P===void 0&&E===void 0?void 0:{...P,...E,layout:{...P==null?void 0:P.layout,...E==null?void 0:E.layout}},O=Y===void 0&&Q===void 0?void 0:{...Y,...Q};return{...Pt.features,...e.features,...O!==void 0?{scrollToBottom:O}:{},...G!==void 0?{artifacts:G}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Pt.suggestionChips,suggestionChipsConfig:{...Pt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Pt.layout,...e.layout,header:{...(a=Pt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(u=Pt.layout)==null?void 0:u.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(d=(p=Pt.layout)==null?void 0:p.messages)==null?void 0:d.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(M=(v=Pt.layout)==null?void 0:v.messages)==null?void 0:M.timestamp,...(S=(C=e.layout)==null?void 0:C.messages)==null?void 0:S.timestamp}},slots:{...(k=Pt.layout)==null?void 0:k.slots,...(H=e.layout)==null?void 0:H.slots}},markdown:{...Pt.markdown,...e.markdown,options:{...(w=Pt.markdown)==null?void 0:w.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...Pt.messageActions,...e.messageActions}}:Pt}var Nc={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"}},Oc={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"}},$c={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:Nn,maxWidth:Ks,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"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"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:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",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 Ro(e,r){if(!r.startsWith("palette.")&&!r.startsWith("semantic.")&&!r.startsWith("components."))return r;let t=r.split("."),n=e;for(let s of t){if(n==null)return;n=n[s]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?Ro(e,n):n}function Zs(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let u=Ro(e,a);u!==void 0&&(r[i]={path:i,value:u,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),r}function _c(e){let r=[],t=[];return e.palette||r.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:r.length===0,errors:r,warnings:t}}function jc(e,r){let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[n]=jc(o,s):t[n]=s}return t}function Bp(e,r){return r?jc(e,r):e}function Ho(e,r={}){var s,o,a,i,u,c,p,d,f,g,v,M,C;let t={palette:Nc,semantic:Oc,components:$c},n={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(u=e==null?void 0:e.palette)==null?void 0:u.borders},radius:{...t.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...t.semantic.colors.interactive,...(f=(d=e==null?void 0:e.semantic)==null?void 0:d.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(v=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(M=e==null?void 0:e.semantic)==null?void 0:M.spacing},typography:{...t.semantic.typography,...(C=e==null?void 0:e.semantic)==null?void 0:C.typography}},components:Bp(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let S=_c(n);if(!S.valid)throw new Error(`Theme validation failed: ${S.errors.map(k=>k.message).join(", ")}`)}if(r.plugins)for(let S of r.plugins)n=S.transform(n);return n}function Qs(e){var v,M,C,S,k,H,w,L,P,E,Y,Q,G,O,re,we,oe,ve,We,ge,ke,Le,se,K,ue,U,te,fe,pe,Re,Xe,j,W,ae,$,q,de,_e,ee,le,It,dt,Dt,Xt,je,me,Ne,Wt,Rt,ot,st,nn,tn,rn,z,He,ye,ht,$e,ce,Se,Oe,Ct,jt,pt,zt,yt,Ze,bt,De,qt,Gn,nr,$n,et,Tr,Kn,Mr,Wn,jr,ur,rr,at,An,_n,dn,mr,En,At,pn,Rn,gr,or,fr,Xn,Tn,Zn,wt,Nt,Ot,Mn,hr,jn,kn,D,zn,Hn,yr,fn,hn;let r=Zs(e),t={};for(let[ie,Ln]of Object.entries(r)){let sr=ie.replace(/\./g,"-");t[`--persona-${sr}`]=Ln.value}t["--persona-primary"]=(v=t["--persona-semantic-colors-primary"])!=null?v:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(M=t["--persona-semantic-colors-secondary"])!=null?M:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(C=t["--persona-semantic-colors-accent"])!=null?C:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(S=t["--persona-semantic-colors-surface"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(k=t["--persona-semantic-colors-background"])!=null?k:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(H=t["--persona-semantic-colors-container"])!=null?H:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(w=t["--persona-semantic-colors-text"])!=null?w:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(L=t["--persona-semantic-colors-text-muted"])!=null?L:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(P=t["--persona-semantic-colors-text-inverse"])!=null?P:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(E=t["--persona-semantic-colors-border"])!=null?E:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(Y=t["--persona-semantic-colors-divider"])!=null?Y:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(Q=t["--persona-components-voice-recording-indicator"])!=null?Q:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(G=t["--persona-components-voice-recording-background"])!=null?G:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(O=t["--persona-components-voice-processing-icon"])!=null?O:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(re=t["--persona-components-voice-speaking-icon"])!=null?re:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(we=t["--persona-components-approval-requested-background"])!=null?we:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(oe=t["--persona-components-approval-requested-border"])!=null?oe:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(ve=t["--persona-components-approval-requested-text"])!=null?ve:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(We=t["--persona-components-approval-approve-background"])!=null?We:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(ge=t["--persona-components-approval-deny-background"])!=null?ge:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(ke=t["--persona-components-attachment-image-background"])!=null?ke:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Le=t["--persona-components-attachment-image-border"])!=null?Le:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(se=t["--persona-semantic-typography-fontFamily"])!=null?se:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(K=t["--persona-semantic-typography-fontSize"])!=null?K:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(ue=t["--persona-semantic-typography-fontWeight"])!=null?ue:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(U=t["--persona-semantic-typography-lineHeight"])!=null?U:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(te=t["--persona-palette-radius-sm"])!=null?te:"0.125rem",t["--persona-radius-md"]=(fe=t["--persona-palette-radius-md"])!=null?fe:"0.375rem",t["--persona-radius-lg"]=(pe=t["--persona-palette-radius-lg"])!=null?pe:"0.5rem",t["--persona-radius-xl"]=(Re=t["--persona-palette-radius-xl"])!=null?Re:"0.75rem",t["--persona-radius-full"]=(Xe=t["--persona-palette-radius-full"])!=null?Xe:"9999px",t["--persona-launcher-radius"]=(W=(j=t["--persona-components-launcher-borderRadius"])!=null?j:t["--persona-palette-radius-full"])!=null?W:"9999px",t["--persona-launcher-bg"]=(ae=t["--persona-components-launcher-background"])!=null?ae:t["--persona-primary"],t["--persona-launcher-fg"]=($=t["--persona-components-launcher-foreground"])!=null?$:t["--persona-text-inverse"],t["--persona-launcher-border"]=(q=t["--persona-components-launcher-border"])!=null?q:t["--persona-border"],t["--persona-button-primary-bg"]=(de=t["--persona-components-button-primary-background"])!=null?de:t["--persona-primary"],t["--persona-button-primary-fg"]=(_e=t["--persona-components-button-primary-foreground"])!=null?_e:t["--persona-text-inverse"],t["--persona-button-radius"]=(le=(ee=t["--persona-components-button-primary-borderRadius"])!=null?ee:t["--persona-palette-radius-full"])!=null?le:"9999px",t["--persona-panel-radius"]=(dt=(It=t["--persona-components-panel-borderRadius"])!=null?It:t["--persona-radius-xl"])!=null?dt:"0.75rem",t["--persona-panel-border"]=(Dt=t["--persona-components-panel-border"])!=null?Dt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(je=(Xt=t["--persona-components-panel-shadow"])!=null?Xt:t["--persona-palette-shadows-xl"])!=null?je:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Ne=(me=t["--persona-components-input-borderRadius"])!=null?me:t["--persona-radius-lg"])!=null?Ne:"0.5rem",t["--persona-message-user-radius"]=(Rt=(Wt=t["--persona-components-message-user-borderRadius"])!=null?Wt:t["--persona-radius-lg"])!=null?Rt:"0.5rem",t["--persona-message-assistant-radius"]=(st=(ot=t["--persona-components-message-assistant-borderRadius"])!=null?ot:t["--persona-radius-lg"])!=null?st:"0.5rem",t["--persona-header-bg"]=(nn=t["--persona-components-header-background"])!=null?nn:t["--persona-surface"],t["--persona-header-border"]=(tn=t["--persona-components-header-border"])!=null?tn:t["--persona-divider"],t["--persona-header-icon-bg"]=(rn=t["--persona-components-header-iconBackground"])!=null?rn:t["--persona-primary"],t["--persona-header-icon-fg"]=(z=t["--persona-components-header-iconForeground"])!=null?z:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(He=t["--persona-components-header-titleForeground"])!=null?He:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(ye=t["--persona-components-header-subtitleForeground"])!=null?ye:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(ht=t["--persona-components-header-actionIconForeground"])!=null?ht:t["--persona-muted"];let n=($e=e.components)==null?void 0:$e.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-input-background"]=(ce=t["--persona-components-input-background"])!=null?ce:t["--persona-surface"],t["--persona-input-placeholder"]=(Se=t["--persona-components-input-placeholder"])!=null?Se:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Oe=t["--persona-components-message-user-background"])!=null?Oe:t["--persona-accent"],t["--persona-message-user-text"]=(Ct=t["--persona-components-message-user-text"])!=null?Ct:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(jt=t["--persona-components-message-user-shadow"])!=null?jt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(pt=t["--persona-components-message-assistant-background"])!=null?pt:t["--persona-surface"],t["--persona-message-assistant-text"]=(zt=t["--persona-components-message-assistant-text"])!=null?zt:t["--persona-text"],t["--persona-message-assistant-border"]=(yt=t["--persona-components-message-assistant-border"])!=null?yt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Ze=t["--persona-components-message-assistant-shadow"])!=null?Ze:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(De=(bt=t["--persona-components-scrollToBottom-background"])!=null?bt:t["--persona-button-primary-bg"])!=null?De:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Gn=(qt=t["--persona-components-scrollToBottom-foreground"])!=null?qt:t["--persona-button-primary-fg"])!=null?Gn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(nr=t["--persona-components-scrollToBottom-border"])!=null?nr:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=($n=t["--persona-components-scrollToBottom-size"])!=null?$n:"40px",t["--persona-scroll-to-bottom-radius"]=(Kn=(Tr=(et=t["--persona-components-scrollToBottom-borderRadius"])!=null?et:t["--persona-button-radius"])!=null?Tr:t["--persona-radius-full"])!=null?Kn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Wn=(Mr=t["--persona-components-scrollToBottom-shadow"])!=null?Mr:t["--persona-palette-shadows-sm"])!=null?Wn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(jr=t["--persona-components-scrollToBottom-padding"])!=null?jr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(ur=t["--persona-components-scrollToBottom-gap"])!=null?ur:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(at=(rr=t["--persona-components-scrollToBottom-fontSize"])!=null?rr:t["--persona-palette-typography-fontSize-sm"])!=null?at:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(An=t["--persona-components-scrollToBottom-iconSize"])!=null?An:"14px",t["--persona-tool-bubble-shadow"]=(_n=t["--persona-components-toolBubble-shadow"])!=null?_n:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(dn=t["--persona-components-reasoningBubble-shadow"])!=null?dn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(mr=t["--persona-components-composer-shadow"])!=null?mr:"none",t["--persona-md-inline-code-bg"]=(En=t["--persona-components-markdown-inlineCode-background"])!=null?En:t["--persona-container"],t["--persona-md-inline-code-color"]=(At=t["--persona-components-markdown-inlineCode-foreground"])!=null?At:t["--persona-text"],t["--persona-md-link-color"]=(Rn=(pn=t["--persona-components-markdown-link-foreground"])!=null?pn:t["--persona-accent"])!=null?Rn:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let u=t["--persona-components-markdown-prose-fontFamily"];u&&u!=="inherit"&&(t["--persona-md-prose-font-family"]=u),t["--persona-md-code-block-bg"]=(gr=t["--persona-components-markdown-codeBlock-background"])!=null?gr:t["--persona-container"],t["--persona-md-code-block-border-color"]=(or=t["--persona-components-markdown-codeBlock-borderColor"])!=null?or:t["--persona-border"],t["--persona-md-code-block-text-color"]=(fr=t["--persona-components-markdown-codeBlock-textColor"])!=null?fr:"inherit",t["--persona-md-table-header-bg"]=(Xn=t["--persona-components-markdown-table-headerBackground"])!=null?Xn:t["--persona-container"],t["--persona-md-table-border-color"]=(Tn=t["--persona-components-markdown-table-borderColor"])!=null?Tn:t["--persona-border"],t["--persona-md-hr-color"]=(Zn=t["--persona-components-markdown-hr-color"])!=null?Zn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(wt=t["--persona-components-markdown-blockquote-borderColor"])!=null?wt:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Nt=t["--persona-components-markdown-blockquote-background"])!=null?Nt:"transparent",t["--persona-md-blockquote-text-color"]=(Ot=t["--persona-components-markdown-blockquote-textColor"])!=null?Ot:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Mn=t["--persona-components-collapsibleWidget-container"])!=null?Mn:t["--persona-surface"],t["--cw-surface"]=(hr=t["--persona-components-collapsibleWidget-surface"])!=null?hr:t["--persona-surface"],t["--cw-border"]=(jn=t["--persona-components-collapsibleWidget-border"])!=null?jn:t["--persona-border"],t["--persona-message-border"]=(kn=t["--persona-components-message-border"])!=null?kn:t["--persona-border"];let c=e.components,p=c==null?void 0:c.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let d=c==null?void 0:c.labelButton;d&&(d.background&&(t["--persona-label-btn-bg"]=d.background),d.border&&(t["--persona-label-btn-border"]=d.border),d.color&&(t["--persona-label-btn-color"]=d.color),d.padding&&(t["--persona-label-btn-padding"]=d.padding),d.borderRadius&&(t["--persona-label-btn-radius"]=d.borderRadius),d.hoverBackground&&(t["--persona-label-btn-hover-bg"]=d.hoverBackground),d.fontSize&&(t["--persona-label-btn-font-size"]=d.fontSize),d.gap&&(t["--persona-label-btn-gap"]=d.gap));let f=c==null?void 0:c.toggleGroup;f&&(f.gap&&(t["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(t["--persona-toggle-group-radius"]=f.borderRadius));let g=c==null?void 0:c.artifact;if(g!=null&&g.toolbar){let ie=g.toolbar;ie.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=ie.iconHoverColor),ie.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=ie.iconHoverBackground),ie.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=ie.iconPadding),ie.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=ie.iconBorderRadius),ie.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=ie.iconBorder),ie.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=ie.toggleGroupGap),ie.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=ie.toggleBorderRadius),ie.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=ie.copyBackground),ie.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=ie.copyBorder),ie.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=ie.copyColor),ie.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=ie.copyBorderRadius),ie.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=ie.copyPadding),ie.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=ie.copyMenuBackground,t["--persona-dropdown-bg"]=(D=t["--persona-dropdown-bg"])!=null?D:ie.copyMenuBackground),ie.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ie.copyMenuBorder,t["--persona-dropdown-border"]=(zn=t["--persona-dropdown-border"])!=null?zn:ie.copyMenuBorder),ie.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ie.copyMenuShadow,t["--persona-dropdown-shadow"]=(Hn=t["--persona-dropdown-shadow"])!=null?Hn:ie.copyMenuShadow),ie.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ie.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(yr=t["--persona-dropdown-radius"])!=null?yr:ie.copyMenuBorderRadius),ie.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ie.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(fn=t["--persona-dropdown-item-hover-bg"])!=null?fn:ie.copyMenuItemHoverBackground),ie.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ie.iconBackground),ie.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ie.toolbarBorder)}if(g!=null&&g.tab){let ie=g.tab;ie.background&&(t["--persona-artifact-tab-bg"]=ie.background),ie.activeBackground&&(t["--persona-artifact-tab-active-bg"]=ie.activeBackground),ie.activeBorder&&(t["--persona-artifact-tab-active-border"]=ie.activeBorder),ie.borderRadius&&(t["--persona-artifact-tab-radius"]=ie.borderRadius),ie.textColor&&(t["--persona-artifact-tab-color"]=ie.textColor),ie.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=ie.hoverBackground),ie.listBackground&&(t["--persona-artifact-tab-list-bg"]=ie.listBackground),ie.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=ie.listBorderColor),ie.listPadding&&(t["--persona-artifact-tab-list-padding"]=ie.listPadding)}if(g!=null&&g.pane){let ie=g.pane;if(ie.toolbarBackground){let Ln=(hn=Ro(e,ie.toolbarBackground))!=null?hn:ie.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Ln}}return t}var Dp={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 Fp={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"}}},zc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ys=()=>{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"},Np=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":ys()},qc=e=>Np(e),Op=e=>Ho(e),$p=e=>{var t;let r=Ho(void 0,{validate:!1});return Ho({...e,palette:{...r.palette,colors:{...Fp.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},bs=e=>{let r=qc(e),t=zc(e==null?void 0:e.theme),n=zc(e==null?void 0:e.darkTheme);return r==="dark"?$p(Wo(t!=null?t:{},n!=null?n:{})):Op(t)},_p=e=>Qs(e),$r=(e,r)=>{var o;let t=bs(r),n=_p(t);for(let[a,i]of Object.entries(n))e.style.setProperty(a,i);let s=(o=r==null?void 0:r.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},ea=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(ys())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(ys());t.addEventListener?(t.addEventListener("change",n),r.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),r.push(()=>t.removeListener(n)))}return()=>{r.forEach(t=>t())}};import{Idiomorph as jp}from"idiomorph";var Uc=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;jp.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&n){if(s.classList.contains("persona-animate-typing"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let u=(a=s.textContent)!=null?a:"",c=(i=o.textContent)!=null?i:"";if(u!==c)return}return!1}}}}})};function Vc(e,r){var t,n,s,o,a,i,u,c,p,d,f,g,v,M,C,S,k,H,w,L,P,E,Y,Q,G,O,re,we,oe;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(u=(i=e.rawContent)==null?void 0:i.length)!=null?u:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(d=e.approval)==null?void 0:d.status)!=null?f:"",(v=(g=e.toolCall)==null?void 0:g.status)!=null?v:"",(C=(M=e.toolCall)==null?void 0:M.name)!=null?C:"",(H=(k=(S=e.toolCall)==null?void 0:S.chunks)==null?void 0:k.length)!=null?H:0,(E=(P=(L=(w=e.toolCall)==null?void 0:w.chunks)==null?void 0:L[e.toolCall.chunks.length-1])==null?void 0:P.slice(-32))!=null?E:"",typeof((Y=e.toolCall)==null?void 0:Y.args)=="string"?e.toolCall.args.length:(Q=e.toolCall)!=null&&Q.args?JSON.stringify(e.toolCall.args).length:0,(re=(O=(G=e.reasoning)==null?void 0:G.chunks)==null?void 0:O.length)!=null?re:0,(oe=(we=e.contentParts)==null?void 0:we.length)!=null?oe:0,r].join("\0")}function Jc(){return new Map}function Yc(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Gc(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Kc(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function xs(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function Bo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Do(e,r){return Bo(e)-e.scrollTop<=r}function vs(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:u=!0,resumeRequiresDownwardScroll:c=!1}=e,p=t-n;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:t}:!r&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:r&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:r&&u&&!s?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function Cs(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:s=!1}=e;return r&&t<0?"pause":!r&&s&&t>0&&n?"resume":"none"}var cn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},wn=1e5,Cr=wn+1;function ta(e,r=wn){let t=e.style.position,n=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(r),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=n,e.style.isolation=s}}var Fo=0,wr=null;function na(e=document){var t;if(Fo++,Fo===1){let n=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;wr={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:o},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${o}px`,n.style.width="100%"}let r=!1;return()=>{var n;if(!r&&(r=!0,Fo=Math.max(0,Fo-1),Fo===0&&wr)){let s=e.body,o=(n=e.defaultView)!=null?n:window;s.style.overflow=wr.originalOverflow,s.style.position=wr.originalPosition,s.style.top=wr.originalTop,s.style.width=wr.originalWidth,o.scrollTo(0,wr.scrollY),wr=null}}}var ws={side:"right",width:"420px",animate:!0,reveal:"resize"},en=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},Jn=e=>{var t,n,s,o,a;let r=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(n=r==null?void 0:r.side)!=null?n:ws.side,width:(s=r==null?void 0:r.width)!=null?s:ws.width,animate:(o=r==null?void 0:r.animate)!=null?o:ws.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:ws.reveal}};var Yn={"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 No=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
8
8
  <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>
9
9
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
10
10
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -12,14 +12,14 @@ import{Marked as sp}from"marked";var ap=e=>{if(e)return e},ss=e=>{var s,o;let r=
12
12
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
13
13
  </span>
14
14
  <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>
15
- `,t.addEventListener("click",r);let n=o=>{var H,w,L,P,E,Y,Q,G,O,re,we,oe,ve,We;let a=(H=o.launcher)!=null?H:{},i=en(o),u=t.querySelector("[data-role='launcher-title']");if(u){let ge=(w=a.title)!=null?w:"Chat Assistant";u.textContent=ge,u.setAttribute("title",ge)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let ge=(L=a.subtitle)!=null?L:"Get answers fast";c.textContent=ge,c.setAttribute("title",ge)}let p=t.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let d=t.querySelector("[data-role='launcher-icon']");if(d)if(a.agentIconHidden)d.style.display="none";else{let ge=(P=a.agentIconSize)!=null?P:"40px";if(d.style.height=ge,d.style.width=ge,d.innerHTML="",a.agentIconName){let ke=parseFloat(ge)||24,Le=be(a.agentIconName,ke*.6,"var(--persona-text-inverse, #ffffff)",2);Le?(d.appendChild(Le),d.style.display=""):(d.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",d.style.display="")}else a.iconUrl?d.style.display="none":(d.textContent=(Y=a.agentIconText)!=null?Y:"\u{1F4AC}",d.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let ge=(Q=a.agentIconSize)!=null?Q:"40px";f.style.height=ge,f.style.width=ge,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=t.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let ge=(G=a.callToActionIconSize)!=null?G:"32px";g.style.height=ge,g.style.width=ge,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 ke=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,ke=(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 Le=parseFloat(ge)||24,se=Math.max(Le-ke,8),K=be(a.callToActionIconName,se,"currentColor",2);K?g.appendChild(K):g.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else g.textContent=(re=a.callToActionIconText)!=null?re:"\u2197"}let v=a.position&&Yn[a.position]?Yn[a.position]:Yn["bottom-right"],M="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",C="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?C:`${M} ${v}`,i||(t.style.zIndex=String((we=a.zIndex)!=null?we:wn));let S="1px solid var(--persona-border, #e5e7eb)",k="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(oe=a.border)!=null?oe:S,t.style.boxShadow=(ve=a.shadow)!=null?ve:k,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(We=a.collapsedMaxWidth)!=null?We:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",r),t.remove()};return e&&n(e),{element:t,update:n,destroy:s}};var Sn={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))"},Sr=e=>{var G,O,re,we,oe,ve,We,ge,ke,Le,se,K,ue,U,te,fe,pe,Re,Xe,j,W,ae,$,q,de,_e,ee,le,Lt,ct,Dt,Xt;let{config:r,showClose:t=!0}=e,n=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(G=r==null?void 0:r.launcher)!=null?G:{},o=(O=s.headerIconSize)!=null?O:"48px",a=(re=s.closeButtonSize)!=null?re:"32px",i=(we=s.closeButtonPlacement)!=null?we:"inline",u=(oe=s.headerIconHidden)!=null?oe:!1,c=s.headerIconName,p=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(p.style.height=o,p.style.width=o,p.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",p.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!u)if(c){let je=parseFloat(o)||24,me=be(c,je*.6,"currentColor",1);me?p.replaceChildren(me):p.textContent=(We=(ve=r==null?void 0:r.launcher)==null?void 0:ve.agentIconText)!=null?We:"\u{1F4AC}"}else if((ge=r==null?void 0:r.launcher)!=null&&ge.iconUrl){let je=h("img");je.src=r.launcher.iconUrl,je.alt="",je.className="persona-rounded-xl persona-object-cover",je.style.height=o,je.style.width=o,p.replaceChildren(je)}else p.textContent=(Le=(ke=r==null?void 0:r.launcher)==null?void 0:ke.agentIconText)!=null?Le:"\u{1F4AC}";let d=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=h("span","persona-text-base persona-font-semibold");f.style.color=Sn.titleColor,f.textContent=(K=(se=r==null?void 0:r.launcher)==null?void 0:se.title)!=null?K:"Chat Assistant";let g=h("span","persona-text-xs");g.style.color=Sn.subtitleColor,g.textContent=(U=(ue=r==null?void 0:r.launcher)==null?void 0:ue.subtitle)!=null?U:"Here to help you get answers fast",d.append(f,g),u?n.append(d):n.append(p,d);let v=(te=s.clearChat)!=null?te:{},M=(fe=v.enabled)!=null?fe:!0,C=(pe=v.placement)!=null?pe:"inline",S=null,k=null;if(M){let je=(Re=v.size)!=null?Re:"32px",me=(Xe=v.iconName)!=null?Xe:"refresh-cw",Ne=(j=v.iconColor)!=null?j:"",Pt=(W=v.backgroundColor)!=null?W:"",Wt=(ae=v.borderWidth)!=null?ae:"",ot=($=v.borderColor)!=null?$:"",st=(q=v.borderRadius)!=null?q:"",nn=(de=v.paddingX)!=null?de:"",tn=(_e=v.paddingY)!=null?_e:"",rn=(ee=v.tooltipText)!=null?ee:"Clear chat",z=(le=v.showTooltip)!=null?le:!0;k=h("div",C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),C==="top-right"&&(k.style.right="48px"),S=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none"),S.style.height=je,S.style.width=je,S.type="button",S.setAttribute("aria-label",rn),S.style.color=Ne||Sn.actionIconColor;let He=be(me,"20px","currentColor",1);if(He&&S.appendChild(He),Pt&&(S.style.backgroundColor=Pt,S.classList.remove("hover:persona-bg-gray-100")),Wt||ot){let ye=Wt||"0px",ht=ot||"transparent";S.style.border=`${ye} solid ${ht}`,S.classList.remove("persona-border-none")}if(st&&(S.style.borderRadius=st,S.classList.remove("persona-rounded-full")),nn?(S.style.paddingLeft=nn,S.style.paddingRight=nn):(S.style.paddingLeft="",S.style.paddingRight=""),tn?(S.style.paddingTop=tn,S.style.paddingBottom=tn):(S.style.paddingTop="",S.style.paddingBottom=""),k.appendChild(S),z&&rn&&S&&k){let ye=null,ht=()=>{if(ye||!S)return;let ce=S.ownerDocument,Se=ce.body;if(!Se)return;ye=er(ce,"div","persona-clear-chat-tooltip"),ye.textContent=rn;let Oe=er(ce,"div");Oe.className="persona-clear-chat-tooltip-arrow",ye.appendChild(Oe);let Ct=S.getBoundingClientRect();ye.style.position="fixed",ye.style.zIndex=String(Cr),ye.style.left=`${Ct.left+Ct.width/2}px`,ye.style.top=`${Ct.top-8}px`,ye.style.transform="translate(-50%, -100%)",Se.appendChild(ye)},$e=()=>{ye&&ye.parentNode&&(ye.parentNode.removeChild(ye),ye=null)};k.addEventListener("mouseenter",ht),k.addEventListener("mouseleave",$e),S.addEventListener("focus",ht),S.addEventListener("blur",$e),k._cleanupTooltip=()=>{$e(),k&&(k.removeEventListener("mouseenter",ht),k.removeEventListener("mouseleave",$e)),S&&(S.removeEventListener("focus",ht),S.removeEventListener("blur",$e))}}C==="inline"&&n.appendChild(k)}let H=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":M&&C==="inline"?"":"persona-ml-auto"),w=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");w.style.height=a,w.style.width=a,w.type="button";let L=(Lt=s.closeButtonTooltipText)!=null?Lt:"Close chat",P=(ct=s.closeButtonShowTooltip)!=null?ct:!0;w.setAttribute("aria-label",L),w.style.display=t?"":"none";let E=(Dt=s.closeButtonIconName)!=null?Dt:"x",Y=(Xt=s.closeButtonIconText)!=null?Xt:"\xD7";w.style.color=s.closeButtonColor||Sn.actionIconColor;let Q=be(E,"20px","currentColor",1);if(Q?w.appendChild(Q):w.textContent=Y,s.closeButtonBackgroundColor?(w.style.backgroundColor=s.closeButtonBackgroundColor,w.classList.remove("hover:persona-bg-gray-100")):(w.style.backgroundColor="",w.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let je=s.closeButtonBorderWidth||"0px",me=s.closeButtonBorderColor||"transparent";w.style.border=`${je} solid ${me}`,w.classList.remove("persona-border-none")}else w.style.border="",w.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(w.style.borderRadius=s.closeButtonBorderRadius,w.classList.remove("persona-rounded-full")):(w.style.borderRadius="",w.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(w.style.paddingLeft=s.closeButtonPaddingX,w.style.paddingRight=s.closeButtonPaddingX):(w.style.paddingLeft="",w.style.paddingRight=""),s.closeButtonPaddingY?(w.style.paddingTop=s.closeButtonPaddingY,w.style.paddingBottom=s.closeButtonPaddingY):(w.style.paddingTop="",w.style.paddingBottom=""),H.appendChild(w),P&&L){let je=null,me=()=>{if(je)return;let Pt=w.ownerDocument,Wt=Pt.body;if(!Wt)return;je=er(Pt,"div","persona-clear-chat-tooltip"),je.textContent=L;let ot=er(Pt,"div");ot.className="persona-clear-chat-tooltip-arrow",je.appendChild(ot);let st=w.getBoundingClientRect();je.style.position="fixed",je.style.zIndex=String(Cr),je.style.left=`${st.left+st.width/2}px`,je.style.top=`${st.top-8}px`,je.style.transform="translate(-50%, -100%)",Wt.appendChild(je)},Ne=()=>{je&&je.parentNode&&(je.parentNode.removeChild(je),je=null)};H.addEventListener("mouseenter",me),H.addEventListener("mouseleave",Ne),w.addEventListener("focus",me),w.addEventListener("blur",Ne),H._cleanupTooltip=()=>{Ne(),H.removeEventListener("mouseenter",me),H.removeEventListener("mouseleave",Ne),w.removeEventListener("focus",me),w.removeEventListener("blur",Ne)}}return i!=="top-right"&&n.appendChild(H),{header:n,iconHolder:p,headerTitle:f,headerSubtitle:g,closeButton:w,closeButtonWrapper:H,clearChatButton:S,clearChatButtonWrapper:k}},to=(e,r,t)=>{var a,i,u,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(u=n.clearChat)==null?void 0:u.placement)!=null?c:"inline";e.appendChild(r.header),s==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function _r(e){let{items:r,onSelect:t,anchor:n,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(Cr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of r){if(g.dividerBefore){let C=document.createElement("hr");a.appendChild(C)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",g.id),g.destructive&&v.setAttribute("data-destructive",""),g.icon){let C=be(g.icon,16,"currentColor",1.5);C&&v.appendChild(C)}let M=document.createElement("span");M.textContent=g.label,v.appendChild(M),v.addEventListener("click",C=>{C.stopPropagation(),p(),t(g.id)}),a.appendChild(v)}let i=null;function u(){if(!o)return;let g=n.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,s==="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(){u(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=v=>{!a.contains(v.target)&&!n.contains(v.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 d(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:p,toggle:d,destroy:f}}function Bt(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,u=h("button","persona-icon-btn"+(o?" "+o:""));u.type="button",u.setAttribute("aria-label",t),u.title=t;let c=be(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&u.appendChild(c),a&&u.addEventListener("click",a),i)for(let[p,d]of Object.entries(i))u.setAttribute(p,d);return u}function Ss(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:u}=e,c="persona-label-btn";n!=="default"&&(c+=" persona-label-btn--"+n),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let p=h("button",c);if(p.type="button",p.setAttribute("aria-label",t),r){let f=be(r,o!=null?o:14,"currentColor",2);f&&p.appendChild(f)}let d=h("span");if(d.textContent=t,p.appendChild(d),i&&p.addEventListener("click",i),u)for(let[f,g]of Object.entries(u))p.setAttribute(f,g);return p}function As(e){let{items:r,selectedId:t,onSelect:n,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function u(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of r){let d;p.icon?d=Bt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,u(),n(p.id)}}):(d=h("button","persona-icon-btn"),d.type="button",d.setAttribute("aria-label",p.label),d.title=p.label,d.textContent=p.label,d.addEventListener("click",()=>{a=p.id,u(),n(p.id)})),d.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:d}),o.appendChild(d)}function c(p){a=p,u()}return{element:o,setSelected:c}}function ra(e){var g,v;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:u}=e,c=h("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",r);let p=h("span","persona-combo-btn-label");p.textContent=r,c.appendChild(p);let d=be(t,14,"currentColor",2);d&&(d.style.marginLeft="4px",d.style.opacity="0.6",c.appendChild(d)),u&&(c.style.borderRadius=(g=u.borderRadius)!=null?g:"10px",c.style.padding=(v=u.padding)!=null?v:"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 M,C;c.style.backgroundColor=(M=u.background)!=null?M:"",c.style.borderColor=(C=u.border)!=null?C:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=_r({items:n,onSelect:M=>{c.setAttribute("aria-expanded","false"),s(M)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",M=>{M.stopPropagation();let C=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",C?"false":"true"),f.toggle()}),c.addEventListener("keydown",M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),c.click())}),{element:c,setLabel:M=>{p.textContent=M,c.setAttribute("aria-label",M)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let M=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",M?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Xc=e=>{var n;let r=Sr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(n=e.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(t){let s=r.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return r};function zp(e,r,t){var n,s,o;if(r!=null&&r.length)for(let a of r){let i=h("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",(s=(n=a.ariaLabel)!=null?n:a.label)!=null?s:a.id),a.icon){let u=be(a.icon,14,"currentColor",2);u&&i.appendChild(u)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let u=h("div","persona-relative");u.appendChild(i);let c=_r({items:a.menuItems,onSelect:p=>t==null?void 0:t(p),anchor:u,position:"bottom-left"});u.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(u)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Zc=e=>{var k,H,w,L,P,E,Y,Q,G;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(k=r==null?void 0:r.launcher)!=null?k:{},i=h("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 u=s==null?void 0:s.titleMenu,c,p;if(u)c=ra({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:u.menuItems,onSelect:u.onSelect,hover:u.hover,className:""}).element,c.style.color=Sn.titleColor,p=(w=c.querySelector(".persona-combo-btn-label"))!=null?w:c;else{if(c=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=h("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Sn.titleColor,p.textContent=(L=a.title)!=null?L:"Chat Assistant",c.appendChild(p),zp(c,s==null?void 0:s.trailingActions,(P=s==null?void 0:s.onAction)!=null?P:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let re=s.onTitleClick;c.addEventListener("click",we=>{we.target.closest("button")||re()}),c.addEventListener("keydown",we=>{(we.key==="Enter"||we.key===" ")&&(we.preventDefault(),re())})}let O=s==null?void 0:s.titleRowHover;O&&(c.style.borderRadius=(E=O.borderRadius)!=null?E:"10px",c.style.padding=(Y=O.padding)!=null?Y:"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 re,we;c.style.backgroundColor=(re=O.background)!=null?re:"",c.style.borderColor=(we=O.border)!=null?we:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let d=(Q=a.closeButtonSize)!=null?Q:"32px",f=h("div",""),g=h("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=d,g.style.width=d,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=t?"":"none",g.style.color=a.closeButtonColor||Sn.actionIconColor;let v=(G=a.closeButtonIconName)!=null?G:"x",M=be(v,"20px","currentColor",2);M?g.appendChild(M):g.textContent="\xD7",n&&g.addEventListener("click",n),f.appendChild(g),i.appendChild(f);let C=h("div");C.style.display="none";let S=h("span");return S.style.display="none",{header:i,iconHolder:C,headerTitle:p,headerSubtitle:S,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},oa={default:Xc,minimal:Zc},Qc=e=>{var r;return(r=oa[e])!=null?r:oa.default},Oo=(e,r,t)=>{var a,i,u;if(r!=null&&r.render){let c=r.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:r.trailingActions,onAction:r.onAction}),p=h("div");p.style.display="none";let d=h("span"),f=h("span"),g=h("button");g.style.display="none";let v=h("div");return v.style.display="none",{header:c,iconHolder:p,headerTitle:d,headerSubtitle:f,closeButton:g,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=Qc(n)({config:e,showClose:(u=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?u:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(o.iconHolder.style.display="none"),r.showTitle===!1&&(o.headerTitle.style.display="none"),r.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(o.closeButton.style.display="none"),r.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var $o=e=>{var pe,Re,Xe,j,W,ae,$,q,de,_e,ee,le,Lt,ct,Dt,Xt,je,me,Ne,Pt,Wt,ot,st,nn,tn,rn,z;let{config:r}=e,t=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let n=h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2"),s=h("form","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");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let o=h("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=(Re=(pe=r==null?void 0:r.copy)==null?void 0:pe.inputPlaceholder)!=null?Re:"Type your message\u2026",o.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",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let u=3*20;o.style.maxHeight=`${u}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let He=Math.min(o.scrollHeight,u);o.style.height=`${He}px`};o.addEventListener("input",c),o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"});let p=(Xe=r==null?void 0:r.sendButton)!=null?Xe:{},d=(j=p.useIcon)!=null?j:!1,f=(W=p.iconText)!=null?W:"\u2191",g=p.iconName,v=(ae=p.tooltipText)!=null?ae:"Send message",M=($=p.showTooltip)!=null?$:!1,C=(q=p.size)!=null?q:"40px",S=p.backgroundColor,k=p.textColor,H=h("div","persona-send-button-wrapper"),w=h("button",d?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");if(w.type="submit",w.setAttribute("data-persona-composer-submit",""),d){if(w.style.width=C,w.style.height=C,w.style.minWidth=C,w.style.minHeight=C,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",k?w.style.color=k:w.style.color="var(--persona-button-primary-fg, #ffffff)",g){let He=parseFloat(C)||24,ye=(k==null?void 0:k.trim())||"currentColor",ht=be(g,He,ye,2);ht?w.appendChild(ht):w.textContent=f}else w.textContent=f;S?w.style.backgroundColor=S:w.classList.add("persona-bg-persona-primary")}else w.textContent=(_e=(de=r==null?void 0:r.copy)==null?void 0:de.sendButtonLabel)!=null?_e:"Send",k?w.style.color=k:w.classList.add("persona-text-white");if(p.borderWidth&&(w.style.borderWidth=p.borderWidth,w.style.borderStyle="solid"),p.borderColor&&(w.style.borderColor=p.borderColor),p.paddingX?(w.style.paddingLeft=p.paddingX,w.style.paddingRight=p.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),p.paddingY?(w.style.paddingTop=p.paddingY,w.style.paddingBottom=p.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),M&&v){let He=h("div","persona-send-button-tooltip");He.textContent=v,H.appendChild(He)}H.appendChild(w);let L=(ee=r==null?void 0:r.voiceRecognition)!=null?ee:{},P=L.enabled===!0,E=null,Y=null,Q=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),G=((le=L.provider)==null?void 0:le.type)==="runtype";if(P&&(Q||G)){Y=h("div","persona-send-button-wrapper"),E=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),E.type="button",E.setAttribute("data-persona-composer-mic",""),E.setAttribute("aria-label","Start voice recognition");let He=(Lt=L.iconName)!=null?Lt:"mic",ye=(ct=L.iconSize)!=null?ct:C,ht=parseFloat(ye)||24,$e=(Dt=L.backgroundColor)!=null?Dt:S,ce=(Xt=L.iconColor)!=null?Xt:k;E.style.width=ye,E.style.height=ye,E.style.minWidth=ye,E.style.minHeight=ye,E.style.fontSize="18px",E.style.lineHeight="1",ce?E.style.color=ce:E.style.color="var(--persona-text, #111827)";let Oe=be(He,ht,ce||"currentColor",1.5);Oe?E.appendChild(Oe):E.textContent="\u{1F3A4}",$e&&(E.style.backgroundColor=$e),L.borderWidth&&(E.style.borderWidth=L.borderWidth,E.style.borderStyle="solid"),L.borderColor&&(E.style.borderColor=L.borderColor),L.paddingX&&(E.style.paddingLeft=L.paddingX,E.style.paddingRight=L.paddingX),L.paddingY&&(E.style.paddingTop=L.paddingY,E.style.paddingBottom=L.paddingY),Y.appendChild(E);let Ct=(je=L.tooltipText)!=null?je:"Start voice recognition";if(((me=L.showTooltip)!=null?me:!1)&&Ct){let dt=h("div","persona-send-button-tooltip");dt.textContent=Ct,Y.appendChild(dt)}}let re=(Ne=r==null?void 0:r.attachments)!=null?Ne:{},we=re.enabled===!0,oe=null,ve=null,We=null,ge=null;if(we){ge=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ge.style.display="none",We=h("input"),We.type="file",We.accept=((Pt=re.allowedTypes)!=null?Pt:dr).join(","),We.multiple=((Wt=re.maxFiles)!=null?Wt:4)>1,We.style.display="none",We.setAttribute("aria-label","Attach files"),ve=h("div","persona-send-button-wrapper"),oe=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),oe.type="button",oe.setAttribute("aria-label",(ot=re.buttonTooltipText)!=null?ot:"Attach file");let He=(st=re.buttonIconName)!=null?st:"paperclip",ye=C,ht=parseFloat(ye)||40,$e=Math.round(ht*.6);oe.style.width=ye,oe.style.height=ye,oe.style.minWidth=ye,oe.style.minHeight=ye,oe.style.fontSize="18px",oe.style.lineHeight="1",oe.style.backgroundColor="transparent",oe.style.color="var(--persona-primary, #111827)",oe.style.border="none",oe.style.borderRadius="6px",oe.style.transition="background-color 0.15s ease",oe.addEventListener("mouseenter",()=>{oe.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),oe.addEventListener("mouseleave",()=>{oe.style.backgroundColor="transparent"});let ce=be(He,$e,"currentColor",1.5);ce?oe.appendChild(ce):oe.textContent="\u{1F4CE}",oe.addEventListener("click",Ct=>{Ct.preventDefault(),We==null||We.click()}),ve.appendChild(oe);let Se=(nn=re.buttonTooltipText)!=null?nn:"Attach file",Oe=h("div","persona-send-button-tooltip");Oe.textContent=Se,ve.appendChild(Oe)}s.addEventListener("click",He=>{He.target!==w&&He.target!==H&&He.target!==E&&He.target!==Y&&He.target!==oe&&He.target!==ve&&o.focus()}),ge&&(ge.style.gap="8px",s.append(ge)),We&&s.append(We),s.append(o);let ke=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),Le=h("div","persona-flex persona-items-center persona-gap-2");ve&&Le.append(ve);let se=h("div","persona-flex persona-items-center persona-gap-1");Y&&se.append(Y),se.append(H),ke.append(Le,se),s.append(ke);let K=(tn=r==null?void 0:r.statusIndicator)!=null?tn:{},ue=K.align==="left"?"persona-text-left":K.align==="center"?"persona-text-center":"persona-text-right",U=h("div",`persona-mt-2 ${ue} persona-text-xs persona-text-persona-muted`);U.setAttribute("data-persona-composer-status","");let te=(rn=K.visible)!=null?rn:!0;U.style.display=te?"":"none";let fe=(z=K.idleText)!=null?z:"Online";if(K.idleLink){let He=h("a");He.href=K.idleLink,He.target="_blank",He.rel="noopener noreferrer",He.textContent=fe,He.style.color="inherit",He.style.textDecoration="none",U.appendChild(He)}else U.textContent=fe;return t.append(n,s,U),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:H,micButton:E,micButtonWrapper:Y,statusText:U,attachmentButton:oe,attachmentButtonWrapper:ve,attachmentInput:We,attachmentPreviewsContainer:ge,actionsRow:ke,leftActions:Le,rightActions:se}};var ed=e=>{var c,p,d,f,g,v,M,C,S;let r=(p=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?p:!0;if(en(e)){let k=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),H=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return k.appendChild(H),{wrapper:k,panel:H}}if(!r){let k=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),H=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=(f=(d=e==null?void 0:e.launcher)==null?void 0:d.width)!=null?f:"100%";return k.style.width=w,H.style.width="100%",k.appendChild(H),{wrapper:k,panel:H}}let n=(g=e==null?void 0:e.launcher)!=null?g:{},s=n.position&&Yn[n.position]?Yn[n.position]:Yn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);o.style.zIndex=String((M=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?M:wn);let a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(S=(C=e==null?void 0:e.launcher)==null?void 0:C.width)!=null?S:e==null?void 0:e.launcherWidth,u=i!=null?i:Nn;return a.style.width=u,a.style.maxWidth=u,o.appendChild(a),{wrapper:o,panel:a}},td=(e,r=!0)=>{var C,S,k,H,w,L,P,E,Y;let t=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-bg-persona-surface persona-text-persona-primary persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let n=(C=e==null?void 0:e.layout)==null?void 0:C.header,s=((S=e==null?void 0:e.layout)==null?void 0:S.showHeader)!==!1,o=n?Oo(e,n,{showClose:r}):Sr({config:e,showClose:r}),a=h("div","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");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=en(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",u=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(H=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeTitle)!=null?H:"Hello \u{1F44B}";let p=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");p.textContent=(L=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",u.append(c,p);let d=h("div","persona-flex persona-flex-col persona-gap-3"),f=(P=e==null?void 0:e.layout)==null?void 0:P.contentMaxWidth;f&&(d.style.maxWidth=f,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%"),u.setAttribute("data-persona-intro-card",""),((E=e==null?void 0:e.copy)==null?void 0:E.showWelcomeCard)!==!1||(u.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(u,d);let v=$o({config:e}),M=((Y=e==null?void 0:e.layout)==null?void 0:Y.showFooter)!==!1;return s?to(t,o,e):(o.header.style.display="none",to(t,o,e)),t.append(a),M||(v.footer.style.display="none"),t.append(v.footer),{container:t,body:a,messagesWrapper:d,suggestions:v.suggestions,textarea:v.textarea,sendButton:v.sendButton,sendButtonWrapper:v.sendButtonWrapper,micButton:v.micButton,micButtonWrapper:v.micButtonWrapper,composerForm:v.composerForm,statusText:v.statusText,introTitle:c,introSubtitle:p,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:v.footer,attachmentButton:v.attachmentButton,attachmentButtonWrapper:v.attachmentButtonWrapper,attachmentInput:v.attachmentInput,attachmentPreviewsContainer:v.attachmentPreviewsContainer,actionsRow:v.actionsRow,leftActions:v.leftActions,rightActions:v.rightActions}};var qp=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},Up=320,Vp=320,Jp=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Yp=(e,r,t)=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),r&&(n.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,n.remove(),t==null||t())};return e.forEach((i,u)=>{var d;let c=h("img");c.alt=((d=i.alt)==null?void 0:d.trim())||`Attached image ${u+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Up}px`,c.style.maxHeight=`${Vp}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;s+=1,c.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{p=!0}),qp(i.image)?(c.src=i.image,n.appendChild(c)):(p=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},no=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";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="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let 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="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(s),e},rd=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:no};if(r){let s=r(n);if(s!==null)return s}return no()},Gp=(e,r)=>{let t=h("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"),n=r==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let s=h("img");s.src=n,s.alt=r==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=n,t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=r==="user"?"U":"A",t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},nd=(e,r)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return r.format?t.textContent=r.format(n):t.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Kp=(e,r="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(r){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},od=(e,r,t)=>{var g,v,M,C,S,k;let n=(g=r.showCopy)!=null?g:!0,s=(v=r.showUpvote)!=null?v:!0,o=(M=r.showDownvote)!=null?M:!0;if(!n&&!s&&!o){let H=h("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let a=(C=r.visibility)!=null?C:"hover",i=(S=r.align)!=null?S:"right",u=(k=r.layout)!=null?k:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[u],d=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);d.id=`actions-${e.id}`,d.setAttribute("data-actions-for",e.id);let f=(H,w,L)=>{let P=Bt({icon:H,label:w,size:14,className:"persona-message-action-btn"});return P.setAttribute("data-action",L),P};return n&&d.appendChild(f("copy","Copy message","copy")),s&&d.appendChild(f("thumbs-up","Upvote","upvote")),o&&d.appendChild(f("thumbs-down","Downvote","downvote")),d},_o=(e,r,t,n,s,o)=>{var G,O,re,we,oe,ve,We;let a=t!=null?t:{},i=(G=a.layout)!=null?G:"bubble",u=a.avatar,c=a.timestamp,p=(O=u==null?void 0:u.show)!=null?O:!1,d=(re=c==null?void 0:c.show)!=null?re:!1,f=(we=u==null?void 0:u.position)!=null?we:"left",g=(oe=c==null?void 0:c.position)!=null?oe:"below",v=Kp(e.role,i),M=h("div",v.join(" "));M.id=`bubble-${e.id}`,M.setAttribute("data-message-id",e.id),M.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(M.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",M.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(M.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",M.style.color="var(--persona-message-assistant-text, var(--persona-text))");let C=Jp(e),S=(We=(ve=e.content)==null?void 0:ve.trim())!=null?We:"",H=C.length>0&&S===ds,w=document.createElement("div");w.classList.add("persona-message-content");let L=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),P=null;if(H?(P=document.createElement("div"),P.innerHTML=L,P.style.display="none",w.appendChild(P)):w.innerHTML=L,d&&g==="inline"&&e.createdAt){let ge=nd(e,c);ge.classList.add("persona-ml-2","persona-inline"),w.appendChild(ge)}if(C.length>0){let ge=Yp(C,!H&&!!S,()=>{H&&P&&(P.style.display="")});ge?M.appendChild(ge):H&&P&&(P.style.display="")}if(M.appendChild(w),d&&g==="below"&&e.createdAt){let ge=nd(e,c);ge.classList.add("persona-mt-1"),M.appendChild(ge)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let ge=rd("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);ge&&M.appendChild(ge)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let ge=od(e,n,s);M.appendChild(ge)}if(!p||e.role==="system")return M;let Y=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Q=Gp(u,e.role);return f==="right"||f==="left"&&e.role==="user"?Y.append(M,Q):Y.append(Q,M),M.classList.remove("persona-max-w-[85%]"),M.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Y},Xp=(e,r,t,n,s,o)=>{let a=t!=null?t:{};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}):_o(e,r,t,n,s,o)};var ro=new Set,Zp=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),Qp=(e,r)=>{var n,s;let t=(s=(n=e.reasoning)==null?void 0:n.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,r).join(`
15
+ `,t.addEventListener("click",r);let n=o=>{var H,w,L,P,E,Y,Q,G,O,re,we,oe,ve,We;let a=(H=o.launcher)!=null?H:{},i=en(o),u=t.querySelector("[data-role='launcher-title']");if(u){let ge=(w=a.title)!=null?w:"Chat Assistant";u.textContent=ge,u.setAttribute("title",ge)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let ge=(L=a.subtitle)!=null?L:"Get answers fast";c.textContent=ge,c.setAttribute("title",ge)}let p=t.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let d=t.querySelector("[data-role='launcher-icon']");if(d)if(a.agentIconHidden)d.style.display="none";else{let ge=(P=a.agentIconSize)!=null?P:"40px";if(d.style.height=ge,d.style.width=ge,d.innerHTML="",a.agentIconName){let ke=parseFloat(ge)||24,Le=be(a.agentIconName,ke*.6,"var(--persona-text-inverse, #ffffff)",2);Le?(d.appendChild(Le),d.style.display=""):(d.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",d.style.display="")}else a.iconUrl?d.style.display="none":(d.textContent=(Y=a.agentIconText)!=null?Y:"\u{1F4AC}",d.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let ge=(Q=a.agentIconSize)!=null?Q:"40px";f.style.height=ge,f.style.width=ge,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=t.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let ge=(G=a.callToActionIconSize)!=null?G:"32px";g.style.height=ge,g.style.width=ge,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 ke=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,ke=(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 Le=parseFloat(ge)||24,se=Math.max(Le-ke,8),K=be(a.callToActionIconName,se,"currentColor",2);K?g.appendChild(K):g.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else g.textContent=(re=a.callToActionIconText)!=null?re:"\u2197"}let v=a.position&&Yn[a.position]?Yn[a.position]:Yn["bottom-right"],M="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",C="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?C:`${M} ${v}`,i||(t.style.zIndex=String((we=a.zIndex)!=null?we:wn));let S="1px solid var(--persona-border, #e5e7eb)",k="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(oe=a.border)!=null?oe:S,t.style.boxShadow=(ve=a.shadow)!=null?ve:k,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(We=a.collapsedMaxWidth)!=null?We:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",r),t.remove()};return e&&n(e),{element:t,update:n,destroy:s}};var Sn={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))"},Sr=e=>{var G,O,re,we,oe,ve,We,ge,ke,Le,se,K,ue,U,te,fe,pe,Re,Xe,j,W,ae,$,q,de,_e,ee,le,It,dt,Dt,Xt;let{config:r,showClose:t=!0}=e,n=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(G=r==null?void 0:r.launcher)!=null?G:{},o=(O=s.headerIconSize)!=null?O:"48px",a=(re=s.closeButtonSize)!=null?re:"32px",i=(we=s.closeButtonPlacement)!=null?we:"inline",u=(oe=s.headerIconHidden)!=null?oe:!1,c=s.headerIconName,p=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(p.style.height=o,p.style.width=o,p.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",p.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!u)if(c){let je=parseFloat(o)||24,me=be(c,je*.6,"currentColor",1);me?p.replaceChildren(me):p.textContent=(We=(ve=r==null?void 0:r.launcher)==null?void 0:ve.agentIconText)!=null?We:"\u{1F4AC}"}else if((ge=r==null?void 0:r.launcher)!=null&&ge.iconUrl){let je=h("img");je.src=r.launcher.iconUrl,je.alt="",je.className="persona-rounded-xl persona-object-cover",je.style.height=o,je.style.width=o,p.replaceChildren(je)}else p.textContent=(Le=(ke=r==null?void 0:r.launcher)==null?void 0:ke.agentIconText)!=null?Le:"\u{1F4AC}";let d=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=h("span","persona-text-base persona-font-semibold");f.style.color=Sn.titleColor,f.textContent=(K=(se=r==null?void 0:r.launcher)==null?void 0:se.title)!=null?K:"Chat Assistant";let g=h("span","persona-text-xs");g.style.color=Sn.subtitleColor,g.textContent=(U=(ue=r==null?void 0:r.launcher)==null?void 0:ue.subtitle)!=null?U:"Here to help you get answers fast",d.append(f,g),u?n.append(d):n.append(p,d);let v=(te=s.clearChat)!=null?te:{},M=(fe=v.enabled)!=null?fe:!0,C=(pe=v.placement)!=null?pe:"inline",S=null,k=null;if(M){let je=(Re=v.size)!=null?Re:"32px",me=(Xe=v.iconName)!=null?Xe:"refresh-cw",Ne=(j=v.iconColor)!=null?j:"",Wt=(W=v.backgroundColor)!=null?W:"",Rt=(ae=v.borderWidth)!=null?ae:"",ot=($=v.borderColor)!=null?$:"",st=(q=v.borderRadius)!=null?q:"",nn=(de=v.paddingX)!=null?de:"",tn=(_e=v.paddingY)!=null?_e:"",rn=(ee=v.tooltipText)!=null?ee:"Clear chat",z=(le=v.showTooltip)!=null?le:!0;k=h("div",C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),C==="top-right"&&(k.style.right="48px"),S=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none"),S.style.height=je,S.style.width=je,S.type="button",S.setAttribute("aria-label",rn),S.style.color=Ne||Sn.actionIconColor;let He=be(me,"20px","currentColor",1);if(He&&S.appendChild(He),Wt&&(S.style.backgroundColor=Wt,S.classList.remove("hover:persona-bg-gray-100")),Rt||ot){let ye=Rt||"0px",ht=ot||"transparent";S.style.border=`${ye} solid ${ht}`,S.classList.remove("persona-border-none")}if(st&&(S.style.borderRadius=st,S.classList.remove("persona-rounded-full")),nn?(S.style.paddingLeft=nn,S.style.paddingRight=nn):(S.style.paddingLeft="",S.style.paddingRight=""),tn?(S.style.paddingTop=tn,S.style.paddingBottom=tn):(S.style.paddingTop="",S.style.paddingBottom=""),k.appendChild(S),z&&rn&&S&&k){let ye=null,ht=()=>{if(ye||!S)return;let ce=S.ownerDocument,Se=ce.body;if(!Se)return;ye=er(ce,"div","persona-clear-chat-tooltip"),ye.textContent=rn;let Oe=er(ce,"div");Oe.className="persona-clear-chat-tooltip-arrow",ye.appendChild(Oe);let Ct=S.getBoundingClientRect();ye.style.position="fixed",ye.style.zIndex=String(Cr),ye.style.left=`${Ct.left+Ct.width/2}px`,ye.style.top=`${Ct.top-8}px`,ye.style.transform="translate(-50%, -100%)",Se.appendChild(ye)},$e=()=>{ye&&ye.parentNode&&(ye.parentNode.removeChild(ye),ye=null)};k.addEventListener("mouseenter",ht),k.addEventListener("mouseleave",$e),S.addEventListener("focus",ht),S.addEventListener("blur",$e),k._cleanupTooltip=()=>{$e(),k&&(k.removeEventListener("mouseenter",ht),k.removeEventListener("mouseleave",$e)),S&&(S.removeEventListener("focus",ht),S.removeEventListener("blur",$e))}}C==="inline"&&n.appendChild(k)}let H=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":M&&C==="inline"?"":"persona-ml-auto"),w=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");w.style.height=a,w.style.width=a,w.type="button";let L=(It=s.closeButtonTooltipText)!=null?It:"Close chat",P=(dt=s.closeButtonShowTooltip)!=null?dt:!0;w.setAttribute("aria-label",L),w.style.display=t?"":"none";let E=(Dt=s.closeButtonIconName)!=null?Dt:"x",Y=(Xt=s.closeButtonIconText)!=null?Xt:"\xD7";w.style.color=s.closeButtonColor||Sn.actionIconColor;let Q=be(E,"20px","currentColor",1);if(Q?w.appendChild(Q):w.textContent=Y,s.closeButtonBackgroundColor?(w.style.backgroundColor=s.closeButtonBackgroundColor,w.classList.remove("hover:persona-bg-gray-100")):(w.style.backgroundColor="",w.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let je=s.closeButtonBorderWidth||"0px",me=s.closeButtonBorderColor||"transparent";w.style.border=`${je} solid ${me}`,w.classList.remove("persona-border-none")}else w.style.border="",w.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(w.style.borderRadius=s.closeButtonBorderRadius,w.classList.remove("persona-rounded-full")):(w.style.borderRadius="",w.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(w.style.paddingLeft=s.closeButtonPaddingX,w.style.paddingRight=s.closeButtonPaddingX):(w.style.paddingLeft="",w.style.paddingRight=""),s.closeButtonPaddingY?(w.style.paddingTop=s.closeButtonPaddingY,w.style.paddingBottom=s.closeButtonPaddingY):(w.style.paddingTop="",w.style.paddingBottom=""),H.appendChild(w),P&&L){let je=null,me=()=>{if(je)return;let Wt=w.ownerDocument,Rt=Wt.body;if(!Rt)return;je=er(Wt,"div","persona-clear-chat-tooltip"),je.textContent=L;let ot=er(Wt,"div");ot.className="persona-clear-chat-tooltip-arrow",je.appendChild(ot);let st=w.getBoundingClientRect();je.style.position="fixed",je.style.zIndex=String(Cr),je.style.left=`${st.left+st.width/2}px`,je.style.top=`${st.top-8}px`,je.style.transform="translate(-50%, -100%)",Rt.appendChild(je)},Ne=()=>{je&&je.parentNode&&(je.parentNode.removeChild(je),je=null)};H.addEventListener("mouseenter",me),H.addEventListener("mouseleave",Ne),w.addEventListener("focus",me),w.addEventListener("blur",Ne),H._cleanupTooltip=()=>{Ne(),H.removeEventListener("mouseenter",me),H.removeEventListener("mouseleave",Ne),w.removeEventListener("focus",me),w.removeEventListener("blur",Ne)}}return i!=="top-right"&&n.appendChild(H),{header:n,iconHolder:p,headerTitle:f,headerSubtitle:g,closeButton:w,closeButtonWrapper:H,clearChatButton:S,clearChatButtonWrapper:k}},to=(e,r,t)=>{var a,i,u,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(u=n.clearChat)==null?void 0:u.placement)!=null?c:"inline";e.appendChild(r.header),s==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function _r(e){let{items:r,onSelect:t,anchor:n,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(Cr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of r){if(g.dividerBefore){let C=document.createElement("hr");a.appendChild(C)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",g.id),g.destructive&&v.setAttribute("data-destructive",""),g.icon){let C=be(g.icon,16,"currentColor",1.5);C&&v.appendChild(C)}let M=document.createElement("span");M.textContent=g.label,v.appendChild(M),v.addEventListener("click",C=>{C.stopPropagation(),p(),t(g.id)}),a.appendChild(v)}let i=null;function u(){if(!o)return;let g=n.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,s==="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(){u(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=v=>{!a.contains(v.target)&&!n.contains(v.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 d(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:p,toggle:d,destroy:f}}function Bt(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,u=h("button","persona-icon-btn"+(o?" "+o:""));u.type="button",u.setAttribute("aria-label",t),u.title=t;let c=be(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&u.appendChild(c),a&&u.addEventListener("click",a),i)for(let[p,d]of Object.entries(i))u.setAttribute(p,d);return u}function Ss(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:u}=e,c="persona-label-btn";n!=="default"&&(c+=" persona-label-btn--"+n),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let p=h("button",c);if(p.type="button",p.setAttribute("aria-label",t),r){let f=be(r,o!=null?o:14,"currentColor",2);f&&p.appendChild(f)}let d=h("span");if(d.textContent=t,p.appendChild(d),i&&p.addEventListener("click",i),u)for(let[f,g]of Object.entries(u))p.setAttribute(f,g);return p}function As(e){let{items:r,selectedId:t,onSelect:n,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function u(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of r){let d;p.icon?d=Bt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,u(),n(p.id)}}):(d=h("button","persona-icon-btn"),d.type="button",d.setAttribute("aria-label",p.label),d.title=p.label,d.textContent=p.label,d.addEventListener("click",()=>{a=p.id,u(),n(p.id)})),d.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:d}),o.appendChild(d)}function c(p){a=p,u()}return{element:o,setSelected:c}}function ra(e){var g,v;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:u}=e,c=h("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",r);let p=h("span","persona-combo-btn-label");p.textContent=r,c.appendChild(p);let d=be(t,14,"currentColor",2);d&&(d.style.marginLeft="4px",d.style.opacity="0.6",c.appendChild(d)),u&&(c.style.borderRadius=(g=u.borderRadius)!=null?g:"10px",c.style.padding=(v=u.padding)!=null?v:"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 M,C;c.style.backgroundColor=(M=u.background)!=null?M:"",c.style.borderColor=(C=u.border)!=null?C:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=_r({items:n,onSelect:M=>{c.setAttribute("aria-expanded","false"),s(M)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",M=>{M.stopPropagation();let C=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",C?"false":"true"),f.toggle()}),c.addEventListener("keydown",M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),c.click())}),{element:c,setLabel:M=>{p.textContent=M,c.setAttribute("aria-label",M)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let M=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",M?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Xc=e=>{var n;let r=Sr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(n=e.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(t){let s=r.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return r};function zp(e,r,t){var n,s,o;if(r!=null&&r.length)for(let a of r){let i=h("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",(s=(n=a.ariaLabel)!=null?n:a.label)!=null?s:a.id),a.icon){let u=be(a.icon,14,"currentColor",2);u&&i.appendChild(u)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let u=h("div","persona-relative");u.appendChild(i);let c=_r({items:a.menuItems,onSelect:p=>t==null?void 0:t(p),anchor:u,position:"bottom-left"});u.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(u)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Zc=e=>{var k,H,w,L,P,E,Y,Q,G;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(k=r==null?void 0:r.launcher)!=null?k:{},i=h("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 u=s==null?void 0:s.titleMenu,c,p;if(u)c=ra({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:u.menuItems,onSelect:u.onSelect,hover:u.hover,className:""}).element,c.style.color=Sn.titleColor,p=(w=c.querySelector(".persona-combo-btn-label"))!=null?w:c;else{if(c=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=h("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Sn.titleColor,p.textContent=(L=a.title)!=null?L:"Chat Assistant",c.appendChild(p),zp(c,s==null?void 0:s.trailingActions,(P=s==null?void 0:s.onAction)!=null?P:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let re=s.onTitleClick;c.addEventListener("click",we=>{we.target.closest("button")||re()}),c.addEventListener("keydown",we=>{(we.key==="Enter"||we.key===" ")&&(we.preventDefault(),re())})}let O=s==null?void 0:s.titleRowHover;O&&(c.style.borderRadius=(E=O.borderRadius)!=null?E:"10px",c.style.padding=(Y=O.padding)!=null?Y:"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 re,we;c.style.backgroundColor=(re=O.background)!=null?re:"",c.style.borderColor=(we=O.border)!=null?we:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let d=(Q=a.closeButtonSize)!=null?Q:"32px",f=h("div",""),g=h("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=d,g.style.width=d,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=t?"":"none",g.style.color=a.closeButtonColor||Sn.actionIconColor;let v=(G=a.closeButtonIconName)!=null?G:"x",M=be(v,"20px","currentColor",2);M?g.appendChild(M):g.textContent="\xD7",n&&g.addEventListener("click",n),f.appendChild(g),i.appendChild(f);let C=h("div");C.style.display="none";let S=h("span");return S.style.display="none",{header:i,iconHolder:C,headerTitle:p,headerSubtitle:S,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},oa={default:Xc,minimal:Zc},Qc=e=>{var r;return(r=oa[e])!=null?r:oa.default},Oo=(e,r,t)=>{var a,i,u;if(r!=null&&r.render){let c=r.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:r.trailingActions,onAction:r.onAction}),p=h("div");p.style.display="none";let d=h("span"),f=h("span"),g=h("button");g.style.display="none";let v=h("div");return v.style.display="none",{header:c,iconHolder:p,headerTitle:d,headerSubtitle:f,closeButton:g,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=Qc(n)({config:e,showClose:(u=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?u:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(o.iconHolder.style.display="none"),r.showTitle===!1&&(o.headerTitle.style.display="none"),r.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(o.closeButton.style.display="none"),r.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var $o=e=>{var pe,Re,Xe,j,W,ae,$,q,de,_e,ee,le,It,dt,Dt,Xt,je,me,Ne,Wt,Rt,ot,st,nn,tn,rn,z;let{config:r}=e,t=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let n=h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2"),s=h("form","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");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let o=h("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=(Re=(pe=r==null?void 0:r.copy)==null?void 0:pe.inputPlaceholder)!=null?Re:"Type your message\u2026",o.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",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let u=3*20;o.style.maxHeight=`${u}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let He=Math.min(o.scrollHeight,u);o.style.height=`${He}px`};o.addEventListener("input",c),o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"});let p=(Xe=r==null?void 0:r.sendButton)!=null?Xe:{},d=(j=p.useIcon)!=null?j:!1,f=(W=p.iconText)!=null?W:"\u2191",g=p.iconName,v=(ae=p.tooltipText)!=null?ae:"Send message",M=($=p.showTooltip)!=null?$:!1,C=(q=p.size)!=null?q:"40px",S=p.backgroundColor,k=p.textColor,H=h("div","persona-send-button-wrapper"),w=h("button",d?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");if(w.type="submit",w.setAttribute("data-persona-composer-submit",""),d){if(w.style.width=C,w.style.height=C,w.style.minWidth=C,w.style.minHeight=C,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",k?w.style.color=k:w.style.color="var(--persona-button-primary-fg, #ffffff)",g){let He=parseFloat(C)||24,ye=(k==null?void 0:k.trim())||"currentColor",ht=be(g,He,ye,2);ht?w.appendChild(ht):w.textContent=f}else w.textContent=f;S?w.style.backgroundColor=S:w.classList.add("persona-bg-persona-primary")}else w.textContent=(_e=(de=r==null?void 0:r.copy)==null?void 0:de.sendButtonLabel)!=null?_e:"Send",k?w.style.color=k:w.classList.add("persona-text-white");if(p.borderWidth&&(w.style.borderWidth=p.borderWidth,w.style.borderStyle="solid"),p.borderColor&&(w.style.borderColor=p.borderColor),p.paddingX?(w.style.paddingLeft=p.paddingX,w.style.paddingRight=p.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),p.paddingY?(w.style.paddingTop=p.paddingY,w.style.paddingBottom=p.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),M&&v){let He=h("div","persona-send-button-tooltip");He.textContent=v,H.appendChild(He)}H.appendChild(w);let L=(ee=r==null?void 0:r.voiceRecognition)!=null?ee:{},P=L.enabled===!0,E=null,Y=null,Q=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),G=((le=L.provider)==null?void 0:le.type)==="runtype";if(P&&(Q||G)){Y=h("div","persona-send-button-wrapper"),E=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),E.type="button",E.setAttribute("data-persona-composer-mic",""),E.setAttribute("aria-label","Start voice recognition");let He=(It=L.iconName)!=null?It:"mic",ye=(dt=L.iconSize)!=null?dt:C,ht=parseFloat(ye)||24,$e=(Dt=L.backgroundColor)!=null?Dt:S,ce=(Xt=L.iconColor)!=null?Xt:k;E.style.width=ye,E.style.height=ye,E.style.minWidth=ye,E.style.minHeight=ye,E.style.fontSize="18px",E.style.lineHeight="1",ce?E.style.color=ce:E.style.color="var(--persona-text, #111827)";let Oe=be(He,ht,ce||"currentColor",1.5);Oe?E.appendChild(Oe):E.textContent="\u{1F3A4}",$e&&(E.style.backgroundColor=$e),L.borderWidth&&(E.style.borderWidth=L.borderWidth,E.style.borderStyle="solid"),L.borderColor&&(E.style.borderColor=L.borderColor),L.paddingX&&(E.style.paddingLeft=L.paddingX,E.style.paddingRight=L.paddingX),L.paddingY&&(E.style.paddingTop=L.paddingY,E.style.paddingBottom=L.paddingY),Y.appendChild(E);let Ct=(je=L.tooltipText)!=null?je:"Start voice recognition";if(((me=L.showTooltip)!=null?me:!1)&&Ct){let pt=h("div","persona-send-button-tooltip");pt.textContent=Ct,Y.appendChild(pt)}}let re=(Ne=r==null?void 0:r.attachments)!=null?Ne:{},we=re.enabled===!0,oe=null,ve=null,We=null,ge=null;if(we){ge=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ge.style.display="none",We=h("input"),We.type="file",We.accept=((Wt=re.allowedTypes)!=null?Wt:dr).join(","),We.multiple=((Rt=re.maxFiles)!=null?Rt:4)>1,We.style.display="none",We.setAttribute("aria-label","Attach files"),ve=h("div","persona-send-button-wrapper"),oe=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),oe.type="button",oe.setAttribute("aria-label",(ot=re.buttonTooltipText)!=null?ot:"Attach file");let He=(st=re.buttonIconName)!=null?st:"paperclip",ye=C,ht=parseFloat(ye)||40,$e=Math.round(ht*.6);oe.style.width=ye,oe.style.height=ye,oe.style.minWidth=ye,oe.style.minHeight=ye,oe.style.fontSize="18px",oe.style.lineHeight="1",oe.style.backgroundColor="transparent",oe.style.color="var(--persona-primary, #111827)",oe.style.border="none",oe.style.borderRadius="6px",oe.style.transition="background-color 0.15s ease",oe.addEventListener("mouseenter",()=>{oe.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),oe.addEventListener("mouseleave",()=>{oe.style.backgroundColor="transparent"});let ce=be(He,$e,"currentColor",1.5);ce?oe.appendChild(ce):oe.textContent="\u{1F4CE}",oe.addEventListener("click",Ct=>{Ct.preventDefault(),We==null||We.click()}),ve.appendChild(oe);let Se=(nn=re.buttonTooltipText)!=null?nn:"Attach file",Oe=h("div","persona-send-button-tooltip");Oe.textContent=Se,ve.appendChild(Oe)}s.addEventListener("click",He=>{He.target!==w&&He.target!==H&&He.target!==E&&He.target!==Y&&He.target!==oe&&He.target!==ve&&o.focus()}),ge&&(ge.style.gap="8px",s.append(ge)),We&&s.append(We),s.append(o);let ke=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),Le=h("div","persona-flex persona-items-center persona-gap-2");ve&&Le.append(ve);let se=h("div","persona-flex persona-items-center persona-gap-1");Y&&se.append(Y),se.append(H),ke.append(Le,se),s.append(ke);let K=(tn=r==null?void 0:r.statusIndicator)!=null?tn:{},ue=K.align==="left"?"persona-text-left":K.align==="center"?"persona-text-center":"persona-text-right",U=h("div",`persona-mt-2 ${ue} persona-text-xs persona-text-persona-muted`);U.setAttribute("data-persona-composer-status","");let te=(rn=K.visible)!=null?rn:!0;U.style.display=te?"":"none";let fe=(z=K.idleText)!=null?z:"Online";if(K.idleLink){let He=h("a");He.href=K.idleLink,He.target="_blank",He.rel="noopener noreferrer",He.textContent=fe,He.style.color="inherit",He.style.textDecoration="none",U.appendChild(He)}else U.textContent=fe;return t.append(n,s,U),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:H,micButton:E,micButtonWrapper:Y,statusText:U,attachmentButton:oe,attachmentButtonWrapper:ve,attachmentInput:We,attachmentPreviewsContainer:ge,actionsRow:ke,leftActions:Le,rightActions:se}};var ed=e=>{var c,p,d,f,g,v,M,C,S;let r=(p=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?p:!0;if(en(e)){let k=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),H=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return k.appendChild(H),{wrapper:k,panel:H}}if(!r){let k=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),H=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=(f=(d=e==null?void 0:e.launcher)==null?void 0:d.width)!=null?f:"100%";return k.style.width=w,H.style.width="100%",k.appendChild(H),{wrapper:k,panel:H}}let n=(g=e==null?void 0:e.launcher)!=null?g:{},s=n.position&&Yn[n.position]?Yn[n.position]:Yn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);o.style.zIndex=String((M=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?M:wn);let a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(S=(C=e==null?void 0:e.launcher)==null?void 0:C.width)!=null?S:e==null?void 0:e.launcherWidth,u=i!=null?i:Nn;return a.style.width=u,a.style.maxWidth=u,o.appendChild(a),{wrapper:o,panel:a}},td=(e,r=!0)=>{var C,S,k,H,w,L,P,E,Y;let t=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-bg-persona-surface persona-text-persona-primary persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let n=(C=e==null?void 0:e.layout)==null?void 0:C.header,s=((S=e==null?void 0:e.layout)==null?void 0:S.showHeader)!==!1,o=n?Oo(e,n,{showClose:r}):Sr({config:e,showClose:r}),a=h("div","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");a.id="persona-scroll-container",a.setAttribute("data-persona-theme-zone","messages");let i=en(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",u=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(H=(k=e==null?void 0:e.copy)==null?void 0:k.welcomeTitle)!=null?H:"Hello \u{1F44B}";let p=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");p.textContent=(L=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",u.append(c,p);let d=h("div","persona-flex persona-flex-col persona-gap-3"),f=(P=e==null?void 0:e.layout)==null?void 0:P.contentMaxWidth;f&&(d.style.maxWidth=f,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%"),u.setAttribute("data-persona-intro-card",""),((E=e==null?void 0:e.copy)==null?void 0:E.showWelcomeCard)!==!1||(u.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(u,d);let v=$o({config:e}),M=((Y=e==null?void 0:e.layout)==null?void 0:Y.showFooter)!==!1;return s?to(t,o,e):(o.header.style.display="none",to(t,o,e)),t.append(a),M||(v.footer.style.display="none"),t.append(v.footer),{container:t,body:a,messagesWrapper:d,suggestions:v.suggestions,textarea:v.textarea,sendButton:v.sendButton,sendButtonWrapper:v.sendButtonWrapper,micButton:v.micButton,micButtonWrapper:v.micButtonWrapper,composerForm:v.composerForm,statusText:v.statusText,introTitle:c,introSubtitle:p,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:v.footer,attachmentButton:v.attachmentButton,attachmentButtonWrapper:v.attachmentButtonWrapper,attachmentInput:v.attachmentInput,attachmentPreviewsContainer:v.attachmentPreviewsContainer,actionsRow:v.actionsRow,leftActions:v.leftActions,rightActions:v.rightActions}};var qp=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},Up=320,Vp=320,Jp=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Yp=(e,r,t)=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),r&&(n.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,n.remove(),t==null||t())};return e.forEach((i,u)=>{var d;let c=h("img");c.alt=((d=i.alt)==null?void 0:d.trim())||`Attached image ${u+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Up}px`,c.style.maxHeight=`${Vp}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;s+=1,c.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{p=!0}),qp(i.image)?(c.src=i.image,n.appendChild(c)):(p=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},no=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";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="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let 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="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(s),e},rd=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:no};if(r){let s=r(n);if(s!==null)return s}return no()},Gp=(e,r)=>{let t=h("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"),n=r==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let s=h("img");s.src=n,s.alt=r==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=n,t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=r==="user"?"U":"A",t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},nd=(e,r)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return r.format?t.textContent=r.format(n):t.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Kp=(e,r="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(r){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},od=(e,r,t)=>{var g,v,M,C,S,k;let n=(g=r.showCopy)!=null?g:!0,s=(v=r.showUpvote)!=null?v:!0,o=(M=r.showDownvote)!=null?M:!0;if(!n&&!s&&!o){let H=h("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let a=(C=r.visibility)!=null?C:"hover",i=(S=r.align)!=null?S:"right",u=(k=r.layout)!=null?k:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[u],d=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);d.id=`actions-${e.id}`,d.setAttribute("data-actions-for",e.id);let f=(H,w,L)=>{let P=Bt({icon:H,label:w,size:14,className:"persona-message-action-btn"});return P.setAttribute("data-action",L),P};return n&&d.appendChild(f("copy","Copy message","copy")),s&&d.appendChild(f("thumbs-up","Upvote","upvote")),o&&d.appendChild(f("thumbs-down","Downvote","downvote")),d},_o=(e,r,t,n,s,o)=>{var G,O,re,we,oe,ve,We;let a=t!=null?t:{},i=(G=a.layout)!=null?G:"bubble",u=a.avatar,c=a.timestamp,p=(O=u==null?void 0:u.show)!=null?O:!1,d=(re=c==null?void 0:c.show)!=null?re:!1,f=(we=u==null?void 0:u.position)!=null?we:"left",g=(oe=c==null?void 0:c.position)!=null?oe:"below",v=Kp(e.role,i),M=h("div",v.join(" "));M.id=`bubble-${e.id}`,M.setAttribute("data-message-id",e.id),M.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(M.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",M.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(M.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",M.style.color="var(--persona-message-assistant-text, var(--persona-text))");let C=Jp(e),S=(We=(ve=e.content)==null?void 0:ve.trim())!=null?We:"",H=C.length>0&&S===ds,w=document.createElement("div");w.classList.add("persona-message-content");let L=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),P=null;if(H?(P=document.createElement("div"),P.innerHTML=L,P.style.display="none",w.appendChild(P)):w.innerHTML=L,d&&g==="inline"&&e.createdAt){let ge=nd(e,c);ge.classList.add("persona-ml-2","persona-inline"),w.appendChild(ge)}if(C.length>0){let ge=Yp(C,!H&&!!S,()=>{H&&P&&(P.style.display="")});ge?M.appendChild(ge):H&&P&&(P.style.display="")}if(M.appendChild(w),d&&g==="below"&&e.createdAt){let ge=nd(e,c);ge.classList.add("persona-mt-1"),M.appendChild(ge)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let ge=rd("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);ge&&M.appendChild(ge)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let ge=od(e,n,s);M.appendChild(ge)}if(!p||e.role==="system")return M;let Y=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Q=Gp(u,e.role);return f==="right"||f==="left"&&e.role==="user"?Y.append(M,Q):Y.append(Q,M),M.classList.remove("persona-max-w-[85%]"),M.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Y},Xp=(e,r,t,n,s,o)=>{let a=t!=null?t:{};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}):_o(e,r,t,n,s,o)};var ro=new Set,Zp=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),Qp=(e,r)=>{var n,s;let t=(s=(n=e.reasoning)==null?void 0:n.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,r).join(`
16
16
  `):""},sd=(e,r)=>{let t=ro.has(e),n=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t"),o=r.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!n||!s)return;n.setAttribute("aria-expanded",t?"true":"false");let a=n.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=be(t?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=t?"Hide":"Show"}s.style.display=t?"":"none",o&&(o.style.display=t?"none":o.textContent||o.childNodes.length?"":"none")},sa=(e,r)=>{var ve,We,ge,ke,Le,se,K,ue,U,te,fe;let t=e.reasoning,n=h("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(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),!t)return n;let s=(We=(ve=r==null?void 0:r.features)==null?void 0:ve.reasoningDisplay)!=null?We:{},o=s.expandable!==!1,a=o&&ro.has(e.id),i=t.status!=="complete",u=Qp(e,(ge=s.previewMaxLines)!=null?ge:3),c=h("button",o?"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",o&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let p=h("div","persona-flex persona-flex-col persona-text-left"),d=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(ke=r==null?void 0:r.reasoning)!=null?ke:{},v=String((Le=t.startedAt)!=null?Le:Date.now()),M=()=>{let pe=h("span","");return pe.setAttribute("data-tool-elapsed",v),pe.textContent=ls(t),pe},C=(se=g.renderCollapsedSummary)==null?void 0:se.call(g,{message:e,reasoning:t,defaultSummary:f,previewText:u,isActive:i,config:r!=null?r:{},elapsed:ls(t),createElapsedElement:M});typeof C=="string"&&C.trim()?(d.textContent=C,p.appendChild(d)):C instanceof HTMLElement?p.appendChild(C):(d.textContent=f,p.appendChild(d));let S=h("span","persona-text-xs persona-text-persona-primary");S.textContent=Lc(t),p.appendChild(S);let k=(K=s.loadingAnimation)!=null?K:"none",H=g.activeTextTemplate,w=g.completeTextTemplate,L=i?H:w,P=C instanceof HTMLElement,E=(pe,Re,Xe)=>{let j=Xe;for(let W of Re){let ae=h("span","persona-tool-char");ae.style.setProperty("--char-index",String(j)),ae.textContent=W===" "?"\xA0":W,pe.appendChild(ae),j++}return j},Y=(pe,Re)=>{d.textContent="";let Xe=cs(pe,""),j=0;for(let W of Xe){let ae=W.styles.length>0?(()=>{let $=h("span",W.styles.map(q=>`persona-tool-text-${q}`).join(" "));return d.appendChild($),$})():d;if(W.isDuration&&i)ae.appendChild(M());else{let $=W.isDuration?ls(t):W.text;Re?j=E(ae,$,j):ae.appendChild(document.createTextNode($))}}};if(!P&&L)if(S.style.display="none",d.style.display="",i&&k!=="none"){let pe=(ue=g.loadingAnimationDuration)!=null?ue:2e3;d.setAttribute("data-preserve-animation","true"),k==="pulse"?(d.classList.add("persona-tool-loading-pulse"),d.style.setProperty("--persona-tool-anim-duration",`${pe}ms`),Y(L,!1)):(d.classList.add(`persona-tool-loading-${k}`),d.style.setProperty("--persona-tool-anim-duration",`${pe}ms`),k==="shimmer-color"&&(g.loadingAnimationColor&&d.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&d.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),Y(L,!0))}else Y(L,!1);else if(!P&&i&&k!=="none"){d.style.display="";let pe=(U=g.loadingAnimationDuration)!=null?U:2e3;if(d.setAttribute("data-preserve-animation","true"),k==="pulse")d.classList.add("persona-tool-loading-pulse"),d.style.setProperty("--persona-tool-anim-duration",`${pe}ms`);else{d.classList.add(`persona-tool-loading-${k}`),d.style.setProperty("--persona-tool-anim-duration",`${pe}ms`),k==="shimmer-color"&&(g.loadingAnimationColor&&d.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&d.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let Re=d.textContent||f;d.textContent="",E(d,Re,0)}t.status==="complete"&&(d.style.display="none")}else P||(t.status==="complete"?d.style.display="none":d.style.display="");let Q=null;if(o){Q=h("div","persona-flex persona-items-center");let Re=be(a?"chevron-up":"chevron-down",16,"currentColor",2);Re?Q.appendChild(Re):Q.textContent=a?"Hide":"Show";let Xe=h("div","persona-flex persona-items-center persona-ml-auto");Xe.append(Q),c.append(p,Xe)}else c.append(p);let G=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(G.setAttribute("data-persona-collapsed-preview","reasoning"),G.style.display="none",G.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&u){let pe=(fe=(te=r==null?void 0:r.reasoning)==null?void 0:te.renderCollapsedPreview)==null?void 0:fe.call(te,{message:e,reasoning:t,defaultPreview:u,isActive:i,config:r!=null?r:{}});Zp(G,pe)||(G.textContent=u),G.style.display=""}if(!a&&i&&s.activeMinHeight&&(n.style.minHeight=s.activeMinHeight),!o)return n.append(c,G),n;let O=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");O.style.display=a?"":"none";let re=t.chunks.join(""),we=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return we.textContent=re||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(we),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),Q){Q.innerHTML="";let Re=be(a?"chevron-up":"chevron-down",16,"currentColor",2);Re?Q.appendChild(Re):Q.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",G.style.display=a?"none":G.textContent||G.childNodes.length?"":"none"})(),n.append(c,G,O),n};var oo=new Set,eu=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),tu=(e,r)=>{var o;let t=e.toolCall;if(!t)return"";let n=((o=t.chunks)!=null?o:[]).join("").trim();if(n)return n.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-r).join(`
17
17
  `);let s=Kr(t.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,r).join(`
18
- `):""},nu=(e,r)=>{var p,d,f,g,v;let t=e.toolCall,n=(p=r==null?void 0:r.features)==null?void 0:p.toolCallDisplay,s=(d=n==null?void 0:n.collapsedMode)!=null?d:"tool-call",o=tu(e,(f=n==null?void 0:n.previewMaxLines)!=null?f:3),a=t?Ic(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",u=(g=r==null?void 0:r.toolCall)!=null?g:{},c=a;return s==="tool-name"?c=((v=t.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(c=o),i&&u.activeTextTemplate?c=js(t,u.activeTextTemplate,c):!i&&u.completeTextTemplate&&(c=js(t,u.completeTextTemplate,c)),{summary:c,previewText:o,isActive:i}},ad=(e,r,t)=>{var p;let n=oo.has(e),s=(p=t==null?void 0:t.toolCall)!=null?p:{},o=r.querySelector('button[data-expand-header="true"]'),a=r.querySelector(".persona-border-t"),i=r.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let u=o.querySelector(".persona-ml-auto"),c=u==null?void 0:u.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let d=s.toggleTextColor||s.headerTextColor||"currentColor",f=be(n?"chevron-up":"chevron-down",16,d,2);f?c.appendChild(f):c.textContent=n?"Hide":"Show"}a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},aa=(e,r)=>{var re,we,oe,ve,We,ge,ke,Le,se;let t=e.toolCall,n=(re=r==null?void 0:r.toolCall)!=null?re:{},s=h("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(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),n.backgroundColor&&(s.style.backgroundColor=n.backgroundColor),n.borderColor&&(s.style.borderColor=n.borderColor),n.borderWidth&&(s.style.borderWidth=n.borderWidth),n.borderRadius&&(s.style.borderRadius=n.borderRadius),!t)return s;let o=(oe=(we=r==null?void 0:r.features)==null?void 0:we.toolCallDisplay)!=null?oe:{},a=o.expandable!==!1,i=a&&oo.has(e.id),{summary:u,previewText:c,isActive:p}=nu(e,r),d=h("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");d.type="button",a&&(d.setAttribute("aria-expanded",i?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(d.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(d.style.paddingLeft=n.headerPaddingX,d.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(d.style.paddingTop=n.headerPaddingY,d.style.paddingBottom=n.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),g=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(g.style.color=n.headerTextColor);let v=String((ve=t.startedAt)!=null?ve:Date.now()),M=()=>{let K=h("span","");return K.setAttribute("data-tool-elapsed",v),K.textContent=ko(t),K},C=(ge=n.renderCollapsedSummary)==null?void 0:ge.call(n,{message:e,toolCall:t,defaultSummary:u,previewText:c,collapsedMode:(We=o.collapsedMode)!=null?We:"tool-call",isActive:p,config:r!=null?r:{},elapsed:ko(t),createElapsedElement:M});typeof C=="string"&&C.trim()?(g.textContent=C,f.appendChild(g)):C instanceof HTMLElement?f.appendChild(C):(g.textContent=u,f.appendChild(g));let S=(ke=o.loadingAnimation)!=null?ke:"none",k=n.activeTextTemplate,H=n.completeTextTemplate,w=p?k:H,L=C instanceof HTMLElement,P=(K,ue,U)=>{let te=U;for(let fe of ue){let pe=h("span","persona-tool-char");pe.style.setProperty("--char-index",String(te)),pe.textContent=fe===" "?"\xA0":fe,K.appendChild(pe),te++}return te},E=(K,ue)=>{var pe;g.textContent="";let U=((pe=t.name)==null?void 0:pe.trim())||"tool",te=cs(K,U),fe=0;for(let Re of te){let Xe=Re.styles.length>0?(()=>{let j=h("span",Re.styles.map(W=>`persona-tool-text-${W}`).join(" "));return g.appendChild(j),j})():g;if(Re.isDuration&&p)Xe.appendChild(M());else{let j=Re.isDuration?ko(t):Re.text;ue?fe=P(Xe,j,fe):Xe.appendChild(document.createTextNode(j))}}};if(!L)if(p&&S!=="none"){let K=(Le=n.loadingAnimationDuration)!=null?Le:2e3;if(g.setAttribute("data-preserve-animation","true"),S==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),w&&E(w,!1);else if(g.classList.add(`persona-tool-loading-${S}`),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),S==="shimmer-color"&&(n.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),w)E(w,!0);else{let ue=g.textContent||u;g.textContent="",P(g,ue,0)}}else w&&E(w,!1);let Y=null;if(a){Y=h("div","persona-flex persona-items-center");let K=n.toggleTextColor||n.headerTextColor||"currentColor",ue=be(i?"chevron-up":"chevron-down",16,K,2);ue?Y.appendChild(ue):Y.textContent=i?"Hide":"Show";let U=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");U.append(Y),d.append(f,U)}else d.append(f);let Q=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(Q.setAttribute("data-persona-collapsed-preview","tool"),Q.style.display="none",Q.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&c){let K=(se=n.renderCollapsedPreview)==null?void 0:se.call(n,{message:e,toolCall:t,defaultPreview:c,isActive:p,config:r!=null?r:{}});eu(Q,K)||(Q.textContent=c),Q.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(d,Q),s;let G=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(G.style.display=i?"":"none",n.contentBackgroundColor&&(G.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(G.style.color=n.contentTextColor),n.contentPaddingX&&(G.style.paddingLeft=n.contentPaddingX,G.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(G.style.paddingTop=n.contentPaddingY,G.style.paddingBottom=n.contentPaddingY),t.name){let K=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?K.style.color=n.contentTextColor:n.headerTextColor&&(K.style.color=n.headerTextColor),K.textContent=t.name,G.appendChild(K)}if(t.args!==void 0){let K=h("div","persona-space-y-1"),ue=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(ue.style.color=n.labelTextColor),ue.textContent="Arguments";let U=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");U.style.fontSize="0.75rem",U.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(U.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(U.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(U.style.color=n.codeBlockTextColor),U.textContent=Kr(t.args),K.append(ue,U),G.appendChild(K)}if(t.chunks&&t.chunks.length){let K=h("div","persona-space-y-1"),ue=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(ue.style.color=n.labelTextColor),ue.textContent="Activity";let U=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");U.style.fontSize="0.75rem",U.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(U.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(U.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(U.style.color=n.codeBlockTextColor),U.textContent=t.chunks.join(""),K.append(ue,U),G.appendChild(K)}if(t.status==="complete"&&t.result!==void 0){let K=h("div","persona-space-y-1"),ue=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(ue.style.color=n.labelTextColor),ue.textContent="Result";let U=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");U.style.fontSize="0.75rem",U.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(U.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(U.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(U.style.color=n.codeBlockTextColor),U.textContent=Kr(t.result),K.append(ue,U),G.appendChild(K)}if(t.status==="complete"&&typeof t.duration=="number"){let K=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(K.style.color=n.contentTextColor),K.textContent=`Duration: ${t.duration}ms`,G.appendChild(K)}return(()=>{if(d.setAttribute("aria-expanded",i?"true":"false"),Y){Y.innerHTML="";let K=n.toggleTextColor||n.headerTextColor||"currentColor",ue=be(i?"chevron-up":"chevron-down",16,K,2);ue?Y.appendChild(ue):Y.textContent=i?"Hide":"Show"}G.style.display=i?"":"none",Q.style.display=i?"none":Q.textContent||Q.childNodes.length?"":"none"})(),s.append(d,Q,G),s};var ia=(e,r)=>{var M,C,S,k,H,w,L,P,E,Y,Q,G;let t=e.approval,n=(r==null?void 0:r.approval)!==!1?r==null?void 0:r.approval:void 0,s=(t==null?void 0:t.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(M=n==null?void 0:n.backgroundColor)!=null?M:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(C=n==null?void 0:n.borderColor)!=null?C:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let u=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(S=n==null?void 0:n.titleColor)!=null?S:"currentColor",p=be(u,20,c,2);p&&i.appendChild(p);let d=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),g=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(g.style.color=n.titleColor),g.textContent=(k=n==null?void 0:n.title)!=null?k:"Approval Required",f.appendChild(g),!s){let O=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");O.setAttribute("data-approval-status",t.status),t.status==="approved"?(O.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",O.style.color="var(--persona-palette-colors-success-700, #15803d)",O.textContent="Approved"):t.status==="denied"?(O.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",O.style.color="var(--persona-palette-colors-error-700, #b91c1c)",O.textContent="Denied"):t.status==="timeout"&&(O.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",O.style.color="var(--persona-palette-colors-warning-700, #b45309)",O.textContent="Timeout"),f.appendChild(O)}d.appendChild(f);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(v.style.color=n.descriptionColor),v.textContent=t.description,d.appendChild(v),t.parameters){let O=h("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");n!=null&&n.parameterBackgroundColor&&(O.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(O.style.color=n.parameterTextColor),O.style.fontSize="0.75rem",O.style.lineHeight="1rem",O.textContent=Kr(t.parameters),d.appendChild(O)}if(s){let O=h("div","persona-flex persona-gap-2 persona-mt-2");O.setAttribute("data-approval-buttons","true");let re=h("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");re.type="button",re.style.backgroundColor=(H=n==null?void 0:n.approveButtonColor)!=null?H:"var(--persona-approval-approve-bg, #22c55e)",re.style.color=(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",re.setAttribute("data-approval-action","approve");let we=be("shield-check",14,(L=n==null?void 0:n.approveButtonTextColor)!=null?L:"#ffffff",2);we&&(we.style.marginRight="4px",re.appendChild(we));let oe=document.createTextNode((P=n==null?void 0:n.approveLabel)!=null?P:"Approve");re.appendChild(oe);let ve=h("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");ve.type="button",ve.style.backgroundColor=(E=n==null?void 0:n.denyButtonColor)!=null?E:"transparent",ve.style.color=(Y=n==null?void 0:n.denyButtonTextColor)!=null?Y:"var(--persona-feedback-error, #dc2626)",ve.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,ve.setAttribute("data-approval-action","deny");let We=be("shield-x",14,(Q=n==null?void 0:n.denyButtonTextColor)!=null?Q:"var(--persona-feedback-error, #dc2626)",2);We&&(We.style.marginRight="4px",ve.appendChild(We));let ge=document.createTextNode((G=n==null?void 0:n.denyLabel)!=null?G:"Deny");ve.appendChild(ge),O.append(re,ve),d.appendChild(O)}return a.append(i,d),o.appendChild(a),o};var id=e=>{let r=[];return{buttons:r,render:(n,s,o,a,i)=>{if(e.innerHTML="",r.length=0,!n||!n.length||(a!=null?a:s?s.getMessages():[]).some(g=>g.role==="user"))return;let p=document.createDocumentFragment(),d=s?s.isStreaming():!1,f=g=>{switch(g){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'}};n.forEach(g=>{let v=h("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=g,v.disabled=d,i!=null&&i.fontFamily&&(v.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(g))}),p.appendChild(v),r.push(v)}),e.appendChild(p)}}};var jo=class{constructor(r=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=r,this.buffer=new Array(r),this.store=t}push(r){var t;this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(r.type),(t=this.store)==null||t.put(r)}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 r=await this.store.getAll();if(r.length===0)return 0;let t=r.length>this.maxSize?r.slice(r.length-this.maxSize):r;for(let n of t)this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(n.type);return this.totalCaptured=r.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(r){let t=this.getAll();return r>=t.length?t:t.slice(t.length-r)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var r;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.clear()}destroy(){var r;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var zo=class{constructor(r="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=r,this.storeName=t}open(){return new Promise((r,t)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}put(r){!this.db||this.isDestroyed||(this.pendingWrites.push(r),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(r){if(!(!this.db||this.isDestroyed||r.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}getAll(){return new Promise((r,t)=>{if(!this.db){r([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{r(a.result)},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}getCount(){return new Promise((r,t)=>{if(!this.db){r(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{r(o.result)},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}clear(){return new Promise((r,t)=>{if(!this.db){r();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{r()},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((r,t)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let r=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}};function so(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var ru={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)"}},ou={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},su=["flowName","stepName","reasoningText","text","name","tool","toolName"],au=100;function iu(e,r){let t={...ru,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return ou}function lu(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function cu(e){let r=new Date(e),t=String(r.getHours()).padStart(2,"0"),n=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0"),o=String(r.getMilliseconds()).padStart(3,"0");return`${t}:${n}:${s}.${o}`}function du(e,r){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let n of r){let s=n.split("."),o=t;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function pu(e){var r;return(r=navigator.clipboard)!=null&&r.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function uu(e){let r;try{r=JSON.parse(e.payload)}catch{r=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:r},null,2)}function mu(e,r,t){let n,s;try{s=JSON.parse(e.payload),n=JSON.stringify(s,null,2)}catch{s=e.payload,n=e.payload}let o=r.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("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]"),u=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return u.textContent=n,i.appendChild(u),i}}function la(e,r,t,n,s,o,a,i){var f;let u=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");so(c,(f=n.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:r,config:i,defaultRenderer:()=>d(),isExpanded:u,onToggleExpand:()=>o(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(d()),c;function d(){var re,we;let g=h("div",""),v=h("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 M=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=be(u?"chevron-down":"chevron-right","14px","currentColor",2);C&&M.appendChild(C);let S=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(re=n.timestampFormat)!=null?re:"relative";S.textContent=k==="relative"?lu(e.timestamp,t):cu(e.timestamp);let H=null;n.showSequenceNumbers!==!1&&(H=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),H.textContent=String(r+1));let w=iu(e.type,n.badgeColors),L=h("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");L.style.backgroundColor=w.bg,L.style.color=w.text,L.style.borderColor=w.text+"50",L.textContent=e.type;let P=(we=n.descriptionFields)!=null?we:su,E=du(e.payload,P),Y=null;E&&(Y=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),Y.textContent=E);let Q=h("div","persona-flex-1 persona-min-w-0"),G=h("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=be("clipboard","12px","currentColor",1.5);return O&&G.appendChild(O),G.addEventListener("click",async oe=>{oe.stopPropagation(),await pu(uu(e)),G.innerHTML="";let ve=be("check","12px","currentColor",1.5);ve&&G.appendChild(ve),setTimeout(()=>{G.innerHTML="";let We=be("clipboard","12px","currentColor",1.5);We&&G.appendChild(We)},1500)}),v.appendChild(M),v.appendChild(S),H&&v.appendChild(H),v.appendChild(L),Y&&v.appendChild(Y),v.appendChild(Q),v.appendChild(G),g.appendChild(v),u&&g.appendChild(mu(e,a,i)),g}}function ld(e){var g,v,M,C,S;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(g=s==null?void 0:s.features)==null?void 0:g.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,u=(v=a==null?void 0:a.iconName)!=null?v:"arrow-down",c=(M=a==null?void 0:a.label)!=null?M:"",p=(S=(C=s==null?void 0:s.features)==null?void 0:C.eventStream)!=null?S:{},d=o.find(k=>k.renderEventStreamView);if(d!=null&&d.renderEventStreamView&&s){let k=d.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>f().element,onClose:n});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return f();function f(){let k=p.classNames,H=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");so(H,k==null?void 0:k.panel);let w=[],L="",P="",E=null,Y=[],Q={},G=0,O=xs(),re=0,we=0,oe=!1,ve=null,We=!1,ge=0,ke=new Set,Le=new Map,se="",K="",ue=null,U,te,fe,pe,Re;function Xe(){let ce=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),Se=h("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");so(Se,k==null?void 0:k.headerBar);let Oe=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Oe.textContent="Events",U=h("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"),U.textContent="0";let Ct=h("div","persona-flex-1");te=h("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 jt=h("option","");jt.value="",jt.textContent="All events",te.appendChild(jt),fe=h("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"),fe.type="button",fe.title="Copy All";let zt=be("clipboard-copy","12px","currentColor",1.5);zt&&fe.appendChild(zt);let yt=h("span","persona-text-xs");yt.textContent="Copy All",fe.appendChild(yt),Se.appendChild(Oe),Se.appendChild(U),Se.appendChild(Ct),Se.appendChild(te),Se.appendChild(fe);let Ze=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");so(Ze,k==null?void 0:k.searchBar);let bt=be("search","14px","var(--persona-muted, #9ca3af)",1.5),De=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");bt&&De.appendChild(bt),pe=h("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"),so(pe,k==null?void 0:k.searchInput),pe.type="text",pe.placeholder="Search event payloads...",Re=h("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"),Re.type="button",Re.style.display="none";let qt=be("x","12px","currentColor",2);return qt&&Re.appendChild(qt),Ze.appendChild(De),Ze.appendChild(pe),Ze.appendChild(Re),ce.appendChild(Se),ce.appendChild(Ze),ce}let j,W=o.find(ce=>ce.renderEventStreamToolbar);if(W!=null&&W.renderEventStreamToolbar&&s){let ce=W.renderEventStreamToolbar({config:s,defaultRenderer:()=>Xe(),eventCount:r.getSize(),filteredCount:0,onFilterChange:Se=>{L=Se,Xt(),Ne()},onSearchChange:Se=>{P=Se,Xt(),Ne()}});j=ce!=null?ce:Xe()}else j=Xe();let ae=h("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");ae.style.display="none";let $=h("div","persona-flex-1 persona-min-h-0 persona-relative"),q=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");q.style.height="100%";let de=h("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");so(de,k==null?void 0:k.scrollIndicator),de.style.display="none",de.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let _e=be(u,"14px","currentColor",2);_e&&de.appendChild(_e);let ee=h("span","");ee.textContent=c,de.appendChild(ee);let le=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");le.style.display="none",$.appendChild(q),$.appendChild(le),$.appendChild(de),H.setAttribute("tabindex","0"),H.appendChild(j),H.appendChild(ae),H.appendChild($);function Lt(){let ce=r.getAll(),Se={};for(let yt of ce)Se[yt.type]=(Se[yt.type]||0)+1;let Oe=Object.keys(Se).sort(),Ct=Oe.length!==Y.length||!Oe.every((yt,Ze)=>yt===Y[Ze]),jt=!Ct&&Oe.some(yt=>Se[yt]!==Q[yt]),dt=ce.length!==Object.values(Q).reduce((yt,Ze)=>yt+Ze,0);if(!Ct&&!jt&&!dt||(Y=Oe,Q=Se,!te))return;let zt=te.value;if(te.options[0].textContent="All events",Ct){for(;te.options.length>1;)te.remove(1);for(let yt of Oe){let Ze=h("option","");Ze.value=yt,Ze.textContent=`${yt} (${Se[yt]||0})`,te.appendChild(Ze)}zt&&Oe.includes(zt)?te.value=zt:zt&&(te.value="",L="")}else for(let yt=1;yt<te.options.length;yt++){let Ze=te.options[yt];Ze.textContent=`${Ze.value} (${Se[Ze.value]||0})`}}function ct(){let ce=r.getAll();if(L&&(ce=ce.filter(Se=>Se.type===L)),P){let Se=P.toLowerCase();ce=ce.filter(Oe=>Oe.type.toLowerCase().includes(Se)||Oe.payload.toLowerCase().includes(Se))}return ce}function Dt(){return L!==""||P!==""}function Xt(){G=0,re=0,O.resume(),de.style.display="none"}function je(ce){ke.has(ce)?ke.delete(ce):ke.add(ce),ue=ce;let Se=q.scrollTop,Oe=O.isFollowing();We=!0,O.pause(),Ne(),q.scrollTop=Se,Oe&&O.resume(),We=!1}function me(){return Do(q,50)}function Ne(){we=Date.now(),oe=!1,Lt();let ce=r.getEvictedCount();ce>0?(ae.textContent=`${ce.toLocaleString()} older events truncated`,ae.style.display=""):ae.style.display="none",w=ct();let Se=w.length,Oe=r.getSize()>0;U&&(U.textContent=String(r.getSize())),Se===0&&Oe&&Dt()?(le.textContent=P?`No events matching '${P}'`:"No events matching filter",le.style.display="",q.style.display="none"):(le.style.display="none",q.style.display=""),fe&&(fe.title=Dt()?`Copy Filtered (${Se})`:"Copy All"),i&&!O.isFollowing()&&Se>G&&(re+=Se-G,ee.textContent=c?`${c}${re>0?` (${re})`:""}`:"",de.style.display=""),G=Se;let Ct=r.getAll(),jt=Ct.length>0?Ct[0].timestamp:0,dt=new Set(w.map(Ze=>Ze.id));for(let Ze of ke)dt.has(Ze)||ke.delete(Ze);let zt=L!==se||P!==K,yt=Le.size===0&&w.length>0;if(zt||yt||w.length===0){q.innerHTML="",Le.clear();let Ze=document.createDocumentFragment();for(let bt=0;bt<w.length;bt++){let De=la(w[bt],bt,jt,p,ke,je,o,s);Le.set(w[bt].id,De),Ze.appendChild(De)}q.appendChild(Ze),se=L,K=P,ue=null}else{if(ue!==null){let bt=Le.get(ue);if(bt&&bt.parentNode===q){let De=w.findIndex(qt=>qt.id===ue);if(De>=0){let qt=la(w[De],De,jt,p,ke,je,o,s);q.insertBefore(qt,bt),bt.remove(),Le.set(ue,qt)}}ue=null}let Ze=new Set(w.map(bt=>bt.id));for(let[bt,De]of Le)Ze.has(bt)||(De.remove(),Le.delete(bt));for(let bt=0;bt<w.length;bt++){let De=w[bt];if(!Le.has(De.id)){let qt=la(De,bt,jt,p,ke,je,o,s);Le.set(De.id,qt),q.appendChild(qt)}}}O.isFollowing()&&(q.scrollTop=q.scrollHeight)}function Pt(){if(Date.now()-we>=au){ve!==null&&(cancelAnimationFrame(ve),ve=null),Ne();return}oe||(oe=!0,ve=requestAnimationFrame(()=>{ve=null,Ne()}))}let Wt=(ce,Se)=>{if(!fe)return;fe.innerHTML="";let Oe=be(ce,"12px","currentColor",1.5);Oe&&fe.appendChild(Oe);let Ct=h("span","persona-text-xs");Ct.textContent="Copy All",fe.appendChild(Ct),setTimeout(()=>{fe.innerHTML="";let jt=be("clipboard-copy","12px","currentColor",1.5);jt&&fe.appendChild(jt);let dt=h("span","persona-text-xs");dt.textContent="Copy All",fe.appendChild(dt),fe.disabled=!1},Se)},ot=async()=>{if(fe){fe.disabled=!0;try{let ce;Dt()?ce=w:t?(ce=await t(),ce.length===0&&(ce=r.getAll())):ce=r.getAll();let Se=ce.map(Oe=>{try{return JSON.parse(Oe.payload)}catch{return Oe.payload}});await navigator.clipboard.writeText(JSON.stringify(Se,null,2)),Wt("check",1500)}catch{Wt("x",1500)}}},st=()=>{te&&(L=te.value,Xt(),Ne())},nn=()=>{!pe||!Re||(Re.style.display=pe.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{P=pe.value,Xt(),Ne()},150))},tn=()=>{!pe||!Re||(pe.value="",P="",Re.style.display="none",E&&clearTimeout(E),Xt(),Ne())},rn=()=>{if(We)return;let ce=q.scrollTop,{action:Se,nextLastScrollTop:Oe}=vs({following:O.isFollowing(),currentScrollTop:ce,lastScrollTop:ge,nearBottom:me(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ge=Oe,Se==="resume"?(O.resume(),re=0,de.style.display="none"):Se==="pause"&&(O.pause(),i&&(ee.textContent=c,de.style.display=""))},z=ce=>{let Se=Cs({following:O.isFollowing(),deltaY:ce.deltaY,nearBottom:me(),resumeWhenNearBottom:!0});Se==="pause"?(O.pause(),i&&(ee.textContent=c,de.style.display="")):Se==="resume"&&(O.resume(),re=0,de.style.display="none")},He=()=>{i&&(q.scrollTop=q.scrollHeight,O.resume(),re=0,de.style.display="none")},ye=ce=>{let Se=ce.target;if(!Se||Se.closest("button"))return;let Oe=Se.closest("[data-event-id]");if(!Oe)return;let Ct=Oe.getAttribute("data-event-id");Ct&&je(Ct)},ht=ce=>{if((ce.metaKey||ce.ctrlKey)&&ce.key==="f"){ce.preventDefault(),pe==null||pe.focus(),pe==null||pe.select();return}ce.key==="Escape"&&(pe&&document.activeElement===pe?(tn(),pe.blur(),H.focus()):n&&n())};fe&&fe.addEventListener("click",ot),te&&te.addEventListener("change",st),pe&&pe.addEventListener("input",nn),Re&&Re.addEventListener("click",tn),q.addEventListener("scroll",rn),q.addEventListener("wheel",z,{passive:!0}),q.addEventListener("click",ye),de.addEventListener("click",He),H.addEventListener("keydown",ht);function $e(){E&&clearTimeout(E),ve!==null&&(cancelAnimationFrame(ve),ve=null),oe=!1,Le.clear(),fe&&fe.removeEventListener("click",ot),te&&te.removeEventListener("change",st),pe&&pe.removeEventListener("input",nn),Re&&Re.removeEventListener("click",tn),q.removeEventListener("scroll",rn),q.removeEventListener("wheel",z),q.removeEventListener("click",ye),de.removeEventListener("click",He),H.removeEventListener("keydown",ht)}return{element:H,update:Pt,destroy:$e}}}function cd(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=typeof e.artifactId=="string"?e.artifactId:"",s=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 ${t} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=t;let d=document.createElement("div");if(d.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",d.style.color="var(--persona-muted, #9ca3af)",s==="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",d.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,d.appendChild(g)}else d.textContent=a;if(c.append(p,d),i.append(u,c),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${t}`,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",n),i.append(f)}return i}var dd=(e,r)=>{var n,s,o;let t=(o=(s=(n=r==null?void 0:r.config)==null?void 0:n.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",u=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=t({artifact:{artifactId:i,title:a,artifactType:c,status:u},config:r.config,defaultRenderer:()=>cd(e,r)});if(p)return p}return cd(e,r)};var ca=class{constructor(){this.components=new Map}register(r,t){this.components.has(r)&&console.warn(`[ComponentRegistry] Component "${r}" is already registered. Overwriting.`),this.components.set(r,t)}unregister(r){this.components.delete(r)}get(r){return this.components.get(r)}has(r){return this.components.has(r)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(r){Object.entries(r).forEach(([t,n])=>{this.register(t,n)})}},Ar=new ca;Ar.register("PersonaArtifactCard",dd);function gu(e){var s;let r=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let n=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),r.appendChild(t),r.appendChild(n),r}function pd(e,r){var fe,pe,Re,Xe;let t=(pe=(fe=e.features)==null?void 0:fe.artifacts)==null?void 0:pe.layout,s=((Re=t==null?void 0:t.toolbarPreset)!=null?Re:"default")==="document",o=(Xe=t==null?void 0:t.panePadding)==null?void 0:Xe.trim(),a=e.markdown?Gr(e.markdown):null,i=To(e.sanitize),u=j=>{let W=a?a(j):Eo(j);return i?i(W):W},c=typeof document!="undefined"?h("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"),d.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};c&&c.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let d=h("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");d.setAttribute("data-persona-theme-zone","artifact-pane"),s&&d.classList.add("persona-artifact-pane-document");let f=h("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"),s&&f.classList.add("persona-artifact-toolbar-document");let g=h("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let v=h("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 j;p(),(j=r.onDismiss)==null||j.call(r)});let M="rendered",C=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),S=s?Bt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Bt({icon:"eye",label:"Rendered view"}),k=s?Bt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Bt({icon:"code-2",label:"Source"}),H=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),w=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,L=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,P=t==null?void 0:t.documentToolbarCopyMenuItems,E=!!(L&&P&&P.length>0),Y=null,Q,G=null,O=null;if(s&&(w||L)&&!E){if(Q=w?Ss({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let j=be("chevron-down",14,"currentColor",2);j&&Q.appendChild(j)}}else s&&E?(Y=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Q=w?Ss({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),G=Bt({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"}}),Y.append(Q,G)):s?Q=Bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):Q=Bt({icon:"copy",label:"Copy"});let re=s?Bt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Bt({icon:"refresh-cw",label:"Refresh"}),we=s?Bt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Bt({icon:"x",label:"Close"}),oe=()=>{var q,de,_e;let j=(q=se.find(ee=>ee.id===K))!=null?q:se[se.length-1],W=(de=j==null?void 0:j.id)!=null?de:null,ae=(j==null?void 0:j.artifactType)==="markdown"&&(_e=j.markdown)!=null?_e:"",$=j?JSON.stringify({component:j.component,props:j.props},null,2):"";return{markdown:ae,jsonPayload:$,id:W}},ve=async()=>{var q;let{markdown:j,jsonPayload:W}=oe(),ae=(q=se.find(de=>de.id===K))!=null?q:se[se.length-1],$=(ae==null?void 0:ae.artifactType)==="markdown"?j:ae?W:"";try{await navigator.clipboard.writeText($)}catch{}};if(Q.addEventListener("click",async()=>{let j=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(j&&E){let{markdown:W,jsonPayload:ae,id:$}=oe();try{await j({actionId:"primary",artifactId:$,markdown:W,jsonPayload:ae})}catch{}return}await ve()}),G&&(P!=null&&P.length)){let j=()=>{var ae;return(ae=d.closest("[data-persona-root]"))!=null?ae:document.body},W=()=>{O=_r({items:P.map(ae=>({id:ae.id,label:ae.label})),onSelect:async ae=>{let{markdown:$,jsonPayload:q,id:de}=oe(),_e=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{_e?await _e({actionId:ae,artifactId:de,markdown:$,jsonPayload:q}):ae==="markdown"||ae==="md"?await navigator.clipboard.writeText($):ae==="json"||ae==="source"?await navigator.clipboard.writeText(q):await navigator.clipboard.writeText($||q)}catch{}},anchor:Y!=null?Y:G,position:"bottom-right",portal:j()})};d.isConnected?W():requestAnimationFrame(W),G.addEventListener("click",ae=>{ae.stopPropagation(),O==null||O.toggle()})}re.addEventListener("click",async()=>{var j;try{await((j=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:j.call(t))}catch{}U()}),we.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let We=()=>{s&&(S.setAttribute("aria-pressed",M==="rendered"?"true":"false"),k.setAttribute("aria-pressed",M==="source"?"true":"false"))};S.addEventListener("click",()=>{M="rendered",We(),U()}),k.addEventListener("click",()=>{M="source",We(),U()});let ge=h("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");s?(f.replaceChildren(),C.append(S,k),Y?H.append(Y,re,we):H.append(Q,re,we),f.append(C,ge,H),We()):(f.appendChild(g),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let ke=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Le=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(ke.style.paddingLeft=o,ke.style.paddingRight=o,Le.style.padding=o),d.appendChild(f),d.appendChild(ke),d.appendChild(Le);let se=[],K=null,ue=!1,U=()=>{var $,q,de,_e;let j=s&&se.length<=1;ke.classList.toggle("persona-hidden",j),ke.replaceChildren();for(let ee of se){let le=h("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");le.type="button",le.textContent=ee.title||ee.id.slice(0,8),ee.id===K&&le.classList.add("persona-bg-persona-container","persona-border-persona-border"),le.addEventListener("click",()=>r.onSelect(ee.id)),ke.appendChild(le)}Le.replaceChildren();let W=K&&se.find(ee=>ee.id===K)||se[se.length-1];if(!W)return;if(s){let ee=W.artifactType==="markdown"?"MD":($=W.component)!=null?$:"Component",Lt=(W.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ge.textContent=`${Lt} \xB7 ${ee}`}else g.textContent="Artifacts";if(W.artifactType==="markdown"){if(s&&M==="source"){let le=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");le.textContent=(q=W.markdown)!=null?q:"",Le.appendChild(le);return}let ee=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ee.innerHTML=u((de=W.markdown)!=null?de:""),Le.appendChild(ee);return}let ae=W.component?Ar.get(W.component):void 0;if(ae){let le={message:{id:W.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Lt=ae((_e=W.props)!=null?_e:{},le);if(Lt){Le.appendChild(Lt);return}}catch{}}Le.appendChild(gu(W))},te=()=>{var W;let j=se.length>0;if(d.classList.toggle("persona-hidden",!j),c){let ae=typeof d.closest=="function"?d.closest("[data-persona-root]"):null,q=((W=ae==null?void 0:ae.classList.contains("persona-artifact-narrow-host"))!=null?W:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;j&&q&&ue?(c.classList.remove("persona-hidden"),d.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open"))}};return{element:d,backdrop:c,update(j){var W,ae,$;se=j.artifacts,K=($=(ae=j.selectedId)!=null?ae:(W=j.artifacts[j.artifacts.length-1])==null?void 0:W.id)!=null?$:null,se.length>0&&(ue=!0),U(),te()},setMobileOpen(j){ue=j,!j&&c?(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open")):te()}}}function On(e){var r,t;return((t=(r=e==null?void 0:e.features)==null?void 0:r.artifacts)==null?void 0:t.enabled)===!0}function ud(e,r){var o,a,i,u;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"),!On(r))return;let t=(a=(o=r.features)==null?void 0:o.artifacts)==null?void 0:a.layout,n=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(u=t==null?void 0:t.paneBorderLeft)==null?void 0:u.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function fu(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 Es(e,r){var u,c,p,d,f,g,v,M,C,S;if(!On(r)){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"),fu(e),ud(e,r);return}let t=(c=(u=r.features)==null?void 0:u.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(p=t==null?void 0:t.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(d=t==null?void 0:t.paneWidth)!=null?d:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let n=(g=t==null?void 0:t.paneBackground)==null?void 0:g.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(M=t==null?void 0:t.documentToolbarIconColor)==null?void 0:M.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(C=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:C.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(S=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:S.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),ud(e,r)}var md=["panel","seamless"];function Ts(e,r){var i,u,c,p,d,f;for(let g of md)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"),!On(r))return;let t=(u=(i=r.features)==null?void 0:i.artifacts)==null?void 0:u.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=md.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=t==null?void 0:t.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(d=t==null?void 0:t.paneShadow)==null?void 0:d.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let g=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function gd(e,r){var t,n,s;return!r||!On(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function hu(e,r){if(!(e!=null&&e.trim()))return r;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):r}function yu(e){if(!(e!=null&&e.trim()))return null;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):null}function bu(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function xu(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function fd(e,r){var a;let n=(a=(r.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(n);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(n);return o?Number(o[1]):8}function hd(e,r,t,n,s,o){let a=hu(s,200),i=xu(r,t,n,200);i=Math.max(a,i);let u=yu(o);return u!==null&&(i=Math.min(i,u)),bu(e,a,i)}var yd={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"}},da=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,M,C;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(M=yd[a])!=null?M:yd.init;o.classList.add("persona-form-card","persona-space-y-4");let u=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,u.appendChild(c),i.description){let S=h("p","persona-text-sm persona-text-persona-muted");S.textContent=i.description,u.appendChild(S)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(S=>{var P,E;let k=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${r.id}-${a}-${S.name}`;let H=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=S.label,k.appendChild(H);let w=(P=S.type)!=null?P:"text",L;w==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=w),L.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",L.id=`${r.id}-${a}-${S.name}`,L.name=S.name,L.placeholder=(E=S.placeholder)!=null?E:"",S.required&&(L.required=!0),k.appendChild(L),p.appendChild(k)});let d=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=h("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=(C=i.submitLabel)!=null?C:"Submit",d.appendChild(f),d.appendChild(g),p.appendChild(d),o.replaceChildren(u,p),p.addEventListener("submit",async S=>{var L,P;S.preventDefault();let k=(L=t.formEndpoint)!=null?L:"/form",H=new FormData(p),w={};H.forEach((E,Y)=>{w[Y]=E}),w.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let E=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let Y=await E.json();f.textContent=(P=Y.message)!=null?P:"Thanks! We'll be in touch soon.",Y.success&&Y.nextPrompt&&await n.sendMessage(String(Y.nextPrompt))}catch(E){f.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var pa=class{constructor(){this.plugins=new Map}register(r){var t;this.plugins.has(r.id)&&console.warn(`Plugin "${r.id}" is already registered. Overwriting.`),this.plugins.set(r.id,r),(t=r.onRegister)==null||t.call(r)}unregister(r){var n;let t=this.plugins.get(r);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(r))}getAll(){return Array.from(this.plugins.values()).sort((r,t)=>{var n,s;return((n=t.priority)!=null?n:0)-((s=r.priority)!=null?s:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let n=new Set(r.map(o=>o.id));return[...t.filter(o=>!n.has(o.id)),...r].sort((o,a)=>{var i,u;return((i=a.priority)!=null?i:0)-((u=o.priority)!=null?u:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},Ms=new pa;var bd=()=>{let e=new Map,r=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:r,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var vu=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},Cu=e=>{let r=e.trim(),t=r.indexOf("{");if(t===-1)return null;let n=0;for(let s=t;s<r.length;s+=1){let o=r[s];if(o==="{"&&(n+=1),o==="}"&&(n-=1,n===0))return r.slice(t,s+1)}return null},ks=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=vu(e),t=Cu(r);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||!n.action)return null;let{action:s,...o}=n;return{type:String(s),payload:o,raw:n}}catch{return null}},ua=e=>typeof e=="string"?e:e==null?"":String(e),ao={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ua(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=ua(t.element);if(n&&((s=r.document)!=null&&s.querySelector)){let o=r.document.querySelector(n);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:ua(t.text)}}},xd=e=>Array.isArray(e)?e.map(r=>String(r)):[],Ls=e=>{let r=new Set(xd(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(xd(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let o=Array.from(r);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||r.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.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:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let u={action:i,message:o.message};e.emit("action:detected",u);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",u)},d=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!d)continue;if(d.handled){let f=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:f,resubmit:d.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:t}};var wu=e=>{if(!e)return null;try{return JSON.parse(e)}catch(r){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",r),null}},Su=e=>e.map(r=>({...r,streaming:!1})),ma=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?wu(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?Su(t.messages):void 0};n.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=r();if(t)try{t.removeItem(e)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};import{parse as Au,STR as Eu,OBJ as Tu}from"partial-json";function Mu(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function ku(e,r){if(!Mu(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:r}}function ga(){let e=null,r=0;return{getExtractedDirective:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e;try{let s=Au(t,Eu|Tu),o=ku(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Lu(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function fa(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=Ar.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:n,config:t,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Iu(){let e=ga();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ha(e){if(!e.rawContent)return!1;try{let r=JSON.parse(e.rawContent);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function ya(e){if(!e.rawContent)return null;try{let r=JSON.parse(e.rawContent);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string")return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e.rawContent}}catch{}return null}var Pu=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ba(e){let{onSubmit:r,onDismiss:t,title:n="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:u=!0,ratingLabels:c=Pu}=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 d=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=n,g.appendChild(v);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=s,g.appendChild(M),f.appendChild(g);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-csat",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Satisfaction rating from 1 to 5");let S=[];for(let P=1;P<=5;P++){let E=document.createElement("button");E.type="button",E.className="persona-feedback-rating-btn persona-feedback-star-btn",E.setAttribute("role","radio"),E.setAttribute("aria-checked","false"),E.setAttribute("aria-label",`${P} star${P>1?"s":""}: ${c[P-1]}`),E.title=c[P-1],E.dataset.rating=String(P),E.innerHTML=`
18
+ `):""},nu=(e,r)=>{var p,d,f,g,v;let t=e.toolCall,n=(p=r==null?void 0:r.features)==null?void 0:p.toolCallDisplay,s=(d=n==null?void 0:n.collapsedMode)!=null?d:"tool-call",o=tu(e,(f=n==null?void 0:n.previewMaxLines)!=null?f:3),a=t?Ic(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",u=(g=r==null?void 0:r.toolCall)!=null?g:{},c=a;return s==="tool-name"?c=((v=t.name)==null?void 0:v.trim())||a:s==="tool-preview"&&o&&(c=o),i&&u.activeTextTemplate?c=js(t,u.activeTextTemplate,c):!i&&u.completeTextTemplate&&(c=js(t,u.completeTextTemplate,c)),{summary:c,previewText:o,isActive:i}},ad=(e,r,t)=>{var p;let n=oo.has(e),s=(p=t==null?void 0:t.toolCall)!=null?p:{},o=r.querySelector('button[data-expand-header="true"]'),a=r.querySelector(".persona-border-t"),i=r.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let u=o.querySelector(".persona-ml-auto"),c=u==null?void 0:u.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let d=s.toggleTextColor||s.headerTextColor||"currentColor",f=be(n?"chevron-up":"chevron-down",16,d,2);f?c.appendChild(f):c.textContent=n?"Hide":"Show"}a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},aa=(e,r)=>{var re,we,oe,ve,We,ge,ke,Le,se;let t=e.toolCall,n=(re=r==null?void 0:r.toolCall)!=null?re:{},s=h("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(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),n.backgroundColor&&(s.style.backgroundColor=n.backgroundColor),n.borderColor&&(s.style.borderColor=n.borderColor),n.borderWidth&&(s.style.borderWidth=n.borderWidth),n.borderRadius&&(s.style.borderRadius=n.borderRadius),!t)return s;let o=(oe=(we=r==null?void 0:r.features)==null?void 0:we.toolCallDisplay)!=null?oe:{},a=o.expandable!==!1,i=a&&oo.has(e.id),{summary:u,previewText:c,isActive:p}=nu(e,r),d=h("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");d.type="button",a&&(d.setAttribute("aria-expanded",i?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(d.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(d.style.paddingLeft=n.headerPaddingX,d.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(d.style.paddingTop=n.headerPaddingY,d.style.paddingBottom=n.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),g=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(g.style.color=n.headerTextColor);let v=String((ve=t.startedAt)!=null?ve:Date.now()),M=()=>{let K=h("span","");return K.setAttribute("data-tool-elapsed",v),K.textContent=ko(t),K},C=(ge=n.renderCollapsedSummary)==null?void 0:ge.call(n,{message:e,toolCall:t,defaultSummary:u,previewText:c,collapsedMode:(We=o.collapsedMode)!=null?We:"tool-call",isActive:p,config:r!=null?r:{},elapsed:ko(t),createElapsedElement:M});typeof C=="string"&&C.trim()?(g.textContent=C,f.appendChild(g)):C instanceof HTMLElement?f.appendChild(C):(g.textContent=u,f.appendChild(g));let S=(ke=o.loadingAnimation)!=null?ke:"none",k=n.activeTextTemplate,H=n.completeTextTemplate,w=p?k:H,L=C instanceof HTMLElement,P=(K,ue,U)=>{let te=U;for(let fe of ue){let pe=h("span","persona-tool-char");pe.style.setProperty("--char-index",String(te)),pe.textContent=fe===" "?"\xA0":fe,K.appendChild(pe),te++}return te},E=(K,ue)=>{var pe;g.textContent="";let U=((pe=t.name)==null?void 0:pe.trim())||"tool",te=cs(K,U),fe=0;for(let Re of te){let Xe=Re.styles.length>0?(()=>{let j=h("span",Re.styles.map(W=>`persona-tool-text-${W}`).join(" "));return g.appendChild(j),j})():g;if(Re.isDuration&&p)Xe.appendChild(M());else{let j=Re.isDuration?ko(t):Re.text;ue?fe=P(Xe,j,fe):Xe.appendChild(document.createTextNode(j))}}};if(!L)if(p&&S!=="none"){let K=(Le=n.loadingAnimationDuration)!=null?Le:2e3;if(g.setAttribute("data-preserve-animation","true"),S==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),w&&E(w,!1);else if(g.classList.add(`persona-tool-loading-${S}`),g.style.setProperty("--persona-tool-anim-duration",`${K}ms`),S==="shimmer-color"&&(n.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),w)E(w,!0);else{let ue=g.textContent||u;g.textContent="",P(g,ue,0)}}else w&&E(w,!1);let Y=null;if(a){Y=h("div","persona-flex persona-items-center");let K=n.toggleTextColor||n.headerTextColor||"currentColor",ue=be(i?"chevron-up":"chevron-down",16,K,2);ue?Y.appendChild(ue):Y.textContent=i?"Hide":"Show";let U=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");U.append(Y),d.append(f,U)}else d.append(f);let Q=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(Q.setAttribute("data-persona-collapsed-preview","tool"),Q.style.display="none",Q.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&c){let K=(se=n.renderCollapsedPreview)==null?void 0:se.call(n,{message:e,toolCall:t,defaultPreview:c,isActive:p,config:r!=null?r:{}});eu(Q,K)||(Q.textContent=c),Q.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(d,Q),s;let G=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(G.style.display=i?"":"none",n.contentBackgroundColor&&(G.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(G.style.color=n.contentTextColor),n.contentPaddingX&&(G.style.paddingLeft=n.contentPaddingX,G.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(G.style.paddingTop=n.contentPaddingY,G.style.paddingBottom=n.contentPaddingY),t.name){let K=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?K.style.color=n.contentTextColor:n.headerTextColor&&(K.style.color=n.headerTextColor),K.textContent=t.name,G.appendChild(K)}if(t.args!==void 0){let K=h("div","persona-space-y-1"),ue=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(ue.style.color=n.labelTextColor),ue.textContent="Arguments";let U=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");U.style.fontSize="0.75rem",U.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(U.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(U.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(U.style.color=n.codeBlockTextColor),U.textContent=Kr(t.args),K.append(ue,U),G.appendChild(K)}if(t.chunks&&t.chunks.length){let K=h("div","persona-space-y-1"),ue=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(ue.style.color=n.labelTextColor),ue.textContent="Activity";let U=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");U.style.fontSize="0.75rem",U.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(U.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(U.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(U.style.color=n.codeBlockTextColor),U.textContent=t.chunks.join(""),K.append(ue,U),G.appendChild(K)}if(t.status==="complete"&&t.result!==void 0){let K=h("div","persona-space-y-1"),ue=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(ue.style.color=n.labelTextColor),ue.textContent="Result";let U=h("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");U.style.fontSize="0.75rem",U.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(U.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(U.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(U.style.color=n.codeBlockTextColor),U.textContent=Kr(t.result),K.append(ue,U),G.appendChild(K)}if(t.status==="complete"&&typeof t.duration=="number"){let K=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(K.style.color=n.contentTextColor),K.textContent=`Duration: ${t.duration}ms`,G.appendChild(K)}return(()=>{if(d.setAttribute("aria-expanded",i?"true":"false"),Y){Y.innerHTML="";let K=n.toggleTextColor||n.headerTextColor||"currentColor",ue=be(i?"chevron-up":"chevron-down",16,K,2);ue?Y.appendChild(ue):Y.textContent=i?"Hide":"Show"}G.style.display=i?"":"none",Q.style.display=i?"none":Q.textContent||Q.childNodes.length?"":"none"})(),s.append(d,Q,G),s};var ia=(e,r)=>{var M,C,S,k,H,w,L,P,E,Y,Q,G;let t=e.approval,n=(r==null?void 0:r.approval)!==!1?r==null?void 0:r.approval:void 0,s=(t==null?void 0:t.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(M=n==null?void 0:n.backgroundColor)!=null?M:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(C=n==null?void 0:n.borderColor)!=null?C:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let u=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(S=n==null?void 0:n.titleColor)!=null?S:"currentColor",p=be(u,20,c,2);p&&i.appendChild(p);let d=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),g=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(g.style.color=n.titleColor),g.textContent=(k=n==null?void 0:n.title)!=null?k:"Approval Required",f.appendChild(g),!s){let O=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");O.setAttribute("data-approval-status",t.status),t.status==="approved"?(O.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",O.style.color="var(--persona-palette-colors-success-700, #15803d)",O.textContent="Approved"):t.status==="denied"?(O.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",O.style.color="var(--persona-palette-colors-error-700, #b91c1c)",O.textContent="Denied"):t.status==="timeout"&&(O.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",O.style.color="var(--persona-palette-colors-warning-700, #b45309)",O.textContent="Timeout"),f.appendChild(O)}d.appendChild(f);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(v.style.color=n.descriptionColor),v.textContent=t.description,d.appendChild(v),t.parameters){let O=h("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");n!=null&&n.parameterBackgroundColor&&(O.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(O.style.color=n.parameterTextColor),O.style.fontSize="0.75rem",O.style.lineHeight="1rem",O.textContent=Kr(t.parameters),d.appendChild(O)}if(s){let O=h("div","persona-flex persona-gap-2 persona-mt-2");O.setAttribute("data-approval-buttons","true");let re=h("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");re.type="button",re.style.backgroundColor=(H=n==null?void 0:n.approveButtonColor)!=null?H:"var(--persona-approval-approve-bg, #22c55e)",re.style.color=(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",re.setAttribute("data-approval-action","approve");let we=be("shield-check",14,(L=n==null?void 0:n.approveButtonTextColor)!=null?L:"#ffffff",2);we&&(we.style.marginRight="4px",re.appendChild(we));let oe=document.createTextNode((P=n==null?void 0:n.approveLabel)!=null?P:"Approve");re.appendChild(oe);let ve=h("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");ve.type="button",ve.style.backgroundColor=(E=n==null?void 0:n.denyButtonColor)!=null?E:"transparent",ve.style.color=(Y=n==null?void 0:n.denyButtonTextColor)!=null?Y:"var(--persona-feedback-error, #dc2626)",ve.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,ve.setAttribute("data-approval-action","deny");let We=be("shield-x",14,(Q=n==null?void 0:n.denyButtonTextColor)!=null?Q:"var(--persona-feedback-error, #dc2626)",2);We&&(We.style.marginRight="4px",ve.appendChild(We));let ge=document.createTextNode((G=n==null?void 0:n.denyLabel)!=null?G:"Deny");ve.appendChild(ge),O.append(re,ve),d.appendChild(O)}return a.append(i,d),o.appendChild(a),o};var id=e=>{let r=[];return{buttons:r,render:(n,s,o,a,i)=>{if(e.innerHTML="",r.length=0,!n||!n.length||(a!=null?a:s?s.getMessages():[]).some(g=>g.role==="user"))return;let p=document.createDocumentFragment(),d=s?s.isStreaming():!1,f=g=>{switch(g){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'}};n.forEach(g=>{let v=h("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=g,v.disabled=d,i!=null&&i.fontFamily&&(v.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(g))}),p.appendChild(v),r.push(v)}),e.appendChild(p)}}};var jo=class{constructor(r=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=r,this.buffer=new Array(r),this.store=t}push(r){var t;this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(r.type),(t=this.store)==null||t.put(r)}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 r=await this.store.getAll();if(r.length===0)return 0;let t=r.length>this.maxSize?r.slice(r.length-this.maxSize):r;for(let n of t)this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(n.type);return this.totalCaptured=r.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(r){let t=this.getAll();return r>=t.length?t:t.slice(t.length-r)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var r;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.clear()}destroy(){var r;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var zo=class{constructor(r="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=r,this.storeName=t}open(){return new Promise((r,t)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}put(r){!this.db||this.isDestroyed||(this.pendingWrites.push(r),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(r){if(!(!this.db||this.isDestroyed||r.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}getAll(){return new Promise((r,t)=>{if(!this.db){r([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{r(a.result)},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}getCount(){return new Promise((r,t)=>{if(!this.db){r(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{r(o.result)},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}clear(){return new Promise((r,t)=>{if(!this.db){r();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{r()},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((r,t)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let r=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}};function so(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var ru={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)"}},ou={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},su=["flowName","stepName","reasoningText","text","name","tool","toolName"],au=100;function iu(e,r){let t={...ru,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return ou}function lu(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function cu(e){let r=new Date(e),t=String(r.getHours()).padStart(2,"0"),n=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0"),o=String(r.getMilliseconds()).padStart(3,"0");return`${t}:${n}:${s}.${o}`}function du(e,r){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let n of r){let s=n.split("."),o=t;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function pu(e){var r;return(r=navigator.clipboard)!=null&&r.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function uu(e){let r;try{r=JSON.parse(e.payload)}catch{r=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:r},null,2)}function mu(e,r,t){let n,s;try{s=JSON.parse(e.payload),n=JSON.stringify(s,null,2)}catch{s=e.payload,n=e.payload}let o=r.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("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]"),u=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return u.textContent=n,i.appendChild(u),i}}function la(e,r,t,n,s,o,a,i){var f;let u=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");so(c,(f=n.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:r,config:i,defaultRenderer:()=>d(),isExpanded:u,onToggleExpand:()=>o(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(d()),c;function d(){var re,we;let g=h("div",""),v=h("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 M=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=be(u?"chevron-down":"chevron-right","14px","currentColor",2);C&&M.appendChild(C);let S=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(re=n.timestampFormat)!=null?re:"relative";S.textContent=k==="relative"?lu(e.timestamp,t):cu(e.timestamp);let H=null;n.showSequenceNumbers!==!1&&(H=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),H.textContent=String(r+1));let w=iu(e.type,n.badgeColors),L=h("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");L.style.backgroundColor=w.bg,L.style.color=w.text,L.style.borderColor=w.text+"50",L.textContent=e.type;let P=(we=n.descriptionFields)!=null?we:su,E=du(e.payload,P),Y=null;E&&(Y=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),Y.textContent=E);let Q=h("div","persona-flex-1 persona-min-w-0"),G=h("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=be("clipboard","12px","currentColor",1.5);return O&&G.appendChild(O),G.addEventListener("click",async oe=>{oe.stopPropagation(),await pu(uu(e)),G.innerHTML="";let ve=be("check","12px","currentColor",1.5);ve&&G.appendChild(ve),setTimeout(()=>{G.innerHTML="";let We=be("clipboard","12px","currentColor",1.5);We&&G.appendChild(We)},1500)}),v.appendChild(M),v.appendChild(S),H&&v.appendChild(H),v.appendChild(L),Y&&v.appendChild(Y),v.appendChild(Q),v.appendChild(G),g.appendChild(v),u&&g.appendChild(mu(e,a,i)),g}}function ld(e){var g,v,M,C,S;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(g=s==null?void 0:s.features)==null?void 0:g.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,u=(v=a==null?void 0:a.iconName)!=null?v:"arrow-down",c=(M=a==null?void 0:a.label)!=null?M:"",p=(S=(C=s==null?void 0:s.features)==null?void 0:C.eventStream)!=null?S:{},d=o.find(k=>k.renderEventStreamView);if(d!=null&&d.renderEventStreamView&&s){let k=d.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>f().element,onClose:n});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return f();function f(){let k=p.classNames,H=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");so(H,k==null?void 0:k.panel);let w=[],L="",P="",E=null,Y=[],Q={},G=0,O=xs(),re=0,we=0,oe=!1,ve=null,We=!1,ge=0,ke=new Set,Le=new Map,se="",K="",ue=null,U,te,fe,pe,Re;function Xe(){let ce=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),Se=h("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");so(Se,k==null?void 0:k.headerBar);let Oe=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Oe.textContent="Events",U=h("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"),U.textContent="0";let Ct=h("div","persona-flex-1");te=h("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 jt=h("option","");jt.value="",jt.textContent="All events",te.appendChild(jt),fe=h("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"),fe.type="button",fe.title="Copy All";let zt=be("clipboard-copy","12px","currentColor",1.5);zt&&fe.appendChild(zt);let yt=h("span","persona-text-xs");yt.textContent="Copy All",fe.appendChild(yt),Se.appendChild(Oe),Se.appendChild(U),Se.appendChild(Ct),Se.appendChild(te),Se.appendChild(fe);let Ze=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");so(Ze,k==null?void 0:k.searchBar);let bt=be("search","14px","var(--persona-muted, #9ca3af)",1.5),De=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");bt&&De.appendChild(bt),pe=h("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"),so(pe,k==null?void 0:k.searchInput),pe.type="text",pe.placeholder="Search event payloads...",Re=h("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"),Re.type="button",Re.style.display="none";let qt=be("x","12px","currentColor",2);return qt&&Re.appendChild(qt),Ze.appendChild(De),Ze.appendChild(pe),Ze.appendChild(Re),ce.appendChild(Se),ce.appendChild(Ze),ce}let j,W=o.find(ce=>ce.renderEventStreamToolbar);if(W!=null&&W.renderEventStreamToolbar&&s){let ce=W.renderEventStreamToolbar({config:s,defaultRenderer:()=>Xe(),eventCount:r.getSize(),filteredCount:0,onFilterChange:Se=>{L=Se,Xt(),Ne()},onSearchChange:Se=>{P=Se,Xt(),Ne()}});j=ce!=null?ce:Xe()}else j=Xe();let ae=h("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");ae.style.display="none";let $=h("div","persona-flex-1 persona-min-h-0 persona-relative"),q=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");q.style.height="100%";let de=h("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");so(de,k==null?void 0:k.scrollIndicator),de.style.display="none",de.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let _e=be(u,"14px","currentColor",2);_e&&de.appendChild(_e);let ee=h("span","");ee.textContent=c,de.appendChild(ee);let le=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");le.style.display="none",$.appendChild(q),$.appendChild(le),$.appendChild(de),H.setAttribute("tabindex","0"),H.appendChild(j),H.appendChild(ae),H.appendChild($);function It(){let ce=r.getAll(),Se={};for(let yt of ce)Se[yt.type]=(Se[yt.type]||0)+1;let Oe=Object.keys(Se).sort(),Ct=Oe.length!==Y.length||!Oe.every((yt,Ze)=>yt===Y[Ze]),jt=!Ct&&Oe.some(yt=>Se[yt]!==Q[yt]),pt=ce.length!==Object.values(Q).reduce((yt,Ze)=>yt+Ze,0);if(!Ct&&!jt&&!pt||(Y=Oe,Q=Se,!te))return;let zt=te.value;if(te.options[0].textContent="All events",Ct){for(;te.options.length>1;)te.remove(1);for(let yt of Oe){let Ze=h("option","");Ze.value=yt,Ze.textContent=`${yt} (${Se[yt]||0})`,te.appendChild(Ze)}zt&&Oe.includes(zt)?te.value=zt:zt&&(te.value="",L="")}else for(let yt=1;yt<te.options.length;yt++){let Ze=te.options[yt];Ze.textContent=`${Ze.value} (${Se[Ze.value]||0})`}}function dt(){let ce=r.getAll();if(L&&(ce=ce.filter(Se=>Se.type===L)),P){let Se=P.toLowerCase();ce=ce.filter(Oe=>Oe.type.toLowerCase().includes(Se)||Oe.payload.toLowerCase().includes(Se))}return ce}function Dt(){return L!==""||P!==""}function Xt(){G=0,re=0,O.resume(),de.style.display="none"}function je(ce){ke.has(ce)?ke.delete(ce):ke.add(ce),ue=ce;let Se=q.scrollTop,Oe=O.isFollowing();We=!0,O.pause(),Ne(),q.scrollTop=Se,Oe&&O.resume(),We=!1}function me(){return Do(q,50)}function Ne(){we=Date.now(),oe=!1,It();let ce=r.getEvictedCount();ce>0?(ae.textContent=`${ce.toLocaleString()} older events truncated`,ae.style.display=""):ae.style.display="none",w=dt();let Se=w.length,Oe=r.getSize()>0;U&&(U.textContent=String(r.getSize())),Se===0&&Oe&&Dt()?(le.textContent=P?`No events matching '${P}'`:"No events matching filter",le.style.display="",q.style.display="none"):(le.style.display="none",q.style.display=""),fe&&(fe.title=Dt()?`Copy Filtered (${Se})`:"Copy All"),i&&!O.isFollowing()&&Se>G&&(re+=Se-G,ee.textContent=c?`${c}${re>0?` (${re})`:""}`:"",de.style.display=""),G=Se;let Ct=r.getAll(),jt=Ct.length>0?Ct[0].timestamp:0,pt=new Set(w.map(Ze=>Ze.id));for(let Ze of ke)pt.has(Ze)||ke.delete(Ze);let zt=L!==se||P!==K,yt=Le.size===0&&w.length>0;if(zt||yt||w.length===0){q.innerHTML="",Le.clear();let Ze=document.createDocumentFragment();for(let bt=0;bt<w.length;bt++){let De=la(w[bt],bt,jt,p,ke,je,o,s);Le.set(w[bt].id,De),Ze.appendChild(De)}q.appendChild(Ze),se=L,K=P,ue=null}else{if(ue!==null){let bt=Le.get(ue);if(bt&&bt.parentNode===q){let De=w.findIndex(qt=>qt.id===ue);if(De>=0){let qt=la(w[De],De,jt,p,ke,je,o,s);q.insertBefore(qt,bt),bt.remove(),Le.set(ue,qt)}}ue=null}let Ze=new Set(w.map(bt=>bt.id));for(let[bt,De]of Le)Ze.has(bt)||(De.remove(),Le.delete(bt));for(let bt=0;bt<w.length;bt++){let De=w[bt];if(!Le.has(De.id)){let qt=la(De,bt,jt,p,ke,je,o,s);Le.set(De.id,qt),q.appendChild(qt)}}}O.isFollowing()&&(q.scrollTop=q.scrollHeight)}function Wt(){if(Date.now()-we>=au){ve!==null&&(cancelAnimationFrame(ve),ve=null),Ne();return}oe||(oe=!0,ve=requestAnimationFrame(()=>{ve=null,Ne()}))}let Rt=(ce,Se)=>{if(!fe)return;fe.innerHTML="";let Oe=be(ce,"12px","currentColor",1.5);Oe&&fe.appendChild(Oe);let Ct=h("span","persona-text-xs");Ct.textContent="Copy All",fe.appendChild(Ct),setTimeout(()=>{fe.innerHTML="";let jt=be("clipboard-copy","12px","currentColor",1.5);jt&&fe.appendChild(jt);let pt=h("span","persona-text-xs");pt.textContent="Copy All",fe.appendChild(pt),fe.disabled=!1},Se)},ot=async()=>{if(fe){fe.disabled=!0;try{let ce;Dt()?ce=w:t?(ce=await t(),ce.length===0&&(ce=r.getAll())):ce=r.getAll();let Se=ce.map(Oe=>{try{return JSON.parse(Oe.payload)}catch{return Oe.payload}});await navigator.clipboard.writeText(JSON.stringify(Se,null,2)),Rt("check",1500)}catch{Rt("x",1500)}}},st=()=>{te&&(L=te.value,Xt(),Ne())},nn=()=>{!pe||!Re||(Re.style.display=pe.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{P=pe.value,Xt(),Ne()},150))},tn=()=>{!pe||!Re||(pe.value="",P="",Re.style.display="none",E&&clearTimeout(E),Xt(),Ne())},rn=()=>{if(We)return;let ce=q.scrollTop,{action:Se,nextLastScrollTop:Oe}=vs({following:O.isFollowing(),currentScrollTop:ce,lastScrollTop:ge,nearBottom:me(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});ge=Oe,Se==="resume"?(O.resume(),re=0,de.style.display="none"):Se==="pause"&&(O.pause(),i&&(ee.textContent=c,de.style.display=""))},z=ce=>{let Se=Cs({following:O.isFollowing(),deltaY:ce.deltaY,nearBottom:me(),resumeWhenNearBottom:!0});Se==="pause"?(O.pause(),i&&(ee.textContent=c,de.style.display="")):Se==="resume"&&(O.resume(),re=0,de.style.display="none")},He=()=>{i&&(q.scrollTop=q.scrollHeight,O.resume(),re=0,de.style.display="none")},ye=ce=>{let Se=ce.target;if(!Se||Se.closest("button"))return;let Oe=Se.closest("[data-event-id]");if(!Oe)return;let Ct=Oe.getAttribute("data-event-id");Ct&&je(Ct)},ht=ce=>{if((ce.metaKey||ce.ctrlKey)&&ce.key==="f"){ce.preventDefault(),pe==null||pe.focus(),pe==null||pe.select();return}ce.key==="Escape"&&(pe&&document.activeElement===pe?(tn(),pe.blur(),H.focus()):n&&n())};fe&&fe.addEventListener("click",ot),te&&te.addEventListener("change",st),pe&&pe.addEventListener("input",nn),Re&&Re.addEventListener("click",tn),q.addEventListener("scroll",rn),q.addEventListener("wheel",z,{passive:!0}),q.addEventListener("click",ye),de.addEventListener("click",He),H.addEventListener("keydown",ht);function $e(){E&&clearTimeout(E),ve!==null&&(cancelAnimationFrame(ve),ve=null),oe=!1,Le.clear(),fe&&fe.removeEventListener("click",ot),te&&te.removeEventListener("change",st),pe&&pe.removeEventListener("input",nn),Re&&Re.removeEventListener("click",tn),q.removeEventListener("scroll",rn),q.removeEventListener("wheel",z),q.removeEventListener("click",ye),de.removeEventListener("click",He),H.removeEventListener("keydown",ht)}return{element:H,update:Wt,destroy:$e}}}function cd(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=typeof e.artifactId=="string"?e.artifactId:"",s=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 ${t} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=t;let d=document.createElement("div");if(d.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",d.style.color="var(--persona-muted, #9ca3af)",s==="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",d.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,d.appendChild(g)}else d.textContent=a;if(c.append(p,d),i.append(u,c),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${t}`,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",n),i.append(f)}return i}var dd=(e,r)=>{var n,s,o;let t=(o=(s=(n=r==null?void 0:r.config)==null?void 0:n.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",u=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=t({artifact:{artifactId:i,title:a,artifactType:c,status:u},config:r.config,defaultRenderer:()=>cd(e,r)});if(p)return p}return cd(e,r)};var ca=class{constructor(){this.components=new Map}register(r,t){this.components.has(r)&&console.warn(`[ComponentRegistry] Component "${r}" is already registered. Overwriting.`),this.components.set(r,t)}unregister(r){this.components.delete(r)}get(r){return this.components.get(r)}has(r){return this.components.has(r)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(r){Object.entries(r).forEach(([t,n])=>{this.register(t,n)})}},Ar=new ca;Ar.register("PersonaArtifactCard",dd);function gu(e){var s;let r=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let n=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),r.appendChild(t),r.appendChild(n),r}function pd(e,r){var fe,pe,Re,Xe;let t=(pe=(fe=e.features)==null?void 0:fe.artifacts)==null?void 0:pe.layout,s=((Re=t==null?void 0:t.toolbarPreset)!=null?Re:"default")==="document",o=(Xe=t==null?void 0:t.panePadding)==null?void 0:Xe.trim(),a=e.markdown?Gr(e.markdown):null,i=To(e.sanitize),u=j=>{let W=a?a(j):Eo(j);return i?i(W):W},c=typeof document!="undefined"?h("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"),d.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};c&&c.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let d=h("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");d.setAttribute("data-persona-theme-zone","artifact-pane"),s&&d.classList.add("persona-artifact-pane-document");let f=h("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"),s&&f.classList.add("persona-artifact-toolbar-document");let g=h("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let v=h("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 j;p(),(j=r.onDismiss)==null||j.call(r)});let M="rendered",C=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),S=s?Bt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Bt({icon:"eye",label:"Rendered view"}),k=s?Bt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Bt({icon:"code-2",label:"Source"}),H=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),w=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,L=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,P=t==null?void 0:t.documentToolbarCopyMenuItems,E=!!(L&&P&&P.length>0),Y=null,Q,G=null,O=null;if(s&&(w||L)&&!E){if(Q=w?Ss({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let j=be("chevron-down",14,"currentColor",2);j&&Q.appendChild(j)}}else s&&E?(Y=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Q=w?Ss({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),G=Bt({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"}}),Y.append(Q,G)):s?Q=Bt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):Q=Bt({icon:"copy",label:"Copy"});let re=s?Bt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Bt({icon:"refresh-cw",label:"Refresh"}),we=s?Bt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Bt({icon:"x",label:"Close"}),oe=()=>{var q,de,_e;let j=(q=se.find(ee=>ee.id===K))!=null?q:se[se.length-1],W=(de=j==null?void 0:j.id)!=null?de:null,ae=(j==null?void 0:j.artifactType)==="markdown"&&(_e=j.markdown)!=null?_e:"",$=j?JSON.stringify({component:j.component,props:j.props},null,2):"";return{markdown:ae,jsonPayload:$,id:W}},ve=async()=>{var q;let{markdown:j,jsonPayload:W}=oe(),ae=(q=se.find(de=>de.id===K))!=null?q:se[se.length-1],$=(ae==null?void 0:ae.artifactType)==="markdown"?j:ae?W:"";try{await navigator.clipboard.writeText($)}catch{}};if(Q.addEventListener("click",async()=>{let j=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(j&&E){let{markdown:W,jsonPayload:ae,id:$}=oe();try{await j({actionId:"primary",artifactId:$,markdown:W,jsonPayload:ae})}catch{}return}await ve()}),G&&(P!=null&&P.length)){let j=()=>{var ae;return(ae=d.closest("[data-persona-root]"))!=null?ae:document.body},W=()=>{O=_r({items:P.map(ae=>({id:ae.id,label:ae.label})),onSelect:async ae=>{let{markdown:$,jsonPayload:q,id:de}=oe(),_e=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{_e?await _e({actionId:ae,artifactId:de,markdown:$,jsonPayload:q}):ae==="markdown"||ae==="md"?await navigator.clipboard.writeText($):ae==="json"||ae==="source"?await navigator.clipboard.writeText(q):await navigator.clipboard.writeText($||q)}catch{}},anchor:Y!=null?Y:G,position:"bottom-right",portal:j()})};d.isConnected?W():requestAnimationFrame(W),G.addEventListener("click",ae=>{ae.stopPropagation(),O==null||O.toggle()})}re.addEventListener("click",async()=>{var j;try{await((j=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:j.call(t))}catch{}U()}),we.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let We=()=>{s&&(S.setAttribute("aria-pressed",M==="rendered"?"true":"false"),k.setAttribute("aria-pressed",M==="source"?"true":"false"))};S.addEventListener("click",()=>{M="rendered",We(),U()}),k.addEventListener("click",()=>{M="source",We(),U()});let ge=h("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");s?(f.replaceChildren(),C.append(S,k),Y?H.append(Y,re,we):H.append(Q,re,we),f.append(C,ge,H),We()):(f.appendChild(g),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let ke=h("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),Le=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(ke.style.paddingLeft=o,ke.style.paddingRight=o,Le.style.padding=o),d.appendChild(f),d.appendChild(ke),d.appendChild(Le);let se=[],K=null,ue=!1,U=()=>{var $,q,de,_e;let j=s&&se.length<=1;ke.classList.toggle("persona-hidden",j),ke.replaceChildren();for(let ee of se){let le=h("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");le.type="button",le.textContent=ee.title||ee.id.slice(0,8),ee.id===K&&le.classList.add("persona-bg-persona-container","persona-border-persona-border"),le.addEventListener("click",()=>r.onSelect(ee.id)),ke.appendChild(le)}Le.replaceChildren();let W=K&&se.find(ee=>ee.id===K)||se[se.length-1];if(!W)return;if(s){let ee=W.artifactType==="markdown"?"MD":($=W.component)!=null?$:"Component",It=(W.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ge.textContent=`${It} \xB7 ${ee}`}else g.textContent="Artifacts";if(W.artifactType==="markdown"){if(s&&M==="source"){let le=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");le.textContent=(q=W.markdown)!=null?q:"",Le.appendChild(le);return}let ee=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ee.innerHTML=u((de=W.markdown)!=null?de:""),Le.appendChild(ee);return}let ae=W.component?Ar.get(W.component):void 0;if(ae){let le={message:{id:W.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let It=ae((_e=W.props)!=null?_e:{},le);if(It){Le.appendChild(It);return}}catch{}}Le.appendChild(gu(W))},te=()=>{var W;let j=se.length>0;if(d.classList.toggle("persona-hidden",!j),c){let ae=typeof d.closest=="function"?d.closest("[data-persona-root]"):null,q=((W=ae==null?void 0:ae.classList.contains("persona-artifact-narrow-host"))!=null?W:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;j&&q&&ue?(c.classList.remove("persona-hidden"),d.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open"))}};return{element:d,backdrop:c,update(j){var W,ae,$;se=j.artifacts,K=($=(ae=j.selectedId)!=null?ae:(W=j.artifacts[j.artifacts.length-1])==null?void 0:W.id)!=null?$:null,se.length>0&&(ue=!0),U(),te()},setMobileOpen(j){ue=j,!j&&c?(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open")):te()}}}function On(e){var r,t;return((t=(r=e==null?void 0:e.features)==null?void 0:r.artifacts)==null?void 0:t.enabled)===!0}function ud(e,r){var o,a,i,u;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"),!On(r))return;let t=(a=(o=r.features)==null?void 0:o.artifacts)==null?void 0:a.layout,n=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(u=t==null?void 0:t.paneBorderLeft)==null?void 0:u.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function fu(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 Es(e,r){var u,c,p,d,f,g,v,M,C,S;if(!On(r)){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"),fu(e),ud(e,r);return}let t=(c=(u=r.features)==null?void 0:u.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(p=t==null?void 0:t.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(d=t==null?void 0:t.paneWidth)!=null?d:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let n=(g=t==null?void 0:t.paneBackground)==null?void 0:g.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(M=t==null?void 0:t.documentToolbarIconColor)==null?void 0:M.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(C=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:C.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(S=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:S.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),ud(e,r)}var md=["panel","seamless"];function Ts(e,r){var i,u,c,p,d,f;for(let g of md)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"),!On(r))return;let t=(u=(i=r.features)==null?void 0:i.artifacts)==null?void 0:u.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=md.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=t==null?void 0:t.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(d=t==null?void 0:t.paneShadow)==null?void 0:d.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let g=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function gd(e,r){var t,n,s;return!r||!On(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function hu(e,r){if(!(e!=null&&e.trim()))return r;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):r}function yu(e){if(!(e!=null&&e.trim()))return null;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):null}function bu(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function xu(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function fd(e,r){var a;let n=(a=(r.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(n);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(n);return o?Number(o[1]):8}function hd(e,r,t,n,s,o){let a=hu(s,200),i=xu(r,t,n,200);i=Math.max(a,i);let u=yu(o);return u!==null&&(i=Math.min(i,u)),bu(e,a,i)}var yd={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"}},da=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,M,C;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(M=yd[a])!=null?M:yd.init;o.classList.add("persona-form-card","persona-space-y-4");let u=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,u.appendChild(c),i.description){let S=h("p","persona-text-sm persona-text-persona-muted");S.textContent=i.description,u.appendChild(S)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(S=>{var P,E;let k=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${r.id}-${a}-${S.name}`;let H=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=S.label,k.appendChild(H);let w=(P=S.type)!=null?P:"text",L;w==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=w),L.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",L.id=`${r.id}-${a}-${S.name}`,L.name=S.name,L.placeholder=(E=S.placeholder)!=null?E:"",S.required&&(L.required=!0),k.appendChild(L),p.appendChild(k)});let d=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),g=h("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=(C=i.submitLabel)!=null?C:"Submit",d.appendChild(f),d.appendChild(g),p.appendChild(d),o.replaceChildren(u,p),p.addEventListener("submit",async S=>{var L,P;S.preventDefault();let k=(L=t.formEndpoint)!=null?L:"/form",H=new FormData(p),w={};H.forEach((E,Y)=>{w[Y]=E}),w.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let E=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let Y=await E.json();f.textContent=(P=Y.message)!=null?P:"Thanks! We'll be in touch soon.",Y.success&&Y.nextPrompt&&await n.sendMessage(String(Y.nextPrompt))}catch(E){f.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var pa=class{constructor(){this.plugins=new Map}register(r){var t;this.plugins.has(r.id)&&console.warn(`Plugin "${r.id}" is already registered. Overwriting.`),this.plugins.set(r.id,r),(t=r.onRegister)==null||t.call(r)}unregister(r){var n;let t=this.plugins.get(r);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(r))}getAll(){return Array.from(this.plugins.values()).sort((r,t)=>{var n,s;return((n=t.priority)!=null?n:0)-((s=r.priority)!=null?s:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let n=new Set(r.map(o=>o.id));return[...t.filter(o=>!n.has(o.id)),...r].sort((o,a)=>{var i,u;return((i=a.priority)!=null?i:0)-((u=o.priority)!=null?u:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},Ms=new pa;var bd=()=>{let e=new Map,r=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:r,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var vu=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},Cu=e=>{let r=e.trim(),t=r.indexOf("{");if(t===-1)return null;let n=0;for(let s=t;s<r.length;s+=1){let o=r[s];if(o==="{"&&(n+=1),o==="}"&&(n-=1,n===0))return r.slice(t,s+1)}return null},ks=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=vu(e),t=Cu(r);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||!n.action)return null;let{action:s,...o}=n;return{type:String(s),payload:o,raw:n}}catch{return null}},ua=e=>typeof e=="string"?e:e==null?"":String(e),ao={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ua(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=ua(t.element);if(n&&((s=r.document)!=null&&s.querySelector)){let o=r.document.querySelector(n);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:ua(t.text)}}},xd=e=>Array.isArray(e)?e.map(r=>String(r)):[],Ls=e=>{let r=new Set(xd(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(xd(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let o=Array.from(r);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||r.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.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:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let u={action:i,message:o.message};e.emit("action:detected",u);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",u)},d=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!d)continue;if(d.handled){let f=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:f,resubmit:d.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:t}};var wu=e=>{if(!e)return null;try{return JSON.parse(e)}catch(r){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",r),null}},Su=e=>e.map(r=>({...r,streaming:!1})),ma=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?wu(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?Su(t.messages):void 0};n.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=r();if(t)try{t.removeItem(e)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};import{parse as Au,STR as Eu,OBJ as Tu}from"partial-json";function Mu(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function ku(e,r){if(!Mu(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:r}}function ga(){let e=null,r=0;return{getExtractedDirective:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e;try{let s=Au(t,Eu|Tu),o=ku(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Lu(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function fa(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=Ar.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:n,config:t,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Iu(){let e=ga();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ha(e){if(!e.rawContent)return!1;try{let r=JSON.parse(e.rawContent);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function ya(e){if(!e.rawContent)return null;try{let r=JSON.parse(e.rawContent);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string")return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e.rawContent}}catch{}return null}var Pu=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ba(e){let{onSubmit:r,onDismiss:t,title:n="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:u=!0,ratingLabels:c=Pu}=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 d=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=n,g.appendChild(v);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=s,g.appendChild(M),f.appendChild(g);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-csat",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Satisfaction rating from 1 to 5");let S=[];for(let P=1;P<=5;P++){let E=document.createElement("button");E.type="button",E.className="persona-feedback-rating-btn persona-feedback-star-btn",E.setAttribute("role","radio"),E.setAttribute("aria-checked","false"),E.setAttribute("aria-label",`${P} star${P>1?"s":""}: ${c[P-1]}`),E.title=c[P-1],E.dataset.rating=String(P),E.innerHTML=`
19
19
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
20
20
  <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>
21
21
  </svg>
22
- `,E.addEventListener("click",()=>{d=P,S.forEach((Y,Q)=>{let G=Q<P;Y.classList.toggle("selected",G),Y.setAttribute("aria-checked",Q===P-1?"true":"false")})}),S.push(E),C.appendChild(E)}f.appendChild(C);let k=null;if(u){let P=document.createElement("div");P.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=o,k.rows=3,k.setAttribute("aria-label","Additional comments"),P.appendChild(k),f.appendChild(P)}let H=document.createElement("div");H.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=i,w.addEventListener("click",()=>{t==null||t(),p.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(d===null){C.classList.add("persona-feedback-shake"),setTimeout(()=>C.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let P=(k==null?void 0:k.value.trim())||void 0;await r(d,P),p.remove()}catch(P){L.disabled=!1,L.textContent=a,console.error("[CSAT Feedback] Failed to submit:",P)}}),H.appendChild(w),H.appendChild(L),f.appendChild(H),p.appendChild(f),p}function xa(e){let{onSubmit:r,onDismiss:t,title:n="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:u=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-nps",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let M=document.createElement("h3");M.className="persona-feedback-title",M.textContent=n,v.appendChild(M);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=s,v.appendChild(C),g.appendChild(v);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=c;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=p,k.appendChild(H),k.appendChild(w);let L=document.createElement("div");L.className="persona-feedback-numbers";let P=[];for(let O=0;O<=10;O++){let re=document.createElement("button");re.type="button",re.className="persona-feedback-rating-btn persona-feedback-number-btn",re.setAttribute("role","radio"),re.setAttribute("aria-checked","false"),re.setAttribute("aria-label",`Rating ${O} out of 10`),re.textContent=String(O),re.dataset.rating=String(O),O<=6?re.classList.add("persona-feedback-detractor"):O<=8?re.classList.add("persona-feedback-passive"):re.classList.add("persona-feedback-promoter"),re.addEventListener("click",()=>{f=O,P.forEach((we,oe)=>{we.classList.toggle("selected",oe===O),we.setAttribute("aria-checked",oe===O?"true":"false")})}),P.push(re),L.appendChild(re)}S.appendChild(k),S.appendChild(L),g.appendChild(S);let E=null;if(u){let O=document.createElement("div");O.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=o,E.rows=3,E.setAttribute("aria-label","Additional comments"),O.appendChild(E),g.appendChild(O)}let Y=document.createElement("div");Y.className="persona-feedback-actions";let Q=document.createElement("button");Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-skip",Q.textContent=i,Q.addEventListener("click",()=>{t==null||t(),d.remove()});let G=document.createElement("button");return G.type="button",G.className="persona-feedback-btn persona-feedback-btn-submit",G.textContent=a,G.addEventListener("click",async()=>{if(f===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}G.disabled=!0,G.textContent="Submitting...";try{let O=(E==null?void 0:E.value.trim())||void 0;await r(f,O),d.remove()}catch(O){G.disabled=!1,G.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),Y.appendChild(Q),Y.appendChild(G),g.appendChild(Y),d.appendChild(g),d}var io="persona-chat-history",Wu=30*1e3,Ru={"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 Hu(e){var n,s,o;if(!e)return[];let r=[],t=Array.from((n=e.items)!=null?n:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){r.push(i);continue}let u=(s=Ru[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${u}`,{type:i.type,lastModified:Date.now()}))}if(r.length>0)return r;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&r.push(a);return r}function Is(e){if(!e)return!1;let r=e.types;return r?typeof r.contains=="function"?r.contains("Files"):Array.from(r).includes("Files"):!1}function Bu(e){var r,t,n,s,o,a,i,u,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(r=e.storage)!=null?r:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(n=e.persist)==null?void 0:n.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(u=(i=e.persist)==null?void 0:i.focusInput)!=null?u:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function Du(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var va=e=>!e||typeof e!="object"?{}:{...e},vd=e=>e.map(r=>({...r,streaming:!1})),Cd=(e,r,t)=>{let n=e!=null&&e.markdown?Gr(e.markdown):null,s=To(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(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."),o=>{var c,p,d;let a=(c=o.text)!=null?c:"",i=(p=o.message.rawContent)!=null?p:null;if(r){let f=r.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&t&&t())}let u;return e!=null&&e.postprocessMessage?u=e.postprocessMessage({...o,text:a,raw:(d=i!=null?i:o.text)!=null?d:""}):n?u=n(a):u=Eo(a),s?s(u):u}};function wd(e){var i,u,c,p;let r=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&r.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&r.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&r.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&r.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&r.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&r.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&r.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",n=(u=e==null?void 0:e.iconSize)!=null?u:"48px",s=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=be(t,n,s,o);if(a&&r.appendChild(a),e!=null&&e.label){let d=h("span","persona-drop-overlay-label");d.textContent=e.label,r.appendChild(d)}return r}var Ca=(e,r,t)=>{var Ha,Ba,Da,Fa,Na,Oa,$a,_a,ja,za,qa,Ua,Va,Ja,Ya,Ga,Ka,Xa,Za,Qa,ei,ti,ni,ri,oi,si,ai,ii,li,ci,di,pi,ui,mi,gi,fi,hi,yi,bi,xi;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 n=Xs(r),s=Ms.getForInstance(n.plugins);n.components&&Ar.registerAll(n.components);let o=bd(),a=(Ha=n.storageAdapter)!=null?Ha:ma(),i={},u=null,c=!1,p=l=>{if(n.onStateLoaded)try{let m=n.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:y,open:A}=m;return A&&(c=!0),y}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")u=l.then(m=>{let y=m!=null?m:{messages:[],metadata:{}};return p(y)});else{let m=l!=null?l:{messages:[],metadata:{}},y=p(m);y.metadata&&(i=va(y.metadata)),(Ba=y.messages)!=null&&Ba.length&&(n={...n,initialMessages:y.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(n.onStateLoaded)try{let l=p({messages:[],metadata:{}});(Da=l.messages)!=null&&Da.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let d=()=>i,f=l=>{var y;i=(y=l({...i}))!=null?y:{},uo()},g=n.actionParsers&&n.actionParsers.length?n.actionParsers:[ks],v=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ao.message,ao.messageAndClick],M=Ls({parsers:g,handlers:v,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let C=(Na=(Fa=n.launcher)==null?void 0:Fa.enabled)!=null?Na:!0,S=($a=(Oa=n.launcher)==null?void 0:Oa.autoExpand)!=null?$a:!1,k=(_a=n.autoFocusInput)!=null?_a:!1,H=S,w=C,L=(za=(ja=n.layout)==null?void 0:ja.header)==null?void 0:za.layout,P=!1,E=C?S:!0,Y=!1,Q=null,G=()=>{Y=!0,Q&&clearTimeout(Q),Q=setTimeout(()=>{Y&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Y=!1)},1e4)},O=Cd(n,M,G),re=(Ua=(qa=n.features)==null?void 0:qa.showReasoning)!=null?Ua:!0,we=(Ja=(Va=n.features)==null?void 0:Va.showToolCalls)!=null?Ja:!0,oe=(Ga=(Ya=n.features)==null?void 0:Ya.showEventStreamToggle)!=null?Ga:!1,ve=(Xa=(Ka=n.features)==null?void 0:Ka.scrollToBottom)!=null?Xa:{},ge=`${(Qa=typeof n.persistState=="object"?(Za=n.persistState)==null?void 0:Za.keyPrefix:void 0)!=null?Qa:"persona-"}event-stream`,ke=oe?new zo(ge):null,Le=(ni=(ti=(ei=n.features)==null?void 0:ei.eventStream)==null?void 0:ti.maxEvents)!=null?ni:2e3,se=oe?new jo(Le,ke):null,K=null,ue=!1,U=null,te=0;ke==null||ke.open().then(()=>se==null?void 0:se.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let fe={onCopy:l=>{var m,y;o.emit("message:copy",l),D!=null&&D.isClientTokenMode()&&D.submitMessageFeedback(l.id,"copy").catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(y=(m=n.messageActions)==null?void 0:m.onCopy)==null||y.call(m,l)},onFeedback:l=>{var m,y;o.emit("message:feedback",l),D!=null&&D.isClientTokenMode()&&D.submitMessageFeedback(l.messageId,l.type).catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(y=(m=n.messageActions)==null?void 0:m.onFeedback)==null||y.call(m,l)}},pe=(ri=n.statusIndicator)!=null?ri:{},Re=l=>{var m,y,A,I;return l==="idle"?(m=pe.idleText)!=null?m:cn.idle:l==="connecting"?(y=pe.connectingText)!=null?y:cn.connecting:l==="connected"?(A=pe.connectedText)!=null?A:cn.connected:l==="error"?(I=pe.errorText)!=null?I:cn.error:cn[l]};function Xe(l,m,y,A){if(A==="idle"&&y.idleLink){l.textContent="";let I=document.createElement("a");I.href=y.idleLink,I.target="_blank",I.rel="noopener noreferrer",I.textContent=m,I.style.color="inherit",I.style.textDecoration="none",l.appendChild(I)}else l.textContent=m}let{wrapper:j,panel:W}=ed(n),ae=td(n,C),{container:$,body:q,messagesWrapper:de,suggestions:_e,textarea:ee,sendButton:le,sendButtonWrapper:Lt,composerForm:ct,statusText:Dt,introTitle:Xt,introSubtitle:je,closeButton:me,iconHolder:Ne,headerTitle:Pt,headerSubtitle:Wt,header:ot,footer:st,actionsRow:nn,leftActions:tn,rightActions:rn}=ae,z=ae.micButton,He=ae.micButtonWrapper,ye=ae.attachmentButton,ht=ae.attachmentButtonWrapper,$e=ae.attachmentInput,ce=ae.attachmentPreviewsContainer;$.classList.add("persona-relative"),q.classList.add("persona-relative");let Se=12,Oe=()=>{var l;return(l=ve.label)!=null?l:""},Ct=()=>{var l;return(l=ve.iconName)!=null?l:"arrow-down"},jt=()=>ve.enabled!==!1,dt=h("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");dt.type="button",dt.style.display="none",dt.setAttribute("data-persona-scroll-to-bottom","true");let zt=h("span","persona-flex persona-items-center"),yt=h("span","");dt.append(zt,yt),$.appendChild(dt);let Ze=()=>{let m=st.style.display==="none"?0:st.offsetHeight;dt.style.bottom=`${m+Se}px`};Ze();let bt=()=>{let l=!!Oe();dt.setAttribute("aria-label",Oe()||"Jump to latest"),dt.title=Oe(),dt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),zt.innerHTML="";let m=be(Ct(),"14px","currentColor",2);m?(zt.appendChild(m),zt.style.display=""):zt.style.display="none",yt.textContent=Oe(),yt.style.display=l?"":"none"};bt();let De=null,qt=null,Gn=s.find(l=>l.renderHeader);if(Gn!=null&&Gn.renderHeader){let l=Gn.renderHeader({config:n,defaultRenderer:()=>{let m=Sr({config:n,showClose:C});return to($,m,n),m.header},onClose:()=>Rt(!1,"user")});if(l){let m=$.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),ot=l)}}let nr=()=>{var m,y,A,I;if(!se)return;if(ue=!0,!K&&se&&(K=ld({buffer:se,getFullHistory:()=>se.getAllFromStore(),onClose:()=>$n(),config:n,plugins:s})),K&&(q.style.display="none",(m=st.parentNode)==null||m.insertBefore(K.element,st),K.update()),et){et.style.boxShadow=`inset 0 0 0 1.5px ${Sn.actionIconColor}`;let R=(I=(A=(y=n.features)==null?void 0:y.eventStream)==null?void 0:A.classNames)==null?void 0:I.toggleButtonActive;R&&R.split(/\s+/).forEach(B=>B&&et.classList.add(B))}let l=()=>{if(!ue)return;let R=Date.now();R-te>=200&&(K==null||K.update(),te=R),U=requestAnimationFrame(l)};te=0,U=requestAnimationFrame(l),ir(),o.emit("eventStream:opened",{timestamp:Date.now()})},$n=()=>{var l,m,y;if(ue){if(ue=!1,K&&K.element.remove(),q.style.display="",et){et.style.boxShadow="";let A=(y=(m=(l=n.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:y.toggleButtonActive;A&&A.split(/\s+/).forEach(I=>I&&et.classList.remove(I))}U!==null&&(cancelAnimationFrame(U),U=null),ir(),o.emit("eventStream:closed",{timestamp:Date.now()})}},et=null;if(oe){let l=(si=(oi=n.features)==null?void 0:oi.eventStream)==null?void 0:si.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:"");et=h("button",m),et.style.width="28px",et.style.height="28px",et.style.color=Sn.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let y=be("activity","18px","currentColor",1.5);y&&et.appendChild(y);let A=ae.clearChatButtonWrapper,I=ae.closeButtonWrapper,R=A||I;R&&R.parentNode===ot?ot.insertBefore(et,R):ot.appendChild(et),et.addEventListener("click",()=>{ue?$n():nr()})}let Tr=l=>{var A,I,R;let m=n.attachments;if(!(m!=null&&m.enabled))return;let y=l.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let B=l.querySelector("[data-persona-composer-form]");B!=null&&B.parentNode?B.parentNode.insertBefore(y,B):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let B=h("input");B.type="file",B.accept=((A=m.allowedTypes)!=null?A:dr).join(","),B.multiple=((I=m.maxFiles)!=null?I:4)>1,B.style.display="none",B.setAttribute("aria-label",(R=m.buttonTooltipText)!=null?R:"Attach files"),l.appendChild(B)}},Kn=s.find(l=>l.renderComposer);if(Kn!=null&&Kn.renderComposer){let l=n.composer,m=Kn.renderComposer({config:n,defaultRenderer:()=>$o({config:n}).footer,onSubmit:y=>{var B;if(!D||D.isStreaming())return;let A=y.trim(),I=(B=De==null?void 0:De.hasAttachments())!=null?B:!1;if(!A&&!I)return;let R;I&&(R=[],R.push(...De.getContentParts()),A&&R.push(ps(A))),D.sendMessage(A,{contentParts:R}),I&&De.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{$e==null||$e.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y},n.agent&&(n.agent={...n.agent,model:y})},onVoiceToggle:((ai=n.voiceRecognition)==null?void 0:ai.enabled)===!0?()=>{qt==null||qt()}:void 0});m&&(st.replaceWith(m),st=m)}let Mr=l=>{let m=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),I=l.querySelector("[data-persona-composer-mic]"),R=l.querySelector("[data-persona-composer-status]");m&&(ct=m),y&&(ee=y),A&&(le=A),I&&(z=I,He=I.parentElement),R&&(Dt=R);let B=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");B&&(_e=B);let V=l.querySelector(".persona-attachment-button");V&&(ye=V,ht=V.parentElement),$e=l.querySelector('input[type="file"]'),ce=l.querySelector(".persona-attachment-previews");let N=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");N&&(nn=N)};Tr(st),Mr(st);let Wn=(ii=n.layout)==null?void 0:ii.contentMaxWidth;if(Wn&&ct&&(ct.style.maxWidth=Wn,ct.style.marginLeft="auto",ct.style.marginRight="auto"),Wn&&_e&&(_e.style.maxWidth=Wn,_e.style.marginLeft="auto",_e.style.marginRight="auto"),Wn&&ce&&(ce.style.maxWidth=Wn,ce.style.marginLeft="auto",ce.style.marginRight="auto"),(li=n.attachments)!=null&&li.enabled&&$e&&ce){De=eo.fromConfig(n.attachments),De.setPreviewsContainer(ce),$e.addEventListener("change",y=>{let A=y.target;De==null||De.handleFileSelect(A.files),A.value=""});let l=n.attachments.dropOverlay,m=wd(l);$.appendChild(m)}(()=>{var A,I;let l=(I=(A=n.layout)==null?void 0:A.slots)!=null?I:{},m=R=>{switch(R){case"body-top":return $.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return de;case"footer-top":return _e;case"composer":return ct;case"footer-bottom":return Dt;default:return null}},y=(R,B)=>{var V;switch(R){case"header-left":case"header-center":case"header-right":if(R==="header-left")ot.insertBefore(B,ot.firstChild);else if(R==="header-right")ot.appendChild(B);else{let N=ot.querySelector(".persona-flex-col");N?(V=N.parentNode)==null||V.insertBefore(B,N.nextSibling):ot.appendChild(B)}break;case"body-top":{let N=q.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith(B):q.insertBefore(B,q.firstChild);break}case"body-bottom":q.appendChild(B);break;case"footer-top":_e.replaceWith(B);break;case"footer-bottom":Dt.replaceWith(B);break;default:break}};for(let[R,B]of Object.entries(l))if(B)try{let V=B({config:n,defaultContent:()=>m(R)});V&&y(R,V)}catch(V){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${R}":`,V)}})();let ur=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let A=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!A)return;let I=A.getAttribute("data-message-id");if(!I)return;let R=y.getAttribute("data-bubble-type");R==="reasoning"?(ro.has(I)?ro.delete(I):ro.add(I),sd(I,A)):R==="tool"&&(oo.has(I)?oo.delete(I):oo.add(I),ad(I,A,n)),Hn.delete(I)};de.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),ur(l))}),de.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),ur(l))});let rr=new Map;de.addEventListener("click",l=>{var B;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.closest("[data-actions-for]");if(!A)return;let I=A.getAttribute("data-actions-for");if(!I)return;let R=y.getAttribute("data-action");if(R==="copy"){let N=D.getMessages().find(xe=>xe.id===I);if(N&&fe.onCopy){let xe=N.content||"";navigator.clipboard.writeText(xe).then(()=>{y.classList.add("persona-message-action-success");let Ee=be("check",14,"currentColor",2);Ee&&(y.innerHTML="",y.appendChild(Ee)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Me=be("copy",14,"currentColor",2);Me&&(y.innerHTML="",y.appendChild(Me))},2e3)}).catch(Ee=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",Ee)}),fe.onCopy(N)}}else if(R==="upvote"||R==="downvote")if(((B=rr.get(I))!=null?B:null)===R)rr.delete(I),y.classList.remove("persona-message-action-active");else{let xe=R==="upvote"?"downvote":"upvote",Ee=A.querySelector(`[data-action="${xe}"]`);Ee&&Ee.classList.remove("persona-message-action-active"),rr.set(I,R),y.classList.add("persona-message-action-active");let Ae=D.getMessages().find(Ie=>Ie.id===I);Ae&&fe.onFeedback&&fe.onFeedback({type:R,messageId:Ae.id,message:Ae})}}),de.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.closest(".persona-approval-bubble");if(!A)return;let I=A.getAttribute("data-message-id");if(!I)return;let R=y.getAttribute("data-approval-action");if(!R)return;let B=R==="approve"?"approved":"denied",N=D.getMessages().find(Ee=>Ee.id===I);if(!(N!=null&&N.approval))return;let xe=A.querySelector("[data-approval-buttons]");xe&&xe.querySelectorAll("button").forEach(Me=>{Me.disabled=!0,Me.style.opacity="0.5",Me.style.cursor="not-allowed"}),D.resolveApproval(N.approval,B)});let at=null,An=null,_n={artifacts:[],selectedId:null},dn=!1,mr={current:null};de.addEventListener("click",l=>{var Me,Ae,Ie,ze,mt;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.getAttribute("data-download-artifact");if(!A||((Ie=(Ae=(Me=n.features)==null?void 0:Me.artifacts)==null?void 0:Ae.onArtifactAction)==null?void 0:Ie.call(Ae,{type:"download",artifactId:A}))===!0)return;let R=D.getArtifactById(A),B=R==null?void 0:R.markdown,V=(R==null?void 0:R.title)||"artifact";if(!B){let Ke=y.closest("[data-open-artifact]"),_=Ke==null?void 0:Ke.closest("[data-message-id]"),Pe=_==null?void 0:_.getAttribute("data-message-id");if(Pe){let Ce=D.getMessages().find(Fe=>Fe.id===Pe);if(Ce!=null&&Ce.rawContent)try{let Fe=JSON.parse(Ce.rawContent);B=(ze=Fe==null?void 0:Fe.props)==null?void 0:ze.markdown,V=((mt=Fe==null?void 0:Fe.props)==null?void 0:mt.title)||V}catch{}}}if(!B)return;let N=new Blob([B],{type:"text/markdown"}),xe=URL.createObjectURL(N),Ee=document.createElement("a");Ee.href=xe,Ee.download=`${V}.md`,Ee.click(),URL.revokeObjectURL(xe)}),de.addEventListener("click",l=>{var R,B,V;let y=l.target.closest("[data-open-artifact]");if(!y)return;let A=y.getAttribute("data-open-artifact");!A||((V=(B=(R=n.features)==null?void 0:R.artifacts)==null?void 0:B.onArtifactAction)==null?void 0:V.call(B,{type:"open",artifactId:A}))===!0||(l.preventDefault(),l.stopPropagation(),dn=!1,D.selectArtifact(A),Tn())}),de.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let En=null,At=null,pn=null,Rn=null,gr=()=>{};function or(){Rn==null||Rn(),Rn=null}let fr=()=>{var B;if(!En||!At)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((B=e.ownerDocument.defaultView)!=null?B:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){At.style.removeProperty("position"),At.style.removeProperty("left"),At.style.removeProperty("top"),At.style.removeProperty("bottom"),At.style.removeProperty("width"),At.style.removeProperty("z-index");return}let A=En.firstElementChild;if(!A||A===At)return;let I=10;At.style.position="absolute",At.style.top="0",At.style.bottom="0",At.style.width=`${I}px`,At.style.zIndex="5";let R=A.offsetWidth-I/2;At.style.left=`${Math.max(0,R)}px`},Xn=()=>{},Tn=()=>{var y,A,I,R,B;if(!at||!On(n))return;Es(e,n),Ts(e,n),Xn();let l=(R=(I=(A=(y=n.features)==null?void 0:y.artifacts)==null?void 0:A.layout)==null?void 0:I.narrowHostMaxWidth)!=null?R:520,m=W.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),at.update(_n),dn?(at.setMobileOpen(!1),at.element.classList.add("persona-hidden"),(B=at.backdrop)==null||B.classList.add("persona-hidden")):_n.artifacts.length>0&&(at.element.classList.remove("persona-hidden"),at.setMobileOpen(!0)),gr()};if(On(n)){W.style.position="relative";let l=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild($),at=pd(n,{onSelect:y=>{var A;return(A=mr.current)==null?void 0:A.selectArtifact(y)},onDismiss:()=>{dn=!0,Tn()}}),at.element.classList.add("persona-hidden"),En=m,m.appendChild(l),m.appendChild(at.element),at.backdrop&&W.appendChild(at.backdrop),W.appendChild(m),gr=()=>{var A,I,R,B;if(!En||!at)return;if(!(((R=(I=(A=n.features)==null?void 0:A.artifacts)==null?void 0:I.layout)==null?void 0:R.resizable)===!0)){pn==null||pn(),pn=null,or(),At&&(At.remove(),At=null),at.element.style.removeProperty("width"),at.element.style.removeProperty("maxWidth");return}if(!At){let V=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");V.setAttribute("role","separator"),V.setAttribute("aria-orientation","vertical"),V.setAttribute("aria-label","Resize artifacts panel"),V.tabIndex=0;let N=e.ownerDocument,xe=(B=N.defaultView)!=null?B:window,Ee=Me=>{var _,Pe;if(!at||Me.button!==0||e.classList.contains("persona-artifact-narrow-host")||xe.innerWidth<=640)return;Me.preventDefault(),or();let Ae=Me.clientX,Ie=at.element.getBoundingClientRect().width,ze=(Pe=(_=n.features)==null?void 0:_.artifacts)==null?void 0:Pe.layout,mt=Be=>{let Ce=En.getBoundingClientRect().width,Fe=e.classList.contains("persona-artifact-appearance-seamless"),St=Fe?0:fd(En,xe),vt=Fe?0:V.getBoundingClientRect().width||6,Gt=Ie-(Be.clientX-Ae),sn=hd(Gt,Ce,St,vt,ze==null?void 0:ze.resizableMinWidth,ze==null?void 0:ze.resizableMaxWidth);at.element.style.width=`${sn}px`,at.element.style.maxWidth="none",fr()},Ke=()=>{N.removeEventListener("pointermove",mt),N.removeEventListener("pointerup",Ke),N.removeEventListener("pointercancel",Ke),Rn=null;try{V.releasePointerCapture(Me.pointerId)}catch{}};Rn=Ke,N.addEventListener("pointermove",mt),N.addEventListener("pointerup",Ke),N.addEventListener("pointercancel",Ke);try{V.setPointerCapture(Me.pointerId)}catch{}};V.addEventListener("pointerdown",Ee),At=V,En.insertBefore(V,at.element),pn=()=>{V.removeEventListener("pointerdown",Ee)}}if(At){let V=_n.artifacts.length>0&&!dn;At.classList.toggle("persona-hidden",!V),fr()}},Xn=()=>{var xe,Ee,Me,Ae,Ie,ze,mt,Ke,_,Pe,Be,Ce,Fe,St;if(!C||!at||((Ee=(xe=n.launcher)==null?void 0:xe.sidebarMode)!=null?Ee:!1)||en(n)&&Jn(n).reveal==="emerge")return;let A=(Me=e.ownerDocument.defaultView)!=null?Me:window,I=(Ie=(Ae=n.launcher)==null?void 0:Ae.mobileFullscreen)!=null?Ie:!0,R=(mt=(ze=n.launcher)==null?void 0:ze.mobileBreakpoint)!=null?mt:640;if(I&&A.innerWidth<=R||!gd(n,C))return;let B=(Pe=(_=(Ke=n.launcher)==null?void 0:Ke.width)!=null?_:n.launcherWidth)!=null?Pe:Nn,V=(St=(Fe=(Ce=(Be=n.features)==null?void 0:Be.artifacts)==null?void 0:Ce.layout)==null?void 0:Fe.expandedPanelWidth)!=null?St:"min(720px, calc(100vw - 24px))";_n.artifacts.length>0&&!dn?(W.style.width=V,W.style.maxWidth=V):(W.style.width=B,W.style.maxWidth=B)},typeof ResizeObserver!="undefined"&&(An=new ResizeObserver(()=>{Tn()}),An.observe(W))}else W.appendChild($);e.appendChild(j);let Zn=()=>{var vt,Gt,sn,Te,bn,an,Un,rt,gt,xn,cr,Je,Mt,Rr,Hr,Qo,es,ts,$s,_s,Ut,ns,vo;let l=en(n),m=(Gt=(vt=n.launcher)==null?void 0:vt.sidebarMode)!=null?Gt:!1,y=l||m||((Te=(sn=n.launcher)==null?void 0:sn.fullHeight)!=null?Te:!1),A=((bn=n.launcher)==null?void 0:bn.enabled)===!1,I=(Un=(an=n.theme)==null?void 0:an.components)==null?void 0:Un.panel,R=bs(n),B=(vn,Fn)=>{var Yr;return vn==null||vn===""?Fn:(Yr=Ro(R,vn))!=null?Yr:vn},V=(rt=e.ownerDocument.defaultView)!=null?rt:window,N=(xn=(gt=n.launcher)==null?void 0:gt.mobileFullscreen)!=null?xn:!0,xe=(Je=(cr=n.launcher)==null?void 0:cr.mobileBreakpoint)!=null?Je:640,Ee=V.innerWidth<=xe,Me=N&&Ee&&C,Ae=(Rr=(Mt=n.launcher)==null?void 0:Mt.position)!=null?Rr:"bottom-left",Ie=Ae==="bottom-left"||Ae==="top-left",ze=(Qo=(Hr=n.launcher)==null?void 0:Hr.zIndex)!=null?Qo:wn,mt=m||Me?"none":"1px solid var(--persona-border)",Ke=Me?"none":m?Ie?"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&&!Me&&(Ke="none",mt="none");let _=m||Me?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Pe=B(I==null?void 0:I.border,mt),Be=B(I==null?void 0:I.shadow,Ke),Ce=B(I==null?void 0:I.borderRadius,_);if(e.style.cssText="",j.style.cssText="",W.style.cssText="",$.style.cssText="",q.style.cssText="",st.style.cssText="",Me){j.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"),j.style.cssText=`
22
+ `,E.addEventListener("click",()=>{d=P,S.forEach((Y,Q)=>{let G=Q<P;Y.classList.toggle("selected",G),Y.setAttribute("aria-checked",Q===P-1?"true":"false")})}),S.push(E),C.appendChild(E)}f.appendChild(C);let k=null;if(u){let P=document.createElement("div");P.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=o,k.rows=3,k.setAttribute("aria-label","Additional comments"),P.appendChild(k),f.appendChild(P)}let H=document.createElement("div");H.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=i,w.addEventListener("click",()=>{t==null||t(),p.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(d===null){C.classList.add("persona-feedback-shake"),setTimeout(()=>C.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let P=(k==null?void 0:k.value.trim())||void 0;await r(d,P),p.remove()}catch(P){L.disabled=!1,L.textContent=a,console.error("[CSAT Feedback] Failed to submit:",P)}}),H.appendChild(w),H.appendChild(L),f.appendChild(H),p.appendChild(f),p}function xa(e){let{onSubmit:r,onDismiss:t,title:n="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:u=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-nps",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let M=document.createElement("h3");M.className="persona-feedback-title",M.textContent=n,v.appendChild(M);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=s,v.appendChild(C),g.appendChild(v);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=c;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=p,k.appendChild(H),k.appendChild(w);let L=document.createElement("div");L.className="persona-feedback-numbers";let P=[];for(let O=0;O<=10;O++){let re=document.createElement("button");re.type="button",re.className="persona-feedback-rating-btn persona-feedback-number-btn",re.setAttribute("role","radio"),re.setAttribute("aria-checked","false"),re.setAttribute("aria-label",`Rating ${O} out of 10`),re.textContent=String(O),re.dataset.rating=String(O),O<=6?re.classList.add("persona-feedback-detractor"):O<=8?re.classList.add("persona-feedback-passive"):re.classList.add("persona-feedback-promoter"),re.addEventListener("click",()=>{f=O,P.forEach((we,oe)=>{we.classList.toggle("selected",oe===O),we.setAttribute("aria-checked",oe===O?"true":"false")})}),P.push(re),L.appendChild(re)}S.appendChild(k),S.appendChild(L),g.appendChild(S);let E=null;if(u){let O=document.createElement("div");O.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=o,E.rows=3,E.setAttribute("aria-label","Additional comments"),O.appendChild(E),g.appendChild(O)}let Y=document.createElement("div");Y.className="persona-feedback-actions";let Q=document.createElement("button");Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-skip",Q.textContent=i,Q.addEventListener("click",()=>{t==null||t(),d.remove()});let G=document.createElement("button");return G.type="button",G.className="persona-feedback-btn persona-feedback-btn-submit",G.textContent=a,G.addEventListener("click",async()=>{if(f===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}G.disabled=!0,G.textContent="Submitting...";try{let O=(E==null?void 0:E.value.trim())||void 0;await r(f,O),d.remove()}catch(O){G.disabled=!1,G.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),Y.appendChild(Q),Y.appendChild(G),g.appendChild(Y),d.appendChild(g),d}var io="persona-chat-history",Wu=30*1e3,Ru={"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 Hu(e){var n,s,o;if(!e)return[];let r=[],t=Array.from((n=e.items)!=null?n:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){r.push(i);continue}let u=(s=Ru[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${u}`,{type:i.type,lastModified:Date.now()}))}if(r.length>0)return r;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&r.push(a);return r}function Is(e){if(!e)return!1;let r=e.types;return r?typeof r.contains=="function"?r.contains("Files"):Array.from(r).includes("Files"):!1}function Bu(e){var r,t,n,s,o,a,i,u,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(r=e.storage)!=null?r:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(n=e.persist)==null?void 0:n.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(u=(i=e.persist)==null?void 0:i.focusInput)!=null?u:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function Du(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var va=e=>!e||typeof e!="object"?{}:{...e},vd=e=>e.map(r=>({...r,streaming:!1})),Cd=(e,r,t)=>{let n=e!=null&&e.markdown?Gr(e.markdown):null,s=To(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(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."),o=>{var c,p,d;let a=(c=o.text)!=null?c:"",i=(p=o.message.rawContent)!=null?p:null;if(r){let f=r.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&t&&t())}let u;return e!=null&&e.postprocessMessage?u=e.postprocessMessage({...o,text:a,raw:(d=i!=null?i:o.text)!=null?d:""}):n?u=n(a):u=Eo(a),s?s(u):u}};function wd(e){var i,u,c,p;let r=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&r.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&r.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&r.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&r.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&r.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&r.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&r.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",n=(u=e==null?void 0:e.iconSize)!=null?u:"48px",s=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=be(t,n,s,o);if(a&&r.appendChild(a),e!=null&&e.label){let d=h("span","persona-drop-overlay-label");d.textContent=e.label,r.appendChild(d)}return r}var Ca=(e,r,t)=>{var Ha,Ba,Da,Fa,Na,Oa,$a,_a,ja,za,qa,Ua,Va,Ja,Ya,Ga,Ka,Xa,Za,Qa,ei,ti,ni,ri,oi,si,ai,ii,li,ci,di,pi,ui,mi,gi,fi,hi,yi,bi,xi;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 n=Xs(r),s=Ms.getForInstance(n.plugins);n.components&&Ar.registerAll(n.components);let o=bd(),a=(Ha=n.storageAdapter)!=null?Ha:ma(),i={},u=null,c=!1,p=l=>{if(n.onStateLoaded)try{let m=n.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:y,open:A}=m;return A&&(c=!0),y}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")u=l.then(m=>{let y=m!=null?m:{messages:[],metadata:{}};return p(y)});else{let m=l!=null?l:{messages:[],metadata:{}},y=p(m);y.metadata&&(i=va(y.metadata)),(Ba=y.messages)!=null&&Ba.length&&(n={...n,initialMessages:y.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(n.onStateLoaded)try{let l=p({messages:[],metadata:{}});(Da=l.messages)!=null&&Da.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let d=()=>i,f=l=>{var y;i=(y=l({...i}))!=null?y:{},uo()},g=n.actionParsers&&n.actionParsers.length?n.actionParsers:[ks],v=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ao.message,ao.messageAndClick],M=Ls({parsers:g,handlers:v,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let C=(Na=(Fa=n.launcher)==null?void 0:Fa.enabled)!=null?Na:!0,S=($a=(Oa=n.launcher)==null?void 0:Oa.autoExpand)!=null?$a:!1,k=(_a=n.autoFocusInput)!=null?_a:!1,H=S,w=C,L=(za=(ja=n.layout)==null?void 0:ja.header)==null?void 0:za.layout,P=!1,E=C?S:!0,Y=!1,Q=null,G=()=>{Y=!0,Q&&clearTimeout(Q),Q=setTimeout(()=>{Y&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Y=!1)},1e4)},O=Cd(n,M,G),re=(Ua=(qa=n.features)==null?void 0:qa.showReasoning)!=null?Ua:!0,we=(Ja=(Va=n.features)==null?void 0:Va.showToolCalls)!=null?Ja:!0,oe=(Ga=(Ya=n.features)==null?void 0:Ya.showEventStreamToggle)!=null?Ga:!1,ve=(Xa=(Ka=n.features)==null?void 0:Ka.scrollToBottom)!=null?Xa:{},ge=`${(Qa=typeof n.persistState=="object"?(Za=n.persistState)==null?void 0:Za.keyPrefix:void 0)!=null?Qa:"persona-"}event-stream`,ke=oe?new zo(ge):null,Le=(ni=(ti=(ei=n.features)==null?void 0:ei.eventStream)==null?void 0:ti.maxEvents)!=null?ni:2e3,se=oe?new jo(Le,ke):null,K=null,ue=!1,U=null,te=0;ke==null||ke.open().then(()=>se==null?void 0:se.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let fe={onCopy:l=>{var m,y;o.emit("message:copy",l),D!=null&&D.isClientTokenMode()&&D.submitMessageFeedback(l.id,"copy").catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(y=(m=n.messageActions)==null?void 0:m.onCopy)==null||y.call(m,l)},onFeedback:l=>{var m,y;o.emit("message:feedback",l),D!=null&&D.isClientTokenMode()&&D.submitMessageFeedback(l.messageId,l.type).catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(y=(m=n.messageActions)==null?void 0:m.onFeedback)==null||y.call(m,l)}},pe=(ri=n.statusIndicator)!=null?ri:{},Re=l=>{var m,y,A,I;return l==="idle"?(m=pe.idleText)!=null?m:cn.idle:l==="connecting"?(y=pe.connectingText)!=null?y:cn.connecting:l==="connected"?(A=pe.connectedText)!=null?A:cn.connected:l==="error"?(I=pe.errorText)!=null?I:cn.error:cn[l]};function Xe(l,m,y,A){if(A==="idle"&&y.idleLink){l.textContent="";let I=document.createElement("a");I.href=y.idleLink,I.target="_blank",I.rel="noopener noreferrer",I.textContent=m,I.style.color="inherit",I.style.textDecoration="none",l.appendChild(I)}else l.textContent=m}let{wrapper:j,panel:W}=ed(n),ae=td(n,C),{container:$,body:q,messagesWrapper:de,suggestions:_e,textarea:ee,sendButton:le,sendButtonWrapper:It,composerForm:dt,statusText:Dt,introTitle:Xt,introSubtitle:je,closeButton:me,iconHolder:Ne,headerTitle:Wt,headerSubtitle:Rt,header:ot,footer:st,actionsRow:nn,leftActions:tn,rightActions:rn}=ae,z=ae.micButton,He=ae.micButtonWrapper,ye=ae.attachmentButton,ht=ae.attachmentButtonWrapper,$e=ae.attachmentInput,ce=ae.attachmentPreviewsContainer;$.classList.add("persona-relative"),q.classList.add("persona-relative");let Se=12,Oe=()=>{var l;return(l=ve.label)!=null?l:""},Ct=()=>{var l;return(l=ve.iconName)!=null?l:"arrow-down"},jt=()=>ve.enabled!==!1,pt=h("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");pt.type="button",pt.style.display="none",pt.setAttribute("data-persona-scroll-to-bottom","true");let zt=h("span","persona-flex persona-items-center"),yt=h("span","");pt.append(zt,yt),$.appendChild(pt);let Ze=()=>{let m=st.style.display==="none"?0:st.offsetHeight;pt.style.bottom=`${m+Se}px`};Ze();let bt=()=>{let l=!!Oe();pt.setAttribute("aria-label",Oe()||"Jump to latest"),pt.title=Oe(),pt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),zt.innerHTML="";let m=be(Ct(),"14px","currentColor",2);m?(zt.appendChild(m),zt.style.display=""):zt.style.display="none",yt.textContent=Oe(),yt.style.display=l?"":"none"};bt();let De=null,qt=null,Gn=s.find(l=>l.renderHeader);if(Gn!=null&&Gn.renderHeader){let l=Gn.renderHeader({config:n,defaultRenderer:()=>{let m=Sr({config:n,showClose:C});return to($,m,n),m.header},onClose:()=>Ht(!1,"user")});if(l){let m=$.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),ot=l)}}let nr=()=>{var m,y,A,I;if(!se)return;if(ue=!0,!K&&se&&(K=ld({buffer:se,getFullHistory:()=>se.getAllFromStore(),onClose:()=>$n(),config:n,plugins:s})),K&&(q.style.display="none",(m=st.parentNode)==null||m.insertBefore(K.element,st),K.update()),et){et.style.boxShadow=`inset 0 0 0 1.5px ${Sn.actionIconColor}`;let R=(I=(A=(y=n.features)==null?void 0:y.eventStream)==null?void 0:A.classNames)==null?void 0:I.toggleButtonActive;R&&R.split(/\s+/).forEach(B=>B&&et.classList.add(B))}let l=()=>{if(!ue)return;let R=Date.now();R-te>=200&&(K==null||K.update(),te=R),U=requestAnimationFrame(l)};te=0,U=requestAnimationFrame(l),ir(),o.emit("eventStream:opened",{timestamp:Date.now()})},$n=()=>{var l,m,y;if(ue){if(ue=!1,K&&K.element.remove(),q.style.display="",et){et.style.boxShadow="";let A=(y=(m=(l=n.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:y.toggleButtonActive;A&&A.split(/\s+/).forEach(I=>I&&et.classList.remove(I))}U!==null&&(cancelAnimationFrame(U),U=null),ir(),o.emit("eventStream:closed",{timestamp:Date.now()})}},et=null;if(oe){let l=(si=(oi=n.features)==null?void 0:oi.eventStream)==null?void 0:si.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:"");et=h("button",m),et.style.width="28px",et.style.height="28px",et.style.color=Sn.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let y=be("activity","18px","currentColor",1.5);y&&et.appendChild(y);let A=ae.clearChatButtonWrapper,I=ae.closeButtonWrapper,R=A||I;R&&R.parentNode===ot?ot.insertBefore(et,R):ot.appendChild(et),et.addEventListener("click",()=>{ue?$n():nr()})}let Tr=l=>{var A,I,R;let m=n.attachments;if(!(m!=null&&m.enabled))return;let y=l.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let B=l.querySelector("[data-persona-composer-form]");B!=null&&B.parentNode?B.parentNode.insertBefore(y,B):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let B=h("input");B.type="file",B.accept=((A=m.allowedTypes)!=null?A:dr).join(","),B.multiple=((I=m.maxFiles)!=null?I:4)>1,B.style.display="none",B.setAttribute("aria-label",(R=m.buttonTooltipText)!=null?R:"Attach files"),l.appendChild(B)}},Kn=s.find(l=>l.renderComposer);if(Kn!=null&&Kn.renderComposer){let l=n.composer,m=Kn.renderComposer({config:n,defaultRenderer:()=>$o({config:n}).footer,onSubmit:y=>{var B;if(!D||D.isStreaming())return;let A=y.trim(),I=(B=De==null?void 0:De.hasAttachments())!=null?B:!1;if(!A&&!I)return;let R;I&&(R=[],R.push(...De.getContentParts()),A&&R.push(ps(A))),D.sendMessage(A,{contentParts:R}),I&&De.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{$e==null||$e.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y},n.agent&&(n.agent={...n.agent,model:y})},onVoiceToggle:((ai=n.voiceRecognition)==null?void 0:ai.enabled)===!0?()=>{qt==null||qt()}:void 0});m&&(st.replaceWith(m),st=m)}let Mr=l=>{let m=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),I=l.querySelector("[data-persona-composer-mic]"),R=l.querySelector("[data-persona-composer-status]");m&&(dt=m),y&&(ee=y),A&&(le=A),I&&(z=I,He=I.parentElement),R&&(Dt=R);let B=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");B&&(_e=B);let V=l.querySelector(".persona-attachment-button");V&&(ye=V,ht=V.parentElement),$e=l.querySelector('input[type="file"]'),ce=l.querySelector(".persona-attachment-previews");let N=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");N&&(nn=N)};Tr(st),Mr(st);let Wn=(ii=n.layout)==null?void 0:ii.contentMaxWidth;if(Wn&&dt&&(dt.style.maxWidth=Wn,dt.style.marginLeft="auto",dt.style.marginRight="auto"),Wn&&_e&&(_e.style.maxWidth=Wn,_e.style.marginLeft="auto",_e.style.marginRight="auto"),Wn&&ce&&(ce.style.maxWidth=Wn,ce.style.marginLeft="auto",ce.style.marginRight="auto"),(li=n.attachments)!=null&&li.enabled&&$e&&ce){De=eo.fromConfig(n.attachments),De.setPreviewsContainer(ce),$e.addEventListener("change",y=>{let A=y.target;De==null||De.handleFileSelect(A.files),A.value=""});let l=n.attachments.dropOverlay,m=wd(l);$.appendChild(m)}(()=>{var A,I;let l=(I=(A=n.layout)==null?void 0:A.slots)!=null?I:{},m=R=>{switch(R){case"body-top":return $.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return de;case"footer-top":return _e;case"composer":return dt;case"footer-bottom":return Dt;default:return null}},y=(R,B)=>{var V;switch(R){case"header-left":case"header-center":case"header-right":if(R==="header-left")ot.insertBefore(B,ot.firstChild);else if(R==="header-right")ot.appendChild(B);else{let N=ot.querySelector(".persona-flex-col");N?(V=N.parentNode)==null||V.insertBefore(B,N.nextSibling):ot.appendChild(B)}break;case"body-top":{let N=q.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith(B):q.insertBefore(B,q.firstChild);break}case"body-bottom":q.appendChild(B);break;case"footer-top":_e.replaceWith(B);break;case"footer-bottom":Dt.replaceWith(B);break;default:break}};for(let[R,B]of Object.entries(l))if(B)try{let V=B({config:n,defaultContent:()=>m(R)});V&&y(R,V)}catch(V){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${R}":`,V)}})();let ur=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let A=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!A)return;let I=A.getAttribute("data-message-id");if(!I)return;let R=y.getAttribute("data-bubble-type");R==="reasoning"?(ro.has(I)?ro.delete(I):ro.add(I),sd(I,A)):R==="tool"&&(oo.has(I)?oo.delete(I):oo.add(I),ad(I,A,n)),Hn.delete(I)};de.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),ur(l))}),de.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),ur(l))});let rr=new Map;de.addEventListener("click",l=>{var B;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.closest("[data-actions-for]");if(!A)return;let I=A.getAttribute("data-actions-for");if(!I)return;let R=y.getAttribute("data-action");if(R==="copy"){let N=D.getMessages().find(xe=>xe.id===I);if(N&&fe.onCopy){let xe=N.content||"";navigator.clipboard.writeText(xe).then(()=>{y.classList.add("persona-message-action-success");let Ee=be("check",14,"currentColor",2);Ee&&(y.innerHTML="",y.appendChild(Ee)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Me=be("copy",14,"currentColor",2);Me&&(y.innerHTML="",y.appendChild(Me))},2e3)}).catch(Ee=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",Ee)}),fe.onCopy(N)}}else if(R==="upvote"||R==="downvote")if(((B=rr.get(I))!=null?B:null)===R)rr.delete(I),y.classList.remove("persona-message-action-active");else{let xe=R==="upvote"?"downvote":"upvote",Ee=A.querySelector(`[data-action="${xe}"]`);Ee&&Ee.classList.remove("persona-message-action-active"),rr.set(I,R),y.classList.add("persona-message-action-active");let Ae=D.getMessages().find(Ie=>Ie.id===I);Ae&&fe.onFeedback&&fe.onFeedback({type:R,messageId:Ae.id,message:Ae})}}),de.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.closest(".persona-approval-bubble");if(!A)return;let I=A.getAttribute("data-message-id");if(!I)return;let R=y.getAttribute("data-approval-action");if(!R)return;let B=R==="approve"?"approved":"denied",N=D.getMessages().find(Ee=>Ee.id===I);if(!(N!=null&&N.approval))return;let xe=A.querySelector("[data-approval-buttons]");xe&&xe.querySelectorAll("button").forEach(Me=>{Me.disabled=!0,Me.style.opacity="0.5",Me.style.cursor="not-allowed"}),D.resolveApproval(N.approval,B)});let at=null,An=null,_n={artifacts:[],selectedId:null},dn=!1,mr={current:null};de.addEventListener("click",l=>{var Me,Ae,Ie,ze,mt;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.getAttribute("data-download-artifact");if(!A||((Ie=(Ae=(Me=n.features)==null?void 0:Me.artifacts)==null?void 0:Ae.onArtifactAction)==null?void 0:Ie.call(Ae,{type:"download",artifactId:A}))===!0)return;let R=D.getArtifactById(A),B=R==null?void 0:R.markdown,V=(R==null?void 0:R.title)||"artifact";if(!B){let Ke=y.closest("[data-open-artifact]"),_=Ke==null?void 0:Ke.closest("[data-message-id]"),Pe=_==null?void 0:_.getAttribute("data-message-id");if(Pe){let Ce=D.getMessages().find(Fe=>Fe.id===Pe);if(Ce!=null&&Ce.rawContent)try{let Fe=JSON.parse(Ce.rawContent);B=(ze=Fe==null?void 0:Fe.props)==null?void 0:ze.markdown,V=((mt=Fe==null?void 0:Fe.props)==null?void 0:mt.title)||V}catch{}}}if(!B)return;let N=new Blob([B],{type:"text/markdown"}),xe=URL.createObjectURL(N),Ee=document.createElement("a");Ee.href=xe,Ee.download=`${V}.md`,Ee.click(),URL.revokeObjectURL(xe)}),de.addEventListener("click",l=>{var R,B,V;let y=l.target.closest("[data-open-artifact]");if(!y)return;let A=y.getAttribute("data-open-artifact");!A||((V=(B=(R=n.features)==null?void 0:R.artifacts)==null?void 0:B.onArtifactAction)==null?void 0:V.call(B,{type:"open",artifactId:A}))===!0||(l.preventDefault(),l.stopPropagation(),dn=!1,D.selectArtifact(A),Tn())}),de.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let En=null,At=null,pn=null,Rn=null,gr=()=>{};function or(){Rn==null||Rn(),Rn=null}let fr=()=>{var B;if(!En||!At)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((B=e.ownerDocument.defaultView)!=null?B:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){At.style.removeProperty("position"),At.style.removeProperty("left"),At.style.removeProperty("top"),At.style.removeProperty("bottom"),At.style.removeProperty("width"),At.style.removeProperty("z-index");return}let A=En.firstElementChild;if(!A||A===At)return;let I=10;At.style.position="absolute",At.style.top="0",At.style.bottom="0",At.style.width=`${I}px`,At.style.zIndex="5";let R=A.offsetWidth-I/2;At.style.left=`${Math.max(0,R)}px`},Xn=()=>{},Tn=()=>{var y,A,I,R,B;if(!at||!On(n))return;Es(e,n),Ts(e,n),Xn();let l=(R=(I=(A=(y=n.features)==null?void 0:y.artifacts)==null?void 0:A.layout)==null?void 0:I.narrowHostMaxWidth)!=null?R:520,m=W.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),at.update(_n),dn?(at.setMobileOpen(!1),at.element.classList.add("persona-hidden"),(B=at.backdrop)==null||B.classList.add("persona-hidden")):_n.artifacts.length>0&&(at.element.classList.remove("persona-hidden"),at.setMobileOpen(!0)),gr()};if(On(n)){W.style.position="relative";let l=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild($),at=pd(n,{onSelect:y=>{var A;return(A=mr.current)==null?void 0:A.selectArtifact(y)},onDismiss:()=>{dn=!0,Tn()}}),at.element.classList.add("persona-hidden"),En=m,m.appendChild(l),m.appendChild(at.element),at.backdrop&&W.appendChild(at.backdrop),W.appendChild(m),gr=()=>{var A,I,R,B;if(!En||!at)return;if(!(((R=(I=(A=n.features)==null?void 0:A.artifacts)==null?void 0:I.layout)==null?void 0:R.resizable)===!0)){pn==null||pn(),pn=null,or(),At&&(At.remove(),At=null),at.element.style.removeProperty("width"),at.element.style.removeProperty("maxWidth");return}if(!At){let V=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");V.setAttribute("role","separator"),V.setAttribute("aria-orientation","vertical"),V.setAttribute("aria-label","Resize artifacts panel"),V.tabIndex=0;let N=e.ownerDocument,xe=(B=N.defaultView)!=null?B:window,Ee=Me=>{var _,Pe;if(!at||Me.button!==0||e.classList.contains("persona-artifact-narrow-host")||xe.innerWidth<=640)return;Me.preventDefault(),or();let Ae=Me.clientX,Ie=at.element.getBoundingClientRect().width,ze=(Pe=(_=n.features)==null?void 0:_.artifacts)==null?void 0:Pe.layout,mt=Be=>{let Ce=En.getBoundingClientRect().width,Fe=e.classList.contains("persona-artifact-appearance-seamless"),St=Fe?0:fd(En,xe),vt=Fe?0:V.getBoundingClientRect().width||6,Gt=Ie-(Be.clientX-Ae),sn=hd(Gt,Ce,St,vt,ze==null?void 0:ze.resizableMinWidth,ze==null?void 0:ze.resizableMaxWidth);at.element.style.width=`${sn}px`,at.element.style.maxWidth="none",fr()},Ke=()=>{N.removeEventListener("pointermove",mt),N.removeEventListener("pointerup",Ke),N.removeEventListener("pointercancel",Ke),Rn=null;try{V.releasePointerCapture(Me.pointerId)}catch{}};Rn=Ke,N.addEventListener("pointermove",mt),N.addEventListener("pointerup",Ke),N.addEventListener("pointercancel",Ke);try{V.setPointerCapture(Me.pointerId)}catch{}};V.addEventListener("pointerdown",Ee),At=V,En.insertBefore(V,at.element),pn=()=>{V.removeEventListener("pointerdown",Ee)}}if(At){let V=_n.artifacts.length>0&&!dn;At.classList.toggle("persona-hidden",!V),fr()}},Xn=()=>{var xe,Ee,Me,Ae,Ie,ze,mt,Ke,_,Pe,Be,Ce,Fe,St;if(!C||!at||((Ee=(xe=n.launcher)==null?void 0:xe.sidebarMode)!=null?Ee:!1)||en(n)&&Jn(n).reveal==="emerge")return;let A=(Me=e.ownerDocument.defaultView)!=null?Me:window,I=(Ie=(Ae=n.launcher)==null?void 0:Ae.mobileFullscreen)!=null?Ie:!0,R=(mt=(ze=n.launcher)==null?void 0:ze.mobileBreakpoint)!=null?mt:640;if(I&&A.innerWidth<=R||!gd(n,C))return;let B=(Pe=(_=(Ke=n.launcher)==null?void 0:Ke.width)!=null?_:n.launcherWidth)!=null?Pe:Nn,V=(St=(Fe=(Ce=(Be=n.features)==null?void 0:Be.artifacts)==null?void 0:Ce.layout)==null?void 0:Fe.expandedPanelWidth)!=null?St:"min(720px, calc(100vw - 24px))";_n.artifacts.length>0&&!dn?(W.style.width=V,W.style.maxWidth=V):(W.style.width=B,W.style.maxWidth=B)},typeof ResizeObserver!="undefined"&&(An=new ResizeObserver(()=>{Tn()}),An.observe(W))}else W.appendChild($);e.appendChild(j);let Zn=()=>{var vt,Gt,sn,Te,bn,an,Un,rt,gt,xn,cr,Je,Mt,Rr,Hr,Qo,es,ts,$s,_s,Ut,ns,vo;let l=en(n),m=(Gt=(vt=n.launcher)==null?void 0:vt.sidebarMode)!=null?Gt:!1,y=l||m||((Te=(sn=n.launcher)==null?void 0:sn.fullHeight)!=null?Te:!1),A=((bn=n.launcher)==null?void 0:bn.enabled)===!1,I=(Un=(an=n.theme)==null?void 0:an.components)==null?void 0:Un.panel,R=bs(n),B=(vn,Fn)=>{var Yr;return vn==null||vn===""?Fn:(Yr=Ro(R,vn))!=null?Yr:vn},V=(rt=e.ownerDocument.defaultView)!=null?rt:window,N=(xn=(gt=n.launcher)==null?void 0:gt.mobileFullscreen)!=null?xn:!0,xe=(Je=(cr=n.launcher)==null?void 0:cr.mobileBreakpoint)!=null?Je:640,Ee=V.innerWidth<=xe,Me=N&&Ee&&C,Ae=(Rr=(Mt=n.launcher)==null?void 0:Mt.position)!=null?Rr:"bottom-left",Ie=Ae==="bottom-left"||Ae==="top-left",ze=(Qo=(Hr=n.launcher)==null?void 0:Hr.zIndex)!=null?Qo:wn,mt=m||Me?"none":"1px solid var(--persona-border)",Ke=Me?"none":m?Ie?"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&&!Me&&(Ke="none",mt="none");let _=m||Me?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Pe=B(I==null?void 0:I.border,mt),Be=B(I==null?void 0:I.shadow,Ke),Ce=B(I==null?void 0:I.borderRadius,_);if(e.style.cssText="",j.style.cssText="",W.style.cssText="",$.style.cssText="",q.style.cssText="",st.style.cssText="",Me){j.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"),j.style.cssText=`
23
23
  position: fixed !important;
24
24
  inset: 0 !important;
25
25
  width: 100% !important;
@@ -96,7 +96,7 @@ import{Marked as sp}from"marked";var ap=e=>{if(e)return e},ss=e=>{var s,o;let r=
96
96
  flex-shrink: 0 !important;
97
97
  border-top: none !important;
98
98
  padding: 8px 16px 12px 16px !important;
99
- `}if(!A&&!l){let vn="max-height: -moz-available !important; max-height: stretch !important;",Fn=m?"":"padding-top: 1.25em !important;",Yr=m?"":`z-index: ${(vo=(ns=n.launcher)==null?void 0:ns.zIndex)!=null?vo:wn} !important;`;j.style.cssText+=vn+Fn+Yr}};Zn(),$r(e,n),Es(e,n),Ts(e,n);let wt=[],Nt=null,Ot=null;wt.push(()=>{Nt==null||Nt(),Nt=null,Ot==null||Ot(),Ot=null}),An&&wt.push(()=>{An==null||An.disconnect(),An=null}),wt.push(()=>{pn==null||pn(),pn=null,or(),At&&(At.remove(),At=null),at==null||at.element.style.removeProperty("width"),at==null||at.element.style.removeProperty("maxWidth")}),oe&&wt.push(()=>{U!==null&&(cancelAnimationFrame(U),U=null),K==null||K.destroy(),K=null,se==null||se.destroy(),se=null,ke=null});let Mn=null,hr=()=>{Mn&&(Mn(),Mn=null),n.colorScheme==="auto"&&(Mn=ea(()=>{$r(e,n)}))};hr(),wt.push(()=>{Mn&&(Mn(),Mn=null)});let jn=id(_e),kn=null,D,zn=!1,Hn=Jc(),yr=0,fn=xs(),hn=0,ie=null,Ln=!1,sr=!1,qo=4,co=24,Uo=80,zr=new Map,Qe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},po=(di=(ci=n.voiceRecognition)==null?void 0:ci.autoResume)!=null?di:!1,Bn=l=>{o.emit("voice:state",{active:Qe.active,source:l,timestamp:Date.now()})},yn=()=>{f(l=>({...l,voiceState:{active:Qe.active,timestamp:Date.now(),manuallyDeactivated:Qe.manuallyDeactivated}}))},Vo=()=>{var A,I;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=va(i.voiceState),m=!!l.active,y=Number((I=l.timestamp)!=null?I:0);Qe.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-y<Wu&&setTimeout(()=>{var R,B;Qe.active||(Qe.manuallyDeactivated=!1,((B=(R=n.voiceRecognition)==null?void 0:R.provider)==null?void 0:B.type)==="runtype"?D.toggleVoice().then(()=>{Qe.active=D.isVoiceActive(),Bn("restore"),D.isVoiceActive()&&X()}):Pr("restore"))},1e3)},Jo=()=>D?vd(D.getMessages()).filter(l=>!l.__skipPersist):[];function uo(l){if(!(a!=null&&a.save))return;let y={messages:l?vd(l):D?Jo():[],metadata:i};try{let A=a.save(y);A instanceof Promise&&A.catch(I=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",I)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let ar=null,Yo=()=>j.querySelector("#persona-scroll-container")||q,kr=()=>{ar!==null&&(cancelAnimationFrame(ar),ar=null),Ln=!1},mo=()=>{ie!==null&&(cancelAnimationFrame(ie),ie=null),sr=!1,kr()},ir=()=>{if(!jt()||ue){dt.parentNode&&dt.remove(),dt.style.display="none";return}dt.parentNode!==$&&$.appendChild(dt),Ze();let l=Bo(q)>0;dt.style.display=fn.isFollowing()||!l?"none":""},go=()=>{fn.pause()&&(mo(),ir())},br=()=>{fn.resume(),ir()},xr=(l=!1)=>{fn.isFollowing()&&(!l&&!zn||(ie!==null&&(cancelAnimationFrame(ie),ie=null),sr=!0,ie=requestAnimationFrame(()=>{ie=null,sr=!1,fn.isFollowing()&&Go(Yo(),l?220:140)})))},Go=(l,m=500)=>{let y=l.scrollTop,A=Bo(l),I=A-y;if(Math.abs(I)<1){hn=l.scrollTop;return}if(Math.abs(I)>=Uo){kr(),Ln=!0,l.scrollTop=A,hn=l.scrollTop,Ln=!1;return}kr();let R=performance.now();Ln=!0;let B=N=>1-Math.pow(1-N,3),V=N=>{if(!fn.isFollowing()){kr();return}let xe=Bo(l);xe!==A&&(A=xe,I=A-y);let Ee=N-R,Me=Math.min(Ee/m,1),Ae=B(Me),Ie=y+I*Ae;l.scrollTop=Ie,hn=l.scrollTop,Me<1?ar=requestAnimationFrame(V):(l.scrollTop=A,hn=l.scrollTop,ar=null,Ln=!1)};ar=requestAnimationFrame(V)},Ko=l=>{let m=new Map;l.forEach(y=>{let A=zr.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!A&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(A!=null&&A.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(A?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),zr.clear(),m.forEach((y,A)=>{zr.set(A,y)})},Lr=(l,m,y)=>{var Me,Ae,Ie,ze,mt,Ke;let A=document.createElement("div"),R=(()=>{var Pe;let _=s.find(Be=>Be.renderLoadingIndicator);if(_!=null&&_.renderLoadingIndicator)return _.renderLoadingIndicator;if((Pe=n.loadingIndicator)!=null&&Pe.render)return n.loadingIndicator.render})(),B=(_,Pe)=>Pe==null?!1:typeof Pe=="string"?(_.textContent=Pe,!0):(_.appendChild(Pe),!0),V=new Set;if(m.forEach(_=>{var Gt,sn;V.add(_.id);let Pe=Vc(_,yr),Be=Yc(Hn,_.id,Pe);if(Be){A.appendChild(Be.cloneNode(!0));return}let Ce=null,Fe=s.find(Te=>!!(_.variant==="reasoning"&&Te.renderReasoning||_.variant==="tool"&&Te.renderToolCall||_.variant==="approval"&&Te.renderApproval||!_.variant&&Te.renderMessage)),St=(Gt=n.layout)==null?void 0:Gt.messages;if(Fe)if(_.variant==="reasoning"&&_.reasoning&&Fe.renderReasoning){if(!re)return;Ce=Fe.renderReasoning({message:_,defaultRenderer:()=>sa(_,n),config:n})}else if(_.variant==="tool"&&_.toolCall&&Fe.renderToolCall){if(!we)return;Ce=Fe.renderToolCall({message:_,defaultRenderer:()=>aa(_,n),config:n})}else if(_.variant==="approval"&&_.approval&&Fe.renderApproval){if(n.approval===!1)return;Ce=Fe.renderApproval({message:_,defaultRenderer:()=>ia(_,n),config:n})}else Fe.renderMessage&&(Ce=Fe.renderMessage({message:_,defaultRenderer:()=>{let Te=_o(_,y,St,n.messageActions,fe,{loadingIndicatorRenderer:R,widgetConfig:n});return _.role!=="user"&&da(Te,_,n,D),Te},config:n}));if(!Ce&&_.role==="assistant"&&!_.variant&&n.enableComponentStreaming!==!1&&ha(_)){let bn=ya(_);if(bn){let an=fa(bn,{config:n,message:_,transform:y});if(an)if(n.wrapComponentDirectiveInBubble!==!1){let rt=document.createElement("div");if(rt.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(" "),rt.id=`bubble-${_.id}`,rt.setAttribute("data-message-id",_.id),_.content&&_.content.trim()){let gt=document.createElement("div");gt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",gt.innerHTML=y({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),rt.appendChild(gt)}rt.appendChild(an),Ce=rt}else{let rt=document.createElement("div");if(rt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",rt.id=`bubble-${_.id}`,rt.setAttribute("data-message-id",_.id),rt.setAttribute("data-persona-component-directive","true"),_.content&&_.content.trim()){let gt=document.createElement("div");gt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",gt.innerHTML=y({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),rt.appendChild(gt)}rt.appendChild(an),Ce=rt}}}if(!Ce)if(_.variant==="reasoning"&&_.reasoning){if(!re)return;Ce=sa(_,n)}else if(_.variant==="tool"&&_.toolCall){if(!we)return;Ce=aa(_,n)}else if(_.variant==="approval"&&_.approval){if(n.approval===!1)return;Ce=ia(_,n)}else{let Te=(sn=n.layout)==null?void 0:sn.messages;Te!=null&&Te.renderUserMessage&&_.role==="user"?Ce=Te.renderUserMessage({message:_,config:n,streaming:!!_.streaming}):Te!=null&&Te.renderAssistantMessage&&_.role==="assistant"?Ce=Te.renderAssistantMessage({message:_,config:n,streaming:!!_.streaming}):Ce=_o(_,y,Te,n.messageActions,fe,{loadingIndicatorRenderer:R,widgetConfig:n}),_.role!=="user"&&Ce&&da(Ce,_,n,D)}let vt=document.createElement("div");vt.className="persona-flex",vt.id=`wrapper-${_.id}`,vt.setAttribute("data-wrapper-id",_.id),_.role==="user"&&vt.classList.add("persona-justify-end"),(Ce==null?void 0:Ce.getAttribute("data-persona-component-directive"))==="true"&&vt.classList.add("persona-w-full"),vt.appendChild(Ce),Gc(Hn,_.id,Pe,vt),A.appendChild(vt)}),(Ae=(Me=n.features)==null?void 0:Me.toolCallDisplay)!=null&&Ae.grouped){let _=[],Pe=[];m.forEach(Be=>{if(Be.variant==="tool"&&Be.toolCall&&we){Pe.push(Be);return}Pe.length>1&&_.push(Pe),Pe=[]}),Pe.length>1&&_.push(Pe),_.forEach((Be,Ce)=>{var an,Un;let Fe=Be.map(rt=>Array.from(A.children).find(gt=>gt instanceof HTMLElement&&gt.getAttribute("data-wrapper-id")===rt.id)).filter(rt=>!!rt);if(Fe.length<2)return;let St=document.createElement("div");St.className="persona-flex",St.id=`wrapper-tool-group-${Ce}-${Be[0].id}`,St.setAttribute("data-wrapper-id",`tool-group-${Ce}-${Be[0].id}`);let vt=document.createElement("div");vt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",vt.setAttribute("data-persona-tool-group","true");let Gt=document.createElement("div");Gt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let sn=`Called ${Be.length} tools`,Te=(Un=(an=n.toolCall)==null?void 0:an.renderGroupedSummary)==null?void 0:Un.call(an,{messages:Be,toolCalls:Be.map(rt=>rt.toolCall).filter(rt=>!!rt),defaultSummary:sn,config:n});B(Gt,Te)||(Gt.textContent=sn);let bn=document.createElement("div");bn.className="persona-tool-group-stack persona-flex persona-flex-col",vt.append(Gt,bn),St.appendChild(vt),Fe[0].before(St),Fe.forEach((rt,gt)=>{let xn=document.createElement("div");xn.className="persona-tool-group-item persona-relative",xn.setAttribute("data-persona-tool-group-item","true"),gt<Fe.length-1&&xn.setAttribute("data-persona-tool-group-connector","true"),xn.appendChild(rt),bn.appendChild(xn)})})}Kc(Hn,V);let N=m.some(_=>_.role==="assistant"&&_.streaming),xe=m[m.length-1],Ee=(xe==null?void 0:xe.role)==="assistant"&&!xe.streaming&&xe.variant!=="approval";if(zn&&m.some(_=>_.role==="user")&&!N&&!Ee){let _={config:n,streaming:!0,location:"standalone",defaultRenderer:no},Pe=s.find(Ce=>Ce.renderLoadingIndicator),Be=null;if(Pe!=null&&Pe.renderLoadingIndicator&&(Be=Pe.renderLoadingIndicator(_)),Be===null&&((Ie=n.loadingIndicator)!=null&&Ie.render)&&(Be=n.loadingIndicator.render(_)),Be===null&&(Be=no()),Be){let Ce=document.createElement("div"),Fe=((ze=n.loadingIndicator)==null?void 0:ze.showBubble)!==!1;Ce.className=Fe?["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(" "),Ce.setAttribute("data-typing-indicator","true"),Ce.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ce.appendChild(Be);let St=document.createElement("div");St.className="persona-flex",St.id="wrapper-typing-indicator",St.setAttribute("data-wrapper-id","typing-indicator"),St.appendChild(Ce),A.appendChild(St)}}if(!zn&&m.length>0){let _=m[m.length-1],Pe={config:n,lastMessage:_,messageCount:m.length},Be=s.find(Fe=>Fe.renderIdleIndicator),Ce=null;if(Be!=null&&Be.renderIdleIndicator&&(Ce=Be.renderIdleIndicator(Pe)),Ce===null&&((mt=n.loadingIndicator)!=null&&mt.renderIdle)&&(Ce=n.loadingIndicator.renderIdle(Pe)),Ce){let Fe=document.createElement("div"),St=((Ke=n.loadingIndicator)==null?void 0:Ke.showBubble)!==!1;Fe.className=St?["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(" "),Fe.setAttribute("data-idle-indicator","true"),Fe.appendChild(Ce);let vt=document.createElement("div");vt.className="persona-flex",vt.id="wrapper-idle-indicator",vt.setAttribute("data-wrapper-id","idle-indicator"),vt.appendChild(Fe),A.appendChild(vt)}}Uc(l,A)},Ir=()=>{var N,xe,Ee,Me,Ae;if(!C)return;let l=en(n),m=(N=e.ownerDocument.defaultView)!=null?N:window,y=(Ee=(xe=n.launcher)==null?void 0:xe.mobileBreakpoint)!=null?Ee:640,A=(Ae=(Me=n.launcher)==null?void 0:Me.mobileFullscreen)!=null?Ae:!0,I=m.innerWidth<=y,R=A&&I&&C,B=Jn(n).reveal;E?(j.style.removeProperty("display"),j.style.display=l?"flex":"",j.classList.remove("persona-pointer-events-none","persona-opacity-0"),W.classList.remove("persona-scale-95","persona-opacity-0"),W.classList.add("persona-scale-100","persona-opacity-100"),ne?ne.element.style.display="none":T&&(T.style.display="none")):(l?l&&(B==="overlay"||B==="push")&&!R?(j.style.removeProperty("display"),j.style.display="flex",j.classList.remove("persona-pointer-events-none","persona-opacity-0"),W.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(j.style.setProperty("display","none","important"),j.classList.remove("persona-pointer-events-none","persona-opacity-0"),W.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(j.style.display="",j.classList.add("persona-pointer-events-none","persona-opacity-0"),W.classList.remove("persona-scale-100","persona-opacity-100"),W.classList.add("persona-scale-95","persona-opacity-0")),ne?ne.element.style.display=l?"none":"":T&&(T.style.display=l?"none":""))},Rt=(l,m="user")=>{var R,B;if(!C||E===l)return;let y=E;E=l,Ir();let A=(()=>{var Ie,ze,mt,Ke,_,Pe,Be;let V=(ze=(Ie=n.launcher)==null?void 0:Ie.sidebarMode)!=null?ze:!1,N=(mt=e.ownerDocument.defaultView)!=null?mt:window,xe=(_=(Ke=n.launcher)==null?void 0:Ke.mobileFullscreen)!=null?_:!0,Ee=(Be=(Pe=n.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Be:640,Me=N.innerWidth<=Ee,Ae=en(n)&&xe&&Me;return V||xe&&Me&&C||Ae})();if(E&&A){if(!Nt){let V=e.getRootNode(),N=V instanceof ShadowRoot?V.host:e.closest(".persona-host");N&&(Nt=ta(N,(B=(R=n.launcher)==null?void 0:R.zIndex)!=null?B:wn))}Ot||(Ot=na(e.ownerDocument))}else E||(Nt==null||Nt(),Nt=null,Ot==null||Ot(),Ot=null);E&&(x(),xr(!0));let I={open:E,source:m,timestamp:Date.now()};E&&!y?o.emit("widget:opened",I):!E&&y&&o.emit("widget:closed",I),o.emit("widget:state",{open:E,launcherEnabled:C,voiceActive:Qe.active,streaming:D.isStreaming()})},qr=l=>{le.disabled=l,z&&(z.disabled=l),jn.buttons.forEach(m=>{m.disabled=l}),st.dataset.personaComposerStreaming=l?"true":"false",st.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},Ur=()=>{Qe.active||ee&&ee.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Ur(),200)});let fo=()=>{var y,A,I,R,B,V,N,xe,Ee,Me,Ae;Xt.textContent=(A=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?A:"Hello \u{1F44B}",je.textContent=(R=(I=n.copy)==null?void 0:I.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",ee.placeholder=(V=(B=n.copy)==null?void 0:B.inputPlaceholder)!=null?V:"How can I help...";let l=q.querySelector("[data-persona-intro-card]");if(l){let Ie=((N=n.copy)==null?void 0:N.showWelcomeCard)!==!1;l.style.display=Ie?"":"none",Ie?(q.classList.remove("persona-gap-3"),q.classList.add("persona-gap-6")):(q.classList.remove("persona-gap-6"),q.classList.add("persona-gap-3"))}(Ee=(xe=n.sendButton)==null?void 0:xe.useIcon)!=null&&Ee||(le.textContent=(Ae=(Me=n.copy)==null?void 0:Me.sendButtonLabel)!=null?Ae:"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))"};n.clientToken&&(n={...n,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(m=>({...m,sessionId:l}))}});let Qn=null,Xo=()=>{Qn==null&&(Qn=setInterval(()=>{let l=de.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Qn),Qn=null;return}let m=Date.now();l.forEach(y=>{let A=Number(y.getAttribute("data-tool-elapsed"));A&&(y.textContent=is(m-A))})},100))};if(D=new Po(n,{onMessagesChanged(l){Lr(de,l,O),Xo(),D&&(l.some(I=>I.role==="user")?jn.render([],D,ee,l):jn.render(n.suggestionChips,D,ee,l,n.suggestionChipsConfig)),xr(!zn),Ko(l);let m=[...l].reverse().find(A=>A.role==="user"),y=Qe.lastUserMessageId;m&&m.id!==y&&(Qe.lastUserMessageId=m.id,o.emit("user:message",m)),Qe.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),uo(l)},onStatusChanged(l){var A;let m=(A=n.statusIndicator)!=null?A:{};Xe(Dt,(I=>{var R,B,V,N;return I==="idle"?(R=m.idleText)!=null?R:cn.idle:I==="connecting"?(B=m.connectingText)!=null?B:cn.connecting:I==="connected"?(V=m.connectedText)!=null?V:cn.connected:I==="error"?(N=m.errorText)!=null?N:cn.error:cn[I]})(l),m,l)},onStreamingChanged(l){zn=l,qr(l),D&&Lr(de,D.getMessages(),O),l||xr(!0)},onVoiceStatusChanged(l){var m,y;if(((y=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype")switch(l){case"listening":break;case"processing":xt(),Ve();break;case"speaking":xt(),tt();break;default:l==="idle"&&D.isBargeInActive()?(xt(),X(),z==null||z.setAttribute("aria-label","End voice session")):(Qe.active=!1,xt(),Bn("system"),yn());break}},onArtifactsState(l){_n=l,Tn()}}),mr.current=D,((ui=(pi=n.voiceRecognition)==null?void 0:pi.provider)==null?void 0:ui.type)==="runtype")try{D.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&D.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),se&&D.setSSEEventCallback((l,m)=>{se==null||se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})}),u&&u.then(l=>{var m;l&&(l.metadata&&(i=va(l.metadata),M.syncFromMetadata()),(m=l.messages)!=null&&m.length&&D.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let ho=l=>{var I;l.preventDefault();let m=ee.value.trim(),y=(I=De==null?void 0:De.hasAttachments())!=null?I:!1;if(!m&&!y)return;let A;y&&(A=[],A.push(...De.getContentParts()),m&&A.push(ps(m))),ee.value="",ee.style.height="auto",D.sendMessage(m,{contentParts:A}),y&&De.clearAttachments()},yo=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),le.click())},bo=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!De)return;let m=Hu(l.clipboardData);m.length!==0&&(l.preventDefault(),await De.handleFiles(m))},un=null,In=!1,lr=null,qe=null,xo=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Pr=(l="user")=>{var R,B,V,N,xe,Ee,Me;if(In||D.isStreaming())return;let m=xo();if(!m)return;un=new m;let A=(B=((R=n.voiceRecognition)!=null?R:{}).pauseDuration)!=null?B:2e3;un.continuous=!0,un.interimResults=!0,un.lang="en-US";let I=ee.value;un.onresult=Ae=>{let Ie="",ze="";for(let Ke=0;Ke<Ae.results.length;Ke++){let _=Ae.results[Ke],Pe=_[0].transcript;_.isFinal?Ie+=Pe+" ":ze=Pe}let mt=I+Ie+ze;ee.value=mt,lr&&clearTimeout(lr),(Ie||ze)&&(lr=window.setTimeout(()=>{let Ke=ee.value.trim();Ke&&un&&In&&(qn(),ee.value="",ee.style.height="auto",D.sendMessage(Ke,{viaVoice:!0}))},A))},un.onerror=Ae=>{Ae.error!=="no-speech"&&qn()},un.onend=()=>{if(In){let Ae=ee.value.trim();Ae&&Ae!==I.trim()&&(ee.value="",ee.style.height="auto",D.sendMessage(Ae,{viaVoice:!0})),qn()}};try{if(un.start(),In=!0,Qe.active=!0,l!=="system"&&(Qe.manuallyDeactivated=!1),Bn(l),yn(),z){let Ae=(V=n.voiceRecognition)!=null?V:{};qe={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(N=Ae.iconName)!=null?N:"mic",iconSize:parseFloat((Me=(Ee=Ae.iconSize)!=null?Ee:(xe=n.sendButton)==null?void 0:xe.size)!=null?Me:"40")||24};let Ie=Ae.recordingBackgroundColor,ze=Ae.recordingIconColor,mt=Ae.recordingBorderColor;if(z.classList.add("persona-voice-recording"),z.style.backgroundColor=Ie!=null?Ie:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=ze!=null?ze:"var(--persona-voice-recording-indicator, #ffffff)",ze){let Ke=z.querySelector("svg");Ke&&Ke.setAttribute("stroke",ze)}mt&&(z.style.borderColor=mt),z.setAttribute("aria-label","Stop voice recognition")}}catch{qn("system")}},qn=(l="user")=>{if(In){if(In=!1,lr&&(clearTimeout(lr),lr=null),un){try{un.stop()}catch{}un=null}if(Qe.active=!1,Bn(l),yn(),z){if(z.classList.remove("persona-voice-recording"),qe){z.style.backgroundColor=qe.backgroundColor,z.style.color=qe.color,z.style.borderColor=qe.borderColor;let m=z.querySelector("svg");m&&m.setAttribute("stroke",qe.color||"currentColor"),qe=null}z.setAttribute("aria-label","Start voice recognition")}}},Zo=(l,m)=>{var _,Pe,Be,Ce,Fe,St,vt,Gt;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((_=l==null?void 0:l.provider)==null?void 0:_.type)==="runtype";if(!(y||A))return null;let R=h("div","persona-send-button-wrapper"),B=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");B.type="button",B.setAttribute("aria-label","Start voice recognition");let V=(Pe=l==null?void 0:l.iconName)!=null?Pe:"mic",N=(Be=m==null?void 0:m.size)!=null?Be:"40px",xe=(Ce=l==null?void 0:l.iconSize)!=null?Ce:N,Ee=parseFloat(xe)||24,Me=(Fe=l==null?void 0:l.backgroundColor)!=null?Fe:m==null?void 0:m.backgroundColor,Ae=(St=l==null?void 0:l.iconColor)!=null?St:m==null?void 0:m.textColor;B.style.width=xe,B.style.height=xe,B.style.minWidth=xe,B.style.minHeight=xe,B.style.fontSize="18px",B.style.lineHeight="1",Ae?B.style.color=Ae:B.style.color="var(--persona-text, #111827)";let ze=be(V,Ee,Ae||"currentColor",1.5);ze?B.appendChild(ze):B.textContent="\u{1F3A4}",Me?B.style.backgroundColor=Me:B.style.backgroundColor="",l!=null&&l.borderWidth&&(B.style.borderWidth=l.borderWidth,B.style.borderStyle="solid"),l!=null&&l.borderColor&&(B.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(B.style.paddingLeft=l.paddingX,B.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(B.style.paddingTop=l.paddingY,B.style.paddingBottom=l.paddingY),R.appendChild(B);let mt=(vt=l==null?void 0:l.tooltipText)!=null?vt:"Start voice recognition";if(((Gt=l==null?void 0:l.showTooltip)!=null?Gt:!1)&&mt){let sn=h("div","persona-send-button-tooltip");sn.textContent=mt,R.appendChild(sn)}return{micButton:B,micButtonWrapper:R}},Vr=()=>{var m,y,A,I,R;if(!z||qe)return;let l=(m=n.voiceRecognition)!=null?m:{};qe={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((R=(I=l.iconSize)!=null?I:(A=n.sendButton)==null?void 0:A.size)!=null?R:"40")||24}},Jr=(l,m)=>{var R,B,V,N,xe;if(!z)return;let y=z.querySelector("svg");y&&y.remove();let A=(xe=qe==null?void 0:qe.iconSize)!=null?xe:parseFloat((N=(V=(R=n.voiceRecognition)==null?void 0:R.iconSize)!=null?V:(B=n.sendButton)==null?void 0:B.size)!=null?N:"40")||24,I=be(l,A,m,1.5);I&&z.appendChild(I)},Wr=()=>{z&&z.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},X=()=>{var I;if(!z)return;Vr();let l=(I=n.voiceRecognition)!=null?I:{},m=l.recordingBackgroundColor,y=l.recordingIconColor,A=l.recordingBorderColor;if(Wr(),z.classList.add("persona-voice-recording"),z.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let R=z.querySelector("svg");R&&R.setAttribute("stroke",y)}A&&(z.style.borderColor=A),z.setAttribute("aria-label","Stop voice recognition")},Ve=()=>{var V,N,xe,Ee,Me,Ae,Ie,ze;if(!z)return;Vr();let l=(V=n.voiceRecognition)!=null?V:{},m=D.getVoiceInterruptionMode(),y=(N=l.processingIconName)!=null?N:"loader",A=(Ee=(xe=l.processingIconColor)!=null?xe:qe==null?void 0:qe.color)!=null?Ee:"",I=(Ae=(Me=l.processingBackgroundColor)!=null?Me:qe==null?void 0:qe.backgroundColor)!=null?Ae:"",R=(ze=(Ie=l.processingBorderColor)!=null?Ie:qe==null?void 0:qe.borderColor)!=null?ze:"";Wr(),z.classList.add("persona-voice-processing"),z.style.backgroundColor=I,z.style.borderColor=R;let B=A||"currentColor";z.style.color=B,Jr(y,B),z.setAttribute("aria-label","Processing voice input"),m==="none"&&(z.style.cursor="default")},tt=()=>{var xe,Ee,Me,Ae,Ie,ze,mt,Ke,_,Pe,Be,Ce;if(!z)return;Vr();let l=(xe=n.voiceRecognition)!=null?xe:{},m=D.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",A=(Ee=l.speakingIconName)!=null?Ee:y,I=(ze=l.speakingIconColor)!=null?ze:m==="barge-in"?(Ae=(Me=l.recordingIconColor)!=null?Me:qe==null?void 0:qe.color)!=null?Ae:"":(Ie=qe==null?void 0:qe.color)!=null?Ie:"",R=(_=l.speakingBackgroundColor)!=null?_:m==="barge-in"?(mt=l.recordingBackgroundColor)!=null?mt:"var(--persona-voice-recording-bg, #ef4444)":(Ke=qe==null?void 0:qe.backgroundColor)!=null?Ke:"",B=(Ce=l.speakingBorderColor)!=null?Ce:m==="barge-in"?(Pe=l.recordingBorderColor)!=null?Pe:"":(Be=qe==null?void 0:qe.borderColor)!=null?Be:"";Wr(),z.classList.add("persona-voice-speaking"),z.style.backgroundColor=R,z.style.borderColor=B;let V=I||"currentColor";z.style.color=V,Jr(A,V);let N=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";z.setAttribute("aria-label",N),m==="none"&&(z.style.cursor="default"),m==="barge-in"&&z.classList.add("persona-voice-recording")},xt=()=>{var l,m,y;z&&(Wr(),qe&&(z.style.backgroundColor=(l=qe.backgroundColor)!=null?l:"",z.style.color=(m=qe.color)!=null?m:"",z.style.borderColor=(y=qe.borderColor)!=null?y:"",Jr(qe.iconName,qe.color||"currentColor"),qe=null),z.style.cursor="",z.setAttribute("aria-label","Start voice recognition"))},lt=()=>{var l,m;if(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let y=D.getVoiceStatus(),A=D.getVoiceInterruptionMode();if(A==="none"&&(y==="processing"||y==="speaking"))return;if(A==="cancel"&&(y==="processing"||y==="speaking")){D.stopVoicePlayback();return}if(D.isBargeInActive()){D.stopVoicePlayback(),D.deactivateBargeIn().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,yn(),Bn("user"),xt()});return}D.toggleVoice().then(()=>{Qe.active=D.isVoiceActive(),Qe.manuallyDeactivated=!D.isVoiceActive(),yn(),Bn("user"),D.isVoiceActive()?X():xt()});return}if(In){let y=ee.value.trim();Qe.manuallyDeactivated=!0,yn(),qn("user"),y&&(ee.value="",ee.style.height="auto",D.sendMessage(y))}else Qe.manuallyDeactivated=!1,yn(),Pr("user")};qt=lt,z&&(z.addEventListener("click",lt),wt.push(()=>{var l,m;((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?(D.isVoiceActive()&&D.toggleVoice(),xt()):qn("system"),z&&z.removeEventListener("click",lt)}));let Et=o.on("assistant:complete",()=>{po&&(Qe.active||Qe.manuallyDeactivated||po==="assistant"&&!Qe.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!Qe.active&&!Qe.manuallyDeactivated&&(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?D.toggleVoice().then(()=>{Qe.active=D.isVoiceActive(),Bn("auto"),D.isVoiceActive()&&X()}):Pr("auto"))},600))});wt.push(Et);let ut=o.on("action:resubmit",()=>{setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)});wt.push(ut);let b=()=>{Rt(!E,"user")},ne=null,T=null;if(C){let l=s.find(m=>m.renderLauncher);if(l!=null&&l.renderLauncher){let m=l.renderLauncher({config:n,defaultRenderer:()=>No(n,b).element,onToggle:b});m&&(T=m)}T||(ne=No(n,b))}ne?e.appendChild(ne.element):T&&e.appendChild(T),Ir(),jn.render(n.suggestionChips,D,ee,void 0,n.suggestionChipsConfig),fo(),qr(D.isStreaming()),xr(!0),Vo(),k&&(C?E&&setTimeout(()=>Ur(),200):setTimeout(()=>Ur(),0));let x=()=>{var N,xe,Ee,Me,Ae,Ie,ze,mt,Ke,_,Pe,Be,Ce,Fe,St,vt,Gt,sn,Te,bn,an,Un;let l=en(n),m=(xe=(N=n.launcher)==null?void 0:N.sidebarMode)!=null?xe:!1,y=l||m||((Me=(Ee=n.launcher)==null?void 0:Ee.fullHeight)!=null?Me:!1),A=(Ae=e.ownerDocument.defaultView)!=null?Ae:window,I=(ze=(Ie=n.launcher)==null?void 0:Ie.mobileFullscreen)!=null?ze:!0,R=(Ke=(mt=n.launcher)==null?void 0:mt.mobileBreakpoint)!=null?Ke:640,B=A.innerWidth<=R,V=I&&B&&C;try{if(V){Zn(),$r(e,n);return}if(P&&(P=!1,Zn(),$r(e,n)),!C&&!l){W.style.height="",W.style.width="";return}if(!m&&!l){let rt=(Pe=(_=n==null?void 0:n.launcher)==null?void 0:_.width)!=null?Pe:n==null?void 0:n.launcherWidth,gt=rt!=null?rt:Nn;W.style.width=gt,W.style.maxWidth=gt}if(Xn(),!y){let rt=A.innerHeight,gt=64,xn=(Ce=(Be=n.launcher)==null?void 0:Be.heightOffset)!=null?Ce:0,cr=Math.max(200,rt-gt),Je=Math.min(640,cr),Mt=Math.max(200,Je-xn);W.style.height=`${Mt}px`}}finally{if(Ze(),Ir(),E&&C){let gt=((Fe=e.ownerDocument.defaultView)!=null?Fe:window).innerWidth<=((vt=(St=n.launcher)==null?void 0:St.mobileBreakpoint)!=null?vt:640),xn=(sn=(Gt=n.launcher)==null?void 0:Gt.sidebarMode)!=null?sn:!1,cr=(bn=(Te=n.launcher)==null?void 0:Te.mobileFullscreen)!=null?bn:!0,Je=en(n)&&cr&&gt,Mt=xn||cr&&gt&&C||Je;if(Mt&&!Ot){let Rr=e.getRootNode(),Hr=Rr instanceof ShadowRoot?Rr.host:e.closest(".persona-host");Hr&&!Nt&&(Nt=ta(Hr,(Un=(an=n.launcher)==null?void 0:an.zIndex)!=null?Un:wn)),Ot=na(e.ownerDocument)}else Mt||(Nt==null||Nt(),Nt=null,Ot==null||Ot(),Ot=null)}}};x();let Z=(mi=e.ownerDocument.defaultView)!=null?mi:window;if(Z.addEventListener("resize",x),wt.push(()=>Z.removeEventListener("resize",x)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Ze()});l.observe(st),wt.push(()=>l.disconnect())}hn=q.scrollTop;let F=()=>{let l=q.scrollTop,{action:m,nextLastScrollTop:y}=vs({following:fn.isFollowing(),currentScrollTop:l,lastScrollTop:hn,nearBottom:Do(q,co),userScrollThreshold:qo,isAutoScrolling:Ln||sr,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(hn=y,m==="resume"){br();return}m==="pause"&&go()};q.addEventListener("scroll",F,{passive:!0}),wt.push(()=>q.removeEventListener("scroll",F));let he=l=>{let m=Cs({following:fn.isFollowing(),deltaY:l.deltaY,nearBottom:Do(q,co),resumeWhenNearBottom:!0});m==="pause"?go():m==="resume"&&br()};q.addEventListener("wheel",he,{passive:!0}),wt.push(()=>q.removeEventListener("wheel",he)),dt.addEventListener("click",()=>{q.scrollTop=q.scrollHeight,hn=q.scrollTop,br(),xr(!0)}),wt.push(()=>dt.remove()),wt.push(()=>{mo()});let Ue=()=>{me&&(kn&&(me.removeEventListener("click",kn),kn=null),C?(me.style.display="",kn=()=>{Rt(!1,"user")},me.addEventListener("click",kn)):me.style.display="none")};Ue(),(()=>{let{clearChatButton:l}=ae;l&&l.addEventListener("click",()=>{D.clearMessages(),Hn.clear(),br();try{localStorage.removeItem(io),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${io}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==io)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),a!=null&&a.clear)try{let y=a.clear();y instanceof Promise&&y.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},M.syncFromMetadata(),se==null||se.clear(),K==null||K.update()})})(),ct&&ct.addEventListener("submit",ho),ee==null||ee.addEventListener("keydown",yo),ee==null||ee.addEventListener("paste",bo);let $t="persona-attachment-drop-active",Vt=0,Jt=()=>{Vt=0,$.classList.remove($t)},Ft=()=>{var l;return((l=n.attachments)==null?void 0:l.enabled)===!0&&De!==null},Ge=l=>{!Is(l.dataTransfer)||!Ft()||(Vt++,Vt===1&&$.classList.add($t))},kt=l=>{!Is(l.dataTransfer)||!Ft()||(Vt--,Vt<=0&&Jt())},Zt=l=>{!Is(l.dataTransfer)||!Ft()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},on=l=>{var y;if(!Is(l.dataTransfer)||!Ft())return;l.preventDefault(),l.stopPropagation(),Jt();let m=Array.from((y=l.dataTransfer.files)!=null?y:[]);m.length!==0&&De.handleFiles(m)},Tt=!0;$.addEventListener("dragenter",Ge,Tt),$.addEventListener("dragleave",kt,Tt),e.addEventListener("dragover",Zt,Tt),e.addEventListener("drop",on,Tt);let mn=e.ownerDocument,Wa=l=>{Ft()&&l.preventDefault()},Ra=l=>{Ft()&&l.preventDefault()};mn.addEventListener("dragover",Wa),mn.addEventListener("drop",Ra),wt.push(()=>{ct&&ct.removeEventListener("submit",ho),ee==null||ee.removeEventListener("keydown",yo),ee==null||ee.removeEventListener("paste",bo)}),wt.push(()=>{$.removeEventListener("dragenter",Ge,Tt),$.removeEventListener("dragleave",kt,Tt),e.removeEventListener("dragover",Zt,Tt),e.removeEventListener("drop",on,Tt),mn.removeEventListener("dragover",Wa),mn.removeEventListener("drop",Ra),Jt()}),wt.push(()=>{D.cancel()}),ne?wt.push(()=>{ne==null||ne.destroy()}):T&&wt.push(()=>{T==null||T.remove()});let Yt={update(l){var vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Ii,Pi,Wi,Ri,Hi,Bi,Di,Fi,Ni,Oi,$i,_i,ji,zi,qi,Ui,Vi,Ji,Yi,Gi,Ki,Xi,Zi,Qi,el,tl,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,ml,gl,fl,hl,yl,bl,xl,vl,Cl,wl,Sl,Al,El,Tl,Ml,kl,Ll,Il,Pl,Wl,Rl,Hl,Bl,Dl,Fl,Nl,Ol,$l,_l,jl,zl,ql,Ul,Vl,Jl,Yl,Gl,Kl,Xl,Zl,Ql,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc;let m=n.toolCall,y=n.messageActions,A=(vi=n.layout)==null?void 0:vi.messages,I=n.colorScheme,R=n.loadingIndicator,B=n.iterationDisplay,V=(Ci=n.features)==null?void 0:Ci.showReasoning,N=(wi=n.features)==null?void 0:wi.showToolCalls,xe=(Si=n.features)==null?void 0:Si.toolCallDisplay,Ee=(Ai=n.features)==null?void 0:Ai.reasoningDisplay;n={...n,...l},Zn(),$r(e,n),Es(e,n),Ts(e,n),Tn(),n.colorScheme!==I&&hr();let Me=Ms.getForInstance(n.plugins);s.length=0,s.push(...Me),C=(Ti=(Ei=n.launcher)==null?void 0:Ei.enabled)!=null?Ti:!0,S=(ki=(Mi=n.launcher)==null?void 0:Mi.autoExpand)!=null?ki:!1,re=(Ii=(Li=n.features)==null?void 0:Li.showReasoning)!=null?Ii:!0,we=(Wi=(Pi=n.features)==null?void 0:Pi.showToolCalls)!=null?Wi:!0,ve=(Hi=(Ri=n.features)==null?void 0:Ri.scrollToBottom)!=null?Hi:{},bt(),ir();let Ae=oe;if(oe=(Di=(Bi=n.features)==null?void 0:Bi.showEventStreamToggle)!=null?Di:!1,oe&&!Ae){if(se||(ke=new zo(ge),se=new jo(Le,ke),ke.open().then(()=>se==null?void 0:se.restore()).catch(()=>{}),D.setSSEEventCallback((J,pt)=>{se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:J,timestamp:Date.now(),payload:JSON.stringify(pt)})})),!et&&ot){let J=(Ni=(Fi=n.features)==null?void 0:Fi.eventStream)==null?void 0:Ni.classNames,pt="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"+(J!=null&&J.toggleButton?" "+J.toggleButton:"");et=h("button",pt),et.style.width="28px",et.style.height="28px",et.style.color=Sn.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let Ht=be("activity","18px","currentColor",1.5);Ht&&et.appendChild(Ht);let Ye=ae.clearChatButtonWrapper,ft=ae.closeButtonWrapper,Kt=Ye||ft;Kt&&Kt.parentNode===ot?ot.insertBefore(et,Kt):ot.appendChild(et),et.addEventListener("click",()=>{ue?$n():nr()})}}else!oe&&Ae&&($n(),et&&(et.remove(),et=null),se==null||se.clear(),ke==null||ke.destroy(),se=null,ke=null);if(((Oi=n.launcher)==null?void 0:Oi.enabled)===!1&&ne&&(ne.destroy(),ne=null),(($i=n.launcher)==null?void 0:$i.enabled)===!1&&T&&(T.remove(),T=null),((_i=n.launcher)==null?void 0:_i.enabled)!==!1&&!ne&&!T){let J=s.find(pt=>pt.renderLauncher);if(J!=null&&J.renderLauncher){let pt=J.renderLauncher({config:n,defaultRenderer:()=>No(n,b).element,onToggle:b});pt&&(T=pt,e.appendChild(T))}T||(ne=No(n,b),e.appendChild(ne.element))}ne&&ne.update(n),Pt&&((ji=n.launcher)==null?void 0:ji.title)!==void 0&&(Pt.textContent=n.launcher.title),Wt&&((zi=n.launcher)==null?void 0:zi.subtitle)!==void 0&&(Wt.textContent=n.launcher.subtitle);let Ie=(qi=n.layout)==null?void 0:qi.header;if((Ie==null?void 0:Ie.layout)!==L&&ot){let J=Ie?Oo(n,Ie,{showClose:C,onClose:()=>Rt(!1,"user")}):Sr({config:n,showClose:C,onClose:()=>Rt(!1,"user")});ot.replaceWith(J.header),ot=J.header,Ne=J.iconHolder,Pt=J.headerTitle,Wt=J.headerSubtitle,me=J.closeButton,L=Ie==null?void 0:Ie.layout}else if(Ie&&(Ne&&(Ne.style.display=Ie.showIcon===!1?"none":""),Pt&&(Pt.style.display=Ie.showTitle===!1?"none":""),Wt&&(Wt.style.display=Ie.showSubtitle===!1?"none":""),me&&(me.style.display=Ie.showCloseButton===!1?"none":""),ae.clearChatButtonWrapper)){let J=Ie.showClearChat;if(J!==void 0){ae.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:pt}=ae;pt&&!pt.classList.contains("persona-absolute")&&(J?pt.classList.remove("persona-ml-auto"):pt.classList.add("persona-ml-auto"))}}let mt=((Ui=n.layout)==null?void 0:Ui.showHeader)!==!1;ot&&(ot.style.display=mt?"":"none");let Ke=((Vi=n.layout)==null?void 0:Vi.showFooter)!==!1;st&&(st.style.display=Ke?"":"none"),Ze(),ir(),C!==w?C?Rt(S,"auto"):(E=!0,Ir()):S!==H&&Rt(S,"auto"),H=S,w=C,x(),Ue();let Be=JSON.stringify(l.toolCall)!==JSON.stringify(m),Ce=JSON.stringify(n.messageActions)!==JSON.stringify(y),Fe=JSON.stringify((Ji=n.layout)==null?void 0:Ji.messages)!==JSON.stringify(A),St=((Yi=n.loadingIndicator)==null?void 0:Yi.render)!==(R==null?void 0:R.render)||((Gi=n.loadingIndicator)==null?void 0:Gi.renderIdle)!==(R==null?void 0:R.renderIdle)||((Ki=n.loadingIndicator)==null?void 0:Ki.showBubble)!==(R==null?void 0:R.showBubble),vt=n.iterationDisplay!==B,Gt=((Zi=(Xi=n.features)==null?void 0:Xi.showReasoning)!=null?Zi:!0)!==(V!=null?V:!0)||((el=(Qi=n.features)==null?void 0:Qi.showToolCalls)!=null?el:!0)!==(N!=null?N:!0)||JSON.stringify((tl=n.features)==null?void 0:tl.toolCallDisplay)!==JSON.stringify(xe)||JSON.stringify((nl=n.features)==null?void 0:nl.reasoningDisplay)!==JSON.stringify(Ee);(Be||Ce||Fe||St||vt||Gt)&&D&&(yr++,Lr(de,D.getMessages(),O));let Te=(rl=n.launcher)!=null?rl:{},bn=(ol=Te.headerIconHidden)!=null?ol:!1,an=(al=(sl=n.layout)==null?void 0:sl.header)==null?void 0:al.showIcon,Un=bn||an===!1,rt=Te.headerIconName,gt=(il=Te.headerIconSize)!=null?il:"48px";if(Ne){let J=$.querySelector(".persona-border-b-persona-divider"),pt=J==null?void 0:J.querySelector(".persona-flex-col");if(Un)Ne.style.display="none",J&&pt&&!J.contains(pt)&&J.insertBefore(pt,J.firstChild);else{if(Ne.style.display="",Ne.style.height=gt,Ne.style.width=gt,J&&pt&&(J.contains(Ne)?Ne.nextSibling!==pt&&(Ne.remove(),J.insertBefore(Ne,pt)):J.insertBefore(Ne,pt)),rt){let Ye=parseFloat(gt)||24,ft=be(rt,Ye*.6,"#ffffff",2);ft?Ne.replaceChildren(ft):Ne.textContent=(ll=Te.agentIconText)!=null?ll:"\u{1F4AC}"}else if(Te.iconUrl){let Ye=Ne.querySelector("img");if(Ye)Ye.src=Te.iconUrl,Ye.style.height=gt,Ye.style.width=gt;else{let ft=document.createElement("img");ft.src=Te.iconUrl,ft.alt="",ft.className="persona-rounded-xl persona-object-cover",ft.style.height=gt,ft.style.width=gt,Ne.replaceChildren(ft)}}else{let Ye=Ne.querySelector("svg"),ft=Ne.querySelector("img");(Ye||ft)&&Ne.replaceChildren(),Ne.textContent=(cl=Te.agentIconText)!=null?cl:"\u{1F4AC}"}let Ht=Ne.querySelector("img");Ht&&(Ht.style.height=gt,Ht.style.width=gt)}}let xn=(pl=(dl=n.layout)==null?void 0:dl.header)==null?void 0:pl.showTitle,cr=(ml=(ul=n.layout)==null?void 0:ul.header)==null?void 0:ml.showSubtitle;if(Pt&&(Pt.style.display=xn===!1?"none":""),Wt&&(Wt.style.display=cr===!1?"none":""),me){((fl=(gl=n.layout)==null?void 0:gl.header)==null?void 0:fl.showCloseButton)===!1?me.style.display="none":me.style.display="";let pt=(hl=Te.closeButtonSize)!=null?hl:"32px",Ht=(yl=Te.closeButtonPlacement)!=null?yl:"inline";me.style.height=pt,me.style.width=pt;let{closeButtonWrapper:Ye}=ae,ft=Ht==="top-right",Kt=Ye==null?void 0:Ye.classList.contains("persona-absolute");if(Ye&&ft!==Kt)if(Ye.remove(),ft)Ye.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",$.style.position="relative",$.appendChild(Ye);else{let nt=(xl=(bl=Te.clearChat)==null?void 0:bl.placement)!=null?xl:"inline",Qt=(Cl=(vl=Te.clearChat)==null?void 0:vl.enabled)!=null?Cl:!0;Ye.className=Qt&&nt==="inline"?"":"persona-ml-auto";let Cn=$.querySelector(".persona-border-b-persona-divider");Cn&&Cn.appendChild(Ye)}if(me.style.color=Te.closeButtonColor||Sn.actionIconColor,Te.closeButtonBackgroundColor?(me.style.backgroundColor=Te.closeButtonBackgroundColor,me.classList.remove("hover:persona-bg-gray-100")):(me.style.backgroundColor="",me.classList.add("hover:persona-bg-gray-100")),Te.closeButtonBorderWidth||Te.closeButtonBorderColor){let nt=Te.closeButtonBorderWidth||"0px",Qt=Te.closeButtonBorderColor||"transparent";me.style.border=`${nt} solid ${Qt}`,me.classList.remove("persona-border-none")}else me.style.border="",me.classList.add("persona-border-none");Te.closeButtonBorderRadius?(me.style.borderRadius=Te.closeButtonBorderRadius,me.classList.remove("persona-rounded-full")):(me.style.borderRadius="",me.classList.add("persona-rounded-full")),Te.closeButtonPaddingX?(me.style.paddingLeft=Te.closeButtonPaddingX,me.style.paddingRight=Te.closeButtonPaddingX):(me.style.paddingLeft="",me.style.paddingRight=""),Te.closeButtonPaddingY?(me.style.paddingTop=Te.closeButtonPaddingY,me.style.paddingBottom=Te.closeButtonPaddingY):(me.style.paddingTop="",me.style.paddingBottom="");let ln=(wl=Te.closeButtonIconName)!=null?wl:"x",Vn=(Sl=Te.closeButtonIconText)!=null?Sl:"\xD7";me.innerHTML="";let gn=be(ln,"20px","currentColor",2);gn?me.appendChild(gn):me.textContent=Vn;let _t=(Al=Te.closeButtonTooltipText)!=null?Al:"Close chat",Pn=(El=Te.closeButtonShowTooltip)!=null?El:!0;if(me.setAttribute("aria-label",_t),Ye&&(Ye._cleanupTooltip&&(Ye._cleanupTooltip(),delete Ye._cleanupTooltip),Pn&&_t)){let nt=null,Qt=()=>{if(nt||!me)return;let Dr=me.ownerDocument,So=Dr.body;if(!So)return;nt=er(Dr,"div","persona-clear-chat-tooltip"),nt.textContent=_t;let Ao=er(Dr,"div");Ao.className="persona-clear-chat-tooltip-arrow",nt.appendChild(Ao);let Fr=me.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(Cr),nt.style.left=`${Fr.left+Fr.width/2}px`,nt.style.top=`${Fr.top-8}px`,nt.style.transform="translate(-50%, -100%)",So.appendChild(nt)},Cn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};Ye.addEventListener("mouseenter",Qt),Ye.addEventListener("mouseleave",Cn),me.addEventListener("focus",Qt),me.addEventListener("blur",Cn),Ye._cleanupTooltip=()=>{Cn(),Ye&&(Ye.removeEventListener("mouseenter",Qt),Ye.removeEventListener("mouseleave",Cn)),me&&(me.removeEventListener("focus",Qt),me.removeEventListener("blur",Cn))}}}let{clearChatButton:Je,clearChatButtonWrapper:Mt}=ae;if(Je){let J=(Tl=Te.clearChat)!=null?Tl:{},pt=(Ml=J.enabled)!=null?Ml:!0,Ht=(Ll=(kl=n.layout)==null?void 0:kl.header)==null?void 0:Ll.showClearChat,Ye=Ht!==void 0?Ht:pt,ft=(Il=J.placement)!=null?Il:"inline";if(Mt){Mt.style.display=Ye?"":"none";let{closeButtonWrapper:Kt}=ae;Kt&&!Kt.classList.contains("persona-absolute")&&(Ye?Kt.classList.remove("persona-ml-auto"):Kt.classList.add("persona-ml-auto"));let ln=ft==="top-right",Vn=Mt.classList.contains("persona-absolute");if(ln!==Vn&&Ye){if(Mt.remove(),ln)Mt.className="persona-absolute persona-top-4 persona-z-50",Mt.style.right="48px",$.style.position="relative",$.appendChild(Mt);else{Mt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Mt.style.right="";let _t=$.querySelector(".persona-border-b-persona-divider"),Pn=ae.closeButtonWrapper;_t&&Pn&&Pn.parentElement===_t?_t.insertBefore(Mt,Pn):_t&&_t.appendChild(Mt)}let gn=ae.closeButtonWrapper;gn&&!gn.classList.contains("persona-absolute")&&(ln?gn.classList.add("persona-ml-auto"):gn.classList.remove("persona-ml-auto"))}}if(Ye){let Kt=(Pl=J.size)!=null?Pl:"32px";Je.style.height=Kt,Je.style.width=Kt;let ln=(Wl=J.iconName)!=null?Wl:"refresh-cw",Vn=(Rl=J.iconColor)!=null?Rl:"";Je.style.color=Vn||Sn.actionIconColor,Je.innerHTML="";let gn=be(ln,"20px","currentColor",2);if(gn&&Je.appendChild(gn),J.backgroundColor?(Je.style.backgroundColor=J.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let nt=J.borderWidth||"0px",Qt=J.borderColor||"transparent";Je.style.border=`${nt} solid ${Qt}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");J.borderRadius?(Je.style.borderRadius=J.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),J.paddingX?(Je.style.paddingLeft=J.paddingX,Je.style.paddingRight=J.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),J.paddingY?(Je.style.paddingTop=J.paddingY,Je.style.paddingBottom=J.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let _t=(Hl=J.tooltipText)!=null?Hl:"Clear chat",Pn=(Bl=J.showTooltip)!=null?Bl:!0;if(Je.setAttribute("aria-label",_t),Mt&&(Mt._cleanupTooltip&&(Mt._cleanupTooltip(),delete Mt._cleanupTooltip),Pn&&_t)){let nt=null,Qt=()=>{if(nt||!Je)return;let Dr=Je.ownerDocument,So=Dr.body;if(!So)return;nt=er(Dr,"div","persona-clear-chat-tooltip"),nt.textContent=_t;let Ao=er(Dr,"div");Ao.className="persona-clear-chat-tooltip-arrow",nt.appendChild(Ao);let Fr=Je.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(Cr),nt.style.left=`${Fr.left+Fr.width/2}px`,nt.style.top=`${Fr.top-8}px`,nt.style.transform="translate(-50%, -100%)",So.appendChild(nt)},Cn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};Mt.addEventListener("mouseenter",Qt),Mt.addEventListener("mouseleave",Cn),Je.addEventListener("focus",Qt),Je.addEventListener("blur",Cn),Mt._cleanupTooltip=()=>{Cn(),Mt&&(Mt.removeEventListener("mouseenter",Qt),Mt.removeEventListener("mouseleave",Cn)),Je&&(Je.removeEventListener("focus",Qt),Je.removeEventListener("blur",Cn))}}}}let Rr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[ks],Hr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ao.message,ao.messageAndClick];M=Ls({parsers:Rr,handlers:Hr,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),O=Cd(n,M,G),D.updateConfig(n),Lr(de,D.getMessages(),O),jn.render(n.suggestionChips,D,ee,void 0,n.suggestionChipsConfig),fo(),qr(D.isStreaming());let Qo=((Dl=n.voiceRecognition)==null?void 0:Dl.enabled)===!0,es=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ts=((Nl=(Fl=n.voiceRecognition)==null?void 0:Fl.provider)==null?void 0:Nl.type)==="runtype";if(Qo&&(es||ts))if(!z||!He){let J=Zo(n.voiceRecognition,n.sendButton);J&&(z=J.micButton,He=J.micButtonWrapper,rn.insertBefore(He,Lt),z.addEventListener("click",lt),z.disabled=D.isStreaming())}else{let J=(Ol=n.voiceRecognition)!=null?Ol:{},pt=($l=n.sendButton)!=null?$l:{},Ht=(_l=J.iconName)!=null?_l:"mic",Ye=(jl=pt.size)!=null?jl:"40px",ft=(zl=J.iconSize)!=null?zl:Ye,Kt=parseFloat(ft)||24;z.style.width=ft,z.style.height=ft,z.style.minWidth=ft,z.style.minHeight=ft;let ln=(Ul=(ql=J.iconColor)!=null?ql:pt.textColor)!=null?Ul:"currentColor";z.innerHTML="";let Vn=be(Ht,Kt,ln,2);Vn?z.appendChild(Vn):z.textContent="\u{1F3A4}";let gn=(Vl=J.backgroundColor)!=null?Vl:pt.backgroundColor;gn?z.style.backgroundColor=gn:z.style.backgroundColor="",ln?z.style.color=ln:z.style.color="var(--persona-text, #111827)",J.borderWidth?(z.style.borderWidth=J.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),J.borderColor?z.style.borderColor=J.borderColor:z.style.borderColor="",J.paddingX?(z.style.paddingLeft=J.paddingX,z.style.paddingRight=J.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),J.paddingY?(z.style.paddingTop=J.paddingY,z.style.paddingBottom=J.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let _t=He==null?void 0:He.querySelector(".persona-send-button-tooltip"),Pn=(Jl=J.tooltipText)!=null?Jl:"Start voice recognition";if(((Yl=J.showTooltip)!=null?Yl:!1)&&Pn)if(_t)_t.textContent=Pn,_t.style.display="";else{let Qt=document.createElement("div");Qt.className="persona-send-button-tooltip",Qt.textContent=Pn,He==null||He.insertBefore(Qt,z)}else _t&&(_t.style.display="none");He.style.display="",z.disabled=D.isStreaming()}else z&&He&&(He.style.display="none",((Kl=(Gl=n.voiceRecognition)==null?void 0:Gl.provider)==null?void 0:Kl.type)==="runtype"?D.isVoiceActive()&&D.toggleVoice():In&&qn());if(((Xl=n.attachments)==null?void 0:Xl.enabled)===!0)if(!ht||!ye){let J=(Zl=n.attachments)!=null?Zl:{},Ht=(ec=((Ql=n.sendButton)!=null?Ql:{}).size)!=null?ec:"40px";ce||(ce=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ce.style.display="none",ct.insertBefore(ce,ee)),$e||($e=document.createElement("input"),$e.type="file",$e.accept=((tc=J.allowedTypes)!=null?tc:dr).join(","),$e.multiple=((nc=J.maxFiles)!=null?nc:4)>1,$e.style.display="none",$e.setAttribute("aria-label","Attach files"),ct.insertBefore($e,ee)),ht=h("div","persona-send-button-wrapper"),ye=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ye.type="button",ye.setAttribute("aria-label",(rc=J.buttonTooltipText)!=null?rc:"Attach file");let Ye=(oc=J.buttonIconName)!=null?oc:"paperclip",ft=Ht,Kt=parseFloat(ft)||40,ln=Math.round(Kt*.6);ye.style.width=ft,ye.style.height=ft,ye.style.minWidth=ft,ye.style.minHeight=ft,ye.style.fontSize="18px",ye.style.lineHeight="1",ye.style.backgroundColor="transparent",ye.style.color="var(--persona-primary, #111827)",ye.style.border="none",ye.style.borderRadius="6px",ye.style.transition="background-color 0.15s ease",ye.addEventListener("mouseenter",()=>{ye.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ye.addEventListener("mouseleave",()=>{ye.style.backgroundColor="transparent"});let Vn=be(Ye,ln,"currentColor",1.5);Vn?ye.appendChild(Vn):ye.textContent="\u{1F4CE}",ye.addEventListener("click",Pn=>{Pn.preventDefault(),$e==null||$e.click()}),ht.appendChild(ye);let gn=(sc=J.buttonTooltipText)!=null?sc:"Attach file",_t=h("div","persona-send-button-tooltip");_t.textContent=gn,ht.appendChild(_t),tn.append(ht),!De&&$e&&ce&&(De=eo.fromConfig(J),De.setPreviewsContainer(ce),$e.addEventListener("change",async()=>{De&&($e!=null&&$e.files)&&(await De.handleFileSelect($e.files),$e.value="")})),$.querySelector(".persona-attachment-drop-overlay")||$.appendChild(wd(J.dropOverlay))}else{ht.style.display="";let J=(ac=n.attachments)!=null?ac:{};$e&&($e.accept=((ic=J.allowedTypes)!=null?ic:dr).join(","),$e.multiple=((lc=J.maxFiles)!=null?lc:4)>1),De&&De.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles})}else ht&&(ht.style.display="none"),De&&De.clearAttachments(),(cc=$.querySelector(".persona-attachment-drop-overlay"))==null||cc.remove();let Ut=(dc=n.sendButton)!=null?dc:{},ns=(pc=Ut.useIcon)!=null?pc:!1,vo=(uc=Ut.iconText)!=null?uc:"\u2191",vn=Ut.iconName,Fn=(mc=Ut.tooltipText)!=null?mc:"Send message",Yr=(gc=Ut.showTooltip)!=null?gc:!1,Co=(fc=Ut.size)!=null?fc:"40px",rs=Ut.backgroundColor,Br=Ut.textColor;if(ns){if(le.style.width=Co,le.style.height=Co,le.style.minWidth=Co,le.style.minHeight=Co,le.style.fontSize="18px",le.style.lineHeight="1",le.innerHTML="",Br?le.style.color=Br:le.style.color="var(--persona-button-primary-fg, #ffffff)",vn){let J=parseFloat(Co)||24,pt=(Br==null?void 0:Br.trim())||"currentColor",Ht=be(vn,J,pt,2);Ht?le.appendChild(Ht):le.textContent=vo}else le.textContent=vo;le.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",rs?(le.style.backgroundColor=rs,le.classList.remove("persona-bg-persona-primary")):(le.style.backgroundColor="",le.classList.add("persona-bg-persona-primary"))}else le.textContent=(yc=(hc=n.copy)==null?void 0:hc.sendButtonLabel)!=null?yc:"Send",le.style.width="",le.style.height="",le.style.minWidth="",le.style.minHeight="",le.style.fontSize="",le.style.lineHeight="",le.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",rs?(le.style.backgroundColor=rs,le.classList.remove("persona-bg-persona-accent")):le.classList.add("persona-bg-persona-accent"),Br?le.style.color=Br:le.classList.add("persona-text-white");Ut.borderWidth?(le.style.borderWidth=Ut.borderWidth,le.style.borderStyle="solid"):(le.style.borderWidth="",le.style.borderStyle=""),Ut.borderColor?le.style.borderColor=Ut.borderColor:le.style.borderColor="",Ut.paddingX?(le.style.paddingLeft=Ut.paddingX,le.style.paddingRight=Ut.paddingX):(le.style.paddingLeft="",le.style.paddingRight=""),Ut.paddingY?(le.style.paddingTop=Ut.paddingY,le.style.paddingBottom=Ut.paddingY):(le.style.paddingTop="",le.style.paddingBottom="");let wo=Lt==null?void 0:Lt.querySelector(".persona-send-button-tooltip");if(Yr&&Fn)if(wo)wo.textContent=Fn,wo.style.display="";else{let J=document.createElement("div");J.className="persona-send-button-tooltip",J.textContent=Fn,Lt==null||Lt.insertBefore(J,le)}else wo&&(wo.style.display="none");let os=(bc=n.layout)==null?void 0:bc.contentMaxWidth;os?(de.style.maxWidth=os,de.style.marginLeft="auto",de.style.marginRight="auto",de.style.width="100%",ct&&(ct.style.maxWidth=os,ct.style.marginLeft="auto",ct.style.marginRight="auto"),_e&&(_e.style.maxWidth=os,_e.style.marginLeft="auto",_e.style.marginRight="auto")):(de.style.maxWidth="",de.style.marginLeft="",de.style.marginRight="",de.style.width="",ct&&(ct.style.maxWidth="",ct.style.marginLeft="",ct.style.marginRight=""),_e&&(_e.style.maxWidth="",_e.style.marginLeft="",_e.style.marginRight=""));let vr=(xc=n.statusIndicator)!=null?xc:{},rp=(vc=vr.visible)!=null?vc:!0;if(Dt.style.display=rp?"":"none",D){let J=D.getStatus();Xe(Dt,(Ht=>{var Ye,ft,Kt,ln;return Ht==="idle"?(Ye=vr.idleText)!=null?Ye:cn.idle:Ht==="connecting"?(ft=vr.connectingText)!=null?ft:cn.connecting:Ht==="connected"?(Kt=vr.connectedText)!=null?Kt:cn.connected:Ht==="error"?(ln=vr.errorText)!=null?ln:cn.error:cn[Ht]})(J),vr,J)}Dt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let op=vr.align==="left"?"persona-text-left":vr.align==="center"?"persona-text-center":"persona-text-right";Dt.classList.add(op)},open(){C&&Rt(!0,"api")},close(){C&&Rt(!1,"api")},toggle(){C&&Rt(!E,"api")},clearChat(){dn=!1,D.clearMessages(),Hn.clear(),br();try{localStorage.removeItem(io),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${io}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==io)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.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),a!=null&&a.clear)try{let m=a.clear();m instanceof Promise&&m.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}i={},M.syncFromMetadata(),se==null||se.clear(),K==null||K.update()},setMessage(l){return!ee||D.isStreaming()?!1:(!E&&C&&Rt(!0,"system"),ee.value=l,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(D.isStreaming())return!1;let m=(l==null?void 0:l.trim())||ee.value.trim();return m?(!E&&C&&Rt(!0,"system"),ee.value="",ee.style.height="auto",D.sendMessage(m),!0):!1},startVoiceRecognition(){var m,y;return D.isStreaming()?!1:((y=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype"?(D.isVoiceActive()||(!E&&C&&Rt(!0,"system"),Qe.manuallyDeactivated=!1,yn(),D.toggleVoice().then(()=>{Qe.active=D.isVoiceActive(),Bn("user"),D.isVoiceActive()&&X()})),!0):In?!0:xo()?(!E&&C&&Rt(!0,"system"),Qe.manuallyDeactivated=!1,yn(),Pr("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?D.isVoiceActive()?(D.toggleVoice().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,yn(),Bn("user"),xt()}),!0):!1:In?(Qe.manuallyDeactivated=!0,yn(),qn("user"),!0):!1},injectMessage(l){return!E&&C&&Rt(!0,"system"),D.injectMessage(l)},injectAssistantMessage(l){!E&&C&&Rt(!0,"system");let m=D.injectAssistantMessage(l);return Y&&(Y=!1,Q&&(clearTimeout(Q),Q=null),setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)),m},injectUserMessage(l){return!E&&C&&Rt(!0,"system"),D.injectUserMessage(l)},injectSystemMessage(l){return!E&&C&&Rt(!0,"system"),D.injectSystemMessage(l)},injectMessageBatch(l){return!E&&C&&Rt(!0,"system"),D.injectMessageBatch(l)},injectTestMessage(l){!E&&C&&Rt(!0,"system"),D.injectTestEvent(l)},async connectStream(l,m){return D.connectStream(l,m)},__pushEventStreamEvent(l){se&&se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!oe||!se||nr()},hideEventStream(){ue&&$n()},isEventStreamVisible(){return ue},showArtifacts(){On(n)&&(dn=!1,Tn(),at==null||at.setMobileOpen(!0))},hideArtifacts(){On(n)&&(dn=!0,Tn())},upsertArtifact(l){return On(n)?(dn=!1,D.upsertArtifact(l)):null},selectArtifact(l){On(n)&&D.selectArtifact(l)},clearArtifacts(){On(n)&&D.clearArtifacts()},focusInput(){return C&&!E||!ee?!1:(ee.focus(),!0)},async resolveApproval(l,m){let A=D.getMessages().find(I=>{var R;return I.variant==="approval"&&((R=I.approval)==null?void 0:R.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return D.resolveApproval(A.approval,m)},getMessages(){return D.getMessages()},getStatus(){return D.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){f(l)},on(l,m){return o.on(l,m)},off(l,m){o.off(l,m)},isOpen(){return C&&E},isVoiceActive(){return Qe.active},getState(){return{open:C&&E,launcherEnabled:C,voiceActive:Qe.active,streaming:D.isStreaming()}},showCSATFeedback(l){!E&&C&&Rt(!0,"system");let m=de.querySelector(".persona-feedback-container");m&&m.remove();let y=ba({onSubmit:async(A,I)=>{var R;D.isClientTokenMode()&&await D.submitCSATFeedback(A,I),(R=l==null?void 0:l.onSubmit)==null||R.call(l,A,I)},onDismiss:l==null?void 0:l.onDismiss,...l});de.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!E&&C&&Rt(!0,"system");let m=de.querySelector(".persona-feedback-container");m&&m.remove();let y=xa({onSubmit:async(A,I)=>{var R;D.isClientTokenMode()&&await D.submitNPSFeedback(A,I),(R=l==null?void 0:l.onSubmit)==null||R.call(l,A,I)},onDismiss:l==null?void 0:l.onDismiss,...l});de.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,m){return D.submitCSATFeedback(l,m)},async submitNPSFeedback(l,m){return D.submitNPSFeedback(l,m)},destroy(){Qn!=null&&(clearInterval(Qn),Qn=null),wt.forEach(l=>l()),j.remove(),ne==null||ne.destroy(),T==null||T.remove(),kn&&me.removeEventListener("click",kn)}};if((((gi=t==null?void 0:t.debugTools)!=null?gi:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:Yt,getMessages:Yt.getMessages,getStatus:Yt.getStatus,getMetadata:Yt.getPersistentMetadata,updateMetadata:Yt.updatePersistentMetadata,clearHistory:()=>Yt.clearChat(),setVoiceActive:y=>y?Yt.startVoiceRecognition():Yt.stopVoiceRecognition()};window.AgentWidgetBrowser=m,wt.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=V=>{let N=V.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&Yt.focusInput()};if(window.addEventListener("persona:focusInput",m),wt.push(()=>{window.removeEventListener("persona:focusInput",m)}),oe){let V=xe=>{let Ee=xe.detail;(!(Ee!=null&&Ee.instanceId)||Ee.instanceId===l)&&Yt.showEventStream()},N=xe=>{let Ee=xe.detail;(!(Ee!=null&&Ee.instanceId)||Ee.instanceId===l)&&Yt.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",N),wt.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",N)})}let y=V=>{let N=V.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&Yt.showArtifacts()},A=V=>{let N=V.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&Yt.hideArtifacts()},I=V=>{let N=V.detail;N!=null&&N.instanceId&&N.instanceId!==l||N!=null&&N.artifact&&Yt.upsertArtifact(N.artifact)},R=V=>{let N=V.detail;N!=null&&N.instanceId&&N.instanceId!==l||typeof(N==null?void 0:N.id)=="string"&&Yt.selectArtifact(N.id)},B=V=>{let N=V.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&Yt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",I),window.addEventListener("persona:selectArtifact",R),window.addEventListener("persona:clearArtifacts",B),wt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",I),window.removeEventListener("persona:selectArtifact",R),window.removeEventListener("persona:clearArtifacts",B)})}let Dn=Bu(n.persistState);if(Dn&&C){let l=Du(Dn.storage),m=`${Dn.keyPrefix}widget-open`,y=`${Dn.keyPrefix}widget-voice`,A=`${Dn.keyPrefix}widget-voice-mode`;if(l){let I=((fi=Dn.persist)==null?void 0:fi.openState)&&l.getItem(m)==="true",R=((hi=Dn.persist)==null?void 0:hi.voiceState)&&l.getItem(y)==="true",B=((yi=Dn.persist)==null?void 0:yi.voiceState)&&l.getItem(A)==="true";if(I&&setTimeout(()=>{Yt.open(),setTimeout(()=>{var V;if(R||B)Yt.startVoiceRecognition();else if((V=Dn.persist)!=null&&V.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),(bi=Dn.persist)!=null&&bi.openState&&(o.on("widget:opened",()=>{l.setItem(m,"true")}),o.on("widget:closed",()=>{l.setItem(m,"false")})),(xi=Dn.persist)!=null&&xi.voiceState&&(o.on("voice:state",V=>{l.setItem(y,V.active?"true":"false")}),o.on("user:message",V=>{l.setItem(A,V.viaVoice?"true":"false")})),Dn.clearOnChatClear){let V=()=>{l.removeItem(m),l.removeItem(y),l.removeItem(A)},N=()=>V();window.addEventListener("persona:clear-chat",N),wt.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return c&&C&&setTimeout(()=>{Yt.open()},0),Yt};var Fu=(e,r)=>{let t=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(n)return Math.max(0,parseFloat(n[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,r*parseFloat(s[1])/100):420},Sd=(e,r)=>{var n,s;let t=(s=(n=r==null?void 0:r.launcher)==null?void 0:n.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},Ea=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=""},Ad=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Ea(e)},wa=e=>{e.style.transition=""},Sa=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=""},Aa=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ps=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},Nu=(e,r,t,n,s)=>{s?t.parentElement!==r&&(e.replaceChildren(),r.replaceChildren(t,n),e.appendChild(r)):t.parentElement===r&&(r.replaceChildren(),e.appendChild(t),e.appendChild(n))},Ou=(e,r,t,n,s,o)=>{let a=o?r:e;s==="left"?a.firstElementChild!==n&&a.replaceChildren(n,t):a.lastElementChild!==n&&a.replaceChildren(t,n)},Ed=(e,r,t,n,s,o,a)=>{var v,M,C,S,k,H;let i=Jn(o),u=i.reveal==="push";Nu(e,r,t,n,u),Ou(e,r,t,n,i.side,u),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",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,p=(M=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?M:!0,d=(S=(C=o==null?void 0:o.launcher)==null?void 0:C.mobileBreakpoint)!=null?S:640,f=c!=null?c.innerWidth<=d:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Sa(r),wa(n),Ad(n),Aa(t),Ps(s,n),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((H=(k=o==null?void 0:o.launcher)==null?void 0:k.zIndex)!=null?H:wn),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",u&&(r.style.display="flex",r.style.flexDirection="column",r.style.width="100%",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.flex="1 1 auto",r.style.alignItems="stretch",r.style.transform="none",r.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Ad(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Sa(r),wa(n),Aa(t),Ps(s,n);let w=i.animate?"transform 180ms ease":"none",L=i.side==="right"?"translateX(100%)":"translateX(-100%)",P=a?"translateX(0)":L;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=w,n.style.transform=P,n.style.pointerEvents=a?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.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",wa(n),Ea(n),Ps(s,n);let w=Fu(i.width,e.clientWidth),L=Math.max(0,e.clientWidth),P=i.animate?"transform 180ms ease":"none",E=i.side==="right"?a?`translateX(-${w}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${w}px)`;r.style.display="flex",r.style.flexDirection="row",r.style.flex="0 0 auto",r.style.minHeight="0",r.style.minWidth="0",r.style.alignItems="stretch",r.style.height="100%",r.style.width=`${L+w}px`,r.style.transition=P,r.style.transform=E,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${L}px`,t.style.maxWidth=`${L}px`,t.style.minWidth=`${L}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Sa(r),Ea(n),Aa(t),Ps(s,n);let w=i.reveal==="emerge";w?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let L=a?i.width:"0px",P=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",E=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${L}`,n.style.width=L,n.style.maxWidth=L,n.style.minWidth=L,n.style.minHeight="0",n.style.position="relative",n.style.overflow=w||E?"hidden":"visible",n.style.transition=P,w&&(n.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},$u=(e,r)=>{let t=e.ownerDocument.createElement("div");return Sd(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){Sd(t,n)},destroy(){t.remove()}}},_u=(e,r)=>{var k,H,w,L;let{ownerDocument:t}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),u=t.createElement("div"),c=t.createElement("aside"),p=t.createElement("div"),d=(H=(k=r==null?void 0:r.launcher)==null?void 0:k.enabled)==null||H?(L=(w=r==null?void 0:r.launcher)==null?void 0:w.autoExpand)!=null?L:!1:!0;i.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),n.insertBefore(a,e),u.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},v=()=>{g(),Jn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Ed(a,i,u,c,p,r,d)}),f.observe(a))},M=()=>{Ed(a,i,u,c,p,r,d),v()},C=a.ownerDocument.defaultView,S=()=>{M()};return C==null||C.addEventListener("resize",S),Jn(r).reveal==="push"?(i.appendChild(u),i.appendChild(c),a.appendChild(i)):(a.appendChild(u),a.appendChild(c)),M(),{mode:"docked",host:p,shell:a,syncWidgetState(P){let E=P.launcherEnabled?P.open:!0;d!==E&&(d=E,M())},updateConfig(P){var E,Y;r=P,((Y=(E=r==null?void 0:r.launcher)==null?void 0:E.enabled)!=null?Y:!0)===!1&&(d=!0),M()},destroy(){C==null||C.removeEventListener("resize",S),g(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},Ws=(e,r)=>en(r)?_u(e,r):$u(e,r);var Ta={},ju=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 r=document.querySelector(e);if(!r)throw new Error(`Chat widget target "${e}" was not found`);return r}return e},zu=()=>{try{if(typeof Ta!="undefined"&&Ta.url)return new URL("../widget.css",Ta.url).href}catch{}return null},Td=(e,r)=>{let t=zu(),n=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=r.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=r.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else n();else if(!r.head.querySelector("link[data-persona]")&&t){let o=r.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),r.head.appendChild(o)}},Md=e=>{var C;let r=ju(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=Ws(r,s),a,i=[],u=(S,k)=>{var P,E;let w=!((E=(P=k==null?void 0:k.launcher)==null?void 0:P.enabled)!=null?E:!0)||en(k),L=n.createElement("div");if(L.setAttribute("data-persona-root","true"),w&&(L.style.height="100%",L.style.display="flex",L.style.flexDirection="column",L.style.flex="1",L.style.minHeight="0"),t){let Y=S.attachShadow({mode:"open"});Y.appendChild(L),Td(Y,n)}else S.appendChild(L),Td(S,n);return r.id&&L.setAttribute("data-persona-instance",r.id),L},c=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},d=()=>{let S=u(o.host,s);a=Ca(S,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(S=>S()),i=[],a.destroy()};d(),(C=e.onReady)==null||C.call(e);let g=S=>{f(),o.destroy(),o=Ws(r,S),s=S,d()},v={update(S){var L,P,E,Y,Q,G;let k={...s,...S,launcher:{...(L=s==null?void 0:s.launcher)!=null?L:{},...(P=S==null?void 0:S.launcher)!=null?P:{},dock:{...(Y=(E=s==null?void 0:s.launcher)==null?void 0:E.dock)!=null?Y:{},...(G=(Q=S==null?void 0:S.launcher)==null?void 0:Q.dock)!=null?G:{}}}},H=en(s),w=en(k);if(H!==w){g(k);return}s=k,o.updateConfig(s),a.update(S),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},M=new Proxy(v,{get(S,k,H){if(k==="host")return o.host;if(k in S)return Reflect.get(S,k,H);let w=a[k];return typeof w=="function"?w.bind(a):w}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=M),M};var Wd=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),qu=new Set(["button","a","input","select","textarea","details","summary"]),Uu=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ma=/\b(product|card|item|listing|result)\b/i,La=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Vu=3e3,Ju=100;function Rd(e){let r=typeof e.className=="string"?e.className:"";if(Ma.test(r)||e.id&&Ma.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&Ma.test(n.value))return!0}return!1}function Hd(e){var r;return La.test(((r=e.textContent)!=null?r:"").trim())}function Bd(e){var t;let r=e.querySelectorAll("a[href]");for(let n=0;n<r.length;n++){let s=(t=r[n].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Yu(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function kd(e){let r=e.match(La);return r?r[0]:null}function Ld(e){var n,s,o;let r=(n=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:e.querySelector("a[href]");if(r&&((s=r.textContent)!=null&&s.trim())){let a=r.getAttribute("href");return{title:r.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function Gu(e){let r=[],t=n=>{let s=n.trim();s&&!r.includes(s)&&r.push(s)};return e.querySelectorAll("button").forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var s;t((s=n.value)!=null?s:"")}),r.slice(0,6)}var Ku="commerce-card",Xu="result-card";function Id(e){return!Rd(e)||!Hd(e)||!Bd(e)&&!Yu(e)?0:5200}function Pd(e){var n;return!Rd(e)||Hd(e)||!Bd(e)||((n=e.textContent)!=null?n:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Dd=[{id:Ku,scoreElement(e){return Id(e)},shouldSuppressDescendant(e,r,t){if(r===e||!e.contains(r))return!1;if(t.interactivity==="static"){let n=t.text.trim();return!!(n.length===0||La.test(n)&&n.length<32)}return!0},formatSummary(e,r){var u,c,p;if(Id(e)===0)return null;let{title:t,href:n}=Ld(e),s=(p=(c=kd(((u=e.textContent)!=null?u:"").trim()))!=null?c:kd(r.text))!=null?p:"",o=Gu(e);return[n&&t?`[${t}](${n})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||r.text.trim().slice(0,120),`selector: ${r.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
99
+ `}if(!A&&!l){let vn="max-height: -moz-available !important; max-height: stretch !important;",Fn=m?"":"padding-top: 1.25em !important;",Yr=m?"":`z-index: ${(vo=(ns=n.launcher)==null?void 0:ns.zIndex)!=null?vo:wn} !important;`;j.style.cssText+=vn+Fn+Yr}};Zn(),$r(e,n),Es(e,n),Ts(e,n);let wt=[],Nt=null,Ot=null;wt.push(()=>{Nt==null||Nt(),Nt=null,Ot==null||Ot(),Ot=null}),An&&wt.push(()=>{An==null||An.disconnect(),An=null}),wt.push(()=>{pn==null||pn(),pn=null,or(),At&&(At.remove(),At=null),at==null||at.element.style.removeProperty("width"),at==null||at.element.style.removeProperty("maxWidth")}),oe&&wt.push(()=>{U!==null&&(cancelAnimationFrame(U),U=null),K==null||K.destroy(),K=null,se==null||se.destroy(),se=null,ke=null});let Mn=null,hr=()=>{Mn&&(Mn(),Mn=null),n.colorScheme==="auto"&&(Mn=ea(()=>{$r(e,n)}))};hr(),wt.push(()=>{Mn&&(Mn(),Mn=null)});let jn=id(_e),kn=null,D,zn=!1,Hn=Jc(),yr=0,fn=xs(),hn=0,ie=null,Ln=!1,sr=!1,qo=4,co=24,Uo=80,zr=new Map,Qe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},po=(di=(ci=n.voiceRecognition)==null?void 0:ci.autoResume)!=null?di:!1,Bn=l=>{o.emit("voice:state",{active:Qe.active,source:l,timestamp:Date.now()})},yn=()=>{f(l=>({...l,voiceState:{active:Qe.active,timestamp:Date.now(),manuallyDeactivated:Qe.manuallyDeactivated}}))},Vo=()=>{var A,I;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=va(i.voiceState),m=!!l.active,y=Number((I=l.timestamp)!=null?I:0);Qe.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-y<Wu&&setTimeout(()=>{var R,B;Qe.active||(Qe.manuallyDeactivated=!1,((B=(R=n.voiceRecognition)==null?void 0:R.provider)==null?void 0:B.type)==="runtype"?D.toggleVoice().then(()=>{Qe.active=D.isVoiceActive(),Bn("restore"),D.isVoiceActive()&&X()}):Pr("restore"))},1e3)},Jo=()=>D?vd(D.getMessages()).filter(l=>!l.__skipPersist):[];function uo(l){if(!(a!=null&&a.save))return;let y={messages:l?vd(l):D?Jo():[],metadata:i};try{let A=a.save(y);A instanceof Promise&&A.catch(I=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",I)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let ar=null,Yo=()=>j.querySelector("#persona-scroll-container")||q,kr=()=>{ar!==null&&(cancelAnimationFrame(ar),ar=null),Ln=!1},mo=()=>{ie!==null&&(cancelAnimationFrame(ie),ie=null),sr=!1,kr()},ir=()=>{if(!jt()||ue){pt.parentNode&&pt.remove(),pt.style.display="none";return}pt.parentNode!==$&&$.appendChild(pt),Ze();let l=Bo(q)>0;pt.style.display=fn.isFollowing()||!l?"none":""},go=()=>{fn.pause()&&(mo(),ir())},br=()=>{fn.resume(),ir()},xr=(l=!1)=>{fn.isFollowing()&&(!l&&!zn||(ie!==null&&(cancelAnimationFrame(ie),ie=null),sr=!0,ie=requestAnimationFrame(()=>{ie=null,sr=!1,fn.isFollowing()&&Go(Yo(),l?220:140)})))},Go=(l,m=500)=>{let y=l.scrollTop,A=Bo(l),I=A-y;if(Math.abs(I)<1){hn=l.scrollTop;return}if(Math.abs(I)>=Uo){kr(),Ln=!0,l.scrollTop=A,hn=l.scrollTop,Ln=!1;return}kr();let R=performance.now();Ln=!0;let B=N=>1-Math.pow(1-N,3),V=N=>{if(!fn.isFollowing()){kr();return}let xe=Bo(l);xe!==A&&(A=xe,I=A-y);let Ee=N-R,Me=Math.min(Ee/m,1),Ae=B(Me),Ie=y+I*Ae;l.scrollTop=Ie,hn=l.scrollTop,Me<1?ar=requestAnimationFrame(V):(l.scrollTop=A,hn=l.scrollTop,ar=null,Ln=!1)};ar=requestAnimationFrame(V)},Ko=l=>{let m=new Map;l.forEach(y=>{let A=zr.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!A&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(A!=null&&A.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(A?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),zr.clear(),m.forEach((y,A)=>{zr.set(A,y)})},Lr=(l,m,y)=>{var Me,Ae,Ie,ze,mt,Ke;let A=document.createElement("div"),R=(()=>{var Pe;let _=s.find(Be=>Be.renderLoadingIndicator);if(_!=null&&_.renderLoadingIndicator)return _.renderLoadingIndicator;if((Pe=n.loadingIndicator)!=null&&Pe.render)return n.loadingIndicator.render})(),B=(_,Pe)=>Pe==null?!1:typeof Pe=="string"?(_.textContent=Pe,!0):(_.appendChild(Pe),!0),V=new Set;if(m.forEach(_=>{var Gt,sn;V.add(_.id);let Pe=Vc(_,yr),Be=Yc(Hn,_.id,Pe);if(Be){A.appendChild(Be.cloneNode(!0));return}let Ce=null,Fe=s.find(Te=>!!(_.variant==="reasoning"&&Te.renderReasoning||_.variant==="tool"&&Te.renderToolCall||_.variant==="approval"&&Te.renderApproval||!_.variant&&Te.renderMessage)),St=(Gt=n.layout)==null?void 0:Gt.messages;if(Fe)if(_.variant==="reasoning"&&_.reasoning&&Fe.renderReasoning){if(!re)return;Ce=Fe.renderReasoning({message:_,defaultRenderer:()=>sa(_,n),config:n})}else if(_.variant==="tool"&&_.toolCall&&Fe.renderToolCall){if(!we)return;Ce=Fe.renderToolCall({message:_,defaultRenderer:()=>aa(_,n),config:n})}else if(_.variant==="approval"&&_.approval&&Fe.renderApproval){if(n.approval===!1)return;Ce=Fe.renderApproval({message:_,defaultRenderer:()=>ia(_,n),config:n})}else Fe.renderMessage&&(Ce=Fe.renderMessage({message:_,defaultRenderer:()=>{let Te=_o(_,y,St,n.messageActions,fe,{loadingIndicatorRenderer:R,widgetConfig:n});return _.role!=="user"&&da(Te,_,n,D),Te},config:n}));if(!Ce&&_.role==="assistant"&&!_.variant&&n.enableComponentStreaming!==!1&&ha(_)){let bn=ya(_);if(bn){let an=fa(bn,{config:n,message:_,transform:y});if(an)if(n.wrapComponentDirectiveInBubble!==!1){let rt=document.createElement("div");if(rt.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(" "),rt.id=`bubble-${_.id}`,rt.setAttribute("data-message-id",_.id),_.content&&_.content.trim()){let gt=document.createElement("div");gt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",gt.innerHTML=y({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),rt.appendChild(gt)}rt.appendChild(an),Ce=rt}else{let rt=document.createElement("div");if(rt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",rt.id=`bubble-${_.id}`,rt.setAttribute("data-message-id",_.id),rt.setAttribute("data-persona-component-directive","true"),_.content&&_.content.trim()){let gt=document.createElement("div");gt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",gt.innerHTML=y({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),rt.appendChild(gt)}rt.appendChild(an),Ce=rt}}}if(!Ce)if(_.variant==="reasoning"&&_.reasoning){if(!re)return;Ce=sa(_,n)}else if(_.variant==="tool"&&_.toolCall){if(!we)return;Ce=aa(_,n)}else if(_.variant==="approval"&&_.approval){if(n.approval===!1)return;Ce=ia(_,n)}else{let Te=(sn=n.layout)==null?void 0:sn.messages;Te!=null&&Te.renderUserMessage&&_.role==="user"?Ce=Te.renderUserMessage({message:_,config:n,streaming:!!_.streaming}):Te!=null&&Te.renderAssistantMessage&&_.role==="assistant"?Ce=Te.renderAssistantMessage({message:_,config:n,streaming:!!_.streaming}):Ce=_o(_,y,Te,n.messageActions,fe,{loadingIndicatorRenderer:R,widgetConfig:n}),_.role!=="user"&&Ce&&da(Ce,_,n,D)}let vt=document.createElement("div");vt.className="persona-flex",vt.id=`wrapper-${_.id}`,vt.setAttribute("data-wrapper-id",_.id),_.role==="user"&&vt.classList.add("persona-justify-end"),(Ce==null?void 0:Ce.getAttribute("data-persona-component-directive"))==="true"&&vt.classList.add("persona-w-full"),vt.appendChild(Ce),Gc(Hn,_.id,Pe,vt),A.appendChild(vt)}),(Ae=(Me=n.features)==null?void 0:Me.toolCallDisplay)!=null&&Ae.grouped){let _=[],Pe=[];m.forEach(Be=>{if(Be.variant==="tool"&&Be.toolCall&&we){Pe.push(Be);return}Pe.length>1&&_.push(Pe),Pe=[]}),Pe.length>1&&_.push(Pe),_.forEach((Be,Ce)=>{var an,Un;let Fe=Be.map(rt=>Array.from(A.children).find(gt=>gt instanceof HTMLElement&&gt.getAttribute("data-wrapper-id")===rt.id)).filter(rt=>!!rt);if(Fe.length<2)return;let St=document.createElement("div");St.className="persona-flex",St.id=`wrapper-tool-group-${Ce}-${Be[0].id}`,St.setAttribute("data-wrapper-id",`tool-group-${Ce}-${Be[0].id}`);let vt=document.createElement("div");vt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",vt.setAttribute("data-persona-tool-group","true");let Gt=document.createElement("div");Gt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let sn=`Called ${Be.length} tools`,Te=(Un=(an=n.toolCall)==null?void 0:an.renderGroupedSummary)==null?void 0:Un.call(an,{messages:Be,toolCalls:Be.map(rt=>rt.toolCall).filter(rt=>!!rt),defaultSummary:sn,config:n});B(Gt,Te)||(Gt.textContent=sn);let bn=document.createElement("div");bn.className="persona-tool-group-stack persona-flex persona-flex-col",vt.append(Gt,bn),St.appendChild(vt),Fe[0].before(St),Fe.forEach((rt,gt)=>{let xn=document.createElement("div");xn.className="persona-tool-group-item persona-relative",xn.setAttribute("data-persona-tool-group-item","true"),gt<Fe.length-1&&xn.setAttribute("data-persona-tool-group-connector","true"),xn.appendChild(rt),bn.appendChild(xn)})})}Kc(Hn,V);let N=m.some(_=>_.role==="assistant"&&_.streaming),xe=m[m.length-1],Ee=(xe==null?void 0:xe.role)==="assistant"&&!xe.streaming&&xe.variant!=="approval";if(zn&&m.some(_=>_.role==="user")&&!N&&!Ee){let _={config:n,streaming:!0,location:"standalone",defaultRenderer:no},Pe=s.find(Ce=>Ce.renderLoadingIndicator),Be=null;if(Pe!=null&&Pe.renderLoadingIndicator&&(Be=Pe.renderLoadingIndicator(_)),Be===null&&((Ie=n.loadingIndicator)!=null&&Ie.render)&&(Be=n.loadingIndicator.render(_)),Be===null&&(Be=no()),Be){let Ce=document.createElement("div"),Fe=((ze=n.loadingIndicator)==null?void 0:ze.showBubble)!==!1;Ce.className=Fe?["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(" "),Ce.setAttribute("data-typing-indicator","true"),Ce.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ce.appendChild(Be);let St=document.createElement("div");St.className="persona-flex",St.id="wrapper-typing-indicator",St.setAttribute("data-wrapper-id","typing-indicator"),St.appendChild(Ce),A.appendChild(St)}}if(!zn&&m.length>0){let _=m[m.length-1],Pe={config:n,lastMessage:_,messageCount:m.length},Be=s.find(Fe=>Fe.renderIdleIndicator),Ce=null;if(Be!=null&&Be.renderIdleIndicator&&(Ce=Be.renderIdleIndicator(Pe)),Ce===null&&((mt=n.loadingIndicator)!=null&&mt.renderIdle)&&(Ce=n.loadingIndicator.renderIdle(Pe)),Ce){let Fe=document.createElement("div"),St=((Ke=n.loadingIndicator)==null?void 0:Ke.showBubble)!==!1;Fe.className=St?["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(" "),Fe.setAttribute("data-idle-indicator","true"),Fe.appendChild(Ce);let vt=document.createElement("div");vt.className="persona-flex",vt.id="wrapper-idle-indicator",vt.setAttribute("data-wrapper-id","idle-indicator"),vt.appendChild(Fe),A.appendChild(vt)}}Uc(l,A)},Ir=()=>{var N,xe,Ee,Me,Ae;if(!C)return;let l=en(n),m=(N=e.ownerDocument.defaultView)!=null?N:window,y=(Ee=(xe=n.launcher)==null?void 0:xe.mobileBreakpoint)!=null?Ee:640,A=(Ae=(Me=n.launcher)==null?void 0:Me.mobileFullscreen)!=null?Ae:!0,I=m.innerWidth<=y,R=A&&I&&C,B=Jn(n).reveal;E?(j.style.removeProperty("display"),j.style.display=l?"flex":"",j.classList.remove("persona-pointer-events-none","persona-opacity-0"),W.classList.remove("persona-scale-95","persona-opacity-0"),W.classList.add("persona-scale-100","persona-opacity-100"),ne?ne.element.style.display="none":T&&(T.style.display="none")):(l?l&&(B==="overlay"||B==="push")&&!R?(j.style.removeProperty("display"),j.style.display="flex",j.classList.remove("persona-pointer-events-none","persona-opacity-0"),W.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(j.style.setProperty("display","none","important"),j.classList.remove("persona-pointer-events-none","persona-opacity-0"),W.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(j.style.display="",j.classList.add("persona-pointer-events-none","persona-opacity-0"),W.classList.remove("persona-scale-100","persona-opacity-100"),W.classList.add("persona-scale-95","persona-opacity-0")),ne?ne.element.style.display=l?"none":"":T&&(T.style.display=l?"none":""))},Ht=(l,m="user")=>{var R,B;if(!C||E===l)return;let y=E;E=l,Ir();let A=(()=>{var Ie,ze,mt,Ke,_,Pe,Be;let V=(ze=(Ie=n.launcher)==null?void 0:Ie.sidebarMode)!=null?ze:!1,N=(mt=e.ownerDocument.defaultView)!=null?mt:window,xe=(_=(Ke=n.launcher)==null?void 0:Ke.mobileFullscreen)!=null?_:!0,Ee=(Be=(Pe=n.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Be:640,Me=N.innerWidth<=Ee,Ae=en(n)&&xe&&Me;return V||xe&&Me&&C||Ae})();if(E&&A){if(!Nt){let V=e.getRootNode(),N=V instanceof ShadowRoot?V.host:e.closest(".persona-host");N&&(Nt=ta(N,(B=(R=n.launcher)==null?void 0:R.zIndex)!=null?B:wn))}Ot||(Ot=na(e.ownerDocument))}else E||(Nt==null||Nt(),Nt=null,Ot==null||Ot(),Ot=null);E&&(x(),xr(!0));let I={open:E,source:m,timestamp:Date.now()};E&&!y?o.emit("widget:opened",I):!E&&y&&o.emit("widget:closed",I),o.emit("widget:state",{open:E,launcherEnabled:C,voiceActive:Qe.active,streaming:D.isStreaming()})},qr=l=>{le.disabled=l,z&&(z.disabled=l),jn.buttons.forEach(m=>{m.disabled=l}),st.dataset.personaComposerStreaming=l?"true":"false",st.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},Ur=()=>{Qe.active||ee&&ee.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Ur(),200)});let fo=()=>{var y,A,I,R,B,V,N,xe,Ee,Me,Ae;Xt.textContent=(A=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?A:"Hello \u{1F44B}",je.textContent=(R=(I=n.copy)==null?void 0:I.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",ee.placeholder=(V=(B=n.copy)==null?void 0:B.inputPlaceholder)!=null?V:"How can I help...";let l=q.querySelector("[data-persona-intro-card]");if(l){let Ie=((N=n.copy)==null?void 0:N.showWelcomeCard)!==!1;l.style.display=Ie?"":"none",Ie?(q.classList.remove("persona-gap-3"),q.classList.add("persona-gap-6")):(q.classList.remove("persona-gap-6"),q.classList.add("persona-gap-3"))}(Ee=(xe=n.sendButton)==null?void 0:xe.useIcon)!=null&&Ee||(le.textContent=(Ae=(Me=n.copy)==null?void 0:Me.sendButtonLabel)!=null?Ae:"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))"};n.clientToken&&(n={...n,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(m=>({...m,sessionId:l}))}});let Qn=null,Xo=()=>{Qn==null&&(Qn=setInterval(()=>{let l=de.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Qn),Qn=null;return}let m=Date.now();l.forEach(y=>{let A=Number(y.getAttribute("data-tool-elapsed"));A&&(y.textContent=is(m-A))})},100))};if(D=new Po(n,{onMessagesChanged(l){Lr(de,l,O),Xo(),D&&(l.some(I=>I.role==="user")?jn.render([],D,ee,l):jn.render(n.suggestionChips,D,ee,l,n.suggestionChipsConfig)),xr(!zn),Ko(l);let m=[...l].reverse().find(A=>A.role==="user"),y=Qe.lastUserMessageId;m&&m.id!==y&&(Qe.lastUserMessageId=m.id,o.emit("user:message",m)),Qe.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),uo(l)},onStatusChanged(l){var A;let m=(A=n.statusIndicator)!=null?A:{};Xe(Dt,(I=>{var R,B,V,N;return I==="idle"?(R=m.idleText)!=null?R:cn.idle:I==="connecting"?(B=m.connectingText)!=null?B:cn.connecting:I==="connected"?(V=m.connectedText)!=null?V:cn.connected:I==="error"?(N=m.errorText)!=null?N:cn.error:cn[I]})(l),m,l)},onStreamingChanged(l){zn=l,qr(l),D&&Lr(de,D.getMessages(),O),l||xr(!0)},onVoiceStatusChanged(l){var m,y;if(((y=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype")switch(l){case"listening":break;case"processing":xt(),Ve();break;case"speaking":xt(),tt();break;default:l==="idle"&&D.isBargeInActive()?(xt(),X(),z==null||z.setAttribute("aria-label","End voice session")):(Qe.active=!1,xt(),Bn("system"),yn());break}},onArtifactsState(l){_n=l,Tn()}}),mr.current=D,((ui=(pi=n.voiceRecognition)==null?void 0:pi.provider)==null?void 0:ui.type)==="runtype")try{D.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&D.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(se||n.onSSEEvent)&&D.setSSEEventCallback((l,m)=>{var y;(y=n.onSSEEvent)==null||y.call(n,l,m),se==null||se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})}),u&&u.then(l=>{var m;l&&(l.metadata&&(i=va(l.metadata),M.syncFromMetadata()),(m=l.messages)!=null&&m.length&&D.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let ho=l=>{var I;l.preventDefault();let m=ee.value.trim(),y=(I=De==null?void 0:De.hasAttachments())!=null?I:!1;if(!m&&!y)return;let A;y&&(A=[],A.push(...De.getContentParts()),m&&A.push(ps(m))),ee.value="",ee.style.height="auto",D.sendMessage(m,{contentParts:A}),y&&De.clearAttachments()},yo=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),le.click())},bo=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!De)return;let m=Hu(l.clipboardData);m.length!==0&&(l.preventDefault(),await De.handleFiles(m))},un=null,In=!1,lr=null,qe=null,xo=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Pr=(l="user")=>{var R,B,V,N,xe,Ee,Me;if(In||D.isStreaming())return;let m=xo();if(!m)return;un=new m;let A=(B=((R=n.voiceRecognition)!=null?R:{}).pauseDuration)!=null?B:2e3;un.continuous=!0,un.interimResults=!0,un.lang="en-US";let I=ee.value;un.onresult=Ae=>{let Ie="",ze="";for(let Ke=0;Ke<Ae.results.length;Ke++){let _=Ae.results[Ke],Pe=_[0].transcript;_.isFinal?Ie+=Pe+" ":ze=Pe}let mt=I+Ie+ze;ee.value=mt,lr&&clearTimeout(lr),(Ie||ze)&&(lr=window.setTimeout(()=>{let Ke=ee.value.trim();Ke&&un&&In&&(qn(),ee.value="",ee.style.height="auto",D.sendMessage(Ke,{viaVoice:!0}))},A))},un.onerror=Ae=>{Ae.error!=="no-speech"&&qn()},un.onend=()=>{if(In){let Ae=ee.value.trim();Ae&&Ae!==I.trim()&&(ee.value="",ee.style.height="auto",D.sendMessage(Ae,{viaVoice:!0})),qn()}};try{if(un.start(),In=!0,Qe.active=!0,l!=="system"&&(Qe.manuallyDeactivated=!1),Bn(l),yn(),z){let Ae=(V=n.voiceRecognition)!=null?V:{};qe={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(N=Ae.iconName)!=null?N:"mic",iconSize:parseFloat((Me=(Ee=Ae.iconSize)!=null?Ee:(xe=n.sendButton)==null?void 0:xe.size)!=null?Me:"40")||24};let Ie=Ae.recordingBackgroundColor,ze=Ae.recordingIconColor,mt=Ae.recordingBorderColor;if(z.classList.add("persona-voice-recording"),z.style.backgroundColor=Ie!=null?Ie:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=ze!=null?ze:"var(--persona-voice-recording-indicator, #ffffff)",ze){let Ke=z.querySelector("svg");Ke&&Ke.setAttribute("stroke",ze)}mt&&(z.style.borderColor=mt),z.setAttribute("aria-label","Stop voice recognition")}}catch{qn("system")}},qn=(l="user")=>{if(In){if(In=!1,lr&&(clearTimeout(lr),lr=null),un){try{un.stop()}catch{}un=null}if(Qe.active=!1,Bn(l),yn(),z){if(z.classList.remove("persona-voice-recording"),qe){z.style.backgroundColor=qe.backgroundColor,z.style.color=qe.color,z.style.borderColor=qe.borderColor;let m=z.querySelector("svg");m&&m.setAttribute("stroke",qe.color||"currentColor"),qe=null}z.setAttribute("aria-label","Start voice recognition")}}},Zo=(l,m)=>{var _,Pe,Be,Ce,Fe,St,vt,Gt;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((_=l==null?void 0:l.provider)==null?void 0:_.type)==="runtype";if(!(y||A))return null;let R=h("div","persona-send-button-wrapper"),B=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");B.type="button",B.setAttribute("aria-label","Start voice recognition");let V=(Pe=l==null?void 0:l.iconName)!=null?Pe:"mic",N=(Be=m==null?void 0:m.size)!=null?Be:"40px",xe=(Ce=l==null?void 0:l.iconSize)!=null?Ce:N,Ee=parseFloat(xe)||24,Me=(Fe=l==null?void 0:l.backgroundColor)!=null?Fe:m==null?void 0:m.backgroundColor,Ae=(St=l==null?void 0:l.iconColor)!=null?St:m==null?void 0:m.textColor;B.style.width=xe,B.style.height=xe,B.style.minWidth=xe,B.style.minHeight=xe,B.style.fontSize="18px",B.style.lineHeight="1",Ae?B.style.color=Ae:B.style.color="var(--persona-text, #111827)";let ze=be(V,Ee,Ae||"currentColor",1.5);ze?B.appendChild(ze):B.textContent="\u{1F3A4}",Me?B.style.backgroundColor=Me:B.style.backgroundColor="",l!=null&&l.borderWidth&&(B.style.borderWidth=l.borderWidth,B.style.borderStyle="solid"),l!=null&&l.borderColor&&(B.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(B.style.paddingLeft=l.paddingX,B.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(B.style.paddingTop=l.paddingY,B.style.paddingBottom=l.paddingY),R.appendChild(B);let mt=(vt=l==null?void 0:l.tooltipText)!=null?vt:"Start voice recognition";if(((Gt=l==null?void 0:l.showTooltip)!=null?Gt:!1)&&mt){let sn=h("div","persona-send-button-tooltip");sn.textContent=mt,R.appendChild(sn)}return{micButton:B,micButtonWrapper:R}},Vr=()=>{var m,y,A,I,R;if(!z||qe)return;let l=(m=n.voiceRecognition)!=null?m:{};qe={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((R=(I=l.iconSize)!=null?I:(A=n.sendButton)==null?void 0:A.size)!=null?R:"40")||24}},Jr=(l,m)=>{var R,B,V,N,xe;if(!z)return;let y=z.querySelector("svg");y&&y.remove();let A=(xe=qe==null?void 0:qe.iconSize)!=null?xe:parseFloat((N=(V=(R=n.voiceRecognition)==null?void 0:R.iconSize)!=null?V:(B=n.sendButton)==null?void 0:B.size)!=null?N:"40")||24,I=be(l,A,m,1.5);I&&z.appendChild(I)},Wr=()=>{z&&z.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},X=()=>{var I;if(!z)return;Vr();let l=(I=n.voiceRecognition)!=null?I:{},m=l.recordingBackgroundColor,y=l.recordingIconColor,A=l.recordingBorderColor;if(Wr(),z.classList.add("persona-voice-recording"),z.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",z.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let R=z.querySelector("svg");R&&R.setAttribute("stroke",y)}A&&(z.style.borderColor=A),z.setAttribute("aria-label","Stop voice recognition")},Ve=()=>{var V,N,xe,Ee,Me,Ae,Ie,ze;if(!z)return;Vr();let l=(V=n.voiceRecognition)!=null?V:{},m=D.getVoiceInterruptionMode(),y=(N=l.processingIconName)!=null?N:"loader",A=(Ee=(xe=l.processingIconColor)!=null?xe:qe==null?void 0:qe.color)!=null?Ee:"",I=(Ae=(Me=l.processingBackgroundColor)!=null?Me:qe==null?void 0:qe.backgroundColor)!=null?Ae:"",R=(ze=(Ie=l.processingBorderColor)!=null?Ie:qe==null?void 0:qe.borderColor)!=null?ze:"";Wr(),z.classList.add("persona-voice-processing"),z.style.backgroundColor=I,z.style.borderColor=R;let B=A||"currentColor";z.style.color=B,Jr(y,B),z.setAttribute("aria-label","Processing voice input"),m==="none"&&(z.style.cursor="default")},tt=()=>{var xe,Ee,Me,Ae,Ie,ze,mt,Ke,_,Pe,Be,Ce;if(!z)return;Vr();let l=(xe=n.voiceRecognition)!=null?xe:{},m=D.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",A=(Ee=l.speakingIconName)!=null?Ee:y,I=(ze=l.speakingIconColor)!=null?ze:m==="barge-in"?(Ae=(Me=l.recordingIconColor)!=null?Me:qe==null?void 0:qe.color)!=null?Ae:"":(Ie=qe==null?void 0:qe.color)!=null?Ie:"",R=(_=l.speakingBackgroundColor)!=null?_:m==="barge-in"?(mt=l.recordingBackgroundColor)!=null?mt:"var(--persona-voice-recording-bg, #ef4444)":(Ke=qe==null?void 0:qe.backgroundColor)!=null?Ke:"",B=(Ce=l.speakingBorderColor)!=null?Ce:m==="barge-in"?(Pe=l.recordingBorderColor)!=null?Pe:"":(Be=qe==null?void 0:qe.borderColor)!=null?Be:"";Wr(),z.classList.add("persona-voice-speaking"),z.style.backgroundColor=R,z.style.borderColor=B;let V=I||"currentColor";z.style.color=V,Jr(A,V);let N=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";z.setAttribute("aria-label",N),m==="none"&&(z.style.cursor="default"),m==="barge-in"&&z.classList.add("persona-voice-recording")},xt=()=>{var l,m,y;z&&(Wr(),qe&&(z.style.backgroundColor=(l=qe.backgroundColor)!=null?l:"",z.style.color=(m=qe.color)!=null?m:"",z.style.borderColor=(y=qe.borderColor)!=null?y:"",Jr(qe.iconName,qe.color||"currentColor"),qe=null),z.style.cursor="",z.setAttribute("aria-label","Start voice recognition"))},lt=()=>{var l,m;if(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let y=D.getVoiceStatus(),A=D.getVoiceInterruptionMode();if(A==="none"&&(y==="processing"||y==="speaking"))return;if(A==="cancel"&&(y==="processing"||y==="speaking")){D.stopVoicePlayback();return}if(D.isBargeInActive()){D.stopVoicePlayback(),D.deactivateBargeIn().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,yn(),Bn("user"),xt()});return}D.toggleVoice().then(()=>{Qe.active=D.isVoiceActive(),Qe.manuallyDeactivated=!D.isVoiceActive(),yn(),Bn("user"),D.isVoiceActive()?X():xt()});return}if(In){let y=ee.value.trim();Qe.manuallyDeactivated=!0,yn(),qn("user"),y&&(ee.value="",ee.style.height="auto",D.sendMessage(y))}else Qe.manuallyDeactivated=!1,yn(),Pr("user")};qt=lt,z&&(z.addEventListener("click",lt),wt.push(()=>{var l,m;((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?(D.isVoiceActive()&&D.toggleVoice(),xt()):qn("system"),z&&z.removeEventListener("click",lt)}));let Et=o.on("assistant:complete",()=>{po&&(Qe.active||Qe.manuallyDeactivated||po==="assistant"&&!Qe.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!Qe.active&&!Qe.manuallyDeactivated&&(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?D.toggleVoice().then(()=>{Qe.active=D.isVoiceActive(),Bn("auto"),D.isVoiceActive()&&X()}):Pr("auto"))},600))});wt.push(Et);let ut=o.on("action:resubmit",()=>{setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)});wt.push(ut);let b=()=>{Ht(!E,"user")},ne=null,T=null;if(C){let l=s.find(m=>m.renderLauncher);if(l!=null&&l.renderLauncher){let m=l.renderLauncher({config:n,defaultRenderer:()=>No(n,b).element,onToggle:b});m&&(T=m)}T||(ne=No(n,b))}ne?e.appendChild(ne.element):T&&e.appendChild(T),Ir(),jn.render(n.suggestionChips,D,ee,void 0,n.suggestionChipsConfig),fo(),qr(D.isStreaming()),xr(!0),Vo(),k&&(C?E&&setTimeout(()=>Ur(),200):setTimeout(()=>Ur(),0));let x=()=>{var N,xe,Ee,Me,Ae,Ie,ze,mt,Ke,_,Pe,Be,Ce,Fe,St,vt,Gt,sn,Te,bn,an,Un;let l=en(n),m=(xe=(N=n.launcher)==null?void 0:N.sidebarMode)!=null?xe:!1,y=l||m||((Me=(Ee=n.launcher)==null?void 0:Ee.fullHeight)!=null?Me:!1),A=(Ae=e.ownerDocument.defaultView)!=null?Ae:window,I=(ze=(Ie=n.launcher)==null?void 0:Ie.mobileFullscreen)!=null?ze:!0,R=(Ke=(mt=n.launcher)==null?void 0:mt.mobileBreakpoint)!=null?Ke:640,B=A.innerWidth<=R,V=I&&B&&C;try{if(V){Zn(),$r(e,n);return}if(P&&(P=!1,Zn(),$r(e,n)),!C&&!l){W.style.height="",W.style.width="";return}if(!m&&!l){let rt=(Pe=(_=n==null?void 0:n.launcher)==null?void 0:_.width)!=null?Pe:n==null?void 0:n.launcherWidth,gt=rt!=null?rt:Nn;W.style.width=gt,W.style.maxWidth=gt}if(Xn(),!y){let rt=A.innerHeight,gt=64,xn=(Ce=(Be=n.launcher)==null?void 0:Be.heightOffset)!=null?Ce:0,cr=Math.max(200,rt-gt),Je=Math.min(640,cr),Mt=Math.max(200,Je-xn);W.style.height=`${Mt}px`}}finally{if(Ze(),Ir(),E&&C){let gt=((Fe=e.ownerDocument.defaultView)!=null?Fe:window).innerWidth<=((vt=(St=n.launcher)==null?void 0:St.mobileBreakpoint)!=null?vt:640),xn=(sn=(Gt=n.launcher)==null?void 0:Gt.sidebarMode)!=null?sn:!1,cr=(bn=(Te=n.launcher)==null?void 0:Te.mobileFullscreen)!=null?bn:!0,Je=en(n)&&cr&&gt,Mt=xn||cr&&gt&&C||Je;if(Mt&&!Ot){let Rr=e.getRootNode(),Hr=Rr instanceof ShadowRoot?Rr.host:e.closest(".persona-host");Hr&&!Nt&&(Nt=ta(Hr,(Un=(an=n.launcher)==null?void 0:an.zIndex)!=null?Un:wn)),Ot=na(e.ownerDocument)}else Mt||(Nt==null||Nt(),Nt=null,Ot==null||Ot(),Ot=null)}}};x();let Z=(mi=e.ownerDocument.defaultView)!=null?mi:window;if(Z.addEventListener("resize",x),wt.push(()=>Z.removeEventListener("resize",x)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Ze()});l.observe(st),wt.push(()=>l.disconnect())}hn=q.scrollTop;let F=()=>{let l=q.scrollTop,{action:m,nextLastScrollTop:y}=vs({following:fn.isFollowing(),currentScrollTop:l,lastScrollTop:hn,nearBottom:Do(q,co),userScrollThreshold:qo,isAutoScrolling:Ln||sr,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(hn=y,m==="resume"){br();return}m==="pause"&&go()};q.addEventListener("scroll",F,{passive:!0}),wt.push(()=>q.removeEventListener("scroll",F));let he=l=>{let m=Cs({following:fn.isFollowing(),deltaY:l.deltaY,nearBottom:Do(q,co),resumeWhenNearBottom:!0});m==="pause"?go():m==="resume"&&br()};q.addEventListener("wheel",he,{passive:!0}),wt.push(()=>q.removeEventListener("wheel",he)),pt.addEventListener("click",()=>{q.scrollTop=q.scrollHeight,hn=q.scrollTop,br(),xr(!0)}),wt.push(()=>pt.remove()),wt.push(()=>{mo()});let Ue=()=>{me&&(kn&&(me.removeEventListener("click",kn),kn=null),C?(me.style.display="",kn=()=>{Ht(!1,"user")},me.addEventListener("click",kn)):me.style.display="none")};Ue(),(()=>{let{clearChatButton:l}=ae;l&&l.addEventListener("click",()=>{D.clearMessages(),Hn.clear(),br();try{localStorage.removeItem(io),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${io}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==io)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),a!=null&&a.clear)try{let y=a.clear();y instanceof Promise&&y.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},M.syncFromMetadata(),se==null||se.clear(),K==null||K.update()})})(),dt&&dt.addEventListener("submit",ho),ee==null||ee.addEventListener("keydown",yo),ee==null||ee.addEventListener("paste",bo);let $t="persona-attachment-drop-active",Vt=0,Jt=()=>{Vt=0,$.classList.remove($t)},Ft=()=>{var l;return((l=n.attachments)==null?void 0:l.enabled)===!0&&De!==null},Ge=l=>{!Is(l.dataTransfer)||!Ft()||(Vt++,Vt===1&&$.classList.add($t))},kt=l=>{!Is(l.dataTransfer)||!Ft()||(Vt--,Vt<=0&&Jt())},Zt=l=>{!Is(l.dataTransfer)||!Ft()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},on=l=>{var y;if(!Is(l.dataTransfer)||!Ft())return;l.preventDefault(),l.stopPropagation(),Jt();let m=Array.from((y=l.dataTransfer.files)!=null?y:[]);m.length!==0&&De.handleFiles(m)},Tt=!0;$.addEventListener("dragenter",Ge,Tt),$.addEventListener("dragleave",kt,Tt),e.addEventListener("dragover",Zt,Tt),e.addEventListener("drop",on,Tt);let mn=e.ownerDocument,Wa=l=>{Ft()&&l.preventDefault()},Ra=l=>{Ft()&&l.preventDefault()};mn.addEventListener("dragover",Wa),mn.addEventListener("drop",Ra),wt.push(()=>{dt&&dt.removeEventListener("submit",ho),ee==null||ee.removeEventListener("keydown",yo),ee==null||ee.removeEventListener("paste",bo)}),wt.push(()=>{$.removeEventListener("dragenter",Ge,Tt),$.removeEventListener("dragleave",kt,Tt),e.removeEventListener("dragover",Zt,Tt),e.removeEventListener("drop",on,Tt),mn.removeEventListener("dragover",Wa),mn.removeEventListener("drop",Ra),Jt()}),wt.push(()=>{D.cancel()}),ne?wt.push(()=>{ne==null||ne.destroy()}):T&&wt.push(()=>{T==null||T.remove()});let Yt={update(l){var vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Ii,Pi,Wi,Ri,Hi,Bi,Di,Fi,Ni,Oi,$i,_i,ji,zi,qi,Ui,Vi,Ji,Yi,Gi,Ki,Xi,Zi,Qi,el,tl,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,ml,gl,fl,hl,yl,bl,xl,vl,Cl,wl,Sl,Al,El,Tl,Ml,kl,Ll,Il,Pl,Wl,Rl,Hl,Bl,Dl,Fl,Nl,Ol,$l,_l,jl,zl,ql,Ul,Vl,Jl,Yl,Gl,Kl,Xl,Zl,Ql,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc;let m=n.toolCall,y=n.messageActions,A=(vi=n.layout)==null?void 0:vi.messages,I=n.colorScheme,R=n.loadingIndicator,B=n.iterationDisplay,V=(Ci=n.features)==null?void 0:Ci.showReasoning,N=(wi=n.features)==null?void 0:wi.showToolCalls,xe=(Si=n.features)==null?void 0:Si.toolCallDisplay,Ee=(Ai=n.features)==null?void 0:Ai.reasoningDisplay;n={...n,...l},Zn(),$r(e,n),Es(e,n),Ts(e,n),Tn(),n.colorScheme!==I&&hr();let Me=Ms.getForInstance(n.plugins);s.length=0,s.push(...Me),C=(Ti=(Ei=n.launcher)==null?void 0:Ei.enabled)!=null?Ti:!0,S=(ki=(Mi=n.launcher)==null?void 0:Mi.autoExpand)!=null?ki:!1,re=(Ii=(Li=n.features)==null?void 0:Li.showReasoning)!=null?Ii:!0,we=(Wi=(Pi=n.features)==null?void 0:Pi.showToolCalls)!=null?Wi:!0,ve=(Hi=(Ri=n.features)==null?void 0:Ri.scrollToBottom)!=null?Hi:{},bt(),ir();let Ae=oe;if(oe=(Di=(Bi=n.features)==null?void 0:Bi.showEventStreamToggle)!=null?Di:!1,oe&&!Ae){if(se||(ke=new zo(ge),se=new jo(Le,ke),ke.open().then(()=>se==null?void 0:se.restore()).catch(()=>{}),D.setSSEEventCallback((J,ct)=>{var Lt;(Lt=n.onSSEEvent)==null||Lt.call(n,J,ct),se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:J,timestamp:Date.now(),payload:JSON.stringify(ct)})})),!et&&ot){let J=(Ni=(Fi=n.features)==null?void 0:Fi.eventStream)==null?void 0:Ni.classNames,ct="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(J!=null&&J.toggleButton?" "+J.toggleButton:"");et=h("button",ct),et.style.width="28px",et.style.height="28px",et.style.color=Sn.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let Lt=be("activity","18px","currentColor",1.5);Lt&&et.appendChild(Lt);let Ye=ae.clearChatButtonWrapper,ft=ae.closeButtonWrapper,Kt=Ye||ft;Kt&&Kt.parentNode===ot?ot.insertBefore(et,Kt):ot.appendChild(et),et.addEventListener("click",()=>{ue?$n():nr()})}}else!oe&&Ae&&($n(),et&&(et.remove(),et=null),se==null||se.clear(),ke==null||ke.destroy(),se=null,ke=null);if(((Oi=n.launcher)==null?void 0:Oi.enabled)===!1&&ne&&(ne.destroy(),ne=null),(($i=n.launcher)==null?void 0:$i.enabled)===!1&&T&&(T.remove(),T=null),((_i=n.launcher)==null?void 0:_i.enabled)!==!1&&!ne&&!T){let J=s.find(ct=>ct.renderLauncher);if(J!=null&&J.renderLauncher){let ct=J.renderLauncher({config:n,defaultRenderer:()=>No(n,b).element,onToggle:b});ct&&(T=ct,e.appendChild(T))}T||(ne=No(n,b),e.appendChild(ne.element))}ne&&ne.update(n),Wt&&((ji=n.launcher)==null?void 0:ji.title)!==void 0&&(Wt.textContent=n.launcher.title),Rt&&((zi=n.launcher)==null?void 0:zi.subtitle)!==void 0&&(Rt.textContent=n.launcher.subtitle);let Ie=(qi=n.layout)==null?void 0:qi.header;if((Ie==null?void 0:Ie.layout)!==L&&ot){let J=Ie?Oo(n,Ie,{showClose:C,onClose:()=>Ht(!1,"user")}):Sr({config:n,showClose:C,onClose:()=>Ht(!1,"user")});ot.replaceWith(J.header),ot=J.header,Ne=J.iconHolder,Wt=J.headerTitle,Rt=J.headerSubtitle,me=J.closeButton,L=Ie==null?void 0:Ie.layout}else if(Ie&&(Ne&&(Ne.style.display=Ie.showIcon===!1?"none":""),Wt&&(Wt.style.display=Ie.showTitle===!1?"none":""),Rt&&(Rt.style.display=Ie.showSubtitle===!1?"none":""),me&&(me.style.display=Ie.showCloseButton===!1?"none":""),ae.clearChatButtonWrapper)){let J=Ie.showClearChat;if(J!==void 0){ae.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:ct}=ae;ct&&!ct.classList.contains("persona-absolute")&&(J?ct.classList.remove("persona-ml-auto"):ct.classList.add("persona-ml-auto"))}}let mt=((Ui=n.layout)==null?void 0:Ui.showHeader)!==!1;ot&&(ot.style.display=mt?"":"none");let Ke=((Vi=n.layout)==null?void 0:Vi.showFooter)!==!1;st&&(st.style.display=Ke?"":"none"),Ze(),ir(),C!==w?C?Ht(S,"auto"):(E=!0,Ir()):S!==H&&Ht(S,"auto"),H=S,w=C,x(),Ue();let Be=JSON.stringify(l.toolCall)!==JSON.stringify(m),Ce=JSON.stringify(n.messageActions)!==JSON.stringify(y),Fe=JSON.stringify((Ji=n.layout)==null?void 0:Ji.messages)!==JSON.stringify(A),St=((Yi=n.loadingIndicator)==null?void 0:Yi.render)!==(R==null?void 0:R.render)||((Gi=n.loadingIndicator)==null?void 0:Gi.renderIdle)!==(R==null?void 0:R.renderIdle)||((Ki=n.loadingIndicator)==null?void 0:Ki.showBubble)!==(R==null?void 0:R.showBubble),vt=n.iterationDisplay!==B,Gt=((Zi=(Xi=n.features)==null?void 0:Xi.showReasoning)!=null?Zi:!0)!==(V!=null?V:!0)||((el=(Qi=n.features)==null?void 0:Qi.showToolCalls)!=null?el:!0)!==(N!=null?N:!0)||JSON.stringify((tl=n.features)==null?void 0:tl.toolCallDisplay)!==JSON.stringify(xe)||JSON.stringify((nl=n.features)==null?void 0:nl.reasoningDisplay)!==JSON.stringify(Ee);(Be||Ce||Fe||St||vt||Gt)&&D&&(yr++,Lr(de,D.getMessages(),O));let Te=(rl=n.launcher)!=null?rl:{},bn=(ol=Te.headerIconHidden)!=null?ol:!1,an=(al=(sl=n.layout)==null?void 0:sl.header)==null?void 0:al.showIcon,Un=bn||an===!1,rt=Te.headerIconName,gt=(il=Te.headerIconSize)!=null?il:"48px";if(Ne){let J=$.querySelector(".persona-border-b-persona-divider"),ct=J==null?void 0:J.querySelector(".persona-flex-col");if(Un)Ne.style.display="none",J&&ct&&!J.contains(ct)&&J.insertBefore(ct,J.firstChild);else{if(Ne.style.display="",Ne.style.height=gt,Ne.style.width=gt,J&&ct&&(J.contains(Ne)?Ne.nextSibling!==ct&&(Ne.remove(),J.insertBefore(Ne,ct)):J.insertBefore(Ne,ct)),rt){let Ye=parseFloat(gt)||24,ft=be(rt,Ye*.6,"#ffffff",2);ft?Ne.replaceChildren(ft):Ne.textContent=(ll=Te.agentIconText)!=null?ll:"\u{1F4AC}"}else if(Te.iconUrl){let Ye=Ne.querySelector("img");if(Ye)Ye.src=Te.iconUrl,Ye.style.height=gt,Ye.style.width=gt;else{let ft=document.createElement("img");ft.src=Te.iconUrl,ft.alt="",ft.className="persona-rounded-xl persona-object-cover",ft.style.height=gt,ft.style.width=gt,Ne.replaceChildren(ft)}}else{let Ye=Ne.querySelector("svg"),ft=Ne.querySelector("img");(Ye||ft)&&Ne.replaceChildren(),Ne.textContent=(cl=Te.agentIconText)!=null?cl:"\u{1F4AC}"}let Lt=Ne.querySelector("img");Lt&&(Lt.style.height=gt,Lt.style.width=gt)}}let xn=(pl=(dl=n.layout)==null?void 0:dl.header)==null?void 0:pl.showTitle,cr=(ml=(ul=n.layout)==null?void 0:ul.header)==null?void 0:ml.showSubtitle;if(Wt&&(Wt.style.display=xn===!1?"none":""),Rt&&(Rt.style.display=cr===!1?"none":""),me){((fl=(gl=n.layout)==null?void 0:gl.header)==null?void 0:fl.showCloseButton)===!1?me.style.display="none":me.style.display="";let ct=(hl=Te.closeButtonSize)!=null?hl:"32px",Lt=(yl=Te.closeButtonPlacement)!=null?yl:"inline";me.style.height=ct,me.style.width=ct;let{closeButtonWrapper:Ye}=ae,ft=Lt==="top-right",Kt=Ye==null?void 0:Ye.classList.contains("persona-absolute");if(Ye&&ft!==Kt)if(Ye.remove(),ft)Ye.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",$.style.position="relative",$.appendChild(Ye);else{let nt=(xl=(bl=Te.clearChat)==null?void 0:bl.placement)!=null?xl:"inline",Qt=(Cl=(vl=Te.clearChat)==null?void 0:vl.enabled)!=null?Cl:!0;Ye.className=Qt&&nt==="inline"?"":"persona-ml-auto";let Cn=$.querySelector(".persona-border-b-persona-divider");Cn&&Cn.appendChild(Ye)}if(me.style.color=Te.closeButtonColor||Sn.actionIconColor,Te.closeButtonBackgroundColor?(me.style.backgroundColor=Te.closeButtonBackgroundColor,me.classList.remove("hover:persona-bg-gray-100")):(me.style.backgroundColor="",me.classList.add("hover:persona-bg-gray-100")),Te.closeButtonBorderWidth||Te.closeButtonBorderColor){let nt=Te.closeButtonBorderWidth||"0px",Qt=Te.closeButtonBorderColor||"transparent";me.style.border=`${nt} solid ${Qt}`,me.classList.remove("persona-border-none")}else me.style.border="",me.classList.add("persona-border-none");Te.closeButtonBorderRadius?(me.style.borderRadius=Te.closeButtonBorderRadius,me.classList.remove("persona-rounded-full")):(me.style.borderRadius="",me.classList.add("persona-rounded-full")),Te.closeButtonPaddingX?(me.style.paddingLeft=Te.closeButtonPaddingX,me.style.paddingRight=Te.closeButtonPaddingX):(me.style.paddingLeft="",me.style.paddingRight=""),Te.closeButtonPaddingY?(me.style.paddingTop=Te.closeButtonPaddingY,me.style.paddingBottom=Te.closeButtonPaddingY):(me.style.paddingTop="",me.style.paddingBottom="");let ln=(wl=Te.closeButtonIconName)!=null?wl:"x",Vn=(Sl=Te.closeButtonIconText)!=null?Sl:"\xD7";me.innerHTML="";let gn=be(ln,"20px","currentColor",2);gn?me.appendChild(gn):me.textContent=Vn;let _t=(Al=Te.closeButtonTooltipText)!=null?Al:"Close chat",Pn=(El=Te.closeButtonShowTooltip)!=null?El:!0;if(me.setAttribute("aria-label",_t),Ye&&(Ye._cleanupTooltip&&(Ye._cleanupTooltip(),delete Ye._cleanupTooltip),Pn&&_t)){let nt=null,Qt=()=>{if(nt||!me)return;let Dr=me.ownerDocument,So=Dr.body;if(!So)return;nt=er(Dr,"div","persona-clear-chat-tooltip"),nt.textContent=_t;let Ao=er(Dr,"div");Ao.className="persona-clear-chat-tooltip-arrow",nt.appendChild(Ao);let Fr=me.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(Cr),nt.style.left=`${Fr.left+Fr.width/2}px`,nt.style.top=`${Fr.top-8}px`,nt.style.transform="translate(-50%, -100%)",So.appendChild(nt)},Cn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};Ye.addEventListener("mouseenter",Qt),Ye.addEventListener("mouseleave",Cn),me.addEventListener("focus",Qt),me.addEventListener("blur",Cn),Ye._cleanupTooltip=()=>{Cn(),Ye&&(Ye.removeEventListener("mouseenter",Qt),Ye.removeEventListener("mouseleave",Cn)),me&&(me.removeEventListener("focus",Qt),me.removeEventListener("blur",Cn))}}}let{clearChatButton:Je,clearChatButtonWrapper:Mt}=ae;if(Je){let J=(Tl=Te.clearChat)!=null?Tl:{},ct=(Ml=J.enabled)!=null?Ml:!0,Lt=(Ll=(kl=n.layout)==null?void 0:kl.header)==null?void 0:Ll.showClearChat,Ye=Lt!==void 0?Lt:ct,ft=(Il=J.placement)!=null?Il:"inline";if(Mt){Mt.style.display=Ye?"":"none";let{closeButtonWrapper:Kt}=ae;Kt&&!Kt.classList.contains("persona-absolute")&&(Ye?Kt.classList.remove("persona-ml-auto"):Kt.classList.add("persona-ml-auto"));let ln=ft==="top-right",Vn=Mt.classList.contains("persona-absolute");if(ln!==Vn&&Ye){if(Mt.remove(),ln)Mt.className="persona-absolute persona-top-4 persona-z-50",Mt.style.right="48px",$.style.position="relative",$.appendChild(Mt);else{Mt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Mt.style.right="";let _t=$.querySelector(".persona-border-b-persona-divider"),Pn=ae.closeButtonWrapper;_t&&Pn&&Pn.parentElement===_t?_t.insertBefore(Mt,Pn):_t&&_t.appendChild(Mt)}let gn=ae.closeButtonWrapper;gn&&!gn.classList.contains("persona-absolute")&&(ln?gn.classList.add("persona-ml-auto"):gn.classList.remove("persona-ml-auto"))}}if(Ye){let Kt=(Pl=J.size)!=null?Pl:"32px";Je.style.height=Kt,Je.style.width=Kt;let ln=(Wl=J.iconName)!=null?Wl:"refresh-cw",Vn=(Rl=J.iconColor)!=null?Rl:"";Je.style.color=Vn||Sn.actionIconColor,Je.innerHTML="";let gn=be(ln,"20px","currentColor",2);if(gn&&Je.appendChild(gn),J.backgroundColor?(Je.style.backgroundColor=J.backgroundColor,Je.classList.remove("hover:persona-bg-gray-100")):(Je.style.backgroundColor="",Je.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let nt=J.borderWidth||"0px",Qt=J.borderColor||"transparent";Je.style.border=`${nt} solid ${Qt}`,Je.classList.remove("persona-border-none")}else Je.style.border="",Je.classList.add("persona-border-none");J.borderRadius?(Je.style.borderRadius=J.borderRadius,Je.classList.remove("persona-rounded-full")):(Je.style.borderRadius="",Je.classList.add("persona-rounded-full")),J.paddingX?(Je.style.paddingLeft=J.paddingX,Je.style.paddingRight=J.paddingX):(Je.style.paddingLeft="",Je.style.paddingRight=""),J.paddingY?(Je.style.paddingTop=J.paddingY,Je.style.paddingBottom=J.paddingY):(Je.style.paddingTop="",Je.style.paddingBottom="");let _t=(Hl=J.tooltipText)!=null?Hl:"Clear chat",Pn=(Bl=J.showTooltip)!=null?Bl:!0;if(Je.setAttribute("aria-label",_t),Mt&&(Mt._cleanupTooltip&&(Mt._cleanupTooltip(),delete Mt._cleanupTooltip),Pn&&_t)){let nt=null,Qt=()=>{if(nt||!Je)return;let Dr=Je.ownerDocument,So=Dr.body;if(!So)return;nt=er(Dr,"div","persona-clear-chat-tooltip"),nt.textContent=_t;let Ao=er(Dr,"div");Ao.className="persona-clear-chat-tooltip-arrow",nt.appendChild(Ao);let Fr=Je.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(Cr),nt.style.left=`${Fr.left+Fr.width/2}px`,nt.style.top=`${Fr.top-8}px`,nt.style.transform="translate(-50%, -100%)",So.appendChild(nt)},Cn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};Mt.addEventListener("mouseenter",Qt),Mt.addEventListener("mouseleave",Cn),Je.addEventListener("focus",Qt),Je.addEventListener("blur",Cn),Mt._cleanupTooltip=()=>{Cn(),Mt&&(Mt.removeEventListener("mouseenter",Qt),Mt.removeEventListener("mouseleave",Cn)),Je&&(Je.removeEventListener("focus",Qt),Je.removeEventListener("blur",Cn))}}}}let Rr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[ks],Hr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[ao.message,ao.messageAndClick];M=Ls({parsers:Rr,handlers:Hr,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),O=Cd(n,M,G),D.updateConfig(n),Lr(de,D.getMessages(),O),jn.render(n.suggestionChips,D,ee,void 0,n.suggestionChipsConfig),fo(),qr(D.isStreaming());let Qo=((Dl=n.voiceRecognition)==null?void 0:Dl.enabled)===!0,es=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ts=((Nl=(Fl=n.voiceRecognition)==null?void 0:Fl.provider)==null?void 0:Nl.type)==="runtype";if(Qo&&(es||ts))if(!z||!He){let J=Zo(n.voiceRecognition,n.sendButton);J&&(z=J.micButton,He=J.micButtonWrapper,rn.insertBefore(He,It),z.addEventListener("click",lt),z.disabled=D.isStreaming())}else{let J=(Ol=n.voiceRecognition)!=null?Ol:{},ct=($l=n.sendButton)!=null?$l:{},Lt=(_l=J.iconName)!=null?_l:"mic",Ye=(jl=ct.size)!=null?jl:"40px",ft=(zl=J.iconSize)!=null?zl:Ye,Kt=parseFloat(ft)||24;z.style.width=ft,z.style.height=ft,z.style.minWidth=ft,z.style.minHeight=ft;let ln=(Ul=(ql=J.iconColor)!=null?ql:ct.textColor)!=null?Ul:"currentColor";z.innerHTML="";let Vn=be(Lt,Kt,ln,2);Vn?z.appendChild(Vn):z.textContent="\u{1F3A4}";let gn=(Vl=J.backgroundColor)!=null?Vl:ct.backgroundColor;gn?z.style.backgroundColor=gn:z.style.backgroundColor="",ln?z.style.color=ln:z.style.color="var(--persona-text, #111827)",J.borderWidth?(z.style.borderWidth=J.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),J.borderColor?z.style.borderColor=J.borderColor:z.style.borderColor="",J.paddingX?(z.style.paddingLeft=J.paddingX,z.style.paddingRight=J.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),J.paddingY?(z.style.paddingTop=J.paddingY,z.style.paddingBottom=J.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let _t=He==null?void 0:He.querySelector(".persona-send-button-tooltip"),Pn=(Jl=J.tooltipText)!=null?Jl:"Start voice recognition";if(((Yl=J.showTooltip)!=null?Yl:!1)&&Pn)if(_t)_t.textContent=Pn,_t.style.display="";else{let Qt=document.createElement("div");Qt.className="persona-send-button-tooltip",Qt.textContent=Pn,He==null||He.insertBefore(Qt,z)}else _t&&(_t.style.display="none");He.style.display="",z.disabled=D.isStreaming()}else z&&He&&(He.style.display="none",((Kl=(Gl=n.voiceRecognition)==null?void 0:Gl.provider)==null?void 0:Kl.type)==="runtype"?D.isVoiceActive()&&D.toggleVoice():In&&qn());if(((Xl=n.attachments)==null?void 0:Xl.enabled)===!0)if(!ht||!ye){let J=(Zl=n.attachments)!=null?Zl:{},Lt=(ec=((Ql=n.sendButton)!=null?Ql:{}).size)!=null?ec:"40px";ce||(ce=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ce.style.display="none",dt.insertBefore(ce,ee)),$e||($e=document.createElement("input"),$e.type="file",$e.accept=((tc=J.allowedTypes)!=null?tc:dr).join(","),$e.multiple=((nc=J.maxFiles)!=null?nc:4)>1,$e.style.display="none",$e.setAttribute("aria-label","Attach files"),dt.insertBefore($e,ee)),ht=h("div","persona-send-button-wrapper"),ye=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ye.type="button",ye.setAttribute("aria-label",(rc=J.buttonTooltipText)!=null?rc:"Attach file");let Ye=(oc=J.buttonIconName)!=null?oc:"paperclip",ft=Lt,Kt=parseFloat(ft)||40,ln=Math.round(Kt*.6);ye.style.width=ft,ye.style.height=ft,ye.style.minWidth=ft,ye.style.minHeight=ft,ye.style.fontSize="18px",ye.style.lineHeight="1",ye.style.backgroundColor="transparent",ye.style.color="var(--persona-primary, #111827)",ye.style.border="none",ye.style.borderRadius="6px",ye.style.transition="background-color 0.15s ease",ye.addEventListener("mouseenter",()=>{ye.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ye.addEventListener("mouseleave",()=>{ye.style.backgroundColor="transparent"});let Vn=be(Ye,ln,"currentColor",1.5);Vn?ye.appendChild(Vn):ye.textContent="\u{1F4CE}",ye.addEventListener("click",Pn=>{Pn.preventDefault(),$e==null||$e.click()}),ht.appendChild(ye);let gn=(sc=J.buttonTooltipText)!=null?sc:"Attach file",_t=h("div","persona-send-button-tooltip");_t.textContent=gn,ht.appendChild(_t),tn.append(ht),!De&&$e&&ce&&(De=eo.fromConfig(J),De.setPreviewsContainer(ce),$e.addEventListener("change",async()=>{De&&($e!=null&&$e.files)&&(await De.handleFileSelect($e.files),$e.value="")})),$.querySelector(".persona-attachment-drop-overlay")||$.appendChild(wd(J.dropOverlay))}else{ht.style.display="";let J=(ac=n.attachments)!=null?ac:{};$e&&($e.accept=((ic=J.allowedTypes)!=null?ic:dr).join(","),$e.multiple=((lc=J.maxFiles)!=null?lc:4)>1),De&&De.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles})}else ht&&(ht.style.display="none"),De&&De.clearAttachments(),(cc=$.querySelector(".persona-attachment-drop-overlay"))==null||cc.remove();let Ut=(dc=n.sendButton)!=null?dc:{},ns=(pc=Ut.useIcon)!=null?pc:!1,vo=(uc=Ut.iconText)!=null?uc:"\u2191",vn=Ut.iconName,Fn=(mc=Ut.tooltipText)!=null?mc:"Send message",Yr=(gc=Ut.showTooltip)!=null?gc:!1,Co=(fc=Ut.size)!=null?fc:"40px",rs=Ut.backgroundColor,Br=Ut.textColor;if(ns){if(le.style.width=Co,le.style.height=Co,le.style.minWidth=Co,le.style.minHeight=Co,le.style.fontSize="18px",le.style.lineHeight="1",le.innerHTML="",Br?le.style.color=Br:le.style.color="var(--persona-button-primary-fg, #ffffff)",vn){let J=parseFloat(Co)||24,ct=(Br==null?void 0:Br.trim())||"currentColor",Lt=be(vn,J,ct,2);Lt?le.appendChild(Lt):le.textContent=vo}else le.textContent=vo;le.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",rs?(le.style.backgroundColor=rs,le.classList.remove("persona-bg-persona-primary")):(le.style.backgroundColor="",le.classList.add("persona-bg-persona-primary"))}else le.textContent=(yc=(hc=n.copy)==null?void 0:hc.sendButtonLabel)!=null?yc:"Send",le.style.width="",le.style.height="",le.style.minWidth="",le.style.minHeight="",le.style.fontSize="",le.style.lineHeight="",le.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",rs?(le.style.backgroundColor=rs,le.classList.remove("persona-bg-persona-accent")):le.classList.add("persona-bg-persona-accent"),Br?le.style.color=Br:le.classList.add("persona-text-white");Ut.borderWidth?(le.style.borderWidth=Ut.borderWidth,le.style.borderStyle="solid"):(le.style.borderWidth="",le.style.borderStyle=""),Ut.borderColor?le.style.borderColor=Ut.borderColor:le.style.borderColor="",Ut.paddingX?(le.style.paddingLeft=Ut.paddingX,le.style.paddingRight=Ut.paddingX):(le.style.paddingLeft="",le.style.paddingRight=""),Ut.paddingY?(le.style.paddingTop=Ut.paddingY,le.style.paddingBottom=Ut.paddingY):(le.style.paddingTop="",le.style.paddingBottom="");let wo=It==null?void 0:It.querySelector(".persona-send-button-tooltip");if(Yr&&Fn)if(wo)wo.textContent=Fn,wo.style.display="";else{let J=document.createElement("div");J.className="persona-send-button-tooltip",J.textContent=Fn,It==null||It.insertBefore(J,le)}else wo&&(wo.style.display="none");let os=(bc=n.layout)==null?void 0:bc.contentMaxWidth;os?(de.style.maxWidth=os,de.style.marginLeft="auto",de.style.marginRight="auto",de.style.width="100%",dt&&(dt.style.maxWidth=os,dt.style.marginLeft="auto",dt.style.marginRight="auto"),_e&&(_e.style.maxWidth=os,_e.style.marginLeft="auto",_e.style.marginRight="auto")):(de.style.maxWidth="",de.style.marginLeft="",de.style.marginRight="",de.style.width="",dt&&(dt.style.maxWidth="",dt.style.marginLeft="",dt.style.marginRight=""),_e&&(_e.style.maxWidth="",_e.style.marginLeft="",_e.style.marginRight=""));let vr=(xc=n.statusIndicator)!=null?xc:{},rp=(vc=vr.visible)!=null?vc:!0;if(Dt.style.display=rp?"":"none",D){let J=D.getStatus();Xe(Dt,(Lt=>{var Ye,ft,Kt,ln;return Lt==="idle"?(Ye=vr.idleText)!=null?Ye:cn.idle:Lt==="connecting"?(ft=vr.connectingText)!=null?ft:cn.connecting:Lt==="connected"?(Kt=vr.connectedText)!=null?Kt:cn.connected:Lt==="error"?(ln=vr.errorText)!=null?ln:cn.error:cn[Lt]})(J),vr,J)}Dt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let op=vr.align==="left"?"persona-text-left":vr.align==="center"?"persona-text-center":"persona-text-right";Dt.classList.add(op)},open(){C&&Ht(!0,"api")},close(){C&&Ht(!1,"api")},toggle(){C&&Ht(!E,"api")},clearChat(){dn=!1,D.clearMessages(),Hn.clear(),br();try{localStorage.removeItem(io),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${io}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==io)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.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),a!=null&&a.clear)try{let m=a.clear();m instanceof Promise&&m.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}i={},M.syncFromMetadata(),se==null||se.clear(),K==null||K.update()},setMessage(l){return!ee||D.isStreaming()?!1:(!E&&C&&Ht(!0,"system"),ee.value=l,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(D.isStreaming())return!1;let m=(l==null?void 0:l.trim())||ee.value.trim();return m?(!E&&C&&Ht(!0,"system"),ee.value="",ee.style.height="auto",D.sendMessage(m),!0):!1},startVoiceRecognition(){var m,y;return D.isStreaming()?!1:((y=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype"?(D.isVoiceActive()||(!E&&C&&Ht(!0,"system"),Qe.manuallyDeactivated=!1,yn(),D.toggleVoice().then(()=>{Qe.active=D.isVoiceActive(),Bn("user"),D.isVoiceActive()&&X()})),!0):In?!0:xo()?(!E&&C&&Ht(!0,"system"),Qe.manuallyDeactivated=!1,yn(),Pr("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?D.isVoiceActive()?(D.toggleVoice().then(()=>{Qe.active=!1,Qe.manuallyDeactivated=!0,yn(),Bn("user"),xt()}),!0):!1:In?(Qe.manuallyDeactivated=!0,yn(),qn("user"),!0):!1},injectMessage(l){return!E&&C&&Ht(!0,"system"),D.injectMessage(l)},injectAssistantMessage(l){!E&&C&&Ht(!0,"system");let m=D.injectAssistantMessage(l);return Y&&(Y=!1,Q&&(clearTimeout(Q),Q=null),setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)),m},injectUserMessage(l){return!E&&C&&Ht(!0,"system"),D.injectUserMessage(l)},injectSystemMessage(l){return!E&&C&&Ht(!0,"system"),D.injectSystemMessage(l)},injectMessageBatch(l){return!E&&C&&Ht(!0,"system"),D.injectMessageBatch(l)},injectTestMessage(l){!E&&C&&Ht(!0,"system"),D.injectTestEvent(l)},async connectStream(l,m){return D.connectStream(l,m)},__pushEventStreamEvent(l){se&&se.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!oe||!se||nr()},hideEventStream(){ue&&$n()},isEventStreamVisible(){return ue},showArtifacts(){On(n)&&(dn=!1,Tn(),at==null||at.setMobileOpen(!0))},hideArtifacts(){On(n)&&(dn=!0,Tn())},upsertArtifact(l){return On(n)?(dn=!1,D.upsertArtifact(l)):null},selectArtifact(l){On(n)&&D.selectArtifact(l)},clearArtifacts(){On(n)&&D.clearArtifacts()},focusInput(){return C&&!E||!ee?!1:(ee.focus(),!0)},async resolveApproval(l,m){let A=D.getMessages().find(I=>{var R;return I.variant==="approval"&&((R=I.approval)==null?void 0:R.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return D.resolveApproval(A.approval,m)},getMessages(){return D.getMessages()},getStatus(){return D.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){f(l)},on(l,m){return o.on(l,m)},off(l,m){o.off(l,m)},isOpen(){return C&&E},isVoiceActive(){return Qe.active},getState(){return{open:C&&E,launcherEnabled:C,voiceActive:Qe.active,streaming:D.isStreaming()}},showCSATFeedback(l){!E&&C&&Ht(!0,"system");let m=de.querySelector(".persona-feedback-container");m&&m.remove();let y=ba({onSubmit:async(A,I)=>{var R;D.isClientTokenMode()&&await D.submitCSATFeedback(A,I),(R=l==null?void 0:l.onSubmit)==null||R.call(l,A,I)},onDismiss:l==null?void 0:l.onDismiss,...l});de.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!E&&C&&Ht(!0,"system");let m=de.querySelector(".persona-feedback-container");m&&m.remove();let y=xa({onSubmit:async(A,I)=>{var R;D.isClientTokenMode()&&await D.submitNPSFeedback(A,I),(R=l==null?void 0:l.onSubmit)==null||R.call(l,A,I)},onDismiss:l==null?void 0:l.onDismiss,...l});de.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,m){return D.submitCSATFeedback(l,m)},async submitNPSFeedback(l,m){return D.submitNPSFeedback(l,m)},destroy(){Qn!=null&&(clearInterval(Qn),Qn=null),wt.forEach(l=>l()),j.remove(),ne==null||ne.destroy(),T==null||T.remove(),kn&&me.removeEventListener("click",kn)}};if((((gi=t==null?void 0:t.debugTools)!=null?gi:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:Yt,getMessages:Yt.getMessages,getStatus:Yt.getStatus,getMetadata:Yt.getPersistentMetadata,updateMetadata:Yt.updatePersistentMetadata,clearHistory:()=>Yt.clearChat(),setVoiceActive:y=>y?Yt.startVoiceRecognition():Yt.stopVoiceRecognition()};window.AgentWidgetBrowser=m,wt.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=V=>{let N=V.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&Yt.focusInput()};if(window.addEventListener("persona:focusInput",m),wt.push(()=>{window.removeEventListener("persona:focusInput",m)}),oe){let V=xe=>{let Ee=xe.detail;(!(Ee!=null&&Ee.instanceId)||Ee.instanceId===l)&&Yt.showEventStream()},N=xe=>{let Ee=xe.detail;(!(Ee!=null&&Ee.instanceId)||Ee.instanceId===l)&&Yt.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",N),wt.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",N)})}let y=V=>{let N=V.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&Yt.showArtifacts()},A=V=>{let N=V.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&Yt.hideArtifacts()},I=V=>{let N=V.detail;N!=null&&N.instanceId&&N.instanceId!==l||N!=null&&N.artifact&&Yt.upsertArtifact(N.artifact)},R=V=>{let N=V.detail;N!=null&&N.instanceId&&N.instanceId!==l||typeof(N==null?void 0:N.id)=="string"&&Yt.selectArtifact(N.id)},B=V=>{let N=V.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&Yt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",I),window.addEventListener("persona:selectArtifact",R),window.addEventListener("persona:clearArtifacts",B),wt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",I),window.removeEventListener("persona:selectArtifact",R),window.removeEventListener("persona:clearArtifacts",B)})}let Dn=Bu(n.persistState);if(Dn&&C){let l=Du(Dn.storage),m=`${Dn.keyPrefix}widget-open`,y=`${Dn.keyPrefix}widget-voice`,A=`${Dn.keyPrefix}widget-voice-mode`;if(l){let I=((fi=Dn.persist)==null?void 0:fi.openState)&&l.getItem(m)==="true",R=((hi=Dn.persist)==null?void 0:hi.voiceState)&&l.getItem(y)==="true",B=((yi=Dn.persist)==null?void 0:yi.voiceState)&&l.getItem(A)==="true";if(I&&setTimeout(()=>{Yt.open(),setTimeout(()=>{var V;if(R||B)Yt.startVoiceRecognition();else if((V=Dn.persist)!=null&&V.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),(bi=Dn.persist)!=null&&bi.openState&&(o.on("widget:opened",()=>{l.setItem(m,"true")}),o.on("widget:closed",()=>{l.setItem(m,"false")})),(xi=Dn.persist)!=null&&xi.voiceState&&(o.on("voice:state",V=>{l.setItem(y,V.active?"true":"false")}),o.on("user:message",V=>{l.setItem(A,V.viaVoice?"true":"false")})),Dn.clearOnChatClear){let V=()=>{l.removeItem(m),l.removeItem(y),l.removeItem(A)},N=()=>V();window.addEventListener("persona:clear-chat",N),wt.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return c&&C&&setTimeout(()=>{Yt.open()},0),Yt};var Fu=(e,r)=>{let t=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(n)return Math.max(0,parseFloat(n[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,r*parseFloat(s[1])/100):420},Sd=(e,r)=>{var n,s;let t=(s=(n=r==null?void 0:r.launcher)==null?void 0:n.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},Ea=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=""},Ad=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Ea(e)},wa=e=>{e.style.transition=""},Sa=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=""},Aa=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Ps=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},Nu=(e,r,t,n,s)=>{s?t.parentElement!==r&&(e.replaceChildren(),r.replaceChildren(t,n),e.appendChild(r)):t.parentElement===r&&(r.replaceChildren(),e.appendChild(t),e.appendChild(n))},Ou=(e,r,t,n,s,o)=>{let a=o?r:e;s==="left"?a.firstElementChild!==n&&a.replaceChildren(n,t):a.lastElementChild!==n&&a.replaceChildren(t,n)},Ed=(e,r,t,n,s,o,a)=>{var v,M,C,S,k,H;let i=Jn(o),u=i.reveal==="push";Nu(e,r,t,n,u),Ou(e,r,t,n,i.side,u),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",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,p=(M=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?M:!0,d=(S=(C=o==null?void 0:o.launcher)==null?void 0:C.mobileBreakpoint)!=null?S:640,f=c!=null?c.innerWidth<=d:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Sa(r),wa(n),Ad(n),Aa(t),Ps(s,n),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((H=(k=o==null?void 0:o.launcher)==null?void 0:k.zIndex)!=null?H:wn),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",u&&(r.style.display="flex",r.style.flexDirection="column",r.style.width="100%",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.flex="1 1 auto",r.style.alignItems="stretch",r.style.transform="none",r.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Ad(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Sa(r),wa(n),Aa(t),Ps(s,n);let w=i.animate?"transform 180ms ease":"none",L=i.side==="right"?"translateX(100%)":"translateX(-100%)",P=a?"translateX(0)":L;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=w,n.style.transform=P,n.style.pointerEvents=a?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.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",wa(n),Ea(n),Ps(s,n);let w=Fu(i.width,e.clientWidth),L=Math.max(0,e.clientWidth),P=i.animate?"transform 180ms ease":"none",E=i.side==="right"?a?`translateX(-${w}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${w}px)`;r.style.display="flex",r.style.flexDirection="row",r.style.flex="0 0 auto",r.style.minHeight="0",r.style.minWidth="0",r.style.alignItems="stretch",r.style.height="100%",r.style.width=`${L+w}px`,r.style.transition=P,r.style.transform=E,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${L}px`,t.style.maxWidth=`${L}px`,t.style.minWidth=`${L}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Sa(r),Ea(n),Aa(t),Ps(s,n);let w=i.reveal==="emerge";w?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let L=a?i.width:"0px",P=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",E=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${L}`,n.style.width=L,n.style.maxWidth=L,n.style.minWidth=L,n.style.minHeight="0",n.style.position="relative",n.style.overflow=w||E?"hidden":"visible",n.style.transition=P,w&&(n.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},$u=(e,r)=>{let t=e.ownerDocument.createElement("div");return Sd(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){Sd(t,n)},destroy(){t.remove()}}},_u=(e,r)=>{var k,H,w,L;let{ownerDocument:t}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),u=t.createElement("div"),c=t.createElement("aside"),p=t.createElement("div"),d=(H=(k=r==null?void 0:r.launcher)==null?void 0:k.enabled)==null||H?(L=(w=r==null?void 0:r.launcher)==null?void 0:w.autoExpand)!=null?L:!1:!0;i.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),n.insertBefore(a,e),u.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},v=()=>{g(),Jn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Ed(a,i,u,c,p,r,d)}),f.observe(a))},M=()=>{Ed(a,i,u,c,p,r,d),v()},C=a.ownerDocument.defaultView,S=()=>{M()};return C==null||C.addEventListener("resize",S),Jn(r).reveal==="push"?(i.appendChild(u),i.appendChild(c),a.appendChild(i)):(a.appendChild(u),a.appendChild(c)),M(),{mode:"docked",host:p,shell:a,syncWidgetState(P){let E=P.launcherEnabled?P.open:!0;d!==E&&(d=E,M())},updateConfig(P){var E,Y;r=P,((Y=(E=r==null?void 0:r.launcher)==null?void 0:E.enabled)!=null?Y:!0)===!1&&(d=!0),M()},destroy(){C==null||C.removeEventListener("resize",S),g(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},Ws=(e,r)=>en(r)?_u(e,r):$u(e,r);var Ta={},ju=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 r=document.querySelector(e);if(!r)throw new Error(`Chat widget target "${e}" was not found`);return r}return e},zu=()=>{try{if(typeof Ta!="undefined"&&Ta.url)return new URL("../widget.css",Ta.url).href}catch{}return null},Td=(e,r)=>{let t=zu(),n=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=r.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=r.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else n();else if(!r.head.querySelector("link[data-persona]")&&t){let o=r.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),r.head.appendChild(o)}},Md=e=>{var C;let r=ju(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=Ws(r,s),a,i=[],u=(S,k)=>{var P,E;let w=!((E=(P=k==null?void 0:k.launcher)==null?void 0:P.enabled)!=null?E:!0)||en(k),L=n.createElement("div");if(L.setAttribute("data-persona-root","true"),w&&(L.style.height="100%",L.style.display="flex",L.style.flexDirection="column",L.style.flex="1",L.style.minHeight="0"),t){let Y=S.attachShadow({mode:"open"});Y.appendChild(L),Td(Y,n)}else S.appendChild(L),Td(S,n);return r.id&&L.setAttribute("data-persona-instance",r.id),L},c=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},d=()=>{let S=u(o.host,s);a=Ca(S,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(S=>S()),i=[],a.destroy()};d(),(C=e.onReady)==null||C.call(e);let g=S=>{f(),o.destroy(),o=Ws(r,S),s=S,d()},v={update(S){var L,P,E,Y,Q,G;let k={...s,...S,launcher:{...(L=s==null?void 0:s.launcher)!=null?L:{},...(P=S==null?void 0:S.launcher)!=null?P:{},dock:{...(Y=(E=s==null?void 0:s.launcher)==null?void 0:E.dock)!=null?Y:{},...(G=(Q=S==null?void 0:S.launcher)==null?void 0:Q.dock)!=null?G:{}}}},H=en(s),w=en(k);if(H!==w){g(k);return}s=k,o.updateConfig(s),a.update(S),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},M=new Proxy(v,{get(S,k,H){if(k==="host")return o.host;if(k in S)return Reflect.get(S,k,H);let w=a[k];return typeof w=="function"?w.bind(a):w}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=M),M};var Wd=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),qu=new Set(["button","a","input","select","textarea","details","summary"]),Uu=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ma=/\b(product|card|item|listing|result)\b/i,La=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Vu=3e3,Ju=100;function Rd(e){let r=typeof e.className=="string"?e.className:"";if(Ma.test(r)||e.id&&Ma.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&Ma.test(n.value))return!0}return!1}function Hd(e){var r;return La.test(((r=e.textContent)!=null?r:"").trim())}function Bd(e){var t;let r=e.querySelectorAll("a[href]");for(let n=0;n<r.length;n++){let s=(t=r[n].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Yu(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function kd(e){let r=e.match(La);return r?r[0]:null}function Ld(e){var n,s,o;let r=(n=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:e.querySelector("a[href]");if(r&&((s=r.textContent)!=null&&s.trim())){let a=r.getAttribute("href");return{title:r.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function Gu(e){let r=[],t=n=>{let s=n.trim();s&&!r.includes(s)&&r.push(s)};return e.querySelectorAll("button").forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var s;t((s=n.value)!=null?s:"")}),r.slice(0,6)}var Ku="commerce-card",Xu="result-card";function Id(e){return!Rd(e)||!Hd(e)||!Bd(e)&&!Yu(e)?0:5200}function Pd(e){var n;return!Rd(e)||Hd(e)||!Bd(e)||((n=e.textContent)!=null?n:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Dd=[{id:Ku,scoreElement(e){return Id(e)},shouldSuppressDescendant(e,r,t){if(r===e||!e.contains(r))return!1;if(t.interactivity==="static"){let n=t.text.trim();return!!(n.length===0||La.test(n)&&n.length<32)}return!0},formatSummary(e,r){var u,c,p;if(Id(e)===0)return null;let{title:t,href:n}=Ld(e),s=(p=(c=kd(((u=e.textContent)!=null?u:"").trim()))!=null?c:kd(r.text))!=null?p:"",o=Gu(e);return[n&&t?`[${t}](${n})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||r.text.trim().slice(0,120),`selector: ${r.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
100
100
  `)}},{id:Xu,scoreElement(e){return Pd(e)},formatSummary(e,r){if(Pd(e)===0)return null;let{title:t,href:n}=Ld(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
101
101
  `)}}];function Zu(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Qu(e){var p,d,f,g,v,M,C,S,k,H,w,L,P;let r=(p=e.options)!=null?p:{},t=(f=(d=r.maxElements)!=null?d:e.maxElements)!=null?f:80,n=(v=(g=r.excludeSelector)!=null?g:e.excludeSelector)!=null?v:".persona-host",s=(C=(M=r.maxTextLength)!=null?M:e.maxTextLength)!=null?C:200,o=(k=(S=r.visibleOnly)!=null?S:e.visibleOnly)!=null?k:!0,a=(H=r.root)!=null?H:e.root,i=(w=r.mode)!=null?w:"structured",u=(L=r.maxCandidates)!=null?L:Math.max(500,t*10),c=(P=e.rules)!=null?P:Dd;return i==="simple"&&e.rules&&e.rules.length>0?(Zu(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:u,excludeSelector:n,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function ka(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var em=["data-testid","data-product","data-action","data-id","data-name","data-type"];function tm(e){let r=e.tagName.toLowerCase(),t=e.getAttribute("role");return r==="a"&&e.hasAttribute("href")?"navigable":r==="input"||r==="select"||r==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":r==="button"||t==="button"||qu.has(r)||t&&Uu.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Fd(e){if(e.hidden)return!1;try{let r=getComputedStyle(e);if(r.display==="none"||r.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function nm(e){let r={},t=e.id;t&&(r.id=t);let n=e.getAttribute("href");n&&(r.href=n);let s=e.getAttribute("aria-label");s&&(r["aria-label"]=s);let o=e.getAttribute("type");o&&(r.type=o);let a=e.getAttribute("value");a&&(r.value=a);let i=e.getAttribute("name");i&&(r.name=i);let u=e.getAttribute("role");u&&(r.role=u);for(let c=0;c<e.attributes.length;c++){let p=e.attributes[c];p.name.startsWith("data-")&&(r[p.name]=p.value)}return r}function Nd(e){let r=e.tagName.toLowerCase();if(e.id){let s=`#${ka(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of em){let o=e.getAttribute(s);if(o){let a=`${r}[${s}="${ka(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let t=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(t.length>0){let s=`${r}.${t.map(a=>ka(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(i>=0){let u=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(u).length===1)return u}catch{}}}}let n=e.parentElement;if(n){let o=Array.from(n.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(o>=0)return`${r}:nth-of-type(${o+1})`}return r}function rm(e){return e==="static"?Ju:Vu}function Od(e,r){var s;let t=e.tagName.toLowerCase(),n=((s=e.textContent)!=null?s:"").trim().substring(0,r);return{selector:Nd(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:tm(e),attributes:nm(e)}}function om(e,r,t,n){let s=rm(r.interactivity),o=null;for(let a of t){let i=a.scoreElement(e,r,n);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function sm(e,r){var t;for(let n of e)if(r.el!==n.el&&(t=n.formattingRule)!=null&&t.shouldSuppressDescendant&&n.el.contains(r.el)&&n.formattingRule.shouldSuppressDescendant(n.el,r.el,r.enriched))return!0;return!1}function am(e,r){let t={doc:r.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,s=[],o=0,a=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,p=c.tagName.toLowerCase();if(Wd.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Fd(c)){i=a.nextNode();continue}let d=Od(c,e.maxTextLength),f=d.text.length>0,g=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(C=>C==="role");if(!f&&!g){i=a.nextNode();continue}if(n.has(d.selector)){i=a.nextNode();continue}n.add(d.selector);let{score:v,formattingRule:M}=om(c,d,e.rules,t);s.push({el:c,domIndex:o,enriched:d,score:v,formattingRule:M}),o+=1}i=a.nextNode()}s.sort((c,p)=>{let d=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return d!==f?d-f:p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex});let u=[];for(let c of s){if(u.length>=e.maxElements)break;sm(u,c)||u.push(c)}return u.sort((c,p)=>{let d=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return d!==f?d-f:d===1&&p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex}),u.map(c=>{var f;let p;if((f=c.formattingRule)!=null&&f.formatSummary){let g=c.formattingRule.formatSummary(c.el,c.enriched,t);g&&(p=g)}let d={...c.enriched};return p&&(d.formattedSummary=p),d})}function im(e,r){let t=[],n=new Set,s=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let u=o,c=u.tagName.toLowerCase();if(Wd.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Fd(u)){o=s.nextNode();continue}let p=Od(u,e.maxTextLength),d=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(g=>g==="role");if(!d&&!f){o=s.nextNode();continue}n.has(p.selector)||(n.add(p.selector),t.push(p))}o=s.nextNode()}let a=[],i=[];for(let u of t)u.interactivity!=="static"?a.push(u):i.push(u);return[...a,...i].slice(0,e.maxElements)}function lm(e={}){var n;let r=Qu(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?im(r,t):am(r,t):[]}var Rs=100;function cm(e,r={}){var o;if(e.length===0)return"No page elements found.";let t=(o=r.mode)!=null?o:"structured",n=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
102
102
  ${a.map(i=>`- ${i.split(`
@@ -112,7 +112,7 @@ ${a.join(`
112
112
  ${a.join(`
113
113
  `)}`)}return n.join(`
114
114
 
115
- `)}var $d={name:"@runtypelabs/persona",version:"3.14.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var lo=$d.version;function pr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function pm(e){if(e)return{getHeaders:pr(e.getHeaders),onFeedback:pr(e.onFeedback),onCopy:pr(e.onCopy),requestMiddleware:pr(e.requestMiddleware),actionHandlers:pr(e.actionHandlers),actionParsers:pr(e.actionParsers),postprocessMessage:pr(e.postprocessMessage),contextProviders:pr(e.contextProviders),streamParser:pr(e.streamParser)}}var _d=`({ text, message }: any) => {
115
+ `)}var $d={name:"@runtypelabs/persona",version:"3.15.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var lo=$d.version;function pr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function pm(e){if(e)return{getHeaders:pr(e.getHeaders),onFeedback:pr(e.onFeedback),onCopy:pr(e.onCopy),requestMiddleware:pr(e.requestMiddleware),actionHandlers:pr(e.actionHandlers),actionParsers:pr(e.actionParsers),postprocessMessage:pr(e.postprocessMessage),contextProviders:pr(e.contextProviders),streamParser:pr(e.streamParser)}}var _d=`({ text, message }: any) => {
116
116
  const jsonSource = (message as any).rawContent || text || message.content;
117
117
  if (!jsonSource || typeof jsonSource !== 'string') return null;
118
118
  let cleanJson = jsonSource
@@ -432,5 +432,5 @@ ${a.join(`
432
432
  min-height: 300px;
433
433
  }
434
434
  }
435
- `;function Sm(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=wm,document.head.appendChild(e)}function Am(e,r){let t=e.clientWidth-Pa*2-Xd,n=e.clientHeight-Pa*2-Xd;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function Em(e,r,t,n,s){e.style.width=`${t.w*n}px`,e.style.height=`${t.h*n}px`,e.style.borderRadius=s==="mobile"?`${32*n}px`:"10px",r.style.width=`${t.w}px`,r.style.height=`${t.h}px`,r.style.transformOrigin="top left",r.style.transform=`scale(${n})`}function Tm(e,r){let{items:t,initialIndex:n=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:u=!0,onChange:c}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");Sm();let p=Math.max(0,Math.min(n,t.length-1)),d=s,f=o,g=null,v=1,M=!1,C=h("div","persona-dc-root"),S=h("div","persona-dc-toolbar"),k=h("div","persona-dc-toolbar-lead"),H=h("div","persona-dc-toolbar-trail"),w=Bt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Re(-1)}),L=h("div");L.style.position="relative";let P=h("button","persona-dc-title-btn");P.type="button",P.setAttribute("aria-expanded","false"),P.setAttribute("aria-haspopup","listbox");let E=h("span","persona-dc-title-text"),Y=h("span","persona-dc-title-chevron"),Q=be("chevron-down",12,"currentColor",2);Q&&Y.appendChild(Q),P.append(E,Y);let G=h("div","persona-dc-dropdown");G.setAttribute("role","listbox"),G.style.display="none";let O=!1;function re(){G.innerHTML="";for(let $=0;$<t.length;$++){let q=t[$],de=h("button","persona-dc-dropdown-item");de.type="button",de.setAttribute("role","option"),de.setAttribute("aria-current",$===p?"true":"false");let _e=h("span");if(_e.textContent=q.title,de.appendChild(_e),q.description){let ee=h("span","persona-dc-dropdown-desc");ee.textContent=q.description,de.appendChild(ee)}de.addEventListener("click",()=>{oe(),Xe($)}),G.appendChild(de)}}function we(){O=!O,G.style.display=O?"":"none",P.setAttribute("aria-expanded",O?"true":"false"),O&&re()}function oe(){O&&(O=!1,G.style.display="none",P.setAttribute("aria-expanded","false"))}P.addEventListener("click",$=>{$.stopPropagation(),we()});let ve=()=>oe();document.addEventListener("click",ve),L.append(P,G);let We=Bt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Re(1)}),ge=h("span","persona-dc-counter");k.append(w,L,We,ge);let ke=null;i&&(ke=As({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:d,onSelect:$=>{d=$,U.dataset.device=d,g=null,j()}}),H.appendChild(ke.element));let Le=null;if(a){let $=h("div","persona-dc-zoom-controls"),q=Bt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let ee=g!=null?g:v;g=Math.max(Gd,ee-Yd),j()}});Le=h("span","persona-dc-zoom-level"),Le.title="Reset to 100%",Le.style.cursor="pointer",Le.addEventListener("click",()=>{g=1,j()});let de=Bt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let ee=g!=null?g:v;g=Math.min(Kd,ee+Yd),j()}}),_e=Bt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,j()}});$.append(q,Le,de,_e),H.appendChild($)}if(u){let $=h("div","persona-dc-separator");H.appendChild($);let q=As({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:de=>{f=de,U.dataset.colorScheme=f,fe()}});H.appendChild(q.element)}let se=h("div","persona-dc-separator");H.appendChild(se);let K=Bt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[p].url,"_blank")}});H.appendChild(K),S.append(k,H);let ue=h("div","persona-dc-stage"),U=h("div","persona-dc-iframe-wrapper");U.dataset.device=d,U.dataset.colorScheme=f;let te=h("iframe","persona-dc-iframe");te.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),te.setAttribute("loading","lazy"),te.title=t[p].title,U.appendChild(te),ue.appendChild(U),C.append(S,ue),e.appendChild(C);function fe(){var $;try{let q=($=te.contentDocument)==null?void 0:$.body;if(!q)return;f==="dark"?q.classList.add("theme-dark"):q.classList.remove("theme-dark")}catch{}}te.addEventListener("load",()=>fe());function pe(){let $=t[p];E.textContent=$.title,ge.textContent=`${p+1} / ${t.length}`,te.title=$.title}function Re($){let q=((p+$)%t.length+t.length)%t.length;Xe(q)}function Xe($){$<0||$>=t.length||(p=$,te.src=t[p].url,pe(),c==null||c(p,t[p]))}function j(){var de;if(M)return;let $=(de=Jd[d])!=null?de:Jd.desktop;v=Am(ue,$);let q=Math.max(Gd,Math.min(Kd,g!=null?g:v));Em(U,te,$,q,d),Le&&(Le.textContent=`${Math.round(q*100)}%`)}let W=new ResizeObserver(()=>j());W.observe(ue),pe(),te.src=t[p].url,requestAnimationFrame(()=>j());function ae(){M||(M=!0,W.disconnect(),document.removeEventListener("click",ve),C.remove())}return{element:C,goTo:Xe,next:()=>Re(1),prev:()=>Re(-1),getIndex:()=>p,setDevice($){d=$,U.dataset.device=$,ke==null||ke.setSelected($),g=null,j()},setColorScheme($){f=$,U.dataset.colorScheme=$},setZoom($){g=$,j()},destroy:ae}}function Mm(){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 km(){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 Lm(e){return{name:"@persona/brand",version:"1.0.0",transform(r){var n;let t={...r.palette};return(n=e.colors)!=null&&n.primary&&(t.colors={...t.colors,primary:{50:tr(e.colors.primary,.95),100:tr(e.colors.primary,.9),200:tr(e.colors.primary,.8),300:tr(e.colors.primary,.7),400:tr(e.colors.primary,.6),500:e.colors.primary,600:tr(e.colors.primary,.8),700:tr(e.colors.primary,.7),800:tr(e.colors.primary,.6),900:tr(e.colors.primary,.5),950:tr(e.colors.primary,.45)}}),{...r,palette:t}}}}function Im(){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 Pm(){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 tr(e,r){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-r)),a=Math.round(n+(255-n)*(1-r)),i=Math.round(s+(255-s)*(1-r));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Wm(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Rm={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"}}},Zd={components:{panel:{borderRadius:"0",shadow:"none"}}},Qd={id:"shop",label:"Shopping Assistant",config:{theme:Rm,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Nn},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?"]}},ep={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Zd}},tp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Zd}},np={shop:Qd,minimal:ep,fullscreen:tp};function Hm(e){return np[e]}var Wy=Md;export{Xr as AgentWidgetClient,Po as AgentWidgetSession,eo as AttachmentManager,$c as DEFAULT_COMPONENTS,Ks as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,Nn as DEFAULT_FLOATING_LAUNCHER_WIDTH,Nc as DEFAULT_PALETTE,Oc as DEFAULT_SEMANTIC,It as DEFAULT_WIDGET_CONFIG,np as PRESETS,tp as PRESET_FULLSCREEN,ep as PRESET_MINIMAL,Qd as PRESET_SHOP,Dp as THEME_ZONES,lo as VERSION,Mm as accessibilityPlugin,km as animationsPlugin,$r as applyThemeVariables,to as attachHeaderToContainer,Lm as brandPlugin,$o as buildComposer,Xc as buildDefaultHeader,Sr as buildHeader,Oo as buildHeaderWithLayout,Zc as buildMinimalHeader,lm as collectEnrichedPageContext,Ar as componentRegistry,Ls as createActionManager,Ca as createAgentExperience,Gs as createBestAvailableVoiceProvider,Xp as createBubbleWithLayout,ba as createCSATFeedback,ra as createComboButton,Iu as createComponentMiddleware,ga as createComponentStreamParser,Ec as createDefaultSanitizer,Tm as createDemoCarousel,lp as createDirectivePostprocessor,_r as createDropdownMenu,hp as createFlexibleJsonStreamParser,Bt as createIconButton,Ep as createImagePart,Us as createJsonStreamParser,Ss as createLabelButton,ma as createLocalStorageAdapter,ss as createMarkdownProcessor,Gr as createMarkdownProcessorFromConfig,od as createMessageActions,xa as createNPSFeedback,zs as createPlainTextParser,Wm as createPlugin,qs as createRegexJsonParser,_o as createStandardBubble,ps as createTextPart,Ho as createTheme,ea as createThemeObserver,As as createToggleGroup,no as createTypingIndicator,Qr as createVoiceProvider,Ws as createWidgetHostLayout,Vs as createXmlParser,Wy as default,ao as defaultActionHandlers,ks as defaultJsonActionParser,Dd as defaultParseRules,ys as detectColorScheme,cp as directivePostprocessor,Eo as escapeHtml,ya as extractComponentDirectiveFromMessage,Tp as fileToImagePart,cm as formatEnrichedContext,Zr as generateAssistantMessageId,fm as generateCodeSnippet,vp as generateMessageId,Nd as generateStableSelector,Lo as generateUserMessageId,bs as getActiveTheme,qc as getColorScheme,wp as getDisplayText,Qc as getHeaderLayout,Ap as getImageParts,Hm as getPreset,ha as hasComponentDirective,Sp as hasImages,oa as headerLayouts,Pm as highContrastPlugin,Md as initAgentWidget,Lu as isComponentDirectiveType,en as isDockedMountMode,fs as isVoiceSupported,wc as markdownPostprocessor,Xs as mergeWithDefaults,Cp as normalizeContent,Ms as pluginRegistry,Im as reducedMotionPlugin,fa as renderComponentDirective,rd as renderLoadingIndicatorWithFallback,Jn as resolveDockConfig,To as resolveSanitizer,Zs as resolveTokens,Qs as themeToCssVariables,Mp as validateImageFile,_c as validateTheme};
435
+ `;function Sm(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=wm,document.head.appendChild(e)}function Am(e,r){let t=e.clientWidth-Pa*2-Xd,n=e.clientHeight-Pa*2-Xd;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function Em(e,r,t,n,s){e.style.width=`${t.w*n}px`,e.style.height=`${t.h*n}px`,e.style.borderRadius=s==="mobile"?`${32*n}px`:"10px",r.style.width=`${t.w}px`,r.style.height=`${t.h}px`,r.style.transformOrigin="top left",r.style.transform=`scale(${n})`}function Tm(e,r){let{items:t,initialIndex:n=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:u=!0,onChange:c}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");Sm();let p=Math.max(0,Math.min(n,t.length-1)),d=s,f=o,g=null,v=1,M=!1,C=h("div","persona-dc-root"),S=h("div","persona-dc-toolbar"),k=h("div","persona-dc-toolbar-lead"),H=h("div","persona-dc-toolbar-trail"),w=Bt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Re(-1)}),L=h("div");L.style.position="relative";let P=h("button","persona-dc-title-btn");P.type="button",P.setAttribute("aria-expanded","false"),P.setAttribute("aria-haspopup","listbox");let E=h("span","persona-dc-title-text"),Y=h("span","persona-dc-title-chevron"),Q=be("chevron-down",12,"currentColor",2);Q&&Y.appendChild(Q),P.append(E,Y);let G=h("div","persona-dc-dropdown");G.setAttribute("role","listbox"),G.style.display="none";let O=!1;function re(){G.innerHTML="";for(let $=0;$<t.length;$++){let q=t[$],de=h("button","persona-dc-dropdown-item");de.type="button",de.setAttribute("role","option"),de.setAttribute("aria-current",$===p?"true":"false");let _e=h("span");if(_e.textContent=q.title,de.appendChild(_e),q.description){let ee=h("span","persona-dc-dropdown-desc");ee.textContent=q.description,de.appendChild(ee)}de.addEventListener("click",()=>{oe(),Xe($)}),G.appendChild(de)}}function we(){O=!O,G.style.display=O?"":"none",P.setAttribute("aria-expanded",O?"true":"false"),O&&re()}function oe(){O&&(O=!1,G.style.display="none",P.setAttribute("aria-expanded","false"))}P.addEventListener("click",$=>{$.stopPropagation(),we()});let ve=()=>oe();document.addEventListener("click",ve),L.append(P,G);let We=Bt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Re(1)}),ge=h("span","persona-dc-counter");k.append(w,L,We,ge);let ke=null;i&&(ke=As({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:d,onSelect:$=>{d=$,U.dataset.device=d,g=null,j()}}),H.appendChild(ke.element));let Le=null;if(a){let $=h("div","persona-dc-zoom-controls"),q=Bt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let ee=g!=null?g:v;g=Math.max(Gd,ee-Yd),j()}});Le=h("span","persona-dc-zoom-level"),Le.title="Reset to 100%",Le.style.cursor="pointer",Le.addEventListener("click",()=>{g=1,j()});let de=Bt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let ee=g!=null?g:v;g=Math.min(Kd,ee+Yd),j()}}),_e=Bt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,j()}});$.append(q,Le,de,_e),H.appendChild($)}if(u){let $=h("div","persona-dc-separator");H.appendChild($);let q=As({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:de=>{f=de,U.dataset.colorScheme=f,fe()}});H.appendChild(q.element)}let se=h("div","persona-dc-separator");H.appendChild(se);let K=Bt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[p].url,"_blank")}});H.appendChild(K),S.append(k,H);let ue=h("div","persona-dc-stage"),U=h("div","persona-dc-iframe-wrapper");U.dataset.device=d,U.dataset.colorScheme=f;let te=h("iframe","persona-dc-iframe");te.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),te.setAttribute("loading","lazy"),te.title=t[p].title,U.appendChild(te),ue.appendChild(U),C.append(S,ue),e.appendChild(C);function fe(){var $;try{let q=($=te.contentDocument)==null?void 0:$.body;if(!q)return;f==="dark"?q.classList.add("theme-dark"):q.classList.remove("theme-dark")}catch{}}te.addEventListener("load",()=>fe());function pe(){let $=t[p];E.textContent=$.title,ge.textContent=`${p+1} / ${t.length}`,te.title=$.title}function Re($){let q=((p+$)%t.length+t.length)%t.length;Xe(q)}function Xe($){$<0||$>=t.length||(p=$,te.src=t[p].url,pe(),c==null||c(p,t[p]))}function j(){var de;if(M)return;let $=(de=Jd[d])!=null?de:Jd.desktop;v=Am(ue,$);let q=Math.max(Gd,Math.min(Kd,g!=null?g:v));Em(U,te,$,q,d),Le&&(Le.textContent=`${Math.round(q*100)}%`)}let W=new ResizeObserver(()=>j());W.observe(ue),pe(),te.src=t[p].url,requestAnimationFrame(()=>j());function ae(){M||(M=!0,W.disconnect(),document.removeEventListener("click",ve),C.remove())}return{element:C,goTo:Xe,next:()=>Re(1),prev:()=>Re(-1),getIndex:()=>p,setDevice($){d=$,U.dataset.device=$,ke==null||ke.setSelected($),g=null,j()},setColorScheme($){f=$,U.dataset.colorScheme=$},setZoom($){g=$,j()},destroy:ae}}function Mm(){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 km(){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 Lm(e){return{name:"@persona/brand",version:"1.0.0",transform(r){var n;let t={...r.palette};return(n=e.colors)!=null&&n.primary&&(t.colors={...t.colors,primary:{50:tr(e.colors.primary,.95),100:tr(e.colors.primary,.9),200:tr(e.colors.primary,.8),300:tr(e.colors.primary,.7),400:tr(e.colors.primary,.6),500:e.colors.primary,600:tr(e.colors.primary,.8),700:tr(e.colors.primary,.7),800:tr(e.colors.primary,.6),900:tr(e.colors.primary,.5),950:tr(e.colors.primary,.45)}}),{...r,palette:t}}}}function Im(){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 Pm(){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 tr(e,r){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-r)),a=Math.round(n+(255-n)*(1-r)),i=Math.round(s+(255-s)*(1-r));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Wm(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Rm={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"}}},Zd={components:{panel:{borderRadius:"0",shadow:"none"}}},Qd={id:"shop",label:"Shopping Assistant",config:{theme:Rm,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Nn},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?"]}},ep={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Zd}},tp={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Zd}},np={shop:Qd,minimal:ep,fullscreen:tp};function Hm(e){return np[e]}var Wy=Md;export{Xr as AgentWidgetClient,Po as AgentWidgetSession,eo as AttachmentManager,$c as DEFAULT_COMPONENTS,Ks as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,Nn as DEFAULT_FLOATING_LAUNCHER_WIDTH,Nc as DEFAULT_PALETTE,Oc as DEFAULT_SEMANTIC,Pt as DEFAULT_WIDGET_CONFIG,np as PRESETS,tp as PRESET_FULLSCREEN,ep as PRESET_MINIMAL,Qd as PRESET_SHOP,Dp as THEME_ZONES,lo as VERSION,Mm as accessibilityPlugin,km as animationsPlugin,$r as applyThemeVariables,to as attachHeaderToContainer,Lm as brandPlugin,$o as buildComposer,Xc as buildDefaultHeader,Sr as buildHeader,Oo as buildHeaderWithLayout,Zc as buildMinimalHeader,lm as collectEnrichedPageContext,Ar as componentRegistry,Ls as createActionManager,Ca as createAgentExperience,Gs as createBestAvailableVoiceProvider,Xp as createBubbleWithLayout,ba as createCSATFeedback,ra as createComboButton,Iu as createComponentMiddleware,ga as createComponentStreamParser,Ec as createDefaultSanitizer,Tm as createDemoCarousel,lp as createDirectivePostprocessor,_r as createDropdownMenu,hp as createFlexibleJsonStreamParser,Bt as createIconButton,Ep as createImagePart,Us as createJsonStreamParser,Ss as createLabelButton,ma as createLocalStorageAdapter,ss as createMarkdownProcessor,Gr as createMarkdownProcessorFromConfig,od as createMessageActions,xa as createNPSFeedback,zs as createPlainTextParser,Wm as createPlugin,qs as createRegexJsonParser,_o as createStandardBubble,ps as createTextPart,Ho as createTheme,ea as createThemeObserver,As as createToggleGroup,no as createTypingIndicator,Qr as createVoiceProvider,Ws as createWidgetHostLayout,Vs as createXmlParser,Wy as default,ao as defaultActionHandlers,ks as defaultJsonActionParser,Dd as defaultParseRules,ys as detectColorScheme,cp as directivePostprocessor,Eo as escapeHtml,ya as extractComponentDirectiveFromMessage,Tp as fileToImagePart,cm as formatEnrichedContext,Zr as generateAssistantMessageId,fm as generateCodeSnippet,vp as generateMessageId,Nd as generateStableSelector,Lo as generateUserMessageId,bs as getActiveTheme,qc as getColorScheme,wp as getDisplayText,Qc as getHeaderLayout,Ap as getImageParts,Hm as getPreset,ha as hasComponentDirective,Sp as hasImages,oa as headerLayouts,Pm as highContrastPlugin,Md as initAgentWidget,Lu as isComponentDirectiveType,en as isDockedMountMode,fs as isVoiceSupported,wc as markdownPostprocessor,Xs as mergeWithDefaults,Cp as normalizeContent,Ms as pluginRegistry,Im as reducedMotionPlugin,fa as renderComponentDirective,rd as renderLoadingIndicatorWithFallback,Jn as resolveDockConfig,To as resolveSanitizer,Zs as resolveTokens,Qs as themeToCssVariables,Mp as validateImageFile,_c as validateTheme};
436
436
  //# sourceMappingURL=index.js.map