@runtypelabs/persona 3.1.1 → 3.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,23 +1,23 @@
1
1
  import{Marked as Wc}from"marked";var Rc=e=>{if(e)return e},Lo=e=>{var s,o;let r=e==null?void 0:e.markedOptions,t=new Wc({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=Rc(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),a=>t.parse(a)},hr=e=>e?Lo({markedOptions:e.options,renderer:e.renderer}):Lo(),Hc=Lo(),rl=e=>Hc(e),Kr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),ol=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),nl=e=>`%%FORM_PLACEHOLDER_${e}%%`,sl=(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=nl(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=nl(r.length);return r.push({token:o,type:s}),o}),t},Bc=e=>{let r=hr(e);return t=>{let n=[],s=sl(t,n),o=r(s);return n.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${ol(i)}"></div>`;o=o.replace(d,u)}),o}},Dc=e=>{let r=[],t=sl(e,r),n=rl(t);return r.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${ol(o)}"></div>`;n=n.replace(a,d)}),n};import Nc from"dompurify";var Oc={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"]},Fc=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,al=()=>{let e=Nc(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:")&&!Fc.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,Oc)},Yr=e=>e===!1?null:typeof e=="function"?e:al();import{parse as il,STR as ll,OBJ as cl}from"partial-json";var Po=e=>e.replace(/\\n/g,`
2
2
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Gr=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)}},$c=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`},dl=e=>e.status==="complete"?$c(e):e.status==="pending"?"Waiting":"",_c=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 pl=e=>e.status==="complete"?_c(e):"Using tool...",jc=()=>{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()=>{}}},Io=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},os=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ss=()=>{var r;let e=jc();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)}},as=()=>{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=il(t,ll|cl);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Po(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Po(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},zc=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Po(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Po(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=il(o,ll|cl),d=s(i);d!==null&&(r=d)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},is=()=>{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 qc="https://api.runtype.com/v1/dispatch",ls="https://api.runtype.com",cs=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 Uc(e){switch(e){case"json":return as;case"regex-json":return ss;case"xml":return is;default:return os}}var yr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:qc,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:Uc(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$/,""))||ls;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$/,""))||ls}/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 d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let m=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:m}),m}let c=await this.buildPayload(r.messages),u=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,p={sessionId:d.sessionId,messages:r.messages.filter(cs).map(m=>{var C,T,b;return{id:m.id,role:m.role,content:(b=(T=(C=m.contentParts)!=null?C:m.llmContent)!=null?T:m.rawContent)!=null?b:m.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:n.signal});if(!f.ok){let m=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 T=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:T}),T}if(f.status===429){let T=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:T}),T}let C=new Error(m.error||"Failed to send message");throw t({type:"error",error:C}),C}if(!f.body){let m=new Error("No response body received");throw t({type:"error",error:m}),m}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(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 d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers: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 d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers: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$/,""))||ls}/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(cs).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(cs).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){if(!this.parseSSEEvent)return!1;try{let a=await this.parseSSEEvent(r);if(a===null)return!1;let i=()=>{if(n.current)return n.current;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()};return n.current=d,s(d),d};if(a.text!==void 0){let d=i();d.content+=a.text,s(d)}return a.done&&(n.current&&(n.current.streaming=!1,s(n.current)),t({type:"status",status:"idle"})),a.error&&t({type:"error",error:new Error(a.error)}),!0}catch(a){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",a),!1}}async streamResponse(r,t,n){var ut,xt,Fe,be,ue,V,Q,re,Me,Xe,ee,Y,Ve,Ie,ft,jt,zt,de,le,ot,gt,Je,st,Ht,Lt,qt,S,U,te,$e,se,ze,Ae,He,ke,Ke,et,we,qn,bn,Un,Bn,ir,Dn,Tn,Ze,nn,G,Jt,Vn,xn,mt,sn,Mn,Lr,lr,Pr,Jn,vn,Kn,wt,Cn,Ir,Nn,wn,H,On,Fn,Wr,kn,Yn,Rr,Ln,Pn,cr,dr,co,po,uo,Hr,pr,je,Br,an,Xt,go,mo,Dr,Gn,In,fo,ho,yo,ts,Xn,Zn,ht,ur,gr,Nr,Or,Fr,$r,Kt,rn,Wn,Be,_r,Qn,un,bo,mr,fr,er,$n,xo,vo,gn,tr;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,u=X=>{let Ye=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,Ne=X.tools?X.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...X,reasoning:Ye,toolCall:tt,tools:Ne}},p=X=>{t({type:"message",message:u(X)})},f=null,m={current:null},C=new Map,T=new Map,b={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},M=X=>{if(X==null)return null;try{return String(X)}catch{return null}},O=X=>{var Ye,tt,Ne,_e,Tt;return M((Tt=(_e=(Ne=(tt=(Ye=X.stepId)!=null?Ye:X.step_id)!=null?tt:X.step)!=null?Ne:X.parentId)!=null?_e:X.flowStepId)!=null?Tt:X.flow_step_id)},A=X=>{var Ye,tt,Ne,_e,Tt,St,v;return M((v=(St=(Tt=(_e=(Ne=(tt=(Ye=X.callId)!=null?Ye:X.call_id)!=null?tt:X.requestId)!=null?Ne:X.request_id)!=null?_e:X.toolCallId)!=null?Tt:X.tool_call_id)!=null?St:X.stepId)!=null?v:X.step_id)},W=()=>f||(f={id:n!=null?n:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},p(f),f),_=(X,Ye)=>{b.lastId=Ye,X&&b.byStep.set(X,Ye)},k=(X,Ye)=>{var Tt;let tt=(Tt=X.reasoningId)!=null?Tt:X.id,Ne=O(X);if(tt){let St=String(tt);return _(Ne,St),St}if(Ne){let St=b.byStep.get(Ne);if(St)return b.lastId=St,St}if(b.lastId&&!Ye)return b.lastId;if(!Ye)return null;let _e=`reason-${c()}`;return _(Ne,_e),_e},q=X=>{let Ye=C.get(X);if(Ye)return Ye;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),p(tt),tt},me=(X,Ye)=>{x.lastId=Ye,X&&x.byCall.set(X,Ye)},ce=new Set,z=new Map,ne=new Set,Ee=new Map,ie=X=>{if(!X)return!1;let Ye=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ye==="emit_artifact_markdown"||Ye==="emit_artifact_component"},ye=(X,Ye)=>{var Tt;let tt=(Tt=X.toolId)!=null?Tt:X.id,Ne=A(X);if(tt){let St=String(tt);return me(Ne,St),St}if(Ne){let St=x.byCall.get(Ne);if(St)return x.lastId=St,St}if(x.lastId&&!Ye)return x.lastId;if(!Ye)return null;let _e=`tool-${c()}`;return me(Ne,_e),_e},xe=X=>{let Ye=T.get(X);if(Ye)return Ye;let tt={id:`tool-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:X,status:"pending"}};return T.set(X,tt),p(tt),tt},J=X=>{if(typeof X=="number"&&Number.isFinite(X))return X;if(typeof X=="string"){let Ye=Number(X);if(!Number.isNaN(Ye)&&Number.isFinite(Ye))return Ye;let tt=Date.parse(X);if(!Number.isNaN(tt))return tt}return Date.now()},ve=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},F=new Map,K=new Map,fe=null,pt=new Map,Ct=(ut=this.config.iterationDisplay)!=null?ut:"separate";for(;;){let{done:X,value:Ye}=await s.read();if(X)break;a+=o.decode(Ye,{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()=>{}}},Io=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},os=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ss=()=>{var r;let e=jc();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)}},as=()=>{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=il(t,ll|cl);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Po(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Po(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},zc=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Po(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Po(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=il(o,ll|cl),d=s(i);d!==null&&(r=d)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},is=()=>{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 qc="https://api.runtype.com/v1/dispatch",ls="https://api.runtype.com",cs=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 Uc(e){switch(e){case"json":return as;case"regex-json":return ss;case"xml":return is;default:return os}}var yr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:qc,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:Uc(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$/,""))||ls;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$/,""))||ls}/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 d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let m=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:m}),m}let c=await this.buildPayload(r.messages),u=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,p={sessionId:d.sessionId,messages:r.messages.filter(cs).map(m=>{var C,T,b;return{id:m.id,role:m.role,content:(b=(T=(C=m.contentParts)!=null?C:m.llmContent)!=null?T:m.rawContent)!=null?b:m.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:n.signal});if(!f.ok){let m=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 T=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:T}),T}if(f.status===429){let T=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:T}),T}let C=new Error(m.error||"Failed to send message");throw t({type:"error",error:C}),C}if(!f.body){let m=new Error("No response body received");throw t({type:"error",error:m}),m}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(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 d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers: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 d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers: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$/,""))||ls}/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(cs).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(cs).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){if(!this.parseSSEEvent)return!1;try{let a=await this.parseSSEEvent(r);if(a===null)return!1;let i=()=>{if(n.current)return n.current;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()};return n.current=d,s(d),d};if(a.text!==void 0){let d=i();d.content+=a.text,s(d)}return a.done&&(n.current&&(n.current.streaming=!1,s(n.current)),t({type:"status",status:"idle"})),a.error&&t({type:"error",error:new Error(a.error)}),!0}catch(a){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",a),!1}}async streamResponse(r,t,n){var ut,xt,Fe,xe,ge,J,Q,re,Me,Xe,ee,Y,Ve,Ie,ft,jt,zt,pe,ce,ot,gt,Je,st,Ht,Lt,qt,S,V,te,$e,se,ze,Se,He,ke,Ke,et,Ce,qn,bn,Un,Bn,ir,Dn,Tn,Ze,nn,G,Jt,Vn,xn,mt,sn,Mn,Lr,lr,Pr,Jn,vn,Kn,wt,Cn,Ir,Nn,wn,H,On,Fn,Wr,kn,Yn,Rr,Ln,Pn,cr,dr,co,po,uo,Hr,pr,je,Br,an,Xt,go,mo,Dr,Gn,In,fo,ho,yo,ts,Xn,Zn,ht,ur,gr,Nr,Or,Fr,$r,Kt,rn,Wn,Be,_r,Qn,un,bo,mr,fr,er,$n,xo,vo,gn,tr;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,u=X=>{let Ye=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,Ne=X.tools?X.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...X,reasoning:Ye,toolCall:tt,tools:Ne}},p=X=>{t({type:"message",message:u(X)})},f=null,m={current:null},C=new Map,T=new Map,b={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},M=X=>{if(X==null)return null;try{return String(X)}catch{return null}},O=X=>{var Ye,tt,Ne,_e,Tt;return M((Tt=(_e=(Ne=(tt=(Ye=X.stepId)!=null?Ye:X.step_id)!=null?tt:X.step)!=null?Ne:X.parentId)!=null?_e:X.flowStepId)!=null?Tt:X.flow_step_id)},A=X=>{var Ye,tt,Ne,_e,Tt,St,v;return M((v=(St=(Tt=(_e=(Ne=(tt=(Ye=X.callId)!=null?Ye:X.call_id)!=null?tt:X.requestId)!=null?Ne:X.request_id)!=null?_e:X.toolCallId)!=null?Tt:X.tool_call_id)!=null?St:X.stepId)!=null?v:X.step_id)},W=()=>f||(f={id:n!=null?n:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},p(f),f),_=(X,Ye)=>{b.lastId=Ye,X&&b.byStep.set(X,Ye)},k=(X,Ye)=>{var Tt;let tt=(Tt=X.reasoningId)!=null?Tt:X.id,Ne=O(X);if(tt){let St=String(tt);return _(Ne,St),St}if(Ne){let St=b.byStep.get(Ne);if(St)return b.lastId=St,St}if(b.lastId&&!Ye)return b.lastId;if(!Ye)return null;let _e=`reason-${c()}`;return _(Ne,_e),_e},q=X=>{let Ye=C.get(X);if(Ye)return Ye;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),p(tt),tt},fe=(X,Ye)=>{x.lastId=Ye,X&&x.byCall.set(X,Ye)},de=new Set,z=new Map,ne=new Set,Ae=new Map,le=X=>{if(!X)return!1;let Ye=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ye==="emit_artifact_markdown"||Ye==="emit_artifact_component"},Ee=(X,Ye)=>{var Tt;let tt=(Tt=X.toolId)!=null?Tt:X.id,Ne=A(X);if(tt){let St=String(tt);return fe(Ne,St),St}if(Ne){let St=x.byCall.get(Ne);if(St)return x.lastId=St,St}if(x.lastId&&!Ye)return x.lastId;if(!Ye)return null;let _e=`tool-${c()}`;return fe(Ne,_e),_e},ie=X=>{let Ye=T.get(X);if(Ye)return Ye;let tt={id:`tool-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:X,status:"pending"}};return T.set(X,tt),p(tt),tt},K=X=>{if(typeof X=="number"&&Number.isFinite(X))return X;if(typeof X=="string"){let Ye=Number(X);if(!Number.isNaN(Ye)&&Number.isFinite(Ye))return Ye;let tt=Date.parse(X);if(!Number.isNaN(tt))return tt}return Date.now()},be=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},F=new Map,U=new Map,he=null,pt=new Map,Ct=(ut=this.config.iterationDisplay)!=null?ut:"separate";for(;;){let{done:X,value:Ye}=await s.read();if(X)break;a+=o.decode(Ye,{stream:!0});let tt=a.split(`
5
5
 
6
6
  `);a=(xt=tt.pop())!=null?xt:"";for(let Ne of tt){let _e=Ne.split(`
7
- `),Tt="message",St="";for(let B of _e)B.startsWith("event:")?Tt=B.replace("event:","").trim():B.startsWith("data:")&&(St+=B.replace("data:","").trim());if(!St)continue;let v;try{v=JSON.parse(St)}catch(B){t({type:"error",error:B instanceof Error?B:new Error("Failed to parse chat stream payload")});continue}let De=Tt!=="message"?Tt:(Fe=v.type)!=null?Fe:"message";if((be=this.onSSEEvent)==null||be.call(this,De,v),this.parseSSEEvent){m.current=f;let B=await this.handleCustomSSEEvent(v,t,m,p,c);if(m.current&&!f&&(f=m.current),B)continue}if(De==="reason_start"){let B=(ue=k(v,!0))!=null?ue:`reason-${c()}`,w=q(B);w.reasoning=(V=w.reasoning)!=null?V:{id:B,status:"streaming",chunks:[]},w.reasoning.startedAt=(re=w.reasoning.startedAt)!=null?re:J((Q=v.startedAt)!=null?Q:v.timestamp),w.reasoning.completedAt=void 0,w.reasoning.durationMs=void 0,w.streaming=!0,w.reasoning.status="streaming",p(w)}else if(De==="reason_delta"||De==="reason_chunk"){let B=(Xe=(Me=k(v,!1))!=null?Me:k(v,!0))!=null?Xe:`reason-${c()}`,w=q(B);w.reasoning=(ee=w.reasoning)!=null?ee:{id:B,status:"streaming",chunks:[]},w.reasoning.startedAt=(Ve=w.reasoning.startedAt)!=null?Ve:J((Y=v.startedAt)!=null?Y:v.timestamp);let N=(jt=(ft=(Ie=v.reasoningText)!=null?Ie:v.text)!=null?ft:v.delta)!=null?jt:"";if(N&&v.hidden!==!0&&w.reasoning.chunks.push(String(N)),w.reasoning.status=v.done?"complete":"streaming",v.done){w.reasoning.completedAt=J((zt=v.completedAt)!=null?zt:v.timestamp);let Z=(de=w.reasoning.startedAt)!=null?de:Date.now();w.reasoning.durationMs=Math.max(0,((le=w.reasoning.completedAt)!=null?le:Date.now())-Z)}w.streaming=w.reasoning.status!=="complete",p(w)}else if(De==="reason_complete"){let B=(gt=(ot=k(v,!1))!=null?ot:k(v,!0))!=null?gt:`reason-${c()}`,w=C.get(B);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=J((Je=v.completedAt)!=null?Je:v.timestamp);let Z=(st=w.reasoning.startedAt)!=null?st:Date.now();w.reasoning.durationMs=Math.max(0,((Ht=w.reasoning.completedAt)!=null?Ht:Date.now())-Z),w.streaming=!1,p(w)}let N=O(v);N&&b.byStep.delete(N)}else if(De==="tool_start"){let B=(Lt=ye(v,!0))!=null?Lt:`tool-${c()}`,w=(qt=v.toolName)!=null?qt:v.name;if(ie(w)){ce.add(B);continue}let N=xe(B),Z=(S=N.toolCall)!=null?S:{id:B,status:"pending"};Z.name=w!=null?w:Z.name,Z.status="running",v.args!==void 0?Z.args=v.args:v.parameters!==void 0&&(Z.args=v.parameters),Z.startedAt=(te=Z.startedAt)!=null?te:J((U=v.startedAt)!=null?U:v.timestamp),Z.completedAt=void 0,Z.durationMs=void 0,N.toolCall=Z,N.streaming=!0;let Se=v.agentContext;(Se||v.executionId)&&(N.agentMetadata={executionId:($e=Se==null?void 0:Se.executionId)!=null?$e:v.executionId,iteration:(se=Se==null?void 0:Se.iteration)!=null?se:v.iteration}),p(N)}else if(De==="tool_chunk"||De==="tool_delta"){let B=(Ae=(ze=ye(v,!1))!=null?ze:ye(v,!0))!=null?Ae:`tool-${c()}`;if(ce.has(B))continue;let w=xe(B),N=(He=w.toolCall)!=null?He:{id:B,status:"running"};N.startedAt=(Ke=N.startedAt)!=null?Ke:J((ke=v.startedAt)!=null?ke:v.timestamp);let Z=(qn=(we=(et=v.text)!=null?et:v.delta)!=null?we:v.message)!=null?qn:"";Z&&(N.chunks=(bn=N.chunks)!=null?bn:[],N.chunks.push(String(Z))),N.status="running",w.toolCall=N,w.streaming=!0;let Se=v.agentContext;(Se||v.executionId)&&(w.agentMetadata=(ir=w.agentMetadata)!=null?ir:{executionId:(Un=Se==null?void 0:Se.executionId)!=null?Un:v.executionId,iteration:(Bn=Se==null?void 0:Se.iteration)!=null?Bn:v.iteration}),p(w)}else if(De==="tool_complete"){let B=(Tn=(Dn=ye(v,!1))!=null?Dn:ye(v,!0))!=null?Tn:`tool-${c()}`;if(ce.has(B)){ce.delete(B);continue}let w=xe(B),N=(Ze=w.toolCall)!=null?Ze:{id:B,status:"running"};N.status="complete",v.result!==void 0&&(N.result=v.result),typeof v.duration=="number"&&(N.duration=v.duration),N.completedAt=J((nn=v.completedAt)!=null?nn:v.timestamp);let Z=(G=v.duration)!=null?G:v.executionTime;if(typeof Z=="number")N.durationMs=Z;else{let Pt=(Jt=N.startedAt)!=null?Jt:Date.now();N.durationMs=Math.max(0,((Vn=N.completedAt)!=null?Vn:Date.now())-Pt)}w.toolCall=N,w.streaming=!1;let Se=v.agentContext;(Se||v.executionId)&&(w.agentMetadata=(sn=w.agentMetadata)!=null?sn:{executionId:(xn=Se==null?void 0:Se.executionId)!=null?xn:v.executionId,iteration:(mt=Se==null?void 0:Se.iteration)!=null?mt:v.iteration}),p(w);let at=A(v);at&&x.byCall.delete(at)}else if(De==="step_chunk"||De==="step_delta"){let B=v.stepType,w=v.executionType;if(B==="tool"||w==="context")continue;let N=W(),Z=(Pr=(lr=(Lr=(Mn=v.text)!=null?Mn:v.delta)!=null?Lr:v.content)!=null?lr:v.chunk)!=null?Pr:"";if(Z){let at=((Jn=K.get(N.id))!=null?Jn:"")+Z;N.rawContent=at,F.has(N.id)||F.set(N.id,this.createStreamParser());let Pt=F.get(N.id),At=at.trim().startsWith("{")||at.trim().startsWith("[");if(At&&K.set(N.id,at),Pt.__isPlainTextParser===!0){N.content+=Z,K.delete(N.id),F.delete(N.id),N.rawContent=void 0,p(N);continue}let It=Pt.processChunk(at);if(It instanceof Promise)It.then(it=>{var Mt;let ct=typeof it=="string"?it:(Mt=it==null?void 0:it.text)!=null?Mt:null;if(ct!==null&&ct.trim()!==""){let dt=f;dt&&dt.id===N.id&&(dt.content=ct,p(dt))}else if(!At&&!at.trim().startsWith("<")){let dt=f;dt&&dt.id===N.id&&(dt.content+=Z,K.delete(dt.id),F.delete(dt.id),dt.rawContent=void 0,p(dt))}}).catch(()=>{N.content+=Z,K.delete(N.id),F.delete(N.id),N.rawContent=void 0,p(N)});else{let it=typeof It=="string"?It:(vn=It==null?void 0:It.text)!=null?vn:null;it!==null&&it.trim()!==""?(N.content=it,p(N)):!At&&!at.trim().startsWith("<")&&(N.content+=Z,K.delete(N.id),F.delete(N.id),N.rawContent=void 0,p(N))}}if(v.isComplete){let Se=(wt=(Kn=v.result)==null?void 0:Kn.response)!=null?wt:N.content;if(Se){let at=K.get(N.id),Pt=at!=null?at:ve(Se);N.rawContent=Pt;let At=F.get(N.id),Bt=null,It=!1;if(At&&(Bt=At.getExtractedText(),Bt===null&&(Bt=Io(Pt)),Bt===null)){let it=At.processChunk(Pt);it instanceof Promise?(It=!0,it.then(ct=>{var dt;let Mt=typeof ct=="string"?ct:(dt=ct==null?void 0:ct.text)!=null?dt:null;if(Mt!==null){let Dt=f;Dt&&Dt.id===N.id&&(Dt.content=Mt,Dt.streaming=!1,F.delete(Dt.id),K.delete(Dt.id),p(Dt))}})):Bt=typeof it=="string"?it:(Cn=it==null?void 0:it.text)!=null?Cn:null}if(!It){Bt!==null&&Bt.trim()!==""?N.content=Bt:K.has(N.id)||(N.content=ve(Se));let it=F.get(N.id);if(it){let ct=(Ir=it.close)==null?void 0:Ir.call(it);ct instanceof Promise&&ct.catch(()=>{}),F.delete(N.id)}K.delete(N.id),N.streaming=!1,p(N)}}}}else if(De==="step_complete"){let B=v.stepType,w=v.executionType;if(B==="tool"||w==="context")continue;let N=(Nn=v.result)==null?void 0:Nn.response,Z=W();if(N!=null){let Se=F.get(Z.id),at=!1,Pt=!1;if(Se){let At=Se.getExtractedText(),Bt=K.get(Z.id),It=Bt!=null?Bt:ve(N);if(Z.rawContent=It,At!==null&&At.trim()!=="")Z.content=At,at=!0;else{let it=Io(It);if(it!==null)Z.content=it,at=!0;else{let ct=Se.processChunk(It);if(ct instanceof Promise)Pt=!0,ct.then(Mt=>{var Dt;let dt=typeof Mt=="string"?Mt:(Dt=Mt==null?void 0:Mt.text)!=null?Dt:null;if(dt!==null&&dt.trim()!==""){let Zt=f;Zt&&Zt.id===Z.id&&(Zt.content=dt,Zt.streaming=!1,F.delete(Zt.id),K.delete(Zt.id),p(Zt))}else{let Zt=Se.getExtractedText(),ln=f;ln&&ln.id===Z.id&&(Zt!==null&&Zt.trim()!==""?ln.content=Zt:K.has(ln.id)||(ln.content=ve(N)),ln.streaming=!1,F.delete(ln.id),K.delete(ln.id),p(ln))}});else{let Mt=typeof ct=="string"?ct:(wn=ct==null?void 0:ct.text)!=null?wn:null;if(Mt!==null&&Mt.trim()!=="")Z.content=Mt,at=!0;else{let dt=Se.getExtractedText();dt!==null&&dt.trim()!==""&&(Z.content=dt,at=!0)}}}}}if(!Pt){if(!Z.rawContent){let At=K.get(Z.id);Z.rawContent=At!=null?At:ve(N)}if(!at&&!K.has(Z.id)&&(Z.content=ve(N)),Se){let At=(H=Se.close)==null?void 0:H.call(Se);At instanceof Promise&&At.catch(()=>{})}F.delete(Z.id),K.delete(Z.id),Z.streaming=!1,p(Z)}}else F.delete(Z.id),K.delete(Z.id),Z.streaming=!1,p(Z)}else if(De==="flow_complete"){let B=(On=v.result)==null?void 0:On.response;if(B!=null){let w=W(),N=K.get(w.id),Z=N!=null?N:ve(B);w.rawContent=Z;let Se=ve(B),at=F.get(w.id);if(at){let Bt=Io(Z);if(Bt!==null)Se=Bt;else{let It=at.processChunk(Z);It instanceof Promise&&It.then(ct=>{var dt;let Mt=typeof ct=="string"?ct:(dt=ct==null?void 0:ct.text)!=null?dt:null;if(Mt!==null){let Dt=f;Dt&&Dt.id===w.id&&(Dt.content=Mt,Dt.streaming=!1,p(Dt))}});let it=at.getExtractedText();it!==null&&(Se=it)}}F.delete(w.id),K.delete(w.id);let Pt=Se!==w.content,At=w.streaming!==!1;Pt&&(w.content=Se),w.streaming=!1,(Pt||At)&&p(w)}else if(f!==null){let w=f;F.delete(w.id),K.delete(w.id),w.streaming!==!1&&(w.streaming=!1,p(w))}t({type:"status",status:"idle"})}else if(De==="agent_start")fe={executionId:v.executionId,agentId:(Fn=v.agentId)!=null?Fn:"virtual",agentName:(Wr=v.agentName)!=null?Wr:"",status:"running",currentIteration:0,maxTurns:(kn=v.maxTurns)!=null?kn:1,startedAt:J(v.startedAt)};else if(De==="agent_iteration_start"){if(fe&&(fe.currentIteration=v.iteration),Ct==="separate"&&v.iteration>1){let B=f;B&&(B.streaming=!1,p(B),pt.set(v.iteration-1,B),f=null)}}else if(De!=="agent_turn_start"){if(De==="agent_turn_delta"){if(v.contentType==="text"){let B=W();B.content+=(Yn=v.delta)!=null?Yn:"",B.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:v.turnId,agentName:fe==null?void 0:fe.agentName},p(B)}else if(v.contentType==="thinking"){let B=(Rr=v.turnId)!=null?Rr:`agent-think-${v.iteration}`,w=q(B);w.reasoning=(Ln=w.reasoning)!=null?Ln:{id:B,status:"streaming",chunks:[]},w.reasoning.chunks.push((Pn=v.delta)!=null?Pn:""),w.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:v.turnId},p(w)}else if(v.contentType==="tool_input"){let B=(cr=v.toolCallId)!=null?cr:x.lastId;if(B){let w=T.get(B);w!=null&&w.toolCall&&(w.toolCall.chunks=(dr=w.toolCall.chunks)!=null?dr:[],w.toolCall.chunks.push((co=v.delta)!=null?co:""),p(w))}}}else if(De==="agent_turn_complete"){let B=v.turnId;if(B){let w=C.get(B);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=J(v.completedAt);let N=(po=w.reasoning.startedAt)!=null?po:Date.now();w.reasoning.durationMs=Math.max(0,((uo=w.reasoning.completedAt)!=null?uo:Date.now())-N),w.streaming=!1,p(w)}}}else if(De==="agent_tool_start"){let B=(Hr=v.toolCallId)!=null?Hr:`agent-tool-${c()}`;me(A(v),B);let w=xe(B),N=(pr=w.toolCall)!=null?pr:{id:B,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};N.name=(Br=(je=v.toolName)!=null?je:v.name)!=null?Br:N.name,N.status="running",v.parameters!==void 0&&(N.args=v.parameters),N.startedAt=J((an=v.startedAt)!=null?an:v.timestamp),w.toolCall=N,w.streaming=!0,w.agentMetadata={executionId:v.executionId,iteration:v.iteration},p(w)}else if(De==="agent_tool_delta"){let B=(Xt=v.toolCallId)!=null?Xt:x.lastId;if(B){let w=(go=T.get(B))!=null?go:xe(B);w.toolCall&&(w.toolCall.chunks=(mo=w.toolCall.chunks)!=null?mo:[],w.toolCall.chunks.push((Dr=v.delta)!=null?Dr:""),w.toolCall.status="running",w.streaming=!0,p(w))}}else if(De==="agent_tool_complete"){let B=(Gn=v.toolCallId)!=null?Gn:x.lastId;if(B){let w=(In=T.get(B))!=null?In:xe(B);if(w.toolCall){w.toolCall.status="complete",v.result!==void 0&&(w.toolCall.result=v.result),typeof v.executionTime=="number"&&(w.toolCall.durationMs=v.executionTime),w.toolCall.completedAt=J((fo=v.completedAt)!=null?fo:v.timestamp),w.streaming=!1,p(w);let N=A(v);N&&x.byCall.delete(N)}}}else if(De!=="agent_iteration_complete"){if(De==="agent_reflection"||De==="agent_reflect"){let B=`agent-reflection-${v.executionId}-${v.iteration}`,w={id:B,role:"assistant",content:(ho=v.reflection)!=null?ho:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:B,status:"complete",chunks:[(yo=v.reflection)!=null?yo:""]},agentMetadata:{executionId:v.executionId,iteration:v.iteration}};p(w)}else if(De==="agent_complete"){fe&&(fe.status=v.success?"complete":"error",fe.completedAt=J(v.completedAt),fe.stopReason=v.stopReason);let B=f;B&&(B.streaming=!1,p(B)),t({type:"status",status:"idle"})}else if(De==="agent_error"){let B=typeof v.error=="string"?v.error:(Xn=(ts=v.error)==null?void 0:ts.message)!=null?Xn:"Agent execution error";v.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",B):t({type:"error",error:new Error(B)})}else if(De!=="agent_ping")if(De==="agent_approval_start"){let B=(Zn=v.approvalId)!=null?Zn:`approval-${c()}`,w={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:"pending",agentId:(ht=fe==null?void 0:fe.agentId)!=null?ht:"virtual",executionId:(gr=(ur=v.executionId)!=null?ur:fe==null?void 0:fe.executionId)!=null?gr:"",toolName:(Nr=v.toolName)!=null?Nr:"",toolType:v.toolType,description:(Fr=v.description)!=null?Fr:`Execute ${(Or=v.toolName)!=null?Or:"tool"}`,parameters:v.parameters}};p(w)}else if(De==="step_await"&&v.awaitReason==="approval_required"){let B=($r=v.approvalId)!=null?$r:`approval-${c()}`,w={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:"pending",agentId:(Kt=fe==null?void 0:fe.agentId)!=null?Kt:"virtual",executionId:(Wn=(rn=v.executionId)!=null?rn:fe==null?void 0:fe.executionId)!=null?Wn:"",toolName:(Be=v.toolName)!=null?Be:"",toolType:v.toolType,description:(Qn=v.description)!=null?Qn:`Execute ${(_r=v.toolName)!=null?_r:"tool"}`,parameters:v.parameters}};p(w)}else if(De==="agent_approval_complete"){let B=v.approvalId;if(B){let N={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:(un=v.decision)!=null?un:"approved",agentId:(bo=fe==null?void 0:fe.agentId)!=null?bo:"virtual",executionId:(fr=(mr=v.executionId)!=null?mr:fe==null?void 0:fe.executionId)!=null?fr:"",toolName:(er=v.toolName)!=null?er:"",description:($n=v.description)!=null?$n:"",resolvedAt:Date.now()}};p(N)}}else if(De==="artifact_start"||De==="artifact_delta"||De==="artifact_update"||De==="artifact_complete"){if(De==="artifact_start"){let B=v.artifactType,w=String(v.id),N=typeof v.title=="string"?v.title:void 0;if(t({type:"artifact_start",id:w,artifactType:B,title:N,component:typeof v.component=="string"?v.component:void 0}),Ee.set(w,{markdown:"",title:N}),!ne.has(w)){ne.add(w);let Z={id:`artifact-ref-${w}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:w,title:N,artifactType:B,status:"streaming"}})};z.set(w,Z),p(Z)}}else if(De==="artifact_delta"){let B=String(v.id),w=typeof v.delta=="string"?v.delta:String((xo=v.delta)!=null?xo:"");t({type:"artifact_delta",id:B,artDelta:w});let N=Ee.get(B);N&&(N.markdown+=w)}else if(De==="artifact_update"){let B=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};t({type:"artifact_update",id:String(v.id),props:B,component:typeof v.component=="string"?v.component:void 0})}else if(De==="artifact_complete"){let B=String(v.id);t({type:"artifact_complete",id:B});let w=z.get(B);if(w){w.streaming=!1;try{let N=JSON.parse((vo=w.rawContent)!=null?vo:"{}");if(N.props){N.props.status="complete";let Z=Ee.get(B);Z!=null&&Z.markdown&&(N.props.markdown=Z.markdown)}w.rawContent=JSON.stringify(N)}catch{}Ee.delete(B),p(w),z.delete(B)}}}else if(De==="transcript_insert"){let B=v.message;if(!B||typeof B!="object")continue;let w=String((gn=B.id)!=null?gn:`msg-${c()}`),N=B.role,Se={id:w,role:N==="user"?"user":N==="system"?"system":"assistant",content:typeof B.content=="string"?B.content:"",rawContent:typeof B.rawContent=="string"?B.rawContent:void 0,createdAt:typeof B.createdAt=="string"?B.createdAt:new Date().toISOString(),streaming:B.streaming===!0,...typeof B.variant=="string"?{variant:B.variant}:{},sequence:c()};if(p(Se),Se.rawContent)try{let at=JSON.parse(Se.rawContent),Pt=(tr=at==null?void 0:at.props)==null?void 0:tr.artifactId;typeof Pt=="string"&&ne.add(Pt)}catch{}f=null,m.current=null,F.delete(w),K.delete(w)}else De==="error"&&v.error&&t({type:"error",error:v.error instanceof Error?v.error:new Error(String(v.error))})}}}}}};function Vc(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function Xr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function br(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var Wo="[Image]";function Jc(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Kc(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function Yc(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Gc(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function ds(e){return{type:"text",text:e}}function Xc(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 Zc(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 Qc(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 ul=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ed=["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"],Rn=[...ul,...ed];function td(e){return ul.includes(e)||e.startsWith("image/")}function Ro(e){return td(e.type)}async function gl(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;Ro(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 ml(e,r=Rn,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 nd(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function fl(e,r){let t=nd(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 Ho=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 d=new Uint8Array(this.remainder.length+r.length);d.set(this.remainder),d.set(r,this.remainder.length),t=d,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 d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,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 Bo=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 u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(n==="silence"?d<s.threshold:d>=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 Zr=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 Bo;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,d=(n=this.config)==null?void 0:n.clientToken;if(!i||!d)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=${d}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let u=`${o}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let C=!1,T=x=>{C||(C=!0,clearTimeout(b),m(new Error(x)))},b=setTimeout(()=>T("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(b),f())},{once:!0}),this.ws.addEventListener("error",()=>{T("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!C){let M=x.code!==1006?` (code ${x.code})`:"";T("WebSocket connection failed"+M+"."+p)}},{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 Ho(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,d=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,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 u=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),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),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await d.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(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({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 xr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Zr(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 ps(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return xr({type:"runtype",runtype:e.runtype});if(or.isSupported())return xr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Do(e){try{return ps(e),!0}catch{return!1}}var Qr=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,d;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"),(d=(i=this.callbacks).onError)==null||d.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 yr(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 Do((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=xr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(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 u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var u,p,f,m,C,T;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=c.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=c.transcript)!=null&&p.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}):(m=c.text)!=null&&m.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let b=(T=this.pendingVoiceAssistantMessageId)!=null?T:(C=[...this.messages].reverse().find(x=>x.role==="assistant"))==null?void 0:C.id;b&&this.ttsSpokenMessageIds.add(b)}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:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var u,p;this.voiceStatus=c,this.voiceActive=c==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,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,d,c,u;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:(d=r.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(u=r.browser)==null?void 0:u.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 yr(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:d,streaming:c=!1,voiceProcessing:u}=r,f={id:a!=null?a:t==="user"?Xr():t==="assistant"?br():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...u!==void 0&&{voiceProcessing:u}};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:d,createdAt:c,sequence:u,streaming:p=!1}=n,m={id:d!=null?d:s==="user"?Xr():s==="assistant"?br():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(m)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(r,t){var c,u,p,f,m;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=Xr(),o=br(),a={id:s,role:"user",content:n||Wo,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(C){let T=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!T){let b={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(b)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,T||(C instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,C):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(C))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=br();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 u={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(u),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(d=(i=this.callbacks).onError)==null||d.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 d,c,u;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 p;if(i?p=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):p=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),p){let f=null;if(p instanceof Response){if(!p.ok){let m=await p.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Approval request failed: ${p.status}`)}f=p.body}else p instanceof ReadableStream&&(f=p);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(p){(u=(c=this.callbacks).onError)==null||u.call(c,p instanceof Error?p:new Error(String(p)))}}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 d,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=(d=t.sequence)!=null?d: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},An=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};import*as rd from"lucide";var ge=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=rd[s];return o?od(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 od(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 d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,u])=>{c!=="stroke"&&d.setAttribute(c,String(u))}),s.appendChild(d)}}}),s}var No={allowedTypes:Rn,maxFileSize:10*1024*1024,maxFiles:4};function sd(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ad(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 vr=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:No.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:No.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:No.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:No.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,d;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 u=ml(c,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(s=u.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,p);continue}try{let p=await gl(c),f=Ro(c)?URL.createObjectURL(c):null,m={id:sd(),file:c,previewUrl:f,contentPart:p};this.attachments.push(m),this.renderPreview(m)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(d=>d.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=Ro(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=ad(r.file.type),d=ge(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=h("span");c.textContent=fl(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=ge("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 hl={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},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"}},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"}},yl={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.gray.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.100",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.500",hover:"palette.colors.primary.600",focus:"palette.colors.primary.700",active:"palette.colors.primary.800",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.primary.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"}},bl={button:{primary:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.text",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:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"semantic.colors.interactive.focus",ring:"semantic.colors.interactive.focus"}},launcher:{size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:"min(400px, calc(100vw - 24px))",maxWidth:"400px",height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"semantic.colors.surface",border:"semantic.colors.border",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"semantic.colors.primary",iconForeground:"semantic.colors.textInverse",titleForeground:"semantic.colors.primary",subtitleForeground:"semantic.colors.textMuted",actionIconForeground:"semantic.colors.textMuted"},message:{user:{background:"semantic.colors.primary",text:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"semantic.colors.container",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},prose:{fontFamily:"inherit"}},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"}},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function eo(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."))?eo(e,n):n}function us(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let d=eo(e,a);d!==void 0&&(r[i]={path:i,value:d,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 xl(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 vl(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]=vl(o,s):t[n]=s}return t}function id(e,r){return r?vl(e,r):e}function to(e,r={}){var s,o,a,i,d,c,u,p,f,m,C,T,b;let t={palette:hl,semantic:yl,components:bl},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,...(d=e==null?void 0:e.palette)==null?void 0:d.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,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(C=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:C.feedback}},spacing:{...t.semantic.spacing,...(T=e==null?void 0:e.semantic)==null?void 0:T.spacing},typography:{...t.semantic.typography,...(b=e==null?void 0:e.semantic)==null?void 0:b.typography}},components:id(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let x=xl(n);if(!x.valid)throw new Error(`Theme validation failed: ${x.errors.map(M=>M.message).join(", ")}`)}if(r.plugins)for(let x of r.plugins)n=x.transform(n);return n}function gs(e){var C,T,b,x,M,O,A,W,_,k,q,me,ce,z,ne,Ee,ie,ye,xe,J,ve,F,K,fe,pt,Ct,ut,xt,Fe,be,ue,V,Q,re,Me,Xe,ee,Y,Ve,Ie,ft,jt,zt,de,le,ot,gt,Je,st,Ht,Lt,qt,S,U,te,$e,se,ze,Ae,He,ke,Ke,et,we,qn,bn,Un,Bn,ir,Dn,Tn,Ze,nn;let r=us(e),t={};for(let[G,Jt]of Object.entries(r)){let Vn=G.replace(/\./g,"-");t[`--persona-${Vn}`]=Jt.value}t["--persona-primary"]=(C=t["--persona-semantic-colors-primary"])!=null?C:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(T=t["--persona-semantic-colors-secondary"])!=null?T:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(b=t["--persona-semantic-colors-accent"])!=null?b:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(x=t["--persona-semantic-colors-surface"])!=null?x:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(M=t["--persona-semantic-colors-background"])!=null?M:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(O=t["--persona-semantic-colors-container"])!=null?O:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(A=t["--persona-semantic-colors-text"])!=null?A:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(W=t["--persona-semantic-colors-text-muted"])!=null?W:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(_=t["--persona-semantic-colors-text-inverse"])!=null?_:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(k=t["--persona-semantic-colors-border"])!=null?k:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(q=t["--persona-semantic-colors-divider"])!=null?q:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(me=t["--persona-components-voice-recording-indicator"])!=null?me:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(ce=t["--persona-components-voice-recording-background"])!=null?ce:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(z=t["--persona-components-voice-processing-icon"])!=null?z:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ne=t["--persona-components-voice-speaking-icon"])!=null?ne:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ee=t["--persona-components-approval-requested-background"])!=null?Ee:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(ie=t["--persona-components-approval-requested-border"])!=null?ie:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(ye=t["--persona-components-approval-requested-text"])!=null?ye:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(xe=t["--persona-components-approval-approve-background"])!=null?xe:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(J=t["--persona-components-approval-deny-background"])!=null?J:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(ve=t["--persona-components-attachment-image-background"])!=null?ve:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(F=t["--persona-components-attachment-image-border"])!=null?F:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(K=t["--persona-semantic-typography-fontFamily"])!=null?K:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(fe=t["--persona-semantic-typography-fontSize"])!=null?fe:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(pt=t["--persona-semantic-typography-fontWeight"])!=null?pt:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(Ct=t["--persona-semantic-typography-lineHeight"])!=null?Ct: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"]=(ut=t["--persona-palette-radius-sm"])!=null?ut:"0.125rem",t["--persona-radius-md"]=(xt=t["--persona-palette-radius-md"])!=null?xt:"0.375rem",t["--persona-radius-lg"]=(Fe=t["--persona-palette-radius-lg"])!=null?Fe:"0.5rem",t["--persona-radius-xl"]=(be=t["--persona-palette-radius-xl"])!=null?be:"0.75rem",t["--persona-launcher-radius"]=(V=(ue=t["--persona-components-launcher-borderRadius"])!=null?ue:t["--persona-palette-radius-full"])!=null?V:"9999px",t["--persona-button-radius"]=(re=(Q=t["--persona-components-button-primary-borderRadius"])!=null?Q:t["--persona-palette-radius-full"])!=null?re:"9999px",t["--persona-panel-radius"]=(Xe=(Me=t["--persona-components-panel-borderRadius"])!=null?Me:t["--persona-radius-xl"])!=null?Xe:"0.75rem",t["--persona-panel-border"]=(ee=t["--persona-components-panel-border"])!=null?ee:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Ve=(Y=t["--persona-components-panel-shadow"])!=null?Y:t["--persona-palette-shadows-xl"])!=null?Ve:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(ft=(Ie=t["--persona-components-input-borderRadius"])!=null?Ie:t["--persona-radius-lg"])!=null?ft:"0.5rem",t["--persona-message-user-radius"]=(zt=(jt=t["--persona-components-message-user-borderRadius"])!=null?jt:t["--persona-radius-lg"])!=null?zt:"0.5rem",t["--persona-message-assistant-radius"]=(le=(de=t["--persona-components-message-assistant-borderRadius"])!=null?de:t["--persona-radius-lg"])!=null?le:"0.5rem",t["--persona-header-bg"]=(ot=t["--persona-components-header-background"])!=null?ot:t["--persona-surface"],t["--persona-header-border"]=(gt=t["--persona-components-header-border"])!=null?gt:t["--persona-divider"],t["--persona-header-icon-bg"]=(Je=t["--persona-components-header-iconBackground"])!=null?Je:t["--persona-primary"],t["--persona-header-icon-fg"]=(st=t["--persona-components-header-iconForeground"])!=null?st:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Ht=t["--persona-components-header-titleForeground"])!=null?Ht:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Lt=t["--persona-components-header-subtitleForeground"])!=null?Lt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(qt=t["--persona-components-header-actionIconForeground"])!=null?qt:t["--persona-muted"];let n=(S=e.components)==null?void 0:S.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-message-user-bg"]=(U=t["--persona-components-message-user-background"])!=null?U:t["--persona-accent"],t["--persona-message-user-text"]=(te=t["--persona-components-message-user-text"])!=null?te:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=($e=t["--persona-components-message-user-shadow"])!=null?$e:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(se=t["--persona-components-message-assistant-background"])!=null?se:t["--persona-surface"],t["--persona-message-assistant-text"]=(ze=t["--persona-components-message-assistant-text"])!=null?ze:t["--persona-text"],t["--persona-message-assistant-border"]=(Ae=t["--persona-components-message-assistant-border"])!=null?Ae:t["--persona-border"],t["--persona-message-assistant-shadow"]=(He=t["--persona-components-message-assistant-shadow"])!=null?He:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-tool-bubble-shadow"]=(ke=t["--persona-components-toolBubble-shadow"])!=null?ke:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Ke=t["--persona-components-reasoningBubble-shadow"])!=null?Ke:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(et=t["--persona-components-composer-shadow"])!=null?et:"none",t["--persona-md-inline-code-bg"]=(we=t["--persona-components-markdown-inlineCode-background"])!=null?we:t["--persona-container"],t["--persona-md-inline-code-color"]=(qn=t["--persona-components-markdown-inlineCode-foreground"])!=null?qn:t["--persona-text"],t["--persona-md-link-color"]=(Un=(bn=t["--persona-components-markdown-link-foreground"])!=null?bn:t["--persona-accent"])!=null?Un:"#3b82f6";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 d=t["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(t["--persona-md-prose-font-family"]=d);let c=e.components,u=c==null?void 0:c.iconButton;u&&(u.background&&(t["--persona-icon-btn-bg"]=u.background),u.border&&(t["--persona-icon-btn-border"]=u.border),u.color&&(t["--persona-icon-btn-color"]=u.color),u.padding&&(t["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(t["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(t["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(t["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(t["--persona-icon-btn-active-border"]=u.activeBorder));let p=c==null?void 0:c.labelButton;p&&(p.background&&(t["--persona-label-btn-bg"]=p.background),p.border&&(t["--persona-label-btn-border"]=p.border),p.color&&(t["--persona-label-btn-color"]=p.color),p.padding&&(t["--persona-label-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-label-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-label-btn-hover-bg"]=p.hoverBackground),p.fontSize&&(t["--persona-label-btn-font-size"]=p.fontSize),p.gap&&(t["--persona-label-btn-gap"]=p.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 m=c==null?void 0:c.artifact;if(m!=null&&m.toolbar){let G=m.toolbar;G.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=G.iconHoverColor),G.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=G.iconHoverBackground),G.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=G.iconPadding),G.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=G.iconBorderRadius),G.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=G.iconBorder),G.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=G.toggleGroupGap),G.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=G.toggleBorderRadius),G.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=G.copyBackground),G.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=G.copyBorder),G.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=G.copyColor),G.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=G.copyBorderRadius),G.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=G.copyPadding),G.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=G.copyMenuBackground,t["--persona-dropdown-bg"]=(Bn=t["--persona-dropdown-bg"])!=null?Bn:G.copyMenuBackground),G.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=G.copyMenuBorder,t["--persona-dropdown-border"]=(ir=t["--persona-dropdown-border"])!=null?ir:G.copyMenuBorder),G.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=G.copyMenuShadow,t["--persona-dropdown-shadow"]=(Dn=t["--persona-dropdown-shadow"])!=null?Dn:G.copyMenuShadow),G.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=G.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Tn=t["--persona-dropdown-radius"])!=null?Tn:G.copyMenuBorderRadius),G.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=G.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Ze=t["--persona-dropdown-item-hover-bg"])!=null?Ze:G.copyMenuItemHoverBackground),G.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=G.iconBackground),G.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=G.toolbarBorder)}if(m!=null&&m.tab){let G=m.tab;G.background&&(t["--persona-artifact-tab-bg"]=G.background),G.activeBackground&&(t["--persona-artifact-tab-active-bg"]=G.activeBackground),G.activeBorder&&(t["--persona-artifact-tab-active-border"]=G.activeBorder),G.borderRadius&&(t["--persona-artifact-tab-radius"]=G.borderRadius),G.textColor&&(t["--persona-artifact-tab-color"]=G.textColor),G.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=G.hoverBackground),G.listBackground&&(t["--persona-artifact-tab-list-bg"]=G.listBackground),G.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=G.listBorderColor),G.listPadding&&(t["--persona-artifact-tab-list-padding"]=G.listPadding)}if(m!=null&&m.pane){let G=m.pane;if(G.toolbarBackground){let Jt=(nn=eo(e,G.toolbarBackground))!=null?nn:G.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Jt}}return t}var ld={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 Cl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function no(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];Cl(o)&&Cl(s)?t[n]=no(o,s):t[n]=s}return t}var cd={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},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"}}},wl=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Oo=()=>{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"},dd=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":Oo()},Sl=e=>dd(e),pd=e=>to(e),ud=e=>{var t;let r=to(void 0,{validate:!1});return to({...e,palette:{...r.palette,colors:{...cd.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Fo=e=>{let r=Sl(e),t=wl(e==null?void 0:e.theme),n=wl(e==null?void 0:e.darkTheme);return r==="dark"?ud(no(t!=null?t:{},n!=null?n:{})):pd(t)},gd=e=>gs(e),sr=(e,r)=>{var o;let t=Fo(r),n=gd(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)},ms=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Oo())});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(Oo());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 md}from"idiomorph";var Al=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;md.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){if(s instanceof HTMLElement&&n&&(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-animation")))return!1}}})};function El(e,r){var t,n,s,o,a,i,d,c,u,p,f,m,C,T,b,x,M,O;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:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(c=e.llmContent)==null?void 0:c.length)!=null?u:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(C=(m=e.toolCall)==null?void 0:m.status)!=null?C:"",(x=(b=(T=e.reasoning)==null?void 0:T.chunks)==null?void 0:b.length)!=null?x:0,(O=(M=e.contentParts)==null?void 0:M.length)!=null?O:0,r].join("\0")}function Tl(){return new Map}function Ml(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function kl(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Ll(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}var Vt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var $o={side:"right",width:"420px",animate:!0,reveal:"resize"},_t=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},fn=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:$o.side,width:(s=r==null?void 0:r.width)!=null?s:$o.width,animate:(o=r==null?void 0:r.animate)!=null?o:$o.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:$o.reveal}};var hn={"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 ro=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
7
+ `),Tt="message",St="";for(let B of _e)B.startsWith("event:")?Tt=B.replace("event:","").trim():B.startsWith("data:")&&(St+=B.replace("data:","").trim());if(!St)continue;let v;try{v=JSON.parse(St)}catch(B){t({type:"error",error:B instanceof Error?B:new Error("Failed to parse chat stream payload")});continue}let De=Tt!=="message"?Tt:(Fe=v.type)!=null?Fe:"message";if((xe=this.onSSEEvent)==null||xe.call(this,De,v),this.parseSSEEvent){m.current=f;let B=await this.handleCustomSSEEvent(v,t,m,p,c);if(m.current&&!f&&(f=m.current),B)continue}if(De==="reason_start"){let B=(ge=k(v,!0))!=null?ge:`reason-${c()}`,w=q(B);w.reasoning=(J=w.reasoning)!=null?J:{id:B,status:"streaming",chunks:[]},w.reasoning.startedAt=(re=w.reasoning.startedAt)!=null?re:K((Q=v.startedAt)!=null?Q:v.timestamp),w.reasoning.completedAt=void 0,w.reasoning.durationMs=void 0,w.streaming=!0,w.reasoning.status="streaming",p(w)}else if(De==="reason_delta"||De==="reason_chunk"){let B=(Xe=(Me=k(v,!1))!=null?Me:k(v,!0))!=null?Xe:`reason-${c()}`,w=q(B);w.reasoning=(ee=w.reasoning)!=null?ee:{id:B,status:"streaming",chunks:[]},w.reasoning.startedAt=(Ve=w.reasoning.startedAt)!=null?Ve:K((Y=v.startedAt)!=null?Y:v.timestamp);let N=(jt=(ft=(Ie=v.reasoningText)!=null?Ie:v.text)!=null?ft:v.delta)!=null?jt:"";if(N&&v.hidden!==!0&&w.reasoning.chunks.push(String(N)),w.reasoning.status=v.done?"complete":"streaming",v.done){w.reasoning.completedAt=K((zt=v.completedAt)!=null?zt:v.timestamp);let Z=(pe=w.reasoning.startedAt)!=null?pe:Date.now();w.reasoning.durationMs=Math.max(0,((ce=w.reasoning.completedAt)!=null?ce:Date.now())-Z)}w.streaming=w.reasoning.status!=="complete",p(w)}else if(De==="reason_complete"){let B=(gt=(ot=k(v,!1))!=null?ot:k(v,!0))!=null?gt:`reason-${c()}`,w=C.get(B);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=K((Je=v.completedAt)!=null?Je:v.timestamp);let Z=(st=w.reasoning.startedAt)!=null?st:Date.now();w.reasoning.durationMs=Math.max(0,((Ht=w.reasoning.completedAt)!=null?Ht:Date.now())-Z),w.streaming=!1,p(w)}let N=O(v);N&&b.byStep.delete(N)}else if(De==="tool_start"){let B=(Lt=Ee(v,!0))!=null?Lt:`tool-${c()}`,w=(qt=v.toolName)!=null?qt:v.name;if(le(w)){de.add(B);continue}let N=ie(B),Z=(S=N.toolCall)!=null?S:{id:B,status:"pending"};Z.name=w!=null?w:Z.name,Z.status="running",v.args!==void 0?Z.args=v.args:v.parameters!==void 0&&(Z.args=v.parameters),Z.startedAt=(te=Z.startedAt)!=null?te:K((V=v.startedAt)!=null?V:v.timestamp),Z.completedAt=void 0,Z.durationMs=void 0,N.toolCall=Z,N.streaming=!0;let we=v.agentContext;(we||v.executionId)&&(N.agentMetadata={executionId:($e=we==null?void 0:we.executionId)!=null?$e:v.executionId,iteration:(se=we==null?void 0:we.iteration)!=null?se:v.iteration}),p(N)}else if(De==="tool_chunk"||De==="tool_delta"){let B=(Se=(ze=Ee(v,!1))!=null?ze:Ee(v,!0))!=null?Se:`tool-${c()}`;if(de.has(B))continue;let w=ie(B),N=(He=w.toolCall)!=null?He:{id:B,status:"running"};N.startedAt=(Ke=N.startedAt)!=null?Ke:K((ke=v.startedAt)!=null?ke:v.timestamp);let Z=(qn=(Ce=(et=v.text)!=null?et:v.delta)!=null?Ce:v.message)!=null?qn:"";Z&&(N.chunks=(bn=N.chunks)!=null?bn:[],N.chunks.push(String(Z))),N.status="running",w.toolCall=N,w.streaming=!0;let we=v.agentContext;(we||v.executionId)&&(w.agentMetadata=(ir=w.agentMetadata)!=null?ir:{executionId:(Un=we==null?void 0:we.executionId)!=null?Un:v.executionId,iteration:(Bn=we==null?void 0:we.iteration)!=null?Bn:v.iteration}),p(w)}else if(De==="tool_complete"){let B=(Tn=(Dn=Ee(v,!1))!=null?Dn:Ee(v,!0))!=null?Tn:`tool-${c()}`;if(de.has(B)){de.delete(B);continue}let w=ie(B),N=(Ze=w.toolCall)!=null?Ze:{id:B,status:"running"};N.status="complete",v.result!==void 0&&(N.result=v.result),typeof v.duration=="number"&&(N.duration=v.duration),N.completedAt=K((nn=v.completedAt)!=null?nn:v.timestamp);let Z=(G=v.duration)!=null?G:v.executionTime;if(typeof Z=="number")N.durationMs=Z;else{let Pt=(Jt=N.startedAt)!=null?Jt:Date.now();N.durationMs=Math.max(0,((Vn=N.completedAt)!=null?Vn:Date.now())-Pt)}w.toolCall=N,w.streaming=!1;let we=v.agentContext;(we||v.executionId)&&(w.agentMetadata=(sn=w.agentMetadata)!=null?sn:{executionId:(xn=we==null?void 0:we.executionId)!=null?xn:v.executionId,iteration:(mt=we==null?void 0:we.iteration)!=null?mt:v.iteration}),p(w);let at=A(v);at&&x.byCall.delete(at)}else if(De==="step_chunk"||De==="step_delta"){let B=v.stepType,w=v.executionType;if(B==="tool"||w==="context")continue;let N=W(),Z=(Pr=(lr=(Lr=(Mn=v.text)!=null?Mn:v.delta)!=null?Lr:v.content)!=null?lr:v.chunk)!=null?Pr:"";if(Z){let at=((Jn=U.get(N.id))!=null?Jn:"")+Z;N.rawContent=at,F.has(N.id)||F.set(N.id,this.createStreamParser());let Pt=F.get(N.id),At=at.trim().startsWith("{")||at.trim().startsWith("[");if(At&&U.set(N.id,at),Pt.__isPlainTextParser===!0){N.content+=Z,U.delete(N.id),F.delete(N.id),N.rawContent=void 0,p(N);continue}let It=Pt.processChunk(at);if(It instanceof Promise)It.then(it=>{var Mt;let ct=typeof it=="string"?it:(Mt=it==null?void 0:it.text)!=null?Mt:null;if(ct!==null&&ct.trim()!==""){let dt=f;dt&&dt.id===N.id&&(dt.content=ct,p(dt))}else if(!At&&!at.trim().startsWith("<")){let dt=f;dt&&dt.id===N.id&&(dt.content+=Z,U.delete(dt.id),F.delete(dt.id),dt.rawContent=void 0,p(dt))}}).catch(()=>{N.content+=Z,U.delete(N.id),F.delete(N.id),N.rawContent=void 0,p(N)});else{let it=typeof It=="string"?It:(vn=It==null?void 0:It.text)!=null?vn:null;it!==null&&it.trim()!==""?(N.content=it,p(N)):!At&&!at.trim().startsWith("<")&&(N.content+=Z,U.delete(N.id),F.delete(N.id),N.rawContent=void 0,p(N))}}if(v.isComplete){let we=(wt=(Kn=v.result)==null?void 0:Kn.response)!=null?wt:N.content;if(we){let at=U.get(N.id),Pt=at!=null?at:be(we);N.rawContent=Pt;let At=F.get(N.id),Bt=null,It=!1;if(At&&(Bt=At.getExtractedText(),Bt===null&&(Bt=Io(Pt)),Bt===null)){let it=At.processChunk(Pt);it instanceof Promise?(It=!0,it.then(ct=>{var dt;let Mt=typeof ct=="string"?ct:(dt=ct==null?void 0:ct.text)!=null?dt:null;if(Mt!==null){let Dt=f;Dt&&Dt.id===N.id&&(Dt.content=Mt,Dt.streaming=!1,F.delete(Dt.id),U.delete(Dt.id),p(Dt))}})):Bt=typeof it=="string"?it:(Cn=it==null?void 0:it.text)!=null?Cn:null}if(!It){Bt!==null&&Bt.trim()!==""?N.content=Bt:U.has(N.id)||(N.content=be(we));let it=F.get(N.id);if(it){let ct=(Ir=it.close)==null?void 0:Ir.call(it);ct instanceof Promise&&ct.catch(()=>{}),F.delete(N.id)}U.delete(N.id),N.streaming=!1,p(N)}}}}else if(De==="step_complete"){let B=v.stepType,w=v.executionType;if(B==="tool"||w==="context")continue;let N=(Nn=v.result)==null?void 0:Nn.response,Z=W();if(N!=null){let we=F.get(Z.id),at=!1,Pt=!1;if(we){let At=we.getExtractedText(),Bt=U.get(Z.id),It=Bt!=null?Bt:be(N);if(Z.rawContent=It,At!==null&&At.trim()!=="")Z.content=At,at=!0;else{let it=Io(It);if(it!==null)Z.content=it,at=!0;else{let ct=we.processChunk(It);if(ct instanceof Promise)Pt=!0,ct.then(Mt=>{var Dt;let dt=typeof Mt=="string"?Mt:(Dt=Mt==null?void 0:Mt.text)!=null?Dt:null;if(dt!==null&&dt.trim()!==""){let Zt=f;Zt&&Zt.id===Z.id&&(Zt.content=dt,Zt.streaming=!1,F.delete(Zt.id),U.delete(Zt.id),p(Zt))}else{let Zt=we.getExtractedText(),ln=f;ln&&ln.id===Z.id&&(Zt!==null&&Zt.trim()!==""?ln.content=Zt:U.has(ln.id)||(ln.content=be(N)),ln.streaming=!1,F.delete(ln.id),U.delete(ln.id),p(ln))}});else{let Mt=typeof ct=="string"?ct:(wn=ct==null?void 0:ct.text)!=null?wn:null;if(Mt!==null&&Mt.trim()!=="")Z.content=Mt,at=!0;else{let dt=we.getExtractedText();dt!==null&&dt.trim()!==""&&(Z.content=dt,at=!0)}}}}}if(!Pt){if(!Z.rawContent){let At=U.get(Z.id);Z.rawContent=At!=null?At:be(N)}if(!at&&!U.has(Z.id)&&(Z.content=be(N)),we){let At=(H=we.close)==null?void 0:H.call(we);At instanceof Promise&&At.catch(()=>{})}F.delete(Z.id),U.delete(Z.id),Z.streaming=!1,p(Z)}}else F.delete(Z.id),U.delete(Z.id),Z.streaming=!1,p(Z)}else if(De==="flow_complete"){let B=(On=v.result)==null?void 0:On.response;if(B!=null){let w=W(),N=U.get(w.id),Z=N!=null?N:be(B);w.rawContent=Z;let we=be(B),at=F.get(w.id);if(at){let Bt=Io(Z);if(Bt!==null)we=Bt;else{let It=at.processChunk(Z);It instanceof Promise&&It.then(ct=>{var dt;let Mt=typeof ct=="string"?ct:(dt=ct==null?void 0:ct.text)!=null?dt:null;if(Mt!==null){let Dt=f;Dt&&Dt.id===w.id&&(Dt.content=Mt,Dt.streaming=!1,p(Dt))}});let it=at.getExtractedText();it!==null&&(we=it)}}F.delete(w.id),U.delete(w.id);let Pt=we!==w.content,At=w.streaming!==!1;Pt&&(w.content=we),w.streaming=!1,(Pt||At)&&p(w)}else if(f!==null){let w=f;F.delete(w.id),U.delete(w.id),w.streaming!==!1&&(w.streaming=!1,p(w))}t({type:"status",status:"idle"})}else if(De==="agent_start")he={executionId:v.executionId,agentId:(Fn=v.agentId)!=null?Fn:"virtual",agentName:(Wr=v.agentName)!=null?Wr:"",status:"running",currentIteration:0,maxTurns:(kn=v.maxTurns)!=null?kn:1,startedAt:K(v.startedAt)};else if(De==="agent_iteration_start"){if(he&&(he.currentIteration=v.iteration),Ct==="separate"&&v.iteration>1){let B=f;B&&(B.streaming=!1,p(B),pt.set(v.iteration-1,B),f=null)}}else if(De!=="agent_turn_start"){if(De==="agent_turn_delta"){if(v.contentType==="text"){let B=W();B.content+=(Yn=v.delta)!=null?Yn:"",B.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:v.turnId,agentName:he==null?void 0:he.agentName},p(B)}else if(v.contentType==="thinking"){let B=(Rr=v.turnId)!=null?Rr:`agent-think-${v.iteration}`,w=q(B);w.reasoning=(Ln=w.reasoning)!=null?Ln:{id:B,status:"streaming",chunks:[]},w.reasoning.chunks.push((Pn=v.delta)!=null?Pn:""),w.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:v.turnId},p(w)}else if(v.contentType==="tool_input"){let B=(cr=v.toolCallId)!=null?cr:x.lastId;if(B){let w=T.get(B);w!=null&&w.toolCall&&(w.toolCall.chunks=(dr=w.toolCall.chunks)!=null?dr:[],w.toolCall.chunks.push((co=v.delta)!=null?co:""),p(w))}}}else if(De==="agent_turn_complete"){let B=v.turnId;if(B){let w=C.get(B);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=K(v.completedAt);let N=(po=w.reasoning.startedAt)!=null?po:Date.now();w.reasoning.durationMs=Math.max(0,((uo=w.reasoning.completedAt)!=null?uo:Date.now())-N),w.streaming=!1,p(w)}}}else if(De==="agent_tool_start"){let B=(Hr=v.toolCallId)!=null?Hr:`agent-tool-${c()}`;fe(A(v),B);let w=ie(B),N=(pr=w.toolCall)!=null?pr:{id:B,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};N.name=(Br=(je=v.toolName)!=null?je:v.name)!=null?Br:N.name,N.status="running",v.parameters!==void 0&&(N.args=v.parameters),N.startedAt=K((an=v.startedAt)!=null?an:v.timestamp),w.toolCall=N,w.streaming=!0,w.agentMetadata={executionId:v.executionId,iteration:v.iteration},p(w)}else if(De==="agent_tool_delta"){let B=(Xt=v.toolCallId)!=null?Xt:x.lastId;if(B){let w=(go=T.get(B))!=null?go:ie(B);w.toolCall&&(w.toolCall.chunks=(mo=w.toolCall.chunks)!=null?mo:[],w.toolCall.chunks.push((Dr=v.delta)!=null?Dr:""),w.toolCall.status="running",w.streaming=!0,p(w))}}else if(De==="agent_tool_complete"){let B=(Gn=v.toolCallId)!=null?Gn:x.lastId;if(B){let w=(In=T.get(B))!=null?In:ie(B);if(w.toolCall){w.toolCall.status="complete",v.result!==void 0&&(w.toolCall.result=v.result),typeof v.executionTime=="number"&&(w.toolCall.durationMs=v.executionTime),w.toolCall.completedAt=K((fo=v.completedAt)!=null?fo:v.timestamp),w.streaming=!1,p(w);let N=A(v);N&&x.byCall.delete(N)}}}else if(De!=="agent_iteration_complete"){if(De==="agent_reflection"||De==="agent_reflect"){let B=`agent-reflection-${v.executionId}-${v.iteration}`,w={id:B,role:"assistant",content:(ho=v.reflection)!=null?ho:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:B,status:"complete",chunks:[(yo=v.reflection)!=null?yo:""]},agentMetadata:{executionId:v.executionId,iteration:v.iteration}};p(w)}else if(De==="agent_complete"){he&&(he.status=v.success?"complete":"error",he.completedAt=K(v.completedAt),he.stopReason=v.stopReason);let B=f;B&&(B.streaming=!1,p(B)),t({type:"status",status:"idle"})}else if(De==="agent_error"){let B=typeof v.error=="string"?v.error:(Xn=(ts=v.error)==null?void 0:ts.message)!=null?Xn:"Agent execution error";v.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",B):t({type:"error",error:new Error(B)})}else if(De!=="agent_ping")if(De==="agent_approval_start"){let B=(Zn=v.approvalId)!=null?Zn:`approval-${c()}`,w={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:"pending",agentId:(ht=he==null?void 0:he.agentId)!=null?ht:"virtual",executionId:(gr=(ur=v.executionId)!=null?ur:he==null?void 0:he.executionId)!=null?gr:"",toolName:(Nr=v.toolName)!=null?Nr:"",toolType:v.toolType,description:(Fr=v.description)!=null?Fr:`Execute ${(Or=v.toolName)!=null?Or:"tool"}`,parameters:v.parameters}};p(w)}else if(De==="step_await"&&v.awaitReason==="approval_required"){let B=($r=v.approvalId)!=null?$r:`approval-${c()}`,w={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:"pending",agentId:(Kt=he==null?void 0:he.agentId)!=null?Kt:"virtual",executionId:(Wn=(rn=v.executionId)!=null?rn:he==null?void 0:he.executionId)!=null?Wn:"",toolName:(Be=v.toolName)!=null?Be:"",toolType:v.toolType,description:(Qn=v.description)!=null?Qn:`Execute ${(_r=v.toolName)!=null?_r:"tool"}`,parameters:v.parameters}};p(w)}else if(De==="agent_approval_complete"){let B=v.approvalId;if(B){let N={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:(un=v.decision)!=null?un:"approved",agentId:(bo=he==null?void 0:he.agentId)!=null?bo:"virtual",executionId:(fr=(mr=v.executionId)!=null?mr:he==null?void 0:he.executionId)!=null?fr:"",toolName:(er=v.toolName)!=null?er:"",description:($n=v.description)!=null?$n:"",resolvedAt:Date.now()}};p(N)}}else if(De==="artifact_start"||De==="artifact_delta"||De==="artifact_update"||De==="artifact_complete"){if(De==="artifact_start"){let B=v.artifactType,w=String(v.id),N=typeof v.title=="string"?v.title:void 0;if(t({type:"artifact_start",id:w,artifactType:B,title:N,component:typeof v.component=="string"?v.component:void 0}),Ae.set(w,{markdown:"",title:N}),!ne.has(w)){ne.add(w);let Z={id:`artifact-ref-${w}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:w,title:N,artifactType:B,status:"streaming"}})};z.set(w,Z),p(Z)}}else if(De==="artifact_delta"){let B=String(v.id),w=typeof v.delta=="string"?v.delta:String((xo=v.delta)!=null?xo:"");t({type:"artifact_delta",id:B,artDelta:w});let N=Ae.get(B);N&&(N.markdown+=w)}else if(De==="artifact_update"){let B=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};t({type:"artifact_update",id:String(v.id),props:B,component:typeof v.component=="string"?v.component:void 0})}else if(De==="artifact_complete"){let B=String(v.id);t({type:"artifact_complete",id:B});let w=z.get(B);if(w){w.streaming=!1;try{let N=JSON.parse((vo=w.rawContent)!=null?vo:"{}");if(N.props){N.props.status="complete";let Z=Ae.get(B);Z!=null&&Z.markdown&&(N.props.markdown=Z.markdown)}w.rawContent=JSON.stringify(N)}catch{}Ae.delete(B),p(w),z.delete(B)}}}else if(De==="transcript_insert"){let B=v.message;if(!B||typeof B!="object")continue;let w=String((gn=B.id)!=null?gn:`msg-${c()}`),N=B.role,we={id:w,role:N==="user"?"user":N==="system"?"system":"assistant",content:typeof B.content=="string"?B.content:"",rawContent:typeof B.rawContent=="string"?B.rawContent:void 0,createdAt:typeof B.createdAt=="string"?B.createdAt:new Date().toISOString(),streaming:B.streaming===!0,...typeof B.variant=="string"?{variant:B.variant}:{},sequence:c()};if(p(we),we.rawContent)try{let at=JSON.parse(we.rawContent),Pt=(tr=at==null?void 0:at.props)==null?void 0:tr.artifactId;typeof Pt=="string"&&ne.add(Pt)}catch{}f=null,m.current=null,F.delete(w),U.delete(w)}else De==="error"&&v.error&&t({type:"error",error:v.error instanceof Error?v.error:new Error(String(v.error))})}}}}}};function Vc(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function Xr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function br(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var Wo="[Image]";function Jc(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Kc(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function Yc(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Gc(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function ds(e){return{type:"text",text:e}}function Xc(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 Zc(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 Qc(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 ul=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ed=["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"],Rn=[...ul,...ed];function td(e){return ul.includes(e)||e.startsWith("image/")}function Ro(e){return td(e.type)}async function gl(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;Ro(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 ml(e,r=Rn,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 nd(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function fl(e,r){let t=nd(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 Ho=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 d=new Uint8Array(this.remainder.length+r.length);d.set(this.remainder),d.set(r,this.remainder.length),t=d,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 d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,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 Bo=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 u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(n==="silence"?d<s.threshold:d>=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 Zr=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 Bo;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,d=(n=this.config)==null?void 0:n.clientToken;if(!i||!d)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=${d}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let u=`${o}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let C=!1,T=x=>{C||(C=!0,clearTimeout(b),m(new Error(x)))},b=setTimeout(()=>T("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(b),f())},{once:!0}),this.ws.addEventListener("error",()=>{T("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!C){let M=x.code!==1006?` (code ${x.code})`:"";T("WebSocket connection failed"+M+"."+p)}},{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 Ho(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,d=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,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 u=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),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),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await d.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(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({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 xr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Zr(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 ps(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return xr({type:"runtype",runtype:e.runtype});if(or.isSupported())return xr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Do(e){try{return ps(e),!0}catch{return!1}}var Qr=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,d;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"),(d=(i=this.callbacks).onError)==null||d.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 yr(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 Do((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=xr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(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 u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var u,p,f,m,C,T;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=c.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=c.transcript)!=null&&p.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}):(m=c.text)!=null&&m.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let b=(T=this.pendingVoiceAssistantMessageId)!=null?T:(C=[...this.messages].reverse().find(x=>x.role==="assistant"))==null?void 0:C.id;b&&this.ttsSpokenMessageIds.add(b)}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:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var u,p;this.voiceStatus=c,this.voiceActive=c==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,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,d,c,u;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:(d=r.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(u=r.browser)==null?void 0:u.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 yr(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:d,streaming:c=!1,voiceProcessing:u}=r,f={id:a!=null?a:t==="user"?Xr():t==="assistant"?br():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...u!==void 0&&{voiceProcessing:u}};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:d,createdAt:c,sequence:u,streaming:p=!1}=n,m={id:d!=null?d:s==="user"?Xr():s==="assistant"?br():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(m)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(r,t){var c,u,p,f,m;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=Xr(),o=br(),a={id:s,role:"user",content:n||Wo,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(C){let T=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!T){let b={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(b)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,T||(C instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,C):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(C))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=br();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 u={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(u),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(d=(i=this.callbacks).onError)==null||d.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 d,c,u;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 p;if(i?p=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):p=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),p){let f=null;if(p instanceof Response){if(!p.ok){let m=await p.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Approval request failed: ${p.status}`)}f=p.body}else p instanceof ReadableStream&&(f=p);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(p){(u=(c=this.callbacks).onError)==null||u.call(c,p instanceof Error?p:new Error(String(p)))}}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 d,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=(d=t.sequence)!=null?d: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},An=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};import*as rd from"lucide";var me=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=rd[s];return o?od(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 od(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 d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,u])=>{c!=="stroke"&&d.setAttribute(c,String(u))}),s.appendChild(d)}}}),s}var No={allowedTypes:Rn,maxFileSize:10*1024*1024,maxFiles:4};function sd(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ad(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 vr=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:No.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:No.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:No.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:No.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,d;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 u=ml(c,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(s=u.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,p);continue}try{let p=await gl(c),f=Ro(c)?URL.createObjectURL(c):null,m={id:sd(),file:c,previewUrl:f,contentPart:p};this.attachments.push(m),this.renderPreview(m)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(d=>d.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=Ro(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=ad(r.file.type),d=me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=h("span");c.textContent=fl(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=me("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 hl={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},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"}},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"}},yl={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.gray.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.100",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.500",hover:"palette.colors.primary.600",focus:"palette.colors.primary.700",active:"palette.colors.primary.800",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.primary.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"}},bl={button:{primary:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.text",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:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"semantic.colors.interactive.focus",ring:"semantic.colors.interactive.focus"}},launcher:{size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:"min(400px, calc(100vw - 24px))",maxWidth:"400px",height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"semantic.colors.surface",border:"semantic.colors.border",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"semantic.colors.primary",iconForeground:"semantic.colors.textInverse",titleForeground:"semantic.colors.primary",subtitleForeground:"semantic.colors.textMuted",actionIconForeground:"semantic.colors.textMuted"},message:{user:{background:"semantic.colors.primary",text:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"semantic.colors.container",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},prose:{fontFamily:"inherit"}},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"}},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function eo(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."))?eo(e,n):n}function us(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let d=eo(e,a);d!==void 0&&(r[i]={path:i,value:d,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 xl(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 vl(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]=vl(o,s):t[n]=s}return t}function id(e,r){return r?vl(e,r):e}function to(e,r={}){var s,o,a,i,d,c,u,p,f,m,C,T,b;let t={palette:hl,semantic:yl,components:bl},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,...(d=e==null?void 0:e.palette)==null?void 0:d.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,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(C=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:C.feedback}},spacing:{...t.semantic.spacing,...(T=e==null?void 0:e.semantic)==null?void 0:T.spacing},typography:{...t.semantic.typography,...(b=e==null?void 0:e.semantic)==null?void 0:b.typography}},components:id(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let x=xl(n);if(!x.valid)throw new Error(`Theme validation failed: ${x.errors.map(M=>M.message).join(", ")}`)}if(r.plugins)for(let x of r.plugins)n=x.transform(n);return n}function gs(e){var C,T,b,x,M,O,A,W,_,k,q,fe,de,z,ne,Ae,le,Ee,ie,K,be,F,U,he,pt,Ct,ut,xt,Fe,xe,ge,J,Q,re,Me,Xe,ee,Y,Ve,Ie,ft,jt,zt,pe,ce,ot,gt,Je,st,Ht,Lt,qt,S,V,te,$e,se,ze,Se,He,ke,Ke,et,Ce,qn,bn,Un,Bn,ir,Dn,Tn,Ze,nn;let r=us(e),t={};for(let[G,Jt]of Object.entries(r)){let Vn=G.replace(/\./g,"-");t[`--persona-${Vn}`]=Jt.value}t["--persona-primary"]=(C=t["--persona-semantic-colors-primary"])!=null?C:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(T=t["--persona-semantic-colors-secondary"])!=null?T:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(b=t["--persona-semantic-colors-accent"])!=null?b:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(x=t["--persona-semantic-colors-surface"])!=null?x:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(M=t["--persona-semantic-colors-background"])!=null?M:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(O=t["--persona-semantic-colors-container"])!=null?O:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(A=t["--persona-semantic-colors-text"])!=null?A:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(W=t["--persona-semantic-colors-text-muted"])!=null?W:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(_=t["--persona-semantic-colors-text-inverse"])!=null?_:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(k=t["--persona-semantic-colors-border"])!=null?k:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(q=t["--persona-semantic-colors-divider"])!=null?q:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(fe=t["--persona-components-voice-recording-indicator"])!=null?fe:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(de=t["--persona-components-voice-recording-background"])!=null?de:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(z=t["--persona-components-voice-processing-icon"])!=null?z:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ne=t["--persona-components-voice-speaking-icon"])!=null?ne:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ae=t["--persona-components-approval-requested-background"])!=null?Ae:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(le=t["--persona-components-approval-requested-border"])!=null?le:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Ee=t["--persona-components-approval-requested-text"])!=null?Ee:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(ie=t["--persona-components-approval-approve-background"])!=null?ie:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(K=t["--persona-components-approval-deny-background"])!=null?K:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(be=t["--persona-components-attachment-image-background"])!=null?be:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(F=t["--persona-components-attachment-image-border"])!=null?F:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(U=t["--persona-semantic-typography-fontFamily"])!=null?U:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(he=t["--persona-semantic-typography-fontSize"])!=null?he:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(pt=t["--persona-semantic-typography-fontWeight"])!=null?pt:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(Ct=t["--persona-semantic-typography-lineHeight"])!=null?Ct: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"]=(ut=t["--persona-palette-radius-sm"])!=null?ut:"0.125rem",t["--persona-radius-md"]=(xt=t["--persona-palette-radius-md"])!=null?xt:"0.375rem",t["--persona-radius-lg"]=(Fe=t["--persona-palette-radius-lg"])!=null?Fe:"0.5rem",t["--persona-radius-xl"]=(xe=t["--persona-palette-radius-xl"])!=null?xe:"0.75rem",t["--persona-launcher-radius"]=(J=(ge=t["--persona-components-launcher-borderRadius"])!=null?ge:t["--persona-palette-radius-full"])!=null?J:"9999px",t["--persona-button-radius"]=(re=(Q=t["--persona-components-button-primary-borderRadius"])!=null?Q:t["--persona-palette-radius-full"])!=null?re:"9999px",t["--persona-panel-radius"]=(Xe=(Me=t["--persona-components-panel-borderRadius"])!=null?Me:t["--persona-radius-xl"])!=null?Xe:"0.75rem",t["--persona-panel-border"]=(ee=t["--persona-components-panel-border"])!=null?ee:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Ve=(Y=t["--persona-components-panel-shadow"])!=null?Y:t["--persona-palette-shadows-xl"])!=null?Ve:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(ft=(Ie=t["--persona-components-input-borderRadius"])!=null?Ie:t["--persona-radius-lg"])!=null?ft:"0.5rem",t["--persona-message-user-radius"]=(zt=(jt=t["--persona-components-message-user-borderRadius"])!=null?jt:t["--persona-radius-lg"])!=null?zt:"0.5rem",t["--persona-message-assistant-radius"]=(ce=(pe=t["--persona-components-message-assistant-borderRadius"])!=null?pe:t["--persona-radius-lg"])!=null?ce:"0.5rem",t["--persona-header-bg"]=(ot=t["--persona-components-header-background"])!=null?ot:t["--persona-surface"],t["--persona-header-border"]=(gt=t["--persona-components-header-border"])!=null?gt:t["--persona-divider"],t["--persona-header-icon-bg"]=(Je=t["--persona-components-header-iconBackground"])!=null?Je:t["--persona-primary"],t["--persona-header-icon-fg"]=(st=t["--persona-components-header-iconForeground"])!=null?st:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Ht=t["--persona-components-header-titleForeground"])!=null?Ht:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Lt=t["--persona-components-header-subtitleForeground"])!=null?Lt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(qt=t["--persona-components-header-actionIconForeground"])!=null?qt:t["--persona-muted"];let n=(S=e.components)==null?void 0:S.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-message-user-bg"]=(V=t["--persona-components-message-user-background"])!=null?V:t["--persona-accent"],t["--persona-message-user-text"]=(te=t["--persona-components-message-user-text"])!=null?te:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=($e=t["--persona-components-message-user-shadow"])!=null?$e:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(se=t["--persona-components-message-assistant-background"])!=null?se:t["--persona-surface"],t["--persona-message-assistant-text"]=(ze=t["--persona-components-message-assistant-text"])!=null?ze:t["--persona-text"],t["--persona-message-assistant-border"]=(Se=t["--persona-components-message-assistant-border"])!=null?Se:t["--persona-border"],t["--persona-message-assistant-shadow"]=(He=t["--persona-components-message-assistant-shadow"])!=null?He:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-tool-bubble-shadow"]=(ke=t["--persona-components-toolBubble-shadow"])!=null?ke:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Ke=t["--persona-components-reasoningBubble-shadow"])!=null?Ke:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(et=t["--persona-components-composer-shadow"])!=null?et:"none",t["--persona-md-inline-code-bg"]=(Ce=t["--persona-components-markdown-inlineCode-background"])!=null?Ce:t["--persona-container"],t["--persona-md-inline-code-color"]=(qn=t["--persona-components-markdown-inlineCode-foreground"])!=null?qn:t["--persona-text"],t["--persona-md-link-color"]=(Un=(bn=t["--persona-components-markdown-link-foreground"])!=null?bn:t["--persona-accent"])!=null?Un:"#3b82f6";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 d=t["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(t["--persona-md-prose-font-family"]=d);let c=e.components,u=c==null?void 0:c.iconButton;u&&(u.background&&(t["--persona-icon-btn-bg"]=u.background),u.border&&(t["--persona-icon-btn-border"]=u.border),u.color&&(t["--persona-icon-btn-color"]=u.color),u.padding&&(t["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(t["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(t["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(t["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(t["--persona-icon-btn-active-border"]=u.activeBorder));let p=c==null?void 0:c.labelButton;p&&(p.background&&(t["--persona-label-btn-bg"]=p.background),p.border&&(t["--persona-label-btn-border"]=p.border),p.color&&(t["--persona-label-btn-color"]=p.color),p.padding&&(t["--persona-label-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-label-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-label-btn-hover-bg"]=p.hoverBackground),p.fontSize&&(t["--persona-label-btn-font-size"]=p.fontSize),p.gap&&(t["--persona-label-btn-gap"]=p.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 m=c==null?void 0:c.artifact;if(m!=null&&m.toolbar){let G=m.toolbar;G.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=G.iconHoverColor),G.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=G.iconHoverBackground),G.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=G.iconPadding),G.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=G.iconBorderRadius),G.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=G.iconBorder),G.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=G.toggleGroupGap),G.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=G.toggleBorderRadius),G.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=G.copyBackground),G.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=G.copyBorder),G.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=G.copyColor),G.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=G.copyBorderRadius),G.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=G.copyPadding),G.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=G.copyMenuBackground,t["--persona-dropdown-bg"]=(Bn=t["--persona-dropdown-bg"])!=null?Bn:G.copyMenuBackground),G.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=G.copyMenuBorder,t["--persona-dropdown-border"]=(ir=t["--persona-dropdown-border"])!=null?ir:G.copyMenuBorder),G.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=G.copyMenuShadow,t["--persona-dropdown-shadow"]=(Dn=t["--persona-dropdown-shadow"])!=null?Dn:G.copyMenuShadow),G.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=G.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Tn=t["--persona-dropdown-radius"])!=null?Tn:G.copyMenuBorderRadius),G.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=G.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Ze=t["--persona-dropdown-item-hover-bg"])!=null?Ze:G.copyMenuItemHoverBackground),G.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=G.iconBackground),G.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=G.toolbarBorder)}if(m!=null&&m.tab){let G=m.tab;G.background&&(t["--persona-artifact-tab-bg"]=G.background),G.activeBackground&&(t["--persona-artifact-tab-active-bg"]=G.activeBackground),G.activeBorder&&(t["--persona-artifact-tab-active-border"]=G.activeBorder),G.borderRadius&&(t["--persona-artifact-tab-radius"]=G.borderRadius),G.textColor&&(t["--persona-artifact-tab-color"]=G.textColor),G.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=G.hoverBackground),G.listBackground&&(t["--persona-artifact-tab-list-bg"]=G.listBackground),G.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=G.listBorderColor),G.listPadding&&(t["--persona-artifact-tab-list-padding"]=G.listPadding)}if(m!=null&&m.pane){let G=m.pane;if(G.toolbarBackground){let Jt=(nn=eo(e,G.toolbarBackground))!=null?nn:G.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Jt}}return t}var ld={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 Cl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function no(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];Cl(o)&&Cl(s)?t[n]=no(o,s):t[n]=s}return t}var cd={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},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"}}},wl=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Oo=()=>{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"},dd=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":Oo()},Sl=e=>dd(e),pd=e=>to(e),ud=e=>{var t;let r=to(void 0,{validate:!1});return to({...e,palette:{...r.palette,colors:{...cd.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Fo=e=>{let r=Sl(e),t=wl(e==null?void 0:e.theme),n=wl(e==null?void 0:e.darkTheme);return r==="dark"?ud(no(t!=null?t:{},n!=null?n:{})):pd(t)},gd=e=>gs(e),sr=(e,r)=>{var o;let t=Fo(r),n=gd(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)},ms=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Oo())});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(Oo());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 md}from"idiomorph";var Al=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;md.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){if(s instanceof HTMLElement&&n&&(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-animation")))return!1}}})};function El(e,r){var t,n,s,o,a,i,d,c,u,p,f,m,C,T,b,x,M,O;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:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(c=e.llmContent)==null?void 0:c.length)!=null?u:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(C=(m=e.toolCall)==null?void 0:m.status)!=null?C:"",(x=(b=(T=e.reasoning)==null?void 0:T.chunks)==null?void 0:b.length)!=null?x:0,(O=(M=e.contentParts)==null?void 0:M.length)!=null?O:0,r].join("\0")}function Tl(){return new Map}function Ml(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function kl(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Ll(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}var Vt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var $o={side:"right",width:"420px",animate:!0,reveal:"resize"},_t=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},fn=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:$o.side,width:(s=r==null?void 0:r.width)!=null?s:$o.width,animate:(o=r==null?void 0:r.animate)!=null?o:$o.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:$o.reveal}};var hn={"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 ro=(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
- <span class="persona-flex persona-flex-col persona-items-start persona-text-left">
11
- <span class="persona-text-sm persona-font-semibold persona-text-persona-primary" data-role="launcher-title"></span>
12
- <span class="persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
10
+ <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
11
+ <span class="persona-block persona-w-full persona-truncate persona-text-sm persona-font-semibold persona-text-persona-primary" data-role="launcher-title"></span>
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 O,A,W,_,k,q,me,ce,z,ne,Ee,ie;let a=(O=o.launcher)!=null?O:{},i=_t(o),d=t.querySelector("[data-role='launcher-title']");d&&(d.textContent=(A=a.title)!=null?A:"Chat Assistant");let c=t.querySelector("[data-role='launcher-subtitle']");c&&(c.textContent=(W=a.subtitle)!=null?W:"Get answers fast");let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let ye=(_=a.agentIconSize)!=null?_:"40px";if(p.style.height=ye,p.style.width=ye,p.innerHTML="",a.agentIconName){let xe=parseFloat(ye)||24,J=ge(a.agentIconName,xe*.6,"var(--persona-text-inverse, #ffffff)",2);J?(p.appendChild(J),p.style.display=""):(p.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(q=a.agentIconText)!=null?q:"\u{1F4AC}",p.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let ye=(me=a.agentIconSize)!=null?me:"40px";f.style.height=ye,f.style.width=ye,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ye=(ce=a.callToActionIconSize)!=null?ce:"32px";m.style.height=ye,m.style.width=ye,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary"));let xe=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,xe=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let J=parseFloat(ye)||24,ve=Math.max(J-xe,8),F=ge(a.callToActionIconName,ve,"currentColor",2);F?m.appendChild(F):m.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}else m.textContent=(ne=a.callToActionIconText)!=null?ne:"\u2197"}let C=a.position&&hn[a.position]?hn[a.position]:hn["bottom-right"],T="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 persona-z-50",b="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?b:`${T} ${C}`;let x="1px solid var(--persona-border, #e5e7eb)",M="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=(Ee=a.border)!=null?Ee:x,t.style.boxShadow=(ie=a.shadow)!=null?ie:M,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="",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 yn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #2563eb))",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))"},_n=e=>{var ce,z,ne,Ee,ie,ye,xe,J,ve,F,K,fe,pt,Ct,ut,xt,Fe,be,ue,V,Q,re,Me,Xe,ee,Y,Ve,Ie,ft,jt,zt,de;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=(ce=r==null?void 0:r.launcher)!=null?ce:{},o=(z=s.headerIconSize)!=null?z:"48px",a=(ne=s.closeButtonSize)!=null?ne:"32px",i=(Ee=s.closeButtonPlacement)!=null?Ee:"inline",d=(ie=s.headerIconHidden)!=null?ie:!1,c=s.headerIconName,u=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(u.style.height=o,u.style.width=o,u.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #2563eb))",u.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!d)if(c){let le=parseFloat(o)||24,ot=ge(c,le*.6,"currentColor",1);ot?u.replaceChildren(ot):u.textContent=(xe=(ye=r==null?void 0:r.launcher)==null?void 0:ye.agentIconText)!=null?xe:"\u{1F4AC}"}else if((J=r==null?void 0:r.launcher)!=null&&J.iconUrl){let le=h("img");le.src=r.launcher.iconUrl,le.alt="",le.className="persona-rounded-xl persona-object-cover",le.style.height=o,le.style.width=o,u.replaceChildren(le)}else u.textContent=(F=(ve=r==null?void 0:r.launcher)==null?void 0:ve.agentIconText)!=null?F:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col"),f=h("span","persona-text-base persona-font-semibold");f.style.color=yn.titleColor,f.textContent=(fe=(K=r==null?void 0:r.launcher)==null?void 0:K.title)!=null?fe:"Chat Assistant";let m=h("span","persona-text-xs");m.style.color=yn.subtitleColor,m.textContent=(Ct=(pt=r==null?void 0:r.launcher)==null?void 0:pt.subtitle)!=null?Ct:"Here to help you get answers fast",p.append(f,m),d?n.append(p):n.append(u,p);let C=(ut=s.clearChat)!=null?ut:{},T=(xt=C.enabled)!=null?xt:!0,b=(Fe=C.placement)!=null?Fe:"inline",x=null,M=null;if(T){let le=(be=C.size)!=null?be:"32px",ot=(ue=C.iconName)!=null?ue:"refresh-cw",gt=(V=C.iconColor)!=null?V:"",Je=(Q=C.backgroundColor)!=null?Q:"",st=(re=C.borderWidth)!=null?re:"",Ht=(Me=C.borderColor)!=null?Me:"",Lt=(Xe=C.borderRadius)!=null?Xe:"",qt=(ee=C.paddingX)!=null?ee:"",S=(Y=C.paddingY)!=null?Y:"",U=(Ve=C.tooltipText)!=null?Ve:"Clear chat",te=(Ie=C.showTooltip)!=null?Ie:!0;M=h("div",b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),b==="top-right"&&(M.style.right="48px"),x=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"),x.style.height=le,x.style.width=le,x.type="button",x.setAttribute("aria-label",U),x.style.color=gt||yn.actionIconColor;let $e=ge(ot,"20px","currentColor",1);if($e&&x.appendChild($e),Je&&(x.style.backgroundColor=Je,x.classList.remove("hover:persona-bg-gray-100")),st||Ht){let se=st||"0px",ze=Ht||"transparent";x.style.border=`${se} solid ${ze}`,x.classList.remove("persona-border-none")}if(Lt&&(x.style.borderRadius=Lt,x.classList.remove("persona-rounded-full")),qt?(x.style.paddingLeft=qt,x.style.paddingRight=qt):(x.style.paddingLeft="",x.style.paddingRight=""),S?(x.style.paddingTop=S,x.style.paddingBottom=S):(x.style.paddingTop="",x.style.paddingBottom=""),M.appendChild(x),te&&U&&x&&M){let se=null,ze=()=>{if(se||!x)return;let He=x.ownerDocument,ke=He.body;if(!ke)return;se=An(He,"div","persona-clear-chat-tooltip"),se.textContent=U;let Ke=An(He,"div");Ke.className="persona-clear-chat-tooltip-arrow",se.appendChild(Ke);let et=x.getBoundingClientRect();se.style.position="fixed",se.style.left=`${et.left+et.width/2}px`,se.style.top=`${et.top-8}px`,se.style.transform="translate(-50%, -100%)",ke.appendChild(se)},Ae=()=>{se&&se.parentNode&&(se.parentNode.removeChild(se),se=null)};M.addEventListener("mouseenter",ze),M.addEventListener("mouseleave",Ae),x.addEventListener("focus",ze),x.addEventListener("blur",Ae),M._cleanupTooltip=()=>{Ae(),M&&(M.removeEventListener("mouseenter",ze),M.removeEventListener("mouseleave",Ae)),x&&(x.removeEventListener("focus",ze),x.removeEventListener("blur",Ae))}}b==="inline"&&n.appendChild(M)}let O=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":T&&b==="inline"?"":"persona-ml-auto"),A=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");A.style.height=a,A.style.width=a,A.type="button";let W=(ft=s.closeButtonTooltipText)!=null?ft:"Close chat",_=(jt=s.closeButtonShowTooltip)!=null?jt:!0;A.setAttribute("aria-label",W),A.style.display=t?"":"none";let k=(zt=s.closeButtonIconName)!=null?zt:"x",q=(de=s.closeButtonIconText)!=null?de:"\xD7";A.style.color=s.closeButtonColor||yn.actionIconColor;let me=ge(k,"20px","currentColor",1);if(me?A.appendChild(me):A.textContent=q,s.closeButtonBackgroundColor?(A.style.backgroundColor=s.closeButtonBackgroundColor,A.classList.remove("hover:persona-bg-gray-100")):(A.style.backgroundColor="",A.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let le=s.closeButtonBorderWidth||"0px",ot=s.closeButtonBorderColor||"transparent";A.style.border=`${le} solid ${ot}`,A.classList.remove("persona-border-none")}else A.style.border="",A.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(A.style.borderRadius=s.closeButtonBorderRadius,A.classList.remove("persona-rounded-full")):(A.style.borderRadius="",A.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(A.style.paddingLeft=s.closeButtonPaddingX,A.style.paddingRight=s.closeButtonPaddingX):(A.style.paddingLeft="",A.style.paddingRight=""),s.closeButtonPaddingY?(A.style.paddingTop=s.closeButtonPaddingY,A.style.paddingBottom=s.closeButtonPaddingY):(A.style.paddingTop="",A.style.paddingBottom=""),O.appendChild(A),_&&W){let le=null,ot=()=>{if(le)return;let Je=A.ownerDocument,st=Je.body;if(!st)return;le=An(Je,"div","persona-clear-chat-tooltip"),le.textContent=W;let Ht=An(Je,"div");Ht.className="persona-clear-chat-tooltip-arrow",le.appendChild(Ht);let Lt=A.getBoundingClientRect();le.style.position="fixed",le.style.left=`${Lt.left+Lt.width/2}px`,le.style.top=`${Lt.top-8}px`,le.style.transform="translate(-50%, -100%)",st.appendChild(le)},gt=()=>{le&&le.parentNode&&(le.parentNode.removeChild(le),le=null)};O.addEventListener("mouseenter",ot),O.addEventListener("mouseleave",gt),A.addEventListener("focus",ot),A.addEventListener("blur",gt),O._cleanupTooltip=()=>{gt(),O.removeEventListener("mouseenter",ot),O.removeEventListener("mouseleave",gt),A.removeEventListener("focus",ot),A.removeEventListener("blur",gt)}}return i!=="top-right"&&n.appendChild(O),{header:n,iconHolder:u,headerTitle:f,headerSubtitle:m,closeButton:A,closeButtonWrapper:O,clearChatButton:x,clearChatButtonWrapper:M}},Cr=(e,r,t)=>{var a,i,d,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(d=n.clearChat)==null?void 0:d.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 ar(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="10000"):(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 m of r){if(m.dividerBefore){let b=document.createElement("hr");a.appendChild(b)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",m.id),m.destructive&&C.setAttribute("data-destructive",""),m.icon){let b=ge(m.icon,16,"currentColor",1.5);b&&C.appendChild(b)}let T=document.createElement("span");T.textContent=m.label,C.appendChild(T),C.addEventListener("click",b=>{b.stopPropagation(),u(),t(m.id)}),a.appendChild(C)}let i=null;function d(){if(!o)return;let m=n.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=C=>{!a.contains(C.target)&&!n.contains(C.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?c():u()}function f(){u(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:u,toggle:p,destroy:f}}function Ft(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=ge(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function _o(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,c="persona-label-btn";n!=="default"&&(c+=" persona-label-btn--"+n),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let u=h("button",c);if(u.type="button",u.setAttribute("aria-label",t),r){let f=ge(r,o!=null?o:14,"currentColor",2);f&&u.appendChild(f)}let p=h("span");if(p.textContent=t,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))u.setAttribute(f,m);return u}function fd(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 d(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of r){let p;u.icon?p=Ft({icon:u.icon,label:u.label,onClick:()=>{a=u.id,d(),n(u.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{a=u.id,d(),n(u.id)})),p.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:p}),o.appendChild(p)}function c(u){a=u,d()}return{element:o,setSelected:c}}function fs(e){var m,C;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=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 u=h("span","persona-combo-btn-label");u.textContent=r,c.appendChild(u);let p=ge(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",c.appendChild(p)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",c.style.padding=(C=d.padding)!=null?C:"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 T,b;c.style.backgroundColor=(T=d.background)!=null?T:"",c.style.borderColor=(b=d.border)!=null?b:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=ar({items:n,onSelect:T=>{c.setAttribute("aria-expanded","false"),s(T)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",T=>{T.stopPropagation();let b=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",b?"false":"true"),f.toggle()}),c.addEventListener("keydown",T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),c.click())}),{element:c,setLabel:T=>{u.textContent=T,c.setAttribute("aria-label",T)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let T=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",T?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Pl=e=>{var n;let r=_n({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 hd(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 d=ge(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let c=ar({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",u=>{u.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Il=e=>{var M,O,A,W,_,k,q,me,ce;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(M=r==null?void 0:r.launcher)!=null?M:{},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 d=s==null?void 0:s.titleMenu,c,u;if(d)c=fs({label:(O=a.title)!=null?O:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=yn.titleColor,u=(A=c.querySelector(".persona-combo-btn-label"))!=null?A:c;else{if(c=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=h("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=yn.titleColor,u.textContent=(W=a.title)!=null?W:"Chat Assistant",c.appendChild(u),hd(c,s==null?void 0:s.trailingActions,(_=s==null?void 0:s.onAction)!=null?_:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let ne=s.onTitleClick;c.addEventListener("click",Ee=>{Ee.target.closest("button")||ne()}),c.addEventListener("keydown",Ee=>{(Ee.key==="Enter"||Ee.key===" ")&&(Ee.preventDefault(),ne())})}let z=s==null?void 0:s.titleRowHover;z&&(c.style.borderRadius=(k=z.borderRadius)!=null?k:"10px",c.style.padding=(q=z.padding)!=null?q:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var ne,Ee;c.style.backgroundColor=(ne=z.background)!=null?ne:"",c.style.borderColor=(Ee=z.border)!=null?Ee:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let p=(me=a.closeButtonSize)!=null?me:"32px",f=h("div",""),m=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");m.style.height=p,m.style.width=p,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||yn.actionIconColor;let C=(ce=a.closeButtonIconName)!=null?ce:"x",T=ge(C,"20px","currentColor",2);T?m.appendChild(T):m.textContent="\xD7",n&&m.addEventListener("click",n),f.appendChild(m),i.appendChild(f);let b=h("div");b.style.display="none";let x=h("span");return x.style.display="none",{header:i,iconHolder:b,headerTitle:u,headerSubtitle:x,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},hs={default:Pl,minimal:Il},Wl=e=>{var r;return(r=hs[e])!=null?r:hs.default},oo=(e,r,t)=>{var a,i,d;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}),u=h("div");u.style.display="none";let p=h("span"),f=h("span"),m=h("button");m.style.display="none";let C=h("div");return C.style.display="none",{header:c,iconHolder:u,headerTitle:p,headerSubtitle:f,closeButton:m,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=Wl(n)({config:e,showClose:(d=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig: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 so=e=>{var ut,xt,Fe,be,ue,V,Q,re,Me,Xe,ee,Y,Ve,Ie,ft,jt,zt,de,le,ot,gt,Je,st,Ht,Lt,qt,S;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=(xt=(ut=r==null?void 0:r.copy)==null?void 0:ut.inputPlaceholder)!=null?xt:"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 d=3*20;o.style.maxHeight=`${d}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let U=Math.min(o.scrollHeight,d);o.style.height=`${U}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 u=(Fe=r==null?void 0:r.sendButton)!=null?Fe:{},p=(be=u.useIcon)!=null?be:!1,f=(ue=u.iconText)!=null?ue:"\u2191",m=u.iconName,C=(V=u.tooltipText)!=null?V:"Send message",T=(Q=u.showTooltip)!=null?Q:!1,b=(re=u.size)!=null?re:"40px",x=u.backgroundColor,M=u.textColor,O=h("div","persona-send-button-wrapper"),A=h("button",p?"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(A.type="submit",A.setAttribute("data-persona-composer-submit",""),p){if(A.style.width=b,A.style.height=b,A.style.minWidth=b,A.style.minHeight=b,A.style.fontSize="18px",A.style.lineHeight="1",A.innerHTML="",m){let U=parseFloat(b)||24,te=M&&typeof M=="string"&&M.trim()?M.trim():"currentColor",$e=ge(m,U,te,2);$e?(A.appendChild($e),A.style.color=te):(A.textContent=f,M?A.style.color=M:A.classList.add("persona-text-white"))}else A.textContent=f,M?A.style.color=M:A.classList.add("persona-text-white");x?A.style.backgroundColor=x:A.classList.add("persona-bg-persona-primary")}else A.textContent=(Xe=(Me=r==null?void 0:r.copy)==null?void 0:Me.sendButtonLabel)!=null?Xe:"Send",M?A.style.color=M:A.classList.add("persona-text-white");if(u.borderWidth&&(A.style.borderWidth=u.borderWidth,A.style.borderStyle="solid"),u.borderColor&&(A.style.borderColor=u.borderColor),u.paddingX?(A.style.paddingLeft=u.paddingX,A.style.paddingRight=u.paddingX):(A.style.paddingLeft="",A.style.paddingRight=""),u.paddingY?(A.style.paddingTop=u.paddingY,A.style.paddingBottom=u.paddingY):(A.style.paddingTop="",A.style.paddingBottom=""),T&&C){let U=h("div","persona-send-button-tooltip");U.textContent=C,O.appendChild(U)}O.appendChild(A);let W=(ee=r==null?void 0:r.voiceRecognition)!=null?ee:{},_=W.enabled===!0,k=null,q=null,me=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ce=((Y=W.provider)==null?void 0:Y.type)==="runtype";if(_&&(me||ce)){q=h("div","persona-send-button-wrapper"),k=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),k.type="button",k.setAttribute("data-persona-composer-mic",""),k.setAttribute("aria-label","Start voice recognition");let U=(Ve=W.iconName)!=null?Ve:"mic",te=(Ie=W.iconSize)!=null?Ie:b,$e=parseFloat(te)||24,se=(ft=W.backgroundColor)!=null?ft:x,ze=(jt=W.iconColor)!=null?jt:M;k.style.width=te,k.style.height=te,k.style.minWidth=te,k.style.minHeight=te,k.style.fontSize="18px",k.style.lineHeight="1";let Ae=ze||"currentColor",He=ge(U,$e,Ae,1.5);He?(k.appendChild(He),k.style.color=Ae):(k.textContent="\u{1F3A4}",k.style.color=Ae),se?k.style.backgroundColor=se:k.classList.add("persona-bg-persona-primary"),ze?k.style.color=ze:!ze&&!M&&k.classList.add("persona-text-white"),W.borderWidth&&(k.style.borderWidth=W.borderWidth,k.style.borderStyle="solid"),W.borderColor&&(k.style.borderColor=W.borderColor),W.paddingX&&(k.style.paddingLeft=W.paddingX,k.style.paddingRight=W.paddingX),W.paddingY&&(k.style.paddingTop=W.paddingY,k.style.paddingBottom=W.paddingY),q.appendChild(k);let ke=(zt=W.tooltipText)!=null?zt:"Start voice recognition";if(((de=W.showTooltip)!=null?de:!1)&&ke){let et=h("div","persona-send-button-tooltip");et.textContent=ke,q.appendChild(et)}}let ne=(le=r==null?void 0:r.attachments)!=null?le:{},Ee=ne.enabled===!0,ie=null,ye=null,xe=null,J=null;if(Ee){J=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),J.style.display="none",xe=h("input"),xe.type="file",xe.accept=((ot=ne.allowedTypes)!=null?ot:Rn).join(","),xe.multiple=((gt=ne.maxFiles)!=null?gt:4)>1,xe.style.display="none",xe.setAttribute("aria-label","Attach files"),ye=h("div","persona-send-button-wrapper"),ie=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ie.type="button",ie.setAttribute("aria-label",(Je=ne.buttonTooltipText)!=null?Je:"Attach file");let U=(st=ne.buttonIconName)!=null?st:"paperclip",te=b,$e=parseFloat(te)||40,se=Math.round($e*.6);ie.style.width=te,ie.style.height=te,ie.style.minWidth=te,ie.style.minHeight=te,ie.style.fontSize="18px",ie.style.lineHeight="1",ie.style.backgroundColor="transparent",ie.style.color="var(--persona-primary, #111827)",ie.style.border="none",ie.style.borderRadius="6px",ie.style.transition="background-color 0.15s ease",ie.addEventListener("mouseenter",()=>{ie.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ie.addEventListener("mouseleave",()=>{ie.style.backgroundColor="transparent"});let ze=ge(U,se,"currentColor",1.5);ze?ie.appendChild(ze):ie.textContent="\u{1F4CE}",ie.addEventListener("click",ke=>{ke.preventDefault(),xe==null||xe.click()}),ye.appendChild(ie);let Ae=(Ht=ne.buttonTooltipText)!=null?Ht:"Attach file",He=h("div","persona-send-button-tooltip");He.textContent=Ae,ye.appendChild(He)}s.addEventListener("click",U=>{U.target!==A&&U.target!==O&&U.target!==k&&U.target!==q&&U.target!==ie&&U.target!==ye&&o.focus()}),J&&(J.style.gap="8px",s.append(J)),xe&&s.append(xe),s.append(o);let ve=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),F=h("div","persona-flex persona-items-center persona-gap-2");ye&&F.append(ye);let K=h("div","persona-flex persona-items-center persona-gap-1");q&&K.append(q),K.append(O),ve.append(F,K),s.append(ve);let fe=h("div","persona-mt-2 persona-text-right persona-text-xs persona-text-persona-muted");fe.setAttribute("data-persona-composer-status","");let pt=(Lt=r==null?void 0:r.statusIndicator)!=null?Lt:{},Ct=(qt=pt.visible)!=null?qt:!0;return fe.style.display=Ct?"":"none",fe.textContent=(S=pt.idleText)!=null?S:"Online",t.append(n,s,fe),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:A,sendButtonWrapper:O,micButton:k,micButtonWrapper:q,statusText:fe,attachmentButton:ie,attachmentButtonWrapper:ye,attachmentInput:xe,attachmentPreviewsContainer:J,actionsRow:ve,leftActions:F,rightActions:K}};var Rl=e=>{var c,u,p,f,m,C,T;let r=(u=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?u:!0;if(_t(e)){let b=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),x=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return b.appendChild(x),{wrapper:b,panel:x}}if(!r){let b=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),x=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),M=(f=(p=e==null?void 0:e.launcher)==null?void 0:p.width)!=null?f:"100%";return b.style.width=M,x.style.width="100%",b.appendChild(x),{wrapper:b,panel:x}}let n=(m=e==null?void 0:e.launcher)!=null?m:{},s=n.position&&hn[n.position]?hn[n.position]:hn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-z-50 persona-transition`),a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(T=(C=e==null?void 0:e.launcher)==null?void 0:C.width)!=null?T:e==null?void 0:e.launcherWidth,d=i!=null?i:"min(400px, calc(100vw - 24px))";return a.style.width=d,a.style.maxWidth=d,o.appendChild(a),{wrapper:o,panel:a}},Hl=(e,r=!0)=>{var b,x,M,O,A,W,_,k,q;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=(b=e==null?void 0:e.layout)==null?void 0:b.header,s=((x=e==null?void 0:e.layout)==null?void 0:x.showHeader)!==!1,o=n?oo(e,n,{showClose:r}):_n({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=_t(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",d=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(O=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?O:"Hello \u{1F44B}";let u=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");u.textContent=(W=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",d.append(c,u);let p=h("div","persona-flex persona-flex-col persona-gap-3"),f=(_=e==null?void 0:e.layout)==null?void 0:_.contentMaxWidth;f&&(p.style.maxWidth=f,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((k=e==null?void 0:e.copy)==null?void 0:k.showWelcomeCard)!==!1?a.append(d,p):(a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3"),a.append(p));let C=so({config:e}),T=((q=e==null?void 0:e.layout)==null?void 0:q.showFooter)!==!1;return s?Cr(t,o,e):(o.header.style.display="none",Cr(t,o,e)),t.append(a),T||(C.footer.style.display="none"),t.append(C.footer),{container:t,body:a,messagesWrapper:p,suggestions:C.suggestions,textarea:C.textarea,sendButton:C.sendButton,sendButtonWrapper:C.sendButtonWrapper,micButton:C.micButton,micButtonWrapper:C.micButtonWrapper,composerForm:C.composerForm,statusText:C.statusText,introTitle:c,introSubtitle:u,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:C.footer,attachmentButton:C.attachmentButton,attachmentButtonWrapper:C.attachmentButtonWrapper,attachmentInput:C.attachmentInput,attachmentPreviewsContainer:C.attachmentPreviewsContainer,actionsRow:C.actionsRow,leftActions:C.leftActions,rightActions:C.rightActions}};var yd=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},bd=320,xd=320,vd=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Cd=(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,d)=>{var p;let c=h("img");c.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${bd}px`,c.style.maxHeight=`${xd}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;s+=1,c.addEventListener("error",()=>{u||(u=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{u=!0}),yd(i.image)?(c.src=i.image,n.appendChild(c)):(u=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},wr=()=>{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-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",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},Dl=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:wr};if(r){let s=r(n);if(s!==null)return s}return wr()},wd=(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},Bl=(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},Sd=(e,r="bubble")=>{let t=["vanilla-message-bubble","persona-max-w-[85%]"];switch(r){case"flat":e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("vanilla-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("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("vanilla-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("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("vanilla-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},Nl=(e,r,t)=>{var m,C,T,b,x,M;let n=(m=r.showCopy)!=null?m:!0,s=(C=r.showUpvote)!=null?C:!0,o=(T=r.showDownvote)!=null?T:!0;if(!n&&!s&&!o){let O=h("div");return O.style.display="none",O.id=`actions-${e.id}`,O.setAttribute("data-actions-for",e.id),O}let a=(b=r.visibility)!=null?b:"hover",i=(x=r.align)!=null?x:"right",d=(M=r.layout)!=null?M:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(O,A,W)=>{let _=Ft({icon:O,label:A,size:14,className:"persona-message-action-btn"});return _.setAttribute("data-action",W),_};return n&&p.appendChild(f("copy","Copy message","copy")),s&&p.appendChild(f("thumbs-up","Upvote","upvote")),o&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},ao=(e,r,t,n,s,o)=>{var ce,z,ne,Ee,ie,ye,xe;let a=t!=null?t:{},i=(ce=a.layout)!=null?ce:"bubble",d=a.avatar,c=a.timestamp,u=(z=d==null?void 0:d.show)!=null?z:!1,p=(ne=c==null?void 0:c.show)!=null?ne:!1,f=(Ee=d==null?void 0:d.position)!=null?Ee:"left",m=(ie=c==null?void 0:c.position)!=null?ie:"below",C=Sd(e.role,i),T=h("div",C.join(" "));T.id=`bubble-${e.id}`,T.setAttribute("data-message-id",e.id),T.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(T.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",T.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(T.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",T.style.color="var(--persona-message-assistant-text, var(--persona-text))");let b=vd(e),x=(xe=(ye=e.content)==null?void 0:ye.trim())!=null?xe:"",O=b.length>0&&x===Wo,A=document.createElement("div");A.classList.add("persona-message-content");let W=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),_=null;if(O?(_=document.createElement("div"),_.innerHTML=W,_.style.display="none",A.appendChild(_)):A.innerHTML=W,p&&m==="inline"&&e.createdAt){let J=Bl(e,c);J.classList.add("persona-ml-2","persona-inline"),A.appendChild(J)}if(b.length>0){let J=Cd(b,!O&&!!x,()=>{O&&_&&(_.style.display="")});J?T.appendChild(J):O&&_&&(_.style.display="")}if(T.appendChild(A),p&&m==="below"&&e.createdAt){let J=Bl(e,c);J.classList.add("persona-mt-1"),T.appendChild(J)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let J=Dl("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);J&&T.appendChild(J)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let J=Nl(e,n,s);T.appendChild(J)}if(!u||e.role==="system")return T;let q=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),me=wd(d,e.role);return f==="right"||f==="left"&&e.role==="user"?q.append(T,me):q.append(me,T),T.classList.remove("persona-max-w-[85%]"),T.classList.add("persona-max-w-[calc(85%-2.5rem)]"),q},Ad=(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}):ao(e,r,t,n,s,o)};var Sr=new Set,Ol=(e,r)=>{let t=Sr.has(e),n=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t");if(!n||!s)return;n.setAttribute("aria-expanded",t?"true":"false");let o=n.querySelector(".persona-ml-auto"),a=o==null?void 0:o.querySelector(":scope > .persona-flex.persona-items-center");if(a){a.innerHTML="";let d=ge(t?"chevron-up":"chevron-down",16,"currentColor",2);d?a.appendChild(d):a.textContent=t?"Hide":"Show"}s.style.display=t?"":"none"},ys=e=>{let r=e.reasoning,t=h("div",["vanilla-message-bubble","vanilla-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(t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),!r)return t;let n=Sr.has(e.id),s=h("button","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");s.type="button",s.setAttribute("aria-expanded",n?"true":"false"),s.setAttribute("data-expand-header","true"),s.setAttribute("data-bubble-type","reasoning");let o=h("div","persona-flex persona-flex-col persona-text-left"),a=h("span","persona-text-xs persona-text-persona-primary");a.textContent="Thinking...",o.appendChild(a);let i=h("span","persona-text-xs persona-text-persona-primary");i.textContent=dl(r),o.appendChild(i),r.status==="complete"?a.style.display="none":a.style.display="";let d=h("div","persona-flex persona-items-center"),u=ge(n?"chevron-up":"chevron-down",16,"currentColor",2);u?d.appendChild(u):d.textContent=n?"Hide":"Show";let p=h("div","persona-flex persona-items-center persona-ml-auto");p.append(d),s.append(o,p);let f=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");f.style.display=n?"":"none";let m=r.chunks.join(""),C=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return C.textContent=m||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(C),(()=>{s.setAttribute("aria-expanded",n?"true":"false"),d.innerHTML="";let x=ge(n?"chevron-up":"chevron-down",16,"currentColor",2);x?d.appendChild(x):d.textContent=n?"Hide":"Show",f.style.display=n?"":"none"})(),t.append(s,f),t};var Ar=new Set,Fl=(e,r,t)=>{var c;let n=Ar.has(e),s=(c=t==null?void 0:t.toolCall)!=null?c:{},o=r.querySelector('button[data-expand-header="true"]'),a=r.querySelector(".persona-border-t");if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto"),d=i==null?void 0:i.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let u=s.toggleTextColor||s.headerTextColor||"currentColor",p=ge(n?"chevron-up":"chevron-down",16,u,2);p?d.appendChild(p):d.textContent=n?"Hide":"Show"}a.style.display=n?"":"none"},bs=(e,r)=>{var T;let t=e.toolCall,n=(T=r==null?void 0:r.toolCall)!=null?T:{},s=h("div",["vanilla-message-bubble","vanilla-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=Ar.has(e.id),a=h("button","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");a.type="button",a.setAttribute("aria-expanded",o?"true":"false"),a.setAttribute("data-expand-header","true"),a.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(a.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(a.style.paddingLeft=n.headerPaddingX,a.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(a.style.paddingTop=n.headerPaddingY,a.style.paddingBottom=n.headerPaddingY);let i=h("div","persona-flex persona-flex-col persona-text-left"),d=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(d.style.color=n.headerTextColor),d.textContent=pl(t),i.appendChild(d);let c=h("div","persona-flex persona-items-center"),u=n.toggleTextColor||n.headerTextColor||"currentColor",p=ge(o?"chevron-up":"chevron-down",16,u,2);p?c.appendChild(p):c.textContent=o?"Hide":"Show";let f=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");f.append(c),a.append(i,f);let m=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(m.style.display=o?"":"none",n.contentBackgroundColor&&(m.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(m.style.color=n.contentTextColor),n.contentPaddingX&&(m.style.paddingLeft=n.contentPaddingX,m.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(m.style.paddingTop=n.contentPaddingY,m.style.paddingBottom=n.contentPaddingY),t.name){let b=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?b.style.color=n.contentTextColor:n.headerTextColor&&(b.style.color=n.headerTextColor),b.textContent=t.name,m.appendChild(b)}if(t.args!==void 0){let b=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Arguments";let M=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");M.style.fontSize="0.75rem",M.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(M.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(M.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(M.style.color=n.codeBlockTextColor),M.textContent=Gr(t.args),b.append(x,M),m.appendChild(b)}if(t.chunks&&t.chunks.length){let b=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Activity";let M=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");M.style.fontSize="0.75rem",M.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(M.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(M.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(M.style.color=n.codeBlockTextColor),M.textContent=t.chunks.join(`
16
- `),b.append(x,M),m.appendChild(b)}if(t.status==="complete"&&t.result!==void 0){let b=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Result";let M=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");M.style.fontSize="0.75rem",M.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(M.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(M.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(M.style.color=n.codeBlockTextColor),M.textContent=Gr(t.result),b.append(x,M),m.appendChild(b)}if(t.status==="complete"&&typeof t.duration=="number"){let b=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(b.style.color=n.contentTextColor),b.textContent=`Duration: ${t.duration}ms`,m.appendChild(b)}return(()=>{a.setAttribute("aria-expanded",o?"true":"false"),c.innerHTML="";let b=n.toggleTextColor||n.headerTextColor||"currentColor",x=ge(o?"chevron-up":"chevron-down",16,b,2);x?c.appendChild(x):c.textContent=o?"Hide":"Show",m.style.display=o?"":"none"})(),s.append(a,m),s};var xs=(e,r)=>{var T,b,x,M,O,A,W,_,k,q,me,ce;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-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=(T=n==null?void 0:n.backgroundColor)!=null?T:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(b=n==null?void 0:n.borderColor)!=null?b:"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 d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(x=n==null?void 0:n.titleColor)!=null?x:"currentColor",u=ge(d,20,c,2);u&&i.appendChild(u);let p=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),m=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(m.style.color=n.titleColor),m.textContent=(M=n==null?void 0:n.title)!=null?M:"Approval Required",f.appendChild(m),!s){let z=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");z.setAttribute("data-approval-status",t.status),t.status==="approved"?(z.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",z.style.color="var(--persona-palette-colors-success-700, #15803d)",z.textContent="Approved"):t.status==="denied"?(z.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",z.style.color="var(--persona-palette-colors-error-700, #b91c1c)",z.textContent="Denied"):t.status==="timeout"&&(z.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",z.style.color="var(--persona-palette-colors-warning-700, #b45309)",z.textContent="Timeout"),f.appendChild(z)}p.appendChild(f);let C=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(C.style.color=n.descriptionColor),C.textContent=t.description,p.appendChild(C),t.parameters){let z=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&&(z.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(z.style.color=n.parameterTextColor),z.style.fontSize="0.75rem",z.style.lineHeight="1rem",z.textContent=Gr(t.parameters),p.appendChild(z)}if(s){let z=h("div","persona-flex persona-gap-2 persona-mt-2");z.setAttribute("data-approval-buttons","true");let ne=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");ne.type="button",ne.style.backgroundColor=(O=n==null?void 0:n.approveButtonColor)!=null?O:"var(--persona-approval-approve-bg, #22c55e)",ne.style.color=(A=n==null?void 0:n.approveButtonTextColor)!=null?A:"#ffffff",ne.setAttribute("data-approval-action","approve");let Ee=ge("shield-check",14,(W=n==null?void 0:n.approveButtonTextColor)!=null?W:"#ffffff",2);Ee&&(Ee.style.marginRight="4px",ne.appendChild(Ee));let ie=document.createTextNode((_=n==null?void 0:n.approveLabel)!=null?_:"Approve");ne.appendChild(ie);let ye=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");ye.type="button",ye.style.backgroundColor=(k=n==null?void 0:n.denyButtonColor)!=null?k:"transparent",ye.style.color=(q=n==null?void 0:n.denyButtonTextColor)!=null?q:"var(--persona-feedback-error, #dc2626)",ye.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,ye.setAttribute("data-approval-action","deny");let xe=ge("shield-x",14,(me=n==null?void 0:n.denyButtonTextColor)!=null?me:"var(--persona-feedback-error, #dc2626)",2);xe&&(xe.style.marginRight="4px",ye.appendChild(xe));let J=document.createTextNode((ce=n==null?void 0:n.denyLabel)!=null?ce:"Deny");ye.appendChild(J),z.append(ne,ye),p.appendChild(z)}return a.append(i,p),o.appendChild(a),o};var $l=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(m=>m.role==="user"))return;let u=document.createDocumentFragment(),p=s?s.isStreaming():!1,f=m=>{switch(m){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(m=>{let C=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-muted hover:persona-opacity-90 persona-cursor-pointer persona-border persona-border-gray-200");C.type="button",C.textContent=m,C.disabled=p,i!=null&&i.fontFamily&&(C.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(C.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(C.style.paddingLeft=i.paddingX,C.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(C.style.paddingTop=i.paddingY,C.style.paddingBottom=i.paddingY),C.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),u.appendChild(C),r.push(C)}),e.appendChild(u)}}};var io=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 lo=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 Er(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var Ed={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, #dbeafe)",text:"var(--persona-palette-colors-primary-700, #1e40af)"},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)"}},Td={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Md=["flowName","stepName","reasoningText","text","name","tool","toolName"],kd=100;function Ld(e,r){let t={...Ed,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return Td}function Pd(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function Id(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 Wd(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 Rd(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 Hd(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 Bd(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]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=n,i.appendChild(d),i}}function vs(e,r,t,n,s,o,a,i){var f;let d=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");Er(c,(f=n.classNames)==null?void 0:f.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(p()),c;function p(){var ne,Ee;let m=h("div",""),C=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");C.setAttribute("data-event-id",e.id);let T=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),b=ge(d?"chevron-down":"chevron-right","14px","currentColor",2);b&&T.appendChild(b);let x=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),M=(ne=n.timestampFormat)!=null?ne:"relative";x.textContent=M==="relative"?Pd(e.timestamp,t):Id(e.timestamp);let O=null;n.showSequenceNumbers!==!1&&(O=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),O.textContent=String(r+1));let A=Ld(e.type,n.badgeColors),W=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");W.style.backgroundColor=A.bg,W.style.color=A.text,W.style.borderColor=A.text+"50",W.textContent=e.type;let _=(Ee=n.descriptionFields)!=null?Ee:Md,k=Wd(e.payload,_),q=null;k&&(q=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),q.textContent=k);let me=h("div","persona-flex-1 persona-min-w-0"),ce=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"),z=ge("clipboard","12px","currentColor",1.5);return z&&ce.appendChild(z),ce.addEventListener("click",async ie=>{ie.stopPropagation(),await Rd(Hd(e)),ce.innerHTML="";let ye=ge("check","12px","currentColor",1.5);ye&&ce.appendChild(ye),setTimeout(()=>{ce.innerHTML="";let xe=ge("clipboard","12px","currentColor",1.5);xe&&ce.appendChild(xe)},1500)}),C.appendChild(T),C.appendChild(x),O&&C.appendChild(O),C.appendChild(W),q&&C.appendChild(q),C.appendChild(me),C.appendChild(ce),m.appendChild(C),d&&m.appendChild(Bd(e,a,i)),m}}function _l(e){var c,u;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(u=(c=s==null?void 0:s.features)==null?void 0:c.eventStream)!=null?u:{},i=o.find(p=>p.renderEventStreamView);if(i!=null&&i.renderEventStreamView&&s){let p=i.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>d().element,onClose:n});if(p)return{element:p,update:()=>{},destroy:()=>{}}}return d();function d(){let p=a.classNames,f=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Er(f,p==null?void 0:p.panel);let m=[],C="",T="",b=null,x=[],M={},O=0,A=!1,W=0,_=0,k=!1,q=null,me=!1,ce=0,z=new Set,ne=new Map,Ee="",ie="",ye=null,xe,J,ve,F,K;function fe(){let S=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),U=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");Er(U,p==null?void 0:p.headerBar);let te=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");te.textContent="Events",xe=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"),xe.textContent="0";let $e=h("div","persona-flex-1");J=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 se=h("option","");se.value="",se.textContent="All events",J.appendChild(se),ve=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"),ve.type="button",ve.title="Copy All";let Ae=ge("clipboard-copy","12px","currentColor",1.5);Ae&&ve.appendChild(Ae);let He=h("span","persona-text-xs");He.textContent="Copy All",ve.appendChild(He),U.appendChild(te),U.appendChild(xe),U.appendChild($e),U.appendChild(J),U.appendChild(ve);let ke=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Er(ke,p==null?void 0:p.searchBar);let Ke=ge("search","14px","var(--persona-muted, #9ca3af)",1.5),et=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");Ke&&et.appendChild(Ke),F=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"),Er(F,p==null?void 0:p.searchInput),F.type="text",F.placeholder="Search event payloads...",K=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"),K.type="button",K.style.display="none";let we=ge("x","12px","currentColor",2);return we&&K.appendChild(we),ke.appendChild(et),ke.appendChild(F),ke.appendChild(K),S.appendChild(U),S.appendChild(ke),S}let pt,Ct=o.find(S=>S.renderEventStreamToolbar);if(Ct!=null&&Ct.renderEventStreamToolbar&&s){let S=Ct.renderEventStreamToolbar({config:s,defaultRenderer:()=>fe(),eventCount:r.getSize(),filteredCount:0,onFilterChange:U=>{C=U,ee(),Ie()},onSearchChange:U=>{T=U,ee(),Ie()}});pt=S!=null?S:fe()}else pt=fe();let ut=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");ut.style.display="none";let xt=h("div","persona-flex-1 persona-min-h-0 persona-relative"),Fe=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Fe.style.height="100%";let be=h("div","persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-bg-persona-accent persona-text-white persona-text-xs persona-px-3 persona-py-1.5 persona-rounded-full persona-cursor-pointer persona-shadow-md persona-z-10 persona-flex persona-items-center persona-gap-1");Er(be,p==null?void 0:p.scrollIndicator),be.style.display="none";let ue=ge("arrow-down","12px","currentColor",2);ue&&be.appendChild(ue);let V=h("span","");be.appendChild(V);let Q=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Q.style.display="none",xt.appendChild(Fe),xt.appendChild(Q),xt.appendChild(be),f.setAttribute("tabindex","0"),f.appendChild(pt),f.appendChild(ut),f.appendChild(xt);function re(){let S=r.getAll(),U={};for(let He of S)U[He.type]=(U[He.type]||0)+1;let te=Object.keys(U).sort(),$e=te.length!==x.length||!te.every((He,ke)=>He===x[ke]),se=!$e&&te.some(He=>U[He]!==M[He]),ze=S.length!==Object.values(M).reduce((He,ke)=>He+ke,0);if(!$e&&!se&&!ze||(x=te,M=U,!J))return;let Ae=J.value;if(J.options[0].textContent="All events",$e){for(;J.options.length>1;)J.remove(1);for(let He of te){let ke=h("option","");ke.value=He,ke.textContent=`${He} (${U[He]||0})`,J.appendChild(ke)}Ae&&te.includes(Ae)?J.value=Ae:Ae&&(J.value="",C="")}else for(let He=1;He<J.options.length;He++){let ke=J.options[He];ke.textContent=`${ke.value} (${U[ke.value]||0})`}}function Me(){let S=r.getAll();if(C&&(S=S.filter(U=>U.type===C)),T){let U=T.toLowerCase();S=S.filter(te=>te.type.toLowerCase().includes(U)||te.payload.toLowerCase().includes(U))}return S}function Xe(){return C!==""||T!==""}function ee(){O=0,W=0,A=!1,be.style.display="none"}function Y(S){z.has(S)?z.delete(S):z.add(S),ye=S;let U=Fe.scrollTop,te=A;me=!0,A=!0,Ie(),Fe.scrollTop=U,A=te,me=!1}function Ve(){return Fe.scrollHeight-Fe.scrollTop-Fe.clientHeight<=50}function Ie(){_=Date.now(),k=!1,re();let S=r.getEvictedCount();S>0?(ut.textContent=`${S.toLocaleString()} older events truncated`,ut.style.display=""):ut.style.display="none",m=Me();let U=m.length,te=r.getSize()>0;xe&&(xe.textContent=String(r.getSize())),U===0&&te&&Xe()?(Q.textContent=T?`No events matching '${T}'`:"No events matching filter",Q.style.display="",Fe.style.display="none"):(Q.style.display="none",Fe.style.display=""),ve&&(ve.title=Xe()?`Copy Filtered (${U})`:"Copy All"),A&&U>O&&(W+=U-O,V.textContent=`${W} new event${W===1?"":"s"}`,be.style.display=""),O=U;let $e=r.getAll(),se=$e.length>0?$e[0].timestamp:0,ze=new Set(m.map(ke=>ke.id));for(let ke of z)ze.has(ke)||z.delete(ke);let Ae=C!==Ee||T!==ie,He=ne.size===0&&m.length>0;if(Ae||He||m.length===0){Fe.innerHTML="",ne.clear();let ke=document.createDocumentFragment();for(let Ke=0;Ke<m.length;Ke++){let et=vs(m[Ke],Ke,se,a,z,Y,o,s);ne.set(m[Ke].id,et),ke.appendChild(et)}Fe.appendChild(ke),Ee=C,ie=T,ye=null}else{if(ye!==null){let Ke=ne.get(ye);if(Ke&&Ke.parentNode===Fe){let et=m.findIndex(we=>we.id===ye);if(et>=0){let we=vs(m[et],et,se,a,z,Y,o,s);Fe.insertBefore(we,Ke),Ke.remove(),ne.set(ye,we)}}ye=null}let ke=new Set(m.map(Ke=>Ke.id));for(let[Ke,et]of ne)ke.has(Ke)||(et.remove(),ne.delete(Ke));for(let Ke=0;Ke<m.length;Ke++){let et=m[Ke];if(!ne.has(et.id)){let we=vs(et,Ke,se,a,z,Y,o,s);ne.set(et.id,we),Fe.appendChild(we)}}}A||(Fe.scrollTop=Fe.scrollHeight)}function ft(){if(Date.now()-_>=kd){q!==null&&(cancelAnimationFrame(q),q=null),Ie();return}k||(k=!0,q=requestAnimationFrame(()=>{q=null,Ie()}))}let jt=(S,U)=>{if(!ve)return;ve.innerHTML="";let te=ge(S,"12px","currentColor",1.5);te&&ve.appendChild(te);let $e=h("span","persona-text-xs");$e.textContent="Copy All",ve.appendChild($e),setTimeout(()=>{ve.innerHTML="";let se=ge("clipboard-copy","12px","currentColor",1.5);se&&ve.appendChild(se);let ze=h("span","persona-text-xs");ze.textContent="Copy All",ve.appendChild(ze),ve.disabled=!1},U)},zt=async()=>{if(ve){ve.disabled=!0;try{let S;Xe()?S=m:t?(S=await t(),S.length===0&&(S=r.getAll())):S=r.getAll();let U=S.map(te=>{try{return JSON.parse(te.payload)}catch{return te.payload}});await navigator.clipboard.writeText(JSON.stringify(U,null,2)),jt("check",1500)}catch{jt("x",1500)}}},de=()=>{J&&(C=J.value,ee(),Ie())},le=()=>{!F||!K||(K.style.display=F.value?"":"none",b&&clearTimeout(b),b=setTimeout(()=>{T=F.value,ee(),Ie()},150))},ot=()=>{!F||!K||(F.value="",T="",K.style.display="none",b&&clearTimeout(b),ee(),Ie())},gt=()=>{if(me)return;let S=Fe.scrollTop,U=S>ce;ce=S,Ve()&&U?(A=!1,W=0,be.style.display="none"):Ve()||(A=!0)},Je=S=>{S.deltaY<0&&(A=!0)},st=()=>{Fe.scrollTop=Fe.scrollHeight,A=!1,W=0,be.style.display="none"},Ht=S=>{let U=S.target;if(!U||U.closest("button"))return;let te=U.closest("[data-event-id]");if(!te)return;let $e=te.getAttribute("data-event-id");$e&&Y($e)},Lt=S=>{if((S.metaKey||S.ctrlKey)&&S.key==="f"){S.preventDefault(),F==null||F.focus(),F==null||F.select();return}S.key==="Escape"&&(F&&document.activeElement===F?(ot(),F.blur(),f.focus()):n&&n())};ve&&ve.addEventListener("click",zt),J&&J.addEventListener("change",de),F&&F.addEventListener("input",le),K&&K.addEventListener("click",ot),Fe.addEventListener("scroll",gt),Fe.addEventListener("wheel",Je,{passive:!0}),Fe.addEventListener("click",Ht),be.addEventListener("click",st),f.addEventListener("keydown",Lt);function qt(){b&&clearTimeout(b),q!==null&&(cancelAnimationFrame(q),q=null),k=!1,ne.clear(),ve&&ve.removeEventListener("click",zt),J&&J.removeEventListener("change",de),F&&F.removeEventListener("input",le),K&&K.removeEventListener("click",ot),Fe.removeEventListener("scroll",gt),Fe.removeEventListener("wheel",Je),Fe.removeEventListener("click",Ht),be.removeEventListener("click",st),f.removeEventListener("keydown",Lt)}return{element:f,update:ft,destroy:qt}}}function jl(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-bg, #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 d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.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, #3b82f6)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(m)}else p.textContent=a;if(c.append(u,p),i.append(d,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 zl=(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:"",d=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:r.config,defaultRenderer:()=>jl(e,r)});if(u)return u}return jl(e,r)};var Cs=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)})}},jn=new Cs;jn.register("PersonaArtifactCard",zl);function Dd(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 ql(e,r){var xt,Fe,be,ue;let t=(Fe=(xt=e.features)==null?void 0:xt.artifacts)==null?void 0:Fe.layout,s=((be=t==null?void 0:t.toolbarPreset)!=null?be:"default")==="document",o=(ue=t==null?void 0:t.panePadding)==null?void 0:ue.trim(),a=e.markdown?hr(e.markdown):null,i=Yr(e.sanitize),d=V=>{let Q=a?a(V):Kr(V);return i?i(Q):Q},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,u=()=>{c==null||c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),z==null||z.hide()};c&&c.addEventListener("click",()=>{var V;u(),(V=r.onDismiss)==null||V.call(r)});let p=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");p.setAttribute("data-persona-theme-zone","artifact-pane"),s&&p.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 m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let C=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");C.type="button",C.textContent="Close",C.setAttribute("aria-label","Close artifacts panel"),C.addEventListener("click",()=>{var V;u(),(V=r.onDismiss)==null||V.call(r)});let T="rendered",b=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),x=s?Ft({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Ft({icon:"eye",label:"Rendered view"}),M=s?Ft({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Ft({icon:"code-2",label:"Source"}),O=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),A=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,W=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,_=t==null?void 0:t.documentToolbarCopyMenuItems,k=!!(W&&_&&_.length>0),q=null,me,ce=null,z=null;if(s&&(A||W)&&!k){if(me=A?_o({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ft({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let V=ge("chevron-down",14,"currentColor",2);V&&me.appendChild(V)}}else s&&k?(q=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),me=A?_o({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ft({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),ce=Ft({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),q.append(me,ce)):s?me=Ft({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):me=Ft({icon:"copy",label:"Copy"});let ne=s?Ft({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Ft({icon:"refresh-cw",label:"Refresh"}),Ee=s?Ft({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Ft({icon:"x",label:"Close"}),ie=()=>{var Xe,ee,Y;let V=(Xe=K.find(Ve=>Ve.id===fe))!=null?Xe:K[K.length-1],Q=(ee=V==null?void 0:V.id)!=null?ee:null,re=(V==null?void 0:V.artifactType)==="markdown"&&(Y=V.markdown)!=null?Y:"",Me=V?JSON.stringify({component:V.component,props:V.props},null,2):"";return{markdown:re,jsonPayload:Me,id:Q}},ye=async()=>{var Xe;let{markdown:V,jsonPayload:Q}=ie(),re=(Xe=K.find(ee=>ee.id===fe))!=null?Xe:K[K.length-1],Me=(re==null?void 0:re.artifactType)==="markdown"?V:re?Q:"";try{await navigator.clipboard.writeText(Me)}catch{}};if(me.addEventListener("click",async()=>{let V=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(V&&k){let{markdown:Q,jsonPayload:re,id:Me}=ie();try{await V({actionId:"primary",artifactId:Me,markdown:Q,jsonPayload:re})}catch{}return}await ye()}),ce&&(_!=null&&_.length)){let V=()=>{var re;return(re=p.closest("[data-persona-root]"))!=null?re:document.body},Q=()=>{z=ar({items:_.map(re=>({id:re.id,label:re.label})),onSelect:async re=>{let{markdown:Me,jsonPayload:Xe,id:ee}=ie(),Y=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Y?await Y({actionId:re,artifactId:ee,markdown:Me,jsonPayload:Xe}):re==="markdown"||re==="md"?await navigator.clipboard.writeText(Me):re==="json"||re==="source"?await navigator.clipboard.writeText(Xe):await navigator.clipboard.writeText(Me||Xe)}catch{}},anchor:q!=null?q:ce,position:"bottom-right",portal:V()})};p.isConnected?Q():requestAnimationFrame(Q),ce.addEventListener("click",re=>{re.stopPropagation(),z==null||z.toggle()})}ne.addEventListener("click",async()=>{var V;try{await((V=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:V.call(t))}catch{}Ct()}),Ee.addEventListener("click",()=>{var V;u(),(V=r.onDismiss)==null||V.call(r)});let xe=()=>{s&&(x.setAttribute("aria-pressed",T==="rendered"?"true":"false"),M.setAttribute("aria-pressed",T==="source"?"true":"false"))};x.addEventListener("click",()=>{T="rendered",xe(),Ct()}),M.addEventListener("click",()=>{T="source",xe(),Ct()});let J=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(),b.append(x,M),q?O.append(q,ne,Ee):O.append(me,ne,Ee),f.append(b,J,O),xe()):(f.appendChild(m),f.appendChild(C)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let ve=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"),F=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(ve.style.paddingLeft=o,ve.style.paddingRight=o,F.style.padding=o),p.appendChild(f),p.appendChild(ve),p.appendChild(F);let K=[],fe=null,pt=!1,Ct=()=>{var Me,Xe,ee,Y;let V=s&&K.length<=1;ve.classList.toggle("persona-hidden",V),ve.replaceChildren();for(let Ve of K){let Ie=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");Ie.type="button",Ie.textContent=Ve.title||Ve.id.slice(0,8),Ve.id===fe&&Ie.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ie.addEventListener("click",()=>r.onSelect(Ve.id)),ve.appendChild(Ie)}F.replaceChildren();let Q=fe&&K.find(Ve=>Ve.id===fe)||K[K.length-1];if(!Q)return;if(s){let Ve=Q.artifactType==="markdown"?"MD":(Me=Q.component)!=null?Me:"Component",ft=(Q.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";J.textContent=`${ft} \xB7 ${Ve}`}else m.textContent="Artifacts";if(Q.artifactType==="markdown"){if(s&&T==="source"){let Ie=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ie.textContent=(Xe=Q.markdown)!=null?Xe:"",F.appendChild(Ie);return}let Ve=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ve.innerHTML=d((ee=Q.markdown)!=null?ee:""),F.appendChild(Ve);return}let re=Q.component?jn.get(Q.component):void 0;if(re){let Ie={message:{id:Q.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let ft=re((Y=Q.props)!=null?Y:{},Ie);if(ft){F.appendChild(ft);return}}catch{}}F.appendChild(Dd(Q))},ut=()=>{var Q;let V=K.length>0;if(p.classList.toggle("persona-hidden",!V),c){let re=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,Xe=((Q=re==null?void 0:re.classList.contains("persona-artifact-narrow-host"))!=null?Q:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;V&&Xe&&pt?(c.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:c,update(V){var Q,re,Me;K=V.artifacts,fe=(Me=(re=V.selectedId)!=null?re:(Q=V.artifacts[V.artifacts.length-1])==null?void 0:Q.id)!=null?Me:null,K.length>0&&(pt=!0),Ct(),ut()},setMobileOpen(V){pt=V,!V&&c?(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ut()}}}function pn(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 Ul(e,r){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!pn(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=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.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 Nd(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 jo(e,r){var d,c,u,p,f,m,C,T,b,x;if(!pn(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"),Nd(e),Ul(e,r);return}let t=(c=(d=r.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"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=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let s=(C=t==null?void 0:t.panePadding)==null?void 0:C.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(T=t==null?void 0:t.documentToolbarIconColor)==null?void 0:T.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(b=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:b.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(x=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:x.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Ul(e,r)}var Vl=["panel","seamless"];function zo(e,r){var i,d,c,u,p,f;for(let m of Vl)e.classList.remove(`persona-artifact-appearance-${m}`);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"),!pn(r))return;let t=(d=(i=r.features)==null?void 0:i.artifacts)==null?void 0:d.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=Vl.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(p=t==null?void 0:t.paneShadow)==null?void 0:p.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 m=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Jl(e,r){var t,n,s;return!r||!pn(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Od(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 Fd(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 $d(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function _d(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function Kl(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 Yl(e,r,t,n,s,o){let a=Od(s,200),i=_d(r,t,n,200);i=Math.max(a,i);let d=Fd(o);return d!==null&&(i=Math.min(i,d)),$d(e,a,i)}var Gl={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"}},ws=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var C,T,b;if(o.dataset.enhanced==="true")return;let a=(C=o.dataset.tvForm)!=null?C:"init";o.dataset.enhanced="true";let i=(T=Gl[a])!=null?T:Gl.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let x=h("p","persona-text-sm persona-text-persona-muted");x.textContent=i.description,d.appendChild(x)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(x=>{var _,k;let M=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");M.htmlFor=`${r.id}-${a}-${x.name}`;let O=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");O.textContent=x.label,M.appendChild(O);let A=(_=x.type)!=null?_:"text",W;A==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=A),W.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",W.id=`${r.id}-${a}-${x.name}`,W.name=x.name,W.placeholder=(k=x.placeholder)!=null?k:"",x.required&&(W.required=!0),M.appendChild(W),u.appendChild(M)});let p=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]"),m=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");m.type="submit",m.textContent=(b=i.submitLabel)!=null?b:"Submit",p.appendChild(f),p.appendChild(m),u.appendChild(p),o.replaceChildren(d,u),u.addEventListener("submit",async x=>{var W,_;x.preventDefault();let M=(W=t.formEndpoint)!=null?W:"/form",O=new FormData(u),A={};O.forEach((k,q)=>{A[q]=k}),A.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let k=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let q=await k.json();f.textContent=(_=q.message)!=null?_:"Thanks! We'll be in touch soon.",q.success&&q.nextPrompt&&await n.sendMessage(String(q.nextPrompt))}catch(k){f.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Ss=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,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},qo=new Ss;var bt={apiUrl:"http://localhost:43111/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}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",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:"1px solid #e5e7eb",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",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",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:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},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 Xl(e,r){if(!(!e&&!r))return e?r?no(e,r):e:r}function As(e){var r,t,n,s,o,a,i,d,c,u,p,f,m,C,T,b,x,M,O,A,W;return e?{...bt,...e,theme:Xl(bt.theme,e.theme),darkTheme:Xl(bt.darkTheme,e.darkTheme),launcher:{...bt.launcher,...e.launcher,dock:{...(r=bt.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=bt.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...bt.copy,...e.copy},sendButton:{...bt.sendButton,...e.sendButton},statusIndicator:{...bt.statusIndicator,...e.statusIndicator},voiceRecognition:{...bt.voiceRecognition,...e.voiceRecognition},features:(()=>{var me,ce;let _=(me=bt.features)==null?void 0:me.artifacts,k=(ce=e.features)==null?void 0:ce.artifacts,q=_===void 0&&k===void 0?void 0:{..._,...k,layout:{..._==null?void 0:_.layout,...k==null?void 0:k.layout}};return{...bt.features,...e.features,...q!==void 0?{artifacts:q}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:bt.suggestionChips,suggestionChipsConfig:{...bt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...bt.layout,...e.layout,header:{...(a=bt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=bt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(p=(u=bt.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(T=(C=bt.layout)==null?void 0:C.messages)==null?void 0:T.timestamp,...(x=(b=e.layout)==null?void 0:b.messages)==null?void 0:x.timestamp}},slots:{...(M=bt.layout)==null?void 0:M.slots,...(O=e.layout)==null?void 0:O.slots}},markdown:{...bt.markdown,...e.markdown,options:{...(A=bt.markdown)==null?void 0:A.options,...(W=e.markdown)==null?void 0:W.options}},messageActions:{...bt.messageActions,...e.messageActions}}:bt}var Zl=()=>{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(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var jd=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},zd=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},Uo=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=jd(e),t=zd(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}},Es=e=>typeof e=="string"?e:e==null?"":String(e),Tr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Es(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=Es(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:Es(t.text)}}},Ql=e=>Array.isArray(e)?e.map(r=>String(r)):[],Vo=e=>{let r=new Set(Ql(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(Ql(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,u)=>c||(u==null?void 0:u({text:a,message:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let d={action:i,message:o.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let u=()=>{e.emit("action:resubmit",d)},p=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var qd=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}},Ud=e=>e.map(r=>({...r,streaming:!1})),Ts=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?qd(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?Ud(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 Vd,STR as Jd,OBJ as Kd}from"partial-json";function Yd(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function Gd(e,r){if(!Yd(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 Ms(){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=Vd(t,Jd|Kd),o=Gd(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Xd(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ks(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=jn.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 Zd(){let e=Ms();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ls(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 Ps(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 Qd=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Is(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:d=!0,ratingLabels:c=Qd}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=n,m.appendChild(C);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=s,m.appendChild(T),f.appendChild(m);let b=document.createElement("div");b.className="persona-feedback-rating persona-feedback-rating-csat",b.setAttribute("role","radiogroup"),b.setAttribute("aria-label","Satisfaction rating from 1 to 5");let x=[];for(let _=1;_<=5;_++){let k=document.createElement("button");k.type="button",k.className="persona-feedback-rating-btn persona-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${_} star${_>1?"s":""}: ${c[_-1]}`),k.title=c[_-1],k.dataset.rating=String(_),k.innerHTML=`
15
+ `,t.addEventListener("click",r);let n=o=>{var O,A,W,_,k,q,fe,de,z,ne,Ae,le,Ee;let a=(O=o.launcher)!=null?O:{},i=_t(o),d=t.querySelector("[data-role='launcher-title']");if(d){let ie=(A=a.title)!=null?A:"Chat Assistant";d.textContent=ie,d.setAttribute("title",ie)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let ie=(W=a.subtitle)!=null?W:"Get answers fast";c.textContent=ie,c.setAttribute("title",ie)}let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let ie=(_=a.agentIconSize)!=null?_:"40px";if(p.style.height=ie,p.style.width=ie,p.innerHTML="",a.agentIconName){let K=parseFloat(ie)||24,be=me(a.agentIconName,K*.6,"var(--persona-text-inverse, #ffffff)",2);be?(p.appendChild(be),p.style.display=""):(p.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(q=a.agentIconText)!=null?q:"\u{1F4AC}",p.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let ie=(fe=a.agentIconSize)!=null?fe:"40px";f.style.height=ie,f.style.width=ie,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ie=(de=a.callToActionIconSize)!=null?de:"32px";m.style.height=ie,m.style.width=ie,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary"));let K=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,K=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let be=parseFloat(ie)||24,F=Math.max(be-K,8),U=me(a.callToActionIconName,F,"currentColor",2);U?m.appendChild(U):m.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}else m.textContent=(ne=a.callToActionIconText)!=null?ne:"\u2197"}let C=a.position&&hn[a.position]?hn[a.position]:hn["bottom-right"],T="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 persona-z-50",b="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?b:`${T} ${C}`;let x="1px solid var(--persona-border, #e5e7eb)",M="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=(Ae=a.border)!=null?Ae:x,t.style.boxShadow=(le=a.shadow)!=null?le:M,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=(Ee=a.collapsedMaxWidth)!=null?Ee:"",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 yn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #2563eb))",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))"},_n=e=>{var de,z,ne,Ae,le,Ee,ie,K,be,F,U,he,pt,Ct,ut,xt,Fe,xe,ge,J,Q,re,Me,Xe,ee,Y,Ve,Ie,ft,jt,zt,pe;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=(de=r==null?void 0:r.launcher)!=null?de:{},o=(z=s.headerIconSize)!=null?z:"48px",a=(ne=s.closeButtonSize)!=null?ne:"32px",i=(Ae=s.closeButtonPlacement)!=null?Ae:"inline",d=(le=s.headerIconHidden)!=null?le:!1,c=s.headerIconName,u=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(u.style.height=o,u.style.width=o,u.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #2563eb))",u.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!d)if(c){let ce=parseFloat(o)||24,ot=me(c,ce*.6,"currentColor",1);ot?u.replaceChildren(ot):u.textContent=(ie=(Ee=r==null?void 0:r.launcher)==null?void 0:Ee.agentIconText)!=null?ie:"\u{1F4AC}"}else if((K=r==null?void 0:r.launcher)!=null&&K.iconUrl){let ce=h("img");ce.src=r.launcher.iconUrl,ce.alt="",ce.className="persona-rounded-xl persona-object-cover",ce.style.height=o,ce.style.width=o,u.replaceChildren(ce)}else u.textContent=(F=(be=r==null?void 0:r.launcher)==null?void 0:be.agentIconText)!=null?F:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col"),f=h("span","persona-text-base persona-font-semibold");f.style.color=yn.titleColor,f.textContent=(he=(U=r==null?void 0:r.launcher)==null?void 0:U.title)!=null?he:"Chat Assistant";let m=h("span","persona-text-xs");m.style.color=yn.subtitleColor,m.textContent=(Ct=(pt=r==null?void 0:r.launcher)==null?void 0:pt.subtitle)!=null?Ct:"Here to help you get answers fast",p.append(f,m),d?n.append(p):n.append(u,p);let C=(ut=s.clearChat)!=null?ut:{},T=(xt=C.enabled)!=null?xt:!0,b=(Fe=C.placement)!=null?Fe:"inline",x=null,M=null;if(T){let ce=(xe=C.size)!=null?xe:"32px",ot=(ge=C.iconName)!=null?ge:"refresh-cw",gt=(J=C.iconColor)!=null?J:"",Je=(Q=C.backgroundColor)!=null?Q:"",st=(re=C.borderWidth)!=null?re:"",Ht=(Me=C.borderColor)!=null?Me:"",Lt=(Xe=C.borderRadius)!=null?Xe:"",qt=(ee=C.paddingX)!=null?ee:"",S=(Y=C.paddingY)!=null?Y:"",V=(Ve=C.tooltipText)!=null?Ve:"Clear chat",te=(Ie=C.showTooltip)!=null?Ie:!0;M=h("div",b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),b==="top-right"&&(M.style.right="48px"),x=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"),x.style.height=ce,x.style.width=ce,x.type="button",x.setAttribute("aria-label",V),x.style.color=gt||yn.actionIconColor;let $e=me(ot,"20px","currentColor",1);if($e&&x.appendChild($e),Je&&(x.style.backgroundColor=Je,x.classList.remove("hover:persona-bg-gray-100")),st||Ht){let se=st||"0px",ze=Ht||"transparent";x.style.border=`${se} solid ${ze}`,x.classList.remove("persona-border-none")}if(Lt&&(x.style.borderRadius=Lt,x.classList.remove("persona-rounded-full")),qt?(x.style.paddingLeft=qt,x.style.paddingRight=qt):(x.style.paddingLeft="",x.style.paddingRight=""),S?(x.style.paddingTop=S,x.style.paddingBottom=S):(x.style.paddingTop="",x.style.paddingBottom=""),M.appendChild(x),te&&V&&x&&M){let se=null,ze=()=>{if(se||!x)return;let He=x.ownerDocument,ke=He.body;if(!ke)return;se=An(He,"div","persona-clear-chat-tooltip"),se.textContent=V;let Ke=An(He,"div");Ke.className="persona-clear-chat-tooltip-arrow",se.appendChild(Ke);let et=x.getBoundingClientRect();se.style.position="fixed",se.style.left=`${et.left+et.width/2}px`,se.style.top=`${et.top-8}px`,se.style.transform="translate(-50%, -100%)",ke.appendChild(se)},Se=()=>{se&&se.parentNode&&(se.parentNode.removeChild(se),se=null)};M.addEventListener("mouseenter",ze),M.addEventListener("mouseleave",Se),x.addEventListener("focus",ze),x.addEventListener("blur",Se),M._cleanupTooltip=()=>{Se(),M&&(M.removeEventListener("mouseenter",ze),M.removeEventListener("mouseleave",Se)),x&&(x.removeEventListener("focus",ze),x.removeEventListener("blur",Se))}}b==="inline"&&n.appendChild(M)}let O=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":T&&b==="inline"?"":"persona-ml-auto"),A=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");A.style.height=a,A.style.width=a,A.type="button";let W=(ft=s.closeButtonTooltipText)!=null?ft:"Close chat",_=(jt=s.closeButtonShowTooltip)!=null?jt:!0;A.setAttribute("aria-label",W),A.style.display=t?"":"none";let k=(zt=s.closeButtonIconName)!=null?zt:"x",q=(pe=s.closeButtonIconText)!=null?pe:"\xD7";A.style.color=s.closeButtonColor||yn.actionIconColor;let fe=me(k,"20px","currentColor",1);if(fe?A.appendChild(fe):A.textContent=q,s.closeButtonBackgroundColor?(A.style.backgroundColor=s.closeButtonBackgroundColor,A.classList.remove("hover:persona-bg-gray-100")):(A.style.backgroundColor="",A.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let ce=s.closeButtonBorderWidth||"0px",ot=s.closeButtonBorderColor||"transparent";A.style.border=`${ce} solid ${ot}`,A.classList.remove("persona-border-none")}else A.style.border="",A.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(A.style.borderRadius=s.closeButtonBorderRadius,A.classList.remove("persona-rounded-full")):(A.style.borderRadius="",A.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(A.style.paddingLeft=s.closeButtonPaddingX,A.style.paddingRight=s.closeButtonPaddingX):(A.style.paddingLeft="",A.style.paddingRight=""),s.closeButtonPaddingY?(A.style.paddingTop=s.closeButtonPaddingY,A.style.paddingBottom=s.closeButtonPaddingY):(A.style.paddingTop="",A.style.paddingBottom=""),O.appendChild(A),_&&W){let ce=null,ot=()=>{if(ce)return;let Je=A.ownerDocument,st=Je.body;if(!st)return;ce=An(Je,"div","persona-clear-chat-tooltip"),ce.textContent=W;let Ht=An(Je,"div");Ht.className="persona-clear-chat-tooltip-arrow",ce.appendChild(Ht);let Lt=A.getBoundingClientRect();ce.style.position="fixed",ce.style.left=`${Lt.left+Lt.width/2}px`,ce.style.top=`${Lt.top-8}px`,ce.style.transform="translate(-50%, -100%)",st.appendChild(ce)},gt=()=>{ce&&ce.parentNode&&(ce.parentNode.removeChild(ce),ce=null)};O.addEventListener("mouseenter",ot),O.addEventListener("mouseleave",gt),A.addEventListener("focus",ot),A.addEventListener("blur",gt),O._cleanupTooltip=()=>{gt(),O.removeEventListener("mouseenter",ot),O.removeEventListener("mouseleave",gt),A.removeEventListener("focus",ot),A.removeEventListener("blur",gt)}}return i!=="top-right"&&n.appendChild(O),{header:n,iconHolder:u,headerTitle:f,headerSubtitle:m,closeButton:A,closeButtonWrapper:O,clearChatButton:x,clearChatButtonWrapper:M}},Cr=(e,r,t)=>{var a,i,d,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(d=n.clearChat)==null?void 0:d.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 ar(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="10000"):(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 m of r){if(m.dividerBefore){let b=document.createElement("hr");a.appendChild(b)}let C=document.createElement("button");if(C.type="button",C.setAttribute("role","menuitem"),C.setAttribute("data-dropdown-item-id",m.id),m.destructive&&C.setAttribute("data-destructive",""),m.icon){let b=me(m.icon,16,"currentColor",1.5);b&&C.appendChild(b)}let T=document.createElement("span");T.textContent=m.label,C.appendChild(T),C.addEventListener("click",b=>{b.stopPropagation(),u(),t(m.id)}),a.appendChild(C)}let i=null;function d(){if(!o)return;let m=n.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=C=>{!a.contains(C.target)&&!n.contains(C.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?c():u()}function f(){u(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:u,toggle:p,destroy:f}}function Ft(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=me(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function _o(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,c="persona-label-btn";n!=="default"&&(c+=" persona-label-btn--"+n),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let u=h("button",c);if(u.type="button",u.setAttribute("aria-label",t),r){let f=me(r,o!=null?o:14,"currentColor",2);f&&u.appendChild(f)}let p=h("span");if(p.textContent=t,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))u.setAttribute(f,m);return u}function fd(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 d(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of r){let p;u.icon?p=Ft({icon:u.icon,label:u.label,onClick:()=>{a=u.id,d(),n(u.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{a=u.id,d(),n(u.id)})),p.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:p}),o.appendChild(p)}function c(u){a=u,d()}return{element:o,setSelected:c}}function fs(e){var m,C;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=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 u=h("span","persona-combo-btn-label");u.textContent=r,c.appendChild(u);let p=me(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",c.appendChild(p)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",c.style.padding=(C=d.padding)!=null?C:"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 T,b;c.style.backgroundColor=(T=d.background)!=null?T:"",c.style.borderColor=(b=d.border)!=null?b:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=ar({items:n,onSelect:T=>{c.setAttribute("aria-expanded","false"),s(T)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",T=>{T.stopPropagation();let b=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",b?"false":"true"),f.toggle()}),c.addEventListener("keydown",T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),c.click())}),{element:c,setLabel:T=>{u.textContent=T,c.setAttribute("aria-label",T)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let T=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",T?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Pl=e=>{var n;let r=_n({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 hd(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 d=me(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let c=ar({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",u=>{u.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Il=e=>{var M,O,A,W,_,k,q,fe,de;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(M=r==null?void 0:r.launcher)!=null?M:{},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 d=s==null?void 0:s.titleMenu,c,u;if(d)c=fs({label:(O=a.title)!=null?O:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=yn.titleColor,u=(A=c.querySelector(".persona-combo-btn-label"))!=null?A:c;else{if(c=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=h("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=yn.titleColor,u.textContent=(W=a.title)!=null?W:"Chat Assistant",c.appendChild(u),hd(c,s==null?void 0:s.trailingActions,(_=s==null?void 0:s.onAction)!=null?_:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let ne=s.onTitleClick;c.addEventListener("click",Ae=>{Ae.target.closest("button")||ne()}),c.addEventListener("keydown",Ae=>{(Ae.key==="Enter"||Ae.key===" ")&&(Ae.preventDefault(),ne())})}let z=s==null?void 0:s.titleRowHover;z&&(c.style.borderRadius=(k=z.borderRadius)!=null?k:"10px",c.style.padding=(q=z.padding)!=null?q:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var ne,Ae;c.style.backgroundColor=(ne=z.background)!=null?ne:"",c.style.borderColor=(Ae=z.border)!=null?Ae:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let p=(fe=a.closeButtonSize)!=null?fe:"32px",f=h("div",""),m=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");m.style.height=p,m.style.width=p,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||yn.actionIconColor;let C=(de=a.closeButtonIconName)!=null?de:"x",T=me(C,"20px","currentColor",2);T?m.appendChild(T):m.textContent="\xD7",n&&m.addEventListener("click",n),f.appendChild(m),i.appendChild(f);let b=h("div");b.style.display="none";let x=h("span");return x.style.display="none",{header:i,iconHolder:b,headerTitle:u,headerSubtitle:x,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},hs={default:Pl,minimal:Il},Wl=e=>{var r;return(r=hs[e])!=null?r:hs.default},oo=(e,r,t)=>{var a,i,d;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}),u=h("div");u.style.display="none";let p=h("span"),f=h("span"),m=h("button");m.style.display="none";let C=h("div");return C.style.display="none",{header:c,iconHolder:u,headerTitle:p,headerSubtitle:f,closeButton:m,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=Wl(n)({config:e,showClose:(d=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig: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 so=e=>{var ut,xt,Fe,xe,ge,J,Q,re,Me,Xe,ee,Y,Ve,Ie,ft,jt,zt,pe,ce,ot,gt,Je,st,Ht,Lt,qt,S;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=(xt=(ut=r==null?void 0:r.copy)==null?void 0:ut.inputPlaceholder)!=null?xt:"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 d=3*20;o.style.maxHeight=`${d}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let V=Math.min(o.scrollHeight,d);o.style.height=`${V}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 u=(Fe=r==null?void 0:r.sendButton)!=null?Fe:{},p=(xe=u.useIcon)!=null?xe:!1,f=(ge=u.iconText)!=null?ge:"\u2191",m=u.iconName,C=(J=u.tooltipText)!=null?J:"Send message",T=(Q=u.showTooltip)!=null?Q:!1,b=(re=u.size)!=null?re:"40px",x=u.backgroundColor,M=u.textColor,O=h("div","persona-send-button-wrapper"),A=h("button",p?"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(A.type="submit",A.setAttribute("data-persona-composer-submit",""),p){if(A.style.width=b,A.style.height=b,A.style.minWidth=b,A.style.minHeight=b,A.style.fontSize="18px",A.style.lineHeight="1",A.innerHTML="",m){let V=parseFloat(b)||24,te=M&&typeof M=="string"&&M.trim()?M.trim():"currentColor",$e=me(m,V,te,2);$e?(A.appendChild($e),A.style.color=te):(A.textContent=f,M?A.style.color=M:A.classList.add("persona-text-white"))}else A.textContent=f,M?A.style.color=M:A.classList.add("persona-text-white");x?A.style.backgroundColor=x:A.classList.add("persona-bg-persona-primary")}else A.textContent=(Xe=(Me=r==null?void 0:r.copy)==null?void 0:Me.sendButtonLabel)!=null?Xe:"Send",M?A.style.color=M:A.classList.add("persona-text-white");if(u.borderWidth&&(A.style.borderWidth=u.borderWidth,A.style.borderStyle="solid"),u.borderColor&&(A.style.borderColor=u.borderColor),u.paddingX?(A.style.paddingLeft=u.paddingX,A.style.paddingRight=u.paddingX):(A.style.paddingLeft="",A.style.paddingRight=""),u.paddingY?(A.style.paddingTop=u.paddingY,A.style.paddingBottom=u.paddingY):(A.style.paddingTop="",A.style.paddingBottom=""),T&&C){let V=h("div","persona-send-button-tooltip");V.textContent=C,O.appendChild(V)}O.appendChild(A);let W=(ee=r==null?void 0:r.voiceRecognition)!=null?ee:{},_=W.enabled===!0,k=null,q=null,fe=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),de=((Y=W.provider)==null?void 0:Y.type)==="runtype";if(_&&(fe||de)){q=h("div","persona-send-button-wrapper"),k=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),k.type="button",k.setAttribute("data-persona-composer-mic",""),k.setAttribute("aria-label","Start voice recognition");let V=(Ve=W.iconName)!=null?Ve:"mic",te=(Ie=W.iconSize)!=null?Ie:b,$e=parseFloat(te)||24,se=(ft=W.backgroundColor)!=null?ft:x,ze=(jt=W.iconColor)!=null?jt:M;k.style.width=te,k.style.height=te,k.style.minWidth=te,k.style.minHeight=te,k.style.fontSize="18px",k.style.lineHeight="1";let Se=ze||"currentColor",He=me(V,$e,Se,1.5);He?(k.appendChild(He),k.style.color=Se):(k.textContent="\u{1F3A4}",k.style.color=Se),se?k.style.backgroundColor=se:k.classList.add("persona-bg-persona-primary"),ze?k.style.color=ze:!ze&&!M&&k.classList.add("persona-text-white"),W.borderWidth&&(k.style.borderWidth=W.borderWidth,k.style.borderStyle="solid"),W.borderColor&&(k.style.borderColor=W.borderColor),W.paddingX&&(k.style.paddingLeft=W.paddingX,k.style.paddingRight=W.paddingX),W.paddingY&&(k.style.paddingTop=W.paddingY,k.style.paddingBottom=W.paddingY),q.appendChild(k);let ke=(zt=W.tooltipText)!=null?zt:"Start voice recognition";if(((pe=W.showTooltip)!=null?pe:!1)&&ke){let et=h("div","persona-send-button-tooltip");et.textContent=ke,q.appendChild(et)}}let ne=(ce=r==null?void 0:r.attachments)!=null?ce:{},Ae=ne.enabled===!0,le=null,Ee=null,ie=null,K=null;if(Ae){K=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),K.style.display="none",ie=h("input"),ie.type="file",ie.accept=((ot=ne.allowedTypes)!=null?ot:Rn).join(","),ie.multiple=((gt=ne.maxFiles)!=null?gt:4)>1,ie.style.display="none",ie.setAttribute("aria-label","Attach files"),Ee=h("div","persona-send-button-wrapper"),le=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),le.type="button",le.setAttribute("aria-label",(Je=ne.buttonTooltipText)!=null?Je:"Attach file");let V=(st=ne.buttonIconName)!=null?st:"paperclip",te=b,$e=parseFloat(te)||40,se=Math.round($e*.6);le.style.width=te,le.style.height=te,le.style.minWidth=te,le.style.minHeight=te,le.style.fontSize="18px",le.style.lineHeight="1",le.style.backgroundColor="transparent",le.style.color="var(--persona-primary, #111827)",le.style.border="none",le.style.borderRadius="6px",le.style.transition="background-color 0.15s ease",le.addEventListener("mouseenter",()=>{le.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),le.addEventListener("mouseleave",()=>{le.style.backgroundColor="transparent"});let ze=me(V,se,"currentColor",1.5);ze?le.appendChild(ze):le.textContent="\u{1F4CE}",le.addEventListener("click",ke=>{ke.preventDefault(),ie==null||ie.click()}),Ee.appendChild(le);let Se=(Ht=ne.buttonTooltipText)!=null?Ht:"Attach file",He=h("div","persona-send-button-tooltip");He.textContent=Se,Ee.appendChild(He)}s.addEventListener("click",V=>{V.target!==A&&V.target!==O&&V.target!==k&&V.target!==q&&V.target!==le&&V.target!==Ee&&o.focus()}),K&&(K.style.gap="8px",s.append(K)),ie&&s.append(ie),s.append(o);let be=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),F=h("div","persona-flex persona-items-center persona-gap-2");Ee&&F.append(Ee);let U=h("div","persona-flex persona-items-center persona-gap-1");q&&U.append(q),U.append(O),be.append(F,U),s.append(be);let he=h("div","persona-mt-2 persona-text-right persona-text-xs persona-text-persona-muted");he.setAttribute("data-persona-composer-status","");let pt=(Lt=r==null?void 0:r.statusIndicator)!=null?Lt:{},Ct=(qt=pt.visible)!=null?qt:!0;return he.style.display=Ct?"":"none",he.textContent=(S=pt.idleText)!=null?S:"Online",t.append(n,s,he),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:A,sendButtonWrapper:O,micButton:k,micButtonWrapper:q,statusText:he,attachmentButton:le,attachmentButtonWrapper:Ee,attachmentInput:ie,attachmentPreviewsContainer:K,actionsRow:be,leftActions:F,rightActions:U}};var Rl=e=>{var c,u,p,f,m,C,T;let r=(u=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?u:!0;if(_t(e)){let b=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),x=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return b.appendChild(x),{wrapper:b,panel:x}}if(!r){let b=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),x=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),M=(f=(p=e==null?void 0:e.launcher)==null?void 0:p.width)!=null?f:"100%";return b.style.width=M,x.style.width="100%",b.appendChild(x),{wrapper:b,panel:x}}let n=(m=e==null?void 0:e.launcher)!=null?m:{},s=n.position&&hn[n.position]?hn[n.position]:hn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-z-50 persona-transition`),a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(T=(C=e==null?void 0:e.launcher)==null?void 0:C.width)!=null?T:e==null?void 0:e.launcherWidth,d=i!=null?i:"min(400px, calc(100vw - 24px))";return a.style.width=d,a.style.maxWidth=d,o.appendChild(a),{wrapper:o,panel:a}},Hl=(e,r=!0)=>{var b,x,M,O,A,W,_,k,q;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=(b=e==null?void 0:e.layout)==null?void 0:b.header,s=((x=e==null?void 0:e.layout)==null?void 0:x.showHeader)!==!1,o=n?oo(e,n,{showClose:r}):_n({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=_t(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",d=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(O=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?O:"Hello \u{1F44B}";let u=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");u.textContent=(W=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",d.append(c,u);let p=h("div","persona-flex persona-flex-col persona-gap-3"),f=(_=e==null?void 0:e.layout)==null?void 0:_.contentMaxWidth;f&&(p.style.maxWidth=f,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((k=e==null?void 0:e.copy)==null?void 0:k.showWelcomeCard)!==!1?a.append(d,p):(a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3"),a.append(p));let C=so({config:e}),T=((q=e==null?void 0:e.layout)==null?void 0:q.showFooter)!==!1;return s?Cr(t,o,e):(o.header.style.display="none",Cr(t,o,e)),t.append(a),T||(C.footer.style.display="none"),t.append(C.footer),{container:t,body:a,messagesWrapper:p,suggestions:C.suggestions,textarea:C.textarea,sendButton:C.sendButton,sendButtonWrapper:C.sendButtonWrapper,micButton:C.micButton,micButtonWrapper:C.micButtonWrapper,composerForm:C.composerForm,statusText:C.statusText,introTitle:c,introSubtitle:u,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:C.footer,attachmentButton:C.attachmentButton,attachmentButtonWrapper:C.attachmentButtonWrapper,attachmentInput:C.attachmentInput,attachmentPreviewsContainer:C.attachmentPreviewsContainer,actionsRow:C.actionsRow,leftActions:C.leftActions,rightActions:C.rightActions}};var yd=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},bd=320,xd=320,vd=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Cd=(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,d)=>{var p;let c=h("img");c.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${bd}px`,c.style.maxHeight=`${xd}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let u=!1;s+=1,c.addEventListener("error",()=>{u||(u=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{u=!0}),yd(i.image)?(c.src=i.image,n.appendChild(c)):(u=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},wr=()=>{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-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",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},Dl=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:wr};if(r){let s=r(n);if(s!==null)return s}return wr()},wd=(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},Bl=(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},Sd=(e,r="bubble")=>{let t=["vanilla-message-bubble","persona-max-w-[85%]"];switch(r){case"flat":e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("vanilla-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("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("vanilla-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("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("vanilla-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},Nl=(e,r,t)=>{var m,C,T,b,x,M;let n=(m=r.showCopy)!=null?m:!0,s=(C=r.showUpvote)!=null?C:!0,o=(T=r.showDownvote)!=null?T:!0;if(!n&&!s&&!o){let O=h("div");return O.style.display="none",O.id=`actions-${e.id}`,O.setAttribute("data-actions-for",e.id),O}let a=(b=r.visibility)!=null?b:"hover",i=(x=r.align)!=null?x:"right",d=(M=r.layout)!=null?M:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(O,A,W)=>{let _=Ft({icon:O,label:A,size:14,className:"persona-message-action-btn"});return _.setAttribute("data-action",W),_};return n&&p.appendChild(f("copy","Copy message","copy")),s&&p.appendChild(f("thumbs-up","Upvote","upvote")),o&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},ao=(e,r,t,n,s,o)=>{var de,z,ne,Ae,le,Ee,ie;let a=t!=null?t:{},i=(de=a.layout)!=null?de:"bubble",d=a.avatar,c=a.timestamp,u=(z=d==null?void 0:d.show)!=null?z:!1,p=(ne=c==null?void 0:c.show)!=null?ne:!1,f=(Ae=d==null?void 0:d.position)!=null?Ae:"left",m=(le=c==null?void 0:c.position)!=null?le:"below",C=Sd(e.role,i),T=h("div",C.join(" "));T.id=`bubble-${e.id}`,T.setAttribute("data-message-id",e.id),T.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(T.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",T.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(T.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",T.style.color="var(--persona-message-assistant-text, var(--persona-text))");let b=vd(e),x=(ie=(Ee=e.content)==null?void 0:Ee.trim())!=null?ie:"",O=b.length>0&&x===Wo,A=document.createElement("div");A.classList.add("persona-message-content");let W=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),_=null;if(O?(_=document.createElement("div"),_.innerHTML=W,_.style.display="none",A.appendChild(_)):A.innerHTML=W,p&&m==="inline"&&e.createdAt){let K=Bl(e,c);K.classList.add("persona-ml-2","persona-inline"),A.appendChild(K)}if(b.length>0){let K=Cd(b,!O&&!!x,()=>{O&&_&&(_.style.display="")});K?T.appendChild(K):O&&_&&(_.style.display="")}if(T.appendChild(A),p&&m==="below"&&e.createdAt){let K=Bl(e,c);K.classList.add("persona-mt-1"),T.appendChild(K)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let K=Dl("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);K&&T.appendChild(K)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let K=Nl(e,n,s);T.appendChild(K)}if(!u||e.role==="system")return T;let q=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),fe=wd(d,e.role);return f==="right"||f==="left"&&e.role==="user"?q.append(T,fe):q.append(fe,T),T.classList.remove("persona-max-w-[85%]"),T.classList.add("persona-max-w-[calc(85%-2.5rem)]"),q},Ad=(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}):ao(e,r,t,n,s,o)};var Sr=new Set,Ol=(e,r)=>{let t=Sr.has(e),n=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t");if(!n||!s)return;n.setAttribute("aria-expanded",t?"true":"false");let o=n.querySelector(".persona-ml-auto"),a=o==null?void 0:o.querySelector(":scope > .persona-flex.persona-items-center");if(a){a.innerHTML="";let d=me(t?"chevron-up":"chevron-down",16,"currentColor",2);d?a.appendChild(d):a.textContent=t?"Hide":"Show"}s.style.display=t?"":"none"},ys=e=>{let r=e.reasoning,t=h("div",["vanilla-message-bubble","vanilla-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(t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),!r)return t;let n=Sr.has(e.id),s=h("button","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");s.type="button",s.setAttribute("aria-expanded",n?"true":"false"),s.setAttribute("data-expand-header","true"),s.setAttribute("data-bubble-type","reasoning");let o=h("div","persona-flex persona-flex-col persona-text-left"),a=h("span","persona-text-xs persona-text-persona-primary");a.textContent="Thinking...",o.appendChild(a);let i=h("span","persona-text-xs persona-text-persona-primary");i.textContent=dl(r),o.appendChild(i),r.status==="complete"?a.style.display="none":a.style.display="";let d=h("div","persona-flex persona-items-center"),u=me(n?"chevron-up":"chevron-down",16,"currentColor",2);u?d.appendChild(u):d.textContent=n?"Hide":"Show";let p=h("div","persona-flex persona-items-center persona-ml-auto");p.append(d),s.append(o,p);let f=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");f.style.display=n?"":"none";let m=r.chunks.join(""),C=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return C.textContent=m||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(C),(()=>{s.setAttribute("aria-expanded",n?"true":"false"),d.innerHTML="";let x=me(n?"chevron-up":"chevron-down",16,"currentColor",2);x?d.appendChild(x):d.textContent=n?"Hide":"Show",f.style.display=n?"":"none"})(),t.append(s,f),t};var Ar=new Set,Fl=(e,r,t)=>{var c;let n=Ar.has(e),s=(c=t==null?void 0:t.toolCall)!=null?c:{},o=r.querySelector('button[data-expand-header="true"]'),a=r.querySelector(".persona-border-t");if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto"),d=i==null?void 0:i.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let u=s.toggleTextColor||s.headerTextColor||"currentColor",p=me(n?"chevron-up":"chevron-down",16,u,2);p?d.appendChild(p):d.textContent=n?"Hide":"Show"}a.style.display=n?"":"none"},bs=(e,r)=>{var T;let t=e.toolCall,n=(T=r==null?void 0:r.toolCall)!=null?T:{},s=h("div",["vanilla-message-bubble","vanilla-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=Ar.has(e.id),a=h("button","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");a.type="button",a.setAttribute("aria-expanded",o?"true":"false"),a.setAttribute("data-expand-header","true"),a.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(a.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(a.style.paddingLeft=n.headerPaddingX,a.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(a.style.paddingTop=n.headerPaddingY,a.style.paddingBottom=n.headerPaddingY);let i=h("div","persona-flex persona-flex-col persona-text-left"),d=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(d.style.color=n.headerTextColor),d.textContent=pl(t),i.appendChild(d);let c=h("div","persona-flex persona-items-center"),u=n.toggleTextColor||n.headerTextColor||"currentColor",p=me(o?"chevron-up":"chevron-down",16,u,2);p?c.appendChild(p):c.textContent=o?"Hide":"Show";let f=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");f.append(c),a.append(i,f);let m=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(m.style.display=o?"":"none",n.contentBackgroundColor&&(m.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(m.style.color=n.contentTextColor),n.contentPaddingX&&(m.style.paddingLeft=n.contentPaddingX,m.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(m.style.paddingTop=n.contentPaddingY,m.style.paddingBottom=n.contentPaddingY),t.name){let b=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?b.style.color=n.contentTextColor:n.headerTextColor&&(b.style.color=n.headerTextColor),b.textContent=t.name,m.appendChild(b)}if(t.args!==void 0){let b=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Arguments";let M=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");M.style.fontSize="0.75rem",M.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(M.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(M.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(M.style.color=n.codeBlockTextColor),M.textContent=Gr(t.args),b.append(x,M),m.appendChild(b)}if(t.chunks&&t.chunks.length){let b=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Activity";let M=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");M.style.fontSize="0.75rem",M.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(M.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(M.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(M.style.color=n.codeBlockTextColor),M.textContent=t.chunks.join(`
16
+ `),b.append(x,M),m.appendChild(b)}if(t.status==="complete"&&t.result!==void 0){let b=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Result";let M=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");M.style.fontSize="0.75rem",M.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(M.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(M.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(M.style.color=n.codeBlockTextColor),M.textContent=Gr(t.result),b.append(x,M),m.appendChild(b)}if(t.status==="complete"&&typeof t.duration=="number"){let b=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(b.style.color=n.contentTextColor),b.textContent=`Duration: ${t.duration}ms`,m.appendChild(b)}return(()=>{a.setAttribute("aria-expanded",o?"true":"false"),c.innerHTML="";let b=n.toggleTextColor||n.headerTextColor||"currentColor",x=me(o?"chevron-up":"chevron-down",16,b,2);x?c.appendChild(x):c.textContent=o?"Hide":"Show",m.style.display=o?"":"none"})(),s.append(a,m),s};var xs=(e,r)=>{var T,b,x,M,O,A,W,_,k,q,fe,de;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-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=(T=n==null?void 0:n.backgroundColor)!=null?T:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(b=n==null?void 0:n.borderColor)!=null?b:"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 d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(x=n==null?void 0:n.titleColor)!=null?x:"currentColor",u=me(d,20,c,2);u&&i.appendChild(u);let p=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),m=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(m.style.color=n.titleColor),m.textContent=(M=n==null?void 0:n.title)!=null?M:"Approval Required",f.appendChild(m),!s){let z=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");z.setAttribute("data-approval-status",t.status),t.status==="approved"?(z.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",z.style.color="var(--persona-palette-colors-success-700, #15803d)",z.textContent="Approved"):t.status==="denied"?(z.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",z.style.color="var(--persona-palette-colors-error-700, #b91c1c)",z.textContent="Denied"):t.status==="timeout"&&(z.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",z.style.color="var(--persona-palette-colors-warning-700, #b45309)",z.textContent="Timeout"),f.appendChild(z)}p.appendChild(f);let C=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(C.style.color=n.descriptionColor),C.textContent=t.description,p.appendChild(C),t.parameters){let z=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&&(z.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(z.style.color=n.parameterTextColor),z.style.fontSize="0.75rem",z.style.lineHeight="1rem",z.textContent=Gr(t.parameters),p.appendChild(z)}if(s){let z=h("div","persona-flex persona-gap-2 persona-mt-2");z.setAttribute("data-approval-buttons","true");let ne=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");ne.type="button",ne.style.backgroundColor=(O=n==null?void 0:n.approveButtonColor)!=null?O:"var(--persona-approval-approve-bg, #22c55e)",ne.style.color=(A=n==null?void 0:n.approveButtonTextColor)!=null?A:"#ffffff",ne.setAttribute("data-approval-action","approve");let Ae=me("shield-check",14,(W=n==null?void 0:n.approveButtonTextColor)!=null?W:"#ffffff",2);Ae&&(Ae.style.marginRight="4px",ne.appendChild(Ae));let le=document.createTextNode((_=n==null?void 0:n.approveLabel)!=null?_:"Approve");ne.appendChild(le);let Ee=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");Ee.type="button",Ee.style.backgroundColor=(k=n==null?void 0:n.denyButtonColor)!=null?k:"transparent",Ee.style.color=(q=n==null?void 0:n.denyButtonTextColor)!=null?q:"var(--persona-feedback-error, #dc2626)",Ee.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Ee.setAttribute("data-approval-action","deny");let ie=me("shield-x",14,(fe=n==null?void 0:n.denyButtonTextColor)!=null?fe:"var(--persona-feedback-error, #dc2626)",2);ie&&(ie.style.marginRight="4px",Ee.appendChild(ie));let K=document.createTextNode((de=n==null?void 0:n.denyLabel)!=null?de:"Deny");Ee.appendChild(K),z.append(ne,Ee),p.appendChild(z)}return a.append(i,p),o.appendChild(a),o};var $l=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(m=>m.role==="user"))return;let u=document.createDocumentFragment(),p=s?s.isStreaming():!1,f=m=>{switch(m){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(m=>{let C=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-muted hover:persona-opacity-90 persona-cursor-pointer persona-border persona-border-gray-200");C.type="button",C.textContent=m,C.disabled=p,i!=null&&i.fontFamily&&(C.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(C.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(C.style.paddingLeft=i.paddingX,C.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(C.style.paddingTop=i.paddingY,C.style.paddingBottom=i.paddingY),C.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),u.appendChild(C),r.push(C)}),e.appendChild(u)}}};var io=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 lo=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 Er(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var Ed={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, #dbeafe)",text:"var(--persona-palette-colors-primary-700, #1e40af)"},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)"}},Td={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Md=["flowName","stepName","reasoningText","text","name","tool","toolName"],kd=100;function Ld(e,r){let t={...Ed,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return Td}function Pd(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function Id(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 Wd(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 Rd(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 Hd(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 Bd(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]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=n,i.appendChild(d),i}}function vs(e,r,t,n,s,o,a,i){var f;let d=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");Er(c,(f=n.classNames)==null?void 0:f.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(p()),c;function p(){var ne,Ae;let m=h("div",""),C=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");C.setAttribute("data-event-id",e.id);let T=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),b=me(d?"chevron-down":"chevron-right","14px","currentColor",2);b&&T.appendChild(b);let x=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),M=(ne=n.timestampFormat)!=null?ne:"relative";x.textContent=M==="relative"?Pd(e.timestamp,t):Id(e.timestamp);let O=null;n.showSequenceNumbers!==!1&&(O=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),O.textContent=String(r+1));let A=Ld(e.type,n.badgeColors),W=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");W.style.backgroundColor=A.bg,W.style.color=A.text,W.style.borderColor=A.text+"50",W.textContent=e.type;let _=(Ae=n.descriptionFields)!=null?Ae:Md,k=Wd(e.payload,_),q=null;k&&(q=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),q.textContent=k);let fe=h("div","persona-flex-1 persona-min-w-0"),de=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"),z=me("clipboard","12px","currentColor",1.5);return z&&de.appendChild(z),de.addEventListener("click",async le=>{le.stopPropagation(),await Rd(Hd(e)),de.innerHTML="";let Ee=me("check","12px","currentColor",1.5);Ee&&de.appendChild(Ee),setTimeout(()=>{de.innerHTML="";let ie=me("clipboard","12px","currentColor",1.5);ie&&de.appendChild(ie)},1500)}),C.appendChild(T),C.appendChild(x),O&&C.appendChild(O),C.appendChild(W),q&&C.appendChild(q),C.appendChild(fe),C.appendChild(de),m.appendChild(C),d&&m.appendChild(Bd(e,a,i)),m}}function _l(e){var c,u;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(u=(c=s==null?void 0:s.features)==null?void 0:c.eventStream)!=null?u:{},i=o.find(p=>p.renderEventStreamView);if(i!=null&&i.renderEventStreamView&&s){let p=i.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>d().element,onClose:n});if(p)return{element:p,update:()=>{},destroy:()=>{}}}return d();function d(){let p=a.classNames,f=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Er(f,p==null?void 0:p.panel);let m=[],C="",T="",b=null,x=[],M={},O=0,A=!1,W=0,_=0,k=!1,q=null,fe=!1,de=0,z=new Set,ne=new Map,Ae="",le="",Ee=null,ie,K,be,F,U;function he(){let S=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),V=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");Er(V,p==null?void 0:p.headerBar);let te=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");te.textContent="Events",ie=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"),ie.textContent="0";let $e=h("div","persona-flex-1");K=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 se=h("option","");se.value="",se.textContent="All events",K.appendChild(se),be=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"),be.type="button",be.title="Copy All";let Se=me("clipboard-copy","12px","currentColor",1.5);Se&&be.appendChild(Se);let He=h("span","persona-text-xs");He.textContent="Copy All",be.appendChild(He),V.appendChild(te),V.appendChild(ie),V.appendChild($e),V.appendChild(K),V.appendChild(be);let ke=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Er(ke,p==null?void 0:p.searchBar);let Ke=me("search","14px","var(--persona-muted, #9ca3af)",1.5),et=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");Ke&&et.appendChild(Ke),F=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"),Er(F,p==null?void 0:p.searchInput),F.type="text",F.placeholder="Search event payloads...",U=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"),U.type="button",U.style.display="none";let Ce=me("x","12px","currentColor",2);return Ce&&U.appendChild(Ce),ke.appendChild(et),ke.appendChild(F),ke.appendChild(U),S.appendChild(V),S.appendChild(ke),S}let pt,Ct=o.find(S=>S.renderEventStreamToolbar);if(Ct!=null&&Ct.renderEventStreamToolbar&&s){let S=Ct.renderEventStreamToolbar({config:s,defaultRenderer:()=>he(),eventCount:r.getSize(),filteredCount:0,onFilterChange:V=>{C=V,ee(),Ie()},onSearchChange:V=>{T=V,ee(),Ie()}});pt=S!=null?S:he()}else pt=he();let ut=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");ut.style.display="none";let xt=h("div","persona-flex-1 persona-min-h-0 persona-relative"),Fe=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Fe.style.height="100%";let xe=h("div","persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-bg-persona-accent persona-text-white persona-text-xs persona-px-3 persona-py-1.5 persona-rounded-full persona-cursor-pointer persona-shadow-md persona-z-10 persona-flex persona-items-center persona-gap-1");Er(xe,p==null?void 0:p.scrollIndicator),xe.style.display="none";let ge=me("arrow-down","12px","currentColor",2);ge&&xe.appendChild(ge);let J=h("span","");xe.appendChild(J);let Q=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Q.style.display="none",xt.appendChild(Fe),xt.appendChild(Q),xt.appendChild(xe),f.setAttribute("tabindex","0"),f.appendChild(pt),f.appendChild(ut),f.appendChild(xt);function re(){let S=r.getAll(),V={};for(let He of S)V[He.type]=(V[He.type]||0)+1;let te=Object.keys(V).sort(),$e=te.length!==x.length||!te.every((He,ke)=>He===x[ke]),se=!$e&&te.some(He=>V[He]!==M[He]),ze=S.length!==Object.values(M).reduce((He,ke)=>He+ke,0);if(!$e&&!se&&!ze||(x=te,M=V,!K))return;let Se=K.value;if(K.options[0].textContent="All events",$e){for(;K.options.length>1;)K.remove(1);for(let He of te){let ke=h("option","");ke.value=He,ke.textContent=`${He} (${V[He]||0})`,K.appendChild(ke)}Se&&te.includes(Se)?K.value=Se:Se&&(K.value="",C="")}else for(let He=1;He<K.options.length;He++){let ke=K.options[He];ke.textContent=`${ke.value} (${V[ke.value]||0})`}}function Me(){let S=r.getAll();if(C&&(S=S.filter(V=>V.type===C)),T){let V=T.toLowerCase();S=S.filter(te=>te.type.toLowerCase().includes(V)||te.payload.toLowerCase().includes(V))}return S}function Xe(){return C!==""||T!==""}function ee(){O=0,W=0,A=!1,xe.style.display="none"}function Y(S){z.has(S)?z.delete(S):z.add(S),Ee=S;let V=Fe.scrollTop,te=A;fe=!0,A=!0,Ie(),Fe.scrollTop=V,A=te,fe=!1}function Ve(){return Fe.scrollHeight-Fe.scrollTop-Fe.clientHeight<=50}function Ie(){_=Date.now(),k=!1,re();let S=r.getEvictedCount();S>0?(ut.textContent=`${S.toLocaleString()} older events truncated`,ut.style.display=""):ut.style.display="none",m=Me();let V=m.length,te=r.getSize()>0;ie&&(ie.textContent=String(r.getSize())),V===0&&te&&Xe()?(Q.textContent=T?`No events matching '${T}'`:"No events matching filter",Q.style.display="",Fe.style.display="none"):(Q.style.display="none",Fe.style.display=""),be&&(be.title=Xe()?`Copy Filtered (${V})`:"Copy All"),A&&V>O&&(W+=V-O,J.textContent=`${W} new event${W===1?"":"s"}`,xe.style.display=""),O=V;let $e=r.getAll(),se=$e.length>0?$e[0].timestamp:0,ze=new Set(m.map(ke=>ke.id));for(let ke of z)ze.has(ke)||z.delete(ke);let Se=C!==Ae||T!==le,He=ne.size===0&&m.length>0;if(Se||He||m.length===0){Fe.innerHTML="",ne.clear();let ke=document.createDocumentFragment();for(let Ke=0;Ke<m.length;Ke++){let et=vs(m[Ke],Ke,se,a,z,Y,o,s);ne.set(m[Ke].id,et),ke.appendChild(et)}Fe.appendChild(ke),Ae=C,le=T,Ee=null}else{if(Ee!==null){let Ke=ne.get(Ee);if(Ke&&Ke.parentNode===Fe){let et=m.findIndex(Ce=>Ce.id===Ee);if(et>=0){let Ce=vs(m[et],et,se,a,z,Y,o,s);Fe.insertBefore(Ce,Ke),Ke.remove(),ne.set(Ee,Ce)}}Ee=null}let ke=new Set(m.map(Ke=>Ke.id));for(let[Ke,et]of ne)ke.has(Ke)||(et.remove(),ne.delete(Ke));for(let Ke=0;Ke<m.length;Ke++){let et=m[Ke];if(!ne.has(et.id)){let Ce=vs(et,Ke,se,a,z,Y,o,s);ne.set(et.id,Ce),Fe.appendChild(Ce)}}}A||(Fe.scrollTop=Fe.scrollHeight)}function ft(){if(Date.now()-_>=kd){q!==null&&(cancelAnimationFrame(q),q=null),Ie();return}k||(k=!0,q=requestAnimationFrame(()=>{q=null,Ie()}))}let jt=(S,V)=>{if(!be)return;be.innerHTML="";let te=me(S,"12px","currentColor",1.5);te&&be.appendChild(te);let $e=h("span","persona-text-xs");$e.textContent="Copy All",be.appendChild($e),setTimeout(()=>{be.innerHTML="";let se=me("clipboard-copy","12px","currentColor",1.5);se&&be.appendChild(se);let ze=h("span","persona-text-xs");ze.textContent="Copy All",be.appendChild(ze),be.disabled=!1},V)},zt=async()=>{if(be){be.disabled=!0;try{let S;Xe()?S=m:t?(S=await t(),S.length===0&&(S=r.getAll())):S=r.getAll();let V=S.map(te=>{try{return JSON.parse(te.payload)}catch{return te.payload}});await navigator.clipboard.writeText(JSON.stringify(V,null,2)),jt("check",1500)}catch{jt("x",1500)}}},pe=()=>{K&&(C=K.value,ee(),Ie())},ce=()=>{!F||!U||(U.style.display=F.value?"":"none",b&&clearTimeout(b),b=setTimeout(()=>{T=F.value,ee(),Ie()},150))},ot=()=>{!F||!U||(F.value="",T="",U.style.display="none",b&&clearTimeout(b),ee(),Ie())},gt=()=>{if(fe)return;let S=Fe.scrollTop,V=S>de;de=S,Ve()&&V?(A=!1,W=0,xe.style.display="none"):Ve()||(A=!0)},Je=S=>{S.deltaY<0&&(A=!0)},st=()=>{Fe.scrollTop=Fe.scrollHeight,A=!1,W=0,xe.style.display="none"},Ht=S=>{let V=S.target;if(!V||V.closest("button"))return;let te=V.closest("[data-event-id]");if(!te)return;let $e=te.getAttribute("data-event-id");$e&&Y($e)},Lt=S=>{if((S.metaKey||S.ctrlKey)&&S.key==="f"){S.preventDefault(),F==null||F.focus(),F==null||F.select();return}S.key==="Escape"&&(F&&document.activeElement===F?(ot(),F.blur(),f.focus()):n&&n())};be&&be.addEventListener("click",zt),K&&K.addEventListener("change",pe),F&&F.addEventListener("input",ce),U&&U.addEventListener("click",ot),Fe.addEventListener("scroll",gt),Fe.addEventListener("wheel",Je,{passive:!0}),Fe.addEventListener("click",Ht),xe.addEventListener("click",st),f.addEventListener("keydown",Lt);function qt(){b&&clearTimeout(b),q!==null&&(cancelAnimationFrame(q),q=null),k=!1,ne.clear(),be&&be.removeEventListener("click",zt),K&&K.removeEventListener("change",pe),F&&F.removeEventListener("input",ce),U&&U.removeEventListener("click",ot),Fe.removeEventListener("scroll",gt),Fe.removeEventListener("wheel",Je),Fe.removeEventListener("click",Ht),xe.removeEventListener("click",st),f.removeEventListener("keydown",Lt)}return{element:f,update:ft,destroy:qt}}}function jl(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-bg, #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 d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.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, #3b82f6)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(m)}else p.textContent=a;if(c.append(u,p),i.append(d,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 zl=(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:"",d=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:r.config,defaultRenderer:()=>jl(e,r)});if(u)return u}return jl(e,r)};var Cs=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)})}},jn=new Cs;jn.register("PersonaArtifactCard",zl);function Dd(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 ql(e,r){var xt,Fe,xe,ge;let t=(Fe=(xt=e.features)==null?void 0:xt.artifacts)==null?void 0:Fe.layout,s=((xe=t==null?void 0:t.toolbarPreset)!=null?xe:"default")==="document",o=(ge=t==null?void 0:t.panePadding)==null?void 0:ge.trim(),a=e.markdown?hr(e.markdown):null,i=Yr(e.sanitize),d=J=>{let Q=a?a(J):Kr(J);return i?i(Q):Q},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,u=()=>{c==null||c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),z==null||z.hide()};c&&c.addEventListener("click",()=>{var J;u(),(J=r.onDismiss)==null||J.call(r)});let p=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");p.setAttribute("data-persona-theme-zone","artifact-pane"),s&&p.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 m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let C=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");C.type="button",C.textContent="Close",C.setAttribute("aria-label","Close artifacts panel"),C.addEventListener("click",()=>{var J;u(),(J=r.onDismiss)==null||J.call(r)});let T="rendered",b=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),x=s?Ft({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Ft({icon:"eye",label:"Rendered view"}),M=s?Ft({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Ft({icon:"code-2",label:"Source"}),O=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),A=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,W=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,_=t==null?void 0:t.documentToolbarCopyMenuItems,k=!!(W&&_&&_.length>0),q=null,fe,de=null,z=null;if(s&&(A||W)&&!k){if(fe=A?_o({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ft({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W){let J=me("chevron-down",14,"currentColor",2);J&&fe.appendChild(J)}}else s&&k?(q=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),fe=A?_o({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ft({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),de=Ft({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),q.append(fe,de)):s?fe=Ft({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):fe=Ft({icon:"copy",label:"Copy"});let ne=s?Ft({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Ft({icon:"refresh-cw",label:"Refresh"}),Ae=s?Ft({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Ft({icon:"x",label:"Close"}),le=()=>{var Xe,ee,Y;let J=(Xe=U.find(Ve=>Ve.id===he))!=null?Xe:U[U.length-1],Q=(ee=J==null?void 0:J.id)!=null?ee:null,re=(J==null?void 0:J.artifactType)==="markdown"&&(Y=J.markdown)!=null?Y:"",Me=J?JSON.stringify({component:J.component,props:J.props},null,2):"";return{markdown:re,jsonPayload:Me,id:Q}},Ee=async()=>{var Xe;let{markdown:J,jsonPayload:Q}=le(),re=(Xe=U.find(ee=>ee.id===he))!=null?Xe:U[U.length-1],Me=(re==null?void 0:re.artifactType)==="markdown"?J:re?Q:"";try{await navigator.clipboard.writeText(Me)}catch{}};if(fe.addEventListener("click",async()=>{let J=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(J&&k){let{markdown:Q,jsonPayload:re,id:Me}=le();try{await J({actionId:"primary",artifactId:Me,markdown:Q,jsonPayload:re})}catch{}return}await Ee()}),de&&(_!=null&&_.length)){let J=()=>{var re;return(re=p.closest("[data-persona-root]"))!=null?re:document.body},Q=()=>{z=ar({items:_.map(re=>({id:re.id,label:re.label})),onSelect:async re=>{let{markdown:Me,jsonPayload:Xe,id:ee}=le(),Y=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Y?await Y({actionId:re,artifactId:ee,markdown:Me,jsonPayload:Xe}):re==="markdown"||re==="md"?await navigator.clipboard.writeText(Me):re==="json"||re==="source"?await navigator.clipboard.writeText(Xe):await navigator.clipboard.writeText(Me||Xe)}catch{}},anchor:q!=null?q:de,position:"bottom-right",portal:J()})};p.isConnected?Q():requestAnimationFrame(Q),de.addEventListener("click",re=>{re.stopPropagation(),z==null||z.toggle()})}ne.addEventListener("click",async()=>{var J;try{await((J=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:J.call(t))}catch{}Ct()}),Ae.addEventListener("click",()=>{var J;u(),(J=r.onDismiss)==null||J.call(r)});let ie=()=>{s&&(x.setAttribute("aria-pressed",T==="rendered"?"true":"false"),M.setAttribute("aria-pressed",T==="source"?"true":"false"))};x.addEventListener("click",()=>{T="rendered",ie(),Ct()}),M.addEventListener("click",()=>{T="source",ie(),Ct()});let K=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(),b.append(x,M),q?O.append(q,ne,Ae):O.append(fe,ne,Ae),f.append(b,K,O),ie()):(f.appendChild(m),f.appendChild(C)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let be=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"),F=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(be.style.paddingLeft=o,be.style.paddingRight=o,F.style.padding=o),p.appendChild(f),p.appendChild(be),p.appendChild(F);let U=[],he=null,pt=!1,Ct=()=>{var Me,Xe,ee,Y;let J=s&&U.length<=1;be.classList.toggle("persona-hidden",J),be.replaceChildren();for(let Ve of U){let Ie=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");Ie.type="button",Ie.textContent=Ve.title||Ve.id.slice(0,8),Ve.id===he&&Ie.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ie.addEventListener("click",()=>r.onSelect(Ve.id)),be.appendChild(Ie)}F.replaceChildren();let Q=he&&U.find(Ve=>Ve.id===he)||U[U.length-1];if(!Q)return;if(s){let Ve=Q.artifactType==="markdown"?"MD":(Me=Q.component)!=null?Me:"Component",ft=(Q.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";K.textContent=`${ft} \xB7 ${Ve}`}else m.textContent="Artifacts";if(Q.artifactType==="markdown"){if(s&&T==="source"){let Ie=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ie.textContent=(Xe=Q.markdown)!=null?Xe:"",F.appendChild(Ie);return}let Ve=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ve.innerHTML=d((ee=Q.markdown)!=null?ee:""),F.appendChild(Ve);return}let re=Q.component?jn.get(Q.component):void 0;if(re){let Ie={message:{id:Q.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let ft=re((Y=Q.props)!=null?Y:{},Ie);if(ft){F.appendChild(ft);return}}catch{}}F.appendChild(Dd(Q))},ut=()=>{var Q;let J=U.length>0;if(p.classList.toggle("persona-hidden",!J),c){let re=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,Xe=((Q=re==null?void 0:re.classList.contains("persona-artifact-narrow-host"))!=null?Q:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;J&&Xe&&pt?(c.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:c,update(J){var Q,re,Me;U=J.artifacts,he=(Me=(re=J.selectedId)!=null?re:(Q=J.artifacts[J.artifacts.length-1])==null?void 0:Q.id)!=null?Me:null,U.length>0&&(pt=!0),Ct(),ut()},setMobileOpen(J){pt=J,!J&&c?(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ut()}}}function pn(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 Ul(e,r){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!pn(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=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.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 Nd(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 jo(e,r){var d,c,u,p,f,m,C,T,b,x;if(!pn(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"),Nd(e),Ul(e,r);return}let t=(c=(d=r.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"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=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let s=(C=t==null?void 0:t.panePadding)==null?void 0:C.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(T=t==null?void 0:t.documentToolbarIconColor)==null?void 0:T.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(b=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:b.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(x=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:x.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Ul(e,r)}var Vl=["panel","seamless"];function zo(e,r){var i,d,c,u,p,f;for(let m of Vl)e.classList.remove(`persona-artifact-appearance-${m}`);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"),!pn(r))return;let t=(d=(i=r.features)==null?void 0:i.artifacts)==null?void 0:d.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=Vl.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(p=t==null?void 0:t.paneShadow)==null?void 0:p.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 m=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Jl(e,r){var t,n,s;return!r||!pn(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Od(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 Fd(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 $d(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function _d(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function Kl(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 Yl(e,r,t,n,s,o){let a=Od(s,200),i=_d(r,t,n,200);i=Math.max(a,i);let d=Fd(o);return d!==null&&(i=Math.min(i,d)),$d(e,a,i)}var Gl={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"}},ws=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var C,T,b;if(o.dataset.enhanced==="true")return;let a=(C=o.dataset.tvForm)!=null?C:"init";o.dataset.enhanced="true";let i=(T=Gl[a])!=null?T:Gl.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let x=h("p","persona-text-sm persona-text-persona-muted");x.textContent=i.description,d.appendChild(x)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(x=>{var _,k;let M=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");M.htmlFor=`${r.id}-${a}-${x.name}`;let O=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");O.textContent=x.label,M.appendChild(O);let A=(_=x.type)!=null?_:"text",W;A==="textarea"?(W=document.createElement("textarea"),W.rows=3):(W=document.createElement("input"),W.type=A),W.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",W.id=`${r.id}-${a}-${x.name}`,W.name=x.name,W.placeholder=(k=x.placeholder)!=null?k:"",x.required&&(W.required=!0),M.appendChild(W),u.appendChild(M)});let p=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]"),m=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");m.type="submit",m.textContent=(b=i.submitLabel)!=null?b:"Submit",p.appendChild(f),p.appendChild(m),u.appendChild(p),o.replaceChildren(d,u),u.addEventListener("submit",async x=>{var W,_;x.preventDefault();let M=(W=t.formEndpoint)!=null?W:"/form",O=new FormData(u),A={};O.forEach((k,q)=>{A[q]=k}),A.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let k=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let q=await k.json();f.textContent=(_=q.message)!=null?_:"Thanks! We'll be in touch soon.",q.success&&q.nextPrompt&&await n.sendMessage(String(q.nextPrompt))}catch(k){f.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Ss=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,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},qo=new Ss;var bt={apiUrl:"http://localhost:43111/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}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",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:"1px solid #e5e7eb",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",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",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:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},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 Xl(e,r){if(!(!e&&!r))return e?r?no(e,r):e:r}function As(e){var r,t,n,s,o,a,i,d,c,u,p,f,m,C,T,b,x,M,O,A,W;return e?{...bt,...e,theme:Xl(bt.theme,e.theme),darkTheme:Xl(bt.darkTheme,e.darkTheme),launcher:{...bt.launcher,...e.launcher,dock:{...(r=bt.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=bt.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...bt.copy,...e.copy},sendButton:{...bt.sendButton,...e.sendButton},statusIndicator:{...bt.statusIndicator,...e.statusIndicator},voiceRecognition:{...bt.voiceRecognition,...e.voiceRecognition},features:(()=>{var fe,de;let _=(fe=bt.features)==null?void 0:fe.artifacts,k=(de=e.features)==null?void 0:de.artifacts,q=_===void 0&&k===void 0?void 0:{..._,...k,layout:{..._==null?void 0:_.layout,...k==null?void 0:k.layout}};return{...bt.features,...e.features,...q!==void 0?{artifacts:q}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:bt.suggestionChips,suggestionChipsConfig:{...bt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...bt.layout,...e.layout,header:{...(a=bt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=bt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(p=(u=bt.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(T=(C=bt.layout)==null?void 0:C.messages)==null?void 0:T.timestamp,...(x=(b=e.layout)==null?void 0:b.messages)==null?void 0:x.timestamp}},slots:{...(M=bt.layout)==null?void 0:M.slots,...(O=e.layout)==null?void 0:O.slots}},markdown:{...bt.markdown,...e.markdown,options:{...(A=bt.markdown)==null?void 0:A.options,...(W=e.markdown)==null?void 0:W.options}},messageActions:{...bt.messageActions,...e.messageActions}}:bt}var Zl=()=>{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(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var jd=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},zd=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},Uo=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=jd(e),t=zd(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}},Es=e=>typeof e=="string"?e:e==null?"":String(e),Tr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Es(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=Es(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:Es(t.text)}}},Ql=e=>Array.isArray(e)?e.map(r=>String(r)):[],Vo=e=>{let r=new Set(Ql(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(Ql(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,u)=>c||(u==null?void 0:u({text:a,message:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let d={action:i,message:o.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let u=()=>{e.emit("action:resubmit",d)},p=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var qd=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}},Ud=e=>e.map(r=>({...r,streaming:!1})),Ts=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?qd(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?Ud(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 Vd,STR as Jd,OBJ as Kd}from"partial-json";function Yd(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function Gd(e,r){if(!Yd(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 Ms(){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=Vd(t,Jd|Kd),o=Gd(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Xd(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ks(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=jn.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 Zd(){let e=Ms();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ls(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 Ps(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 Qd=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Is(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:d=!0,ratingLabels:c=Qd}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=n,m.appendChild(C);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=s,m.appendChild(T),f.appendChild(m);let b=document.createElement("div");b.className="persona-feedback-rating persona-feedback-rating-csat",b.setAttribute("role","radiogroup"),b.setAttribute("aria-label","Satisfaction rating from 1 to 5");let x=[];for(let _=1;_<=5;_++){let k=document.createElement("button");k.type="button",k.className="persona-feedback-rating-btn persona-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${_} star${_>1?"s":""}: ${c[_-1]}`),k.title=c[_-1],k.dataset.rating=String(_),k.innerHTML=`
17
17
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
18
18
  <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>
19
19
  </svg>
20
- `,k.addEventListener("click",()=>{p=_,x.forEach((q,me)=>{let ce=me<_;q.classList.toggle("selected",ce),q.setAttribute("aria-checked",me===_-1?"true":"false")})}),x.push(k),b.appendChild(k)}f.appendChild(b);let M=null;if(d){let _=document.createElement("div");_.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=o,M.rows=3,M.setAttribute("aria-label","Additional comments"),_.appendChild(M),f.appendChild(_)}let O=document.createElement("div");O.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=i,A.addEventListener("click",()=>{t==null||t(),u.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(p===null){b.classList.add("persona-feedback-shake"),setTimeout(()=>b.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let _=(M==null?void 0:M.value.trim())||void 0;await r(p,_),u.remove()}catch(_){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",_)}}),O.appendChild(A),O.appendChild(W),f.appendChild(O),u.appendChild(f),u}function Ws(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:d=!0,lowLabel:c="Not likely",highLabel:u="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let T=document.createElement("h3");T.className="persona-feedback-title",T.textContent=n,C.appendChild(T);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=s,C.appendChild(b),m.appendChild(C);let x=document.createElement("div");x.className="persona-feedback-rating persona-feedback-rating-nps",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let O=document.createElement("span");O.className="persona-feedback-label-low",O.textContent=c;let A=document.createElement("span");A.className="persona-feedback-label-high",A.textContent=u,M.appendChild(O),M.appendChild(A);let W=document.createElement("div");W.className="persona-feedback-numbers";let _=[];for(let z=0;z<=10;z++){let ne=document.createElement("button");ne.type="button",ne.className="persona-feedback-rating-btn persona-feedback-number-btn",ne.setAttribute("role","radio"),ne.setAttribute("aria-checked","false"),ne.setAttribute("aria-label",`Rating ${z} out of 10`),ne.textContent=String(z),ne.dataset.rating=String(z),z<=6?ne.classList.add("persona-feedback-detractor"):z<=8?ne.classList.add("persona-feedback-passive"):ne.classList.add("persona-feedback-promoter"),ne.addEventListener("click",()=>{f=z,_.forEach((Ee,ie)=>{Ee.classList.toggle("selected",ie===z),Ee.setAttribute("aria-checked",ie===z?"true":"false")})}),_.push(ne),W.appendChild(ne)}x.appendChild(M),x.appendChild(W),m.appendChild(x);let k=null;if(d){let z=document.createElement("div");z.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"),z.appendChild(k),m.appendChild(z)}let q=document.createElement("div");q.className="persona-feedback-actions";let me=document.createElement("button");me.type="button",me.className="persona-feedback-btn persona-feedback-btn-skip",me.textContent=i,me.addEventListener("click",()=>{t==null||t(),p.remove()});let ce=document.createElement("button");return ce.type="button",ce.className="persona-feedback-btn persona-feedback-btn-submit",ce.textContent=a,ce.addEventListener("click",async()=>{if(f===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}ce.disabled=!0,ce.textContent="Submitting...";try{let z=(k==null?void 0:k.value.trim())||void 0;await r(f,z),p.remove()}catch(z){ce.disabled=!1,ce.textContent=a,console.error("[NPS Feedback] Failed to submit:",z)}}),q.appendChild(me),q.appendChild(ce),m.appendChild(q),p.appendChild(m),p}var Mr="persona-chat-history",ep=30*1e3,tp={"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 np(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 d=(s=tp[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{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 rp(e){var r,t,n,s,o,a,i,d,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:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function op(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Rs=e=>!e||typeof e!="object"?{}:{...e},ec=e=>e.map(r=>({...r,streaming:!1})),tc=(e,r,t)=>{let n=e!=null&&e.markdown?hr(e.markdown):null,s=Yr(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,u,p;let a=(c=o.text)!=null?c:"",i=(u=o.message.rawContent)!=null?u: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 d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(p=i!=null?i:o.text)!=null?p:""}):n?d=n(a):d=Kr(a),s?s(d):d}},Hs=(e,r,t)=>{var Se,at,Pt,At,Bt,It,it,ct,Mt,dt,Dt,Zt,ln,qs,Us,Vs,Js,Ks,Ys,Gs,Xs,Zs,Qs,ea,ta,na,ra,oa,sa,aa,ia,la,ca,da,pa,ua,ga,ma;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=As(r),s=qo.getForInstance(n.plugins);n.components&&jn.registerAll(n.components);let o=Zl(),a=(Se=n.storageAdapter)!=null?Se:Ts(),i={},d=null,c=!1,u=l=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(l);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:E}=g;return E&&(c=!0),y}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")d=l.then(g=>{let y=g!=null?g:{messages:[],metadata:{}};return u(y)});else{let g=l!=null?l:{messages:[],metadata:{}},y=u(g);y.metadata&&(i=Rs(y.metadata)),(at=y.messages)!=null&&at.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=u({messages:[],metadata:{}});(Pt=l.messages)!=null&&Pt.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let p=()=>i,f=l=>{var y;i=(y=l({...i}))!=null?y:{},Dr()},m=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Uo],C=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Tr.message,Tr.messageAndClick],T=Vo({parsers:m,handlers:C,getSessionMetadata:p,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let b=(Bt=(At=n.launcher)==null?void 0:At.enabled)!=null?Bt:!0,x=(it=(It=n.launcher)==null?void 0:It.autoExpand)!=null?it:!1,M=(ct=n.autoFocusInput)!=null?ct:!1,O=x,A=b,W=(dt=(Mt=n.layout)==null?void 0:Mt.header)==null?void 0:dt.layout,_=!1,k=b?x:!0,q=!1,me=null,ce=()=>{q=!0,me&&clearTimeout(me),me=setTimeout(()=>{q&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),q=!1)},1e4)},z=tc(n,T,ce),ne=(Zt=(Dt=n.features)==null?void 0:Dt.showReasoning)!=null?Zt:!0,Ee=(qs=(ln=n.features)==null?void 0:ln.showToolCalls)!=null?qs:!0,ie=(Vs=(Us=n.features)==null?void 0:Us.showEventStreamToggle)!=null?Vs:!1,xe=`${(Ks=typeof n.persistState=="object"?(Js=n.persistState)==null?void 0:Js.keyPrefix:void 0)!=null?Ks:"persona-"}event-stream`,J=ie?new lo(xe):null,ve=(Xs=(Gs=(Ys=n.features)==null?void 0:Ys.eventStream)==null?void 0:Gs.maxEvents)!=null?Xs:2e3,F=ie?new io(ve,J):null,K=null,fe=!1,pt=null,Ct=0;J==null||J.open().then(()=>F==null?void 0:F.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ut={onCopy:l=>{var g,y;o.emit("message:copy",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.id,"copy").catch(E=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",E)}),(y=(g=n.messageActions)==null?void 0:g.onCopy)==null||y.call(g,l)},onFeedback:l=>{var g,y;o.emit("message:feedback",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.messageId,l.type).catch(E=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",E)}),(y=(g=n.messageActions)==null?void 0:g.onFeedback)==null||y.call(g,l)}},xt=(Zs=n.statusIndicator)!=null?Zs:{},Fe=l=>{var g,y,E,L;return l==="idle"?(g=xt.idleText)!=null?g:Vt.idle:l==="connecting"?(y=xt.connectingText)!=null?y:Vt.connecting:l==="connected"?(E=xt.connectedText)!=null?E:Vt.connected:l==="error"?(L=xt.errorText)!=null?L:Vt.error:Vt[l]},{wrapper:be,panel:ue}=Rl(n),V=Hl(n,b),{container:Q,body:re,messagesWrapper:Me,suggestions:Xe,textarea:ee,sendButton:Y,sendButtonWrapper:Ve,composerForm:Ie,statusText:ft,introTitle:jt,introSubtitle:zt,closeButton:de,iconHolder:le,headerTitle:ot,headerSubtitle:gt,header:Je,footer:st,actionsRow:Ht,leftActions:Lt,rightActions:qt}=V,S=V.micButton,U=V.micButtonWrapper,te=V.attachmentButton,$e=V.attachmentButtonWrapper,se=V.attachmentInput,ze=V.attachmentPreviewsContainer,Ae=null,He=null,ke=s.find(l=>l.renderHeader);if(ke!=null&&ke.renderHeader){let l=ke.renderHeader({config:n,defaultRenderer:()=>{let g=_n({config:n,showClose:b});return Cr(Q,g,n),g.header},onClose:()=>ht(!1,"user")});if(l){let g=Q.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),Je=l)}}let Ke=()=>{var g,y,E,L;if(!F)return;if(fe=!0,!K&&F&&(K=_l({buffer:F,getFullHistory:()=>F.getAllFromStore(),onClose:()=>et(),config:n,plugins:s})),K&&(re.style.display="none",(g=st.parentNode)==null||g.insertBefore(K.element,st),K.update()),we){we.classList.remove("persona-text-persona-muted"),we.classList.add("persona-text-persona-accent"),we.style.boxShadow="inset 0 0 0 1.5px var(--persona-accent, #3b82f6)";let I=(L=(E=(y=n.features)==null?void 0:y.eventStream)==null?void 0:E.classNames)==null?void 0:L.toggleButtonActive;I&&I.split(/\s+/).forEach(P=>P&&we.classList.add(P))}let l=()=>{if(!fe)return;let I=Date.now();I-Ct>=200&&(K==null||K.update(),Ct=I),pt=requestAnimationFrame(l)};Ct=0,pt=requestAnimationFrame(l),o.emit("eventStream:opened",{timestamp:Date.now()})},et=()=>{var l,g,y;if(fe){if(fe=!1,K&&K.element.remove(),re.style.display="",we){we.classList.remove("persona-text-persona-accent"),we.classList.add("persona-text-persona-muted"),we.style.boxShadow="";let E=(y=(g=(l=n.features)==null?void 0:l.eventStream)==null?void 0:g.classNames)==null?void 0:y.toggleButtonActive;E&&E.split(/\s+/).forEach(L=>L&&we.classList.remove(L))}pt!==null&&(cancelAnimationFrame(pt),pt=null),o.emit("eventStream:closed",{timestamp:Date.now()})}},we=null;if(ie){let l=(ea=(Qs=n.features)==null?void 0:Qs.eventStream)==null?void 0:ea.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");we=h("button",g),we.style.width="28px",we.style.height="28px",we.type="button",we.setAttribute("aria-label","Event Stream"),we.title="Event Stream";let y=ge("activity","18px","currentColor",1.5);y&&we.appendChild(y);let E=V.clearChatButtonWrapper,L=V.closeButtonWrapper,I=E||L;I&&I.parentNode===Je?Je.insertBefore(we,I):Je.appendChild(we),we.addEventListener("click",()=>{fe?et():Ke()})}let qn=l=>{var E,L,I;let g=n.attachments;if(!(g!=null&&g.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 P=l.querySelector("[data-persona-composer-form]");P!=null&&P.parentNode?P.parentNode.insertBefore(y,P):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let P=h("input");P.type="file",P.accept=((E=g.allowedTypes)!=null?E:Rn).join(","),P.multiple=((L=g.maxFiles)!=null?L:4)>1,P.style.display="none",P.setAttribute("aria-label",(I=g.buttonTooltipText)!=null?I:"Attach files"),l.appendChild(P)}},bn=s.find(l=>l.renderComposer);if(bn!=null&&bn.renderComposer){let l=n.composer,g=bn.renderComposer({config:n,defaultRenderer:()=>so({config:n}).footer,onSubmit:y=>{H&&!H.isStreaming()&&H.sendMessage(y)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{se==null||se.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y}},onVoiceToggle:((ta=n.voiceRecognition)==null?void 0:ta.enabled)===!0?()=>{He==null||He()}:void 0});g&&(st.replaceWith(g),st=g)}let Un=l=>{let g=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),E=l.querySelector("[data-persona-composer-submit]"),L=l.querySelector("[data-persona-composer-mic]"),I=l.querySelector("[data-persona-composer-status]");g&&(Ie=g),y&&(ee=y),E&&(Y=E),L&&(S=L,U=L.parentElement),I&&(ft=I);let P=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");P&&(Xe=P);let j=l.querySelector(".persona-attachment-button");j&&(te=j,$e=j.parentElement),se=l.querySelector('input[type="file"]'),ze=l.querySelector(".persona-attachment-previews");let D=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");D&&(Ht=D)};qn(st),Un(st);let Bn=(na=n.layout)==null?void 0:na.contentMaxWidth;Bn&&Ie&&(Ie.style.maxWidth=Bn,Ie.style.marginLeft="auto",Ie.style.marginRight="auto"),(ra=n.attachments)!=null&&ra.enabled&&se&&ze&&(Ae=vr.fromConfig(n.attachments),Ae.setPreviewsContainer(ze),se.addEventListener("change",l=>{let g=l.target;Ae==null||Ae.handleFileSelect(g.files),g.value=""})),(()=>{var E,L;let l=(L=(E=n.layout)==null?void 0:E.slots)!=null?L:{},g=I=>{switch(I){case"body-top":return Q.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Me;case"footer-top":return Xe;case"composer":return Ie;case"footer-bottom":return ft;default:return null}},y=(I,P)=>{var j;switch(I){case"header-left":case"header-center":case"header-right":if(I==="header-left")Je.insertBefore(P,Je.firstChild);else if(I==="header-right")Je.appendChild(P);else{let D=Je.querySelector(".persona-flex-col");D?(j=D.parentNode)==null||j.insertBefore(P,D.nextSibling):Je.appendChild(P)}break;case"body-top":{let D=re.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith(P):re.insertBefore(P,re.firstChild);break}case"body-bottom":re.appendChild(P);break;case"footer-top":Xe.replaceWith(P);break;case"footer-bottom":ft.replaceWith(P);break;default:break}};for(let[I,P]of Object.entries(l))if(P)try{let j=P({config:n,defaultContent:()=>g(I)});j&&y(I,j)}catch(j){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${I}":`,j)}})();let Dn=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let E=y.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!E)return;let L=E.getAttribute("data-message-id");if(!L)return;let I=y.getAttribute("data-bubble-type");I==="reasoning"?(Sr.has(L)?Sr.delete(L):Sr.add(L),Ol(L,E)):I==="tool"&&(Ar.has(L)?Ar.delete(L):Ar.add(L),Fl(L,E,n))};Me.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Dn(l))}),Me.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Dn(l))});let Tn=new Map;Me.addEventListener("click",l=>{var P;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.closest("[data-actions-for]");if(!E)return;let L=E.getAttribute("data-actions-for");if(!L)return;let I=y.getAttribute("data-action");if(I==="copy"){let D=H.getMessages().find(oe=>oe.id===L);if(D&&ut.onCopy){let oe=D.content||"";navigator.clipboard.writeText(oe).then(()=>{y.classList.add("persona-message-action-success");let he=ge("check",14,"currentColor",2);he&&(y.innerHTML="",y.appendChild(he)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Ce=ge("copy",14,"currentColor",2);Ce&&(y.innerHTML="",y.appendChild(Ce))},2e3)}).catch(he=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",he)}),ut.onCopy(D)}}else if(I==="upvote"||I==="downvote")if(((P=Tn.get(L))!=null?P:null)===I)Tn.delete(L),y.classList.remove("persona-message-action-active");else{let oe=I==="upvote"?"downvote":"upvote",he=E.querySelector(`[data-action="${oe}"]`);he&&he.classList.remove("persona-message-action-active"),Tn.set(L,I),y.classList.add("persona-message-action-active");let We=H.getMessages().find(Te=>Te.id===L);We&&ut.onFeedback&&ut.onFeedback({type:I,messageId:We.id,message:We})}}),Me.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.closest(".vanilla-approval-bubble");if(!E)return;let L=E.getAttribute("data-message-id");if(!L)return;let I=y.getAttribute("data-approval-action");if(!I)return;let P=I==="approve"?"approved":"denied",D=H.getMessages().find(he=>he.id===L);if(!(D!=null&&D.approval))return;let oe=E.querySelector("[data-approval-buttons]");oe&&oe.querySelectorAll("button").forEach(Ce=>{Ce.disabled=!0,Ce.style.opacity="0.5",Ce.style.cursor="not-allowed"}),H.resolveApproval(D.approval,P)});let Ze=null,nn=null,G={artifacts:[],selectedId:null},Jt=!1,Vn={current:null};Me.addEventListener("click",l=>{var Ce,We,Te,R,Le;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.getAttribute("data-download-artifact");if(!E||((Te=(We=(Ce=n.features)==null?void 0:Ce.artifacts)==null?void 0:We.onArtifactAction)==null?void 0:Te.call(We,{type:"download",artifactId:E}))===!0)return;let I=H.getArtifactById(E),P=I==null?void 0:I.markdown,j=(I==null?void 0:I.title)||"artifact";if(!P){let Pe=y.closest("[data-open-artifact]"),ae=Pe==null?void 0:Pe.closest("[data-message-id]"),Re=ae==null?void 0:ae.getAttribute("data-message-id");if(Re){let qe=H.getMessages().find(pe=>pe.id===Re);if(qe!=null&&qe.rawContent)try{let pe=JSON.parse(qe.rawContent);P=(R=pe==null?void 0:pe.props)==null?void 0:R.markdown,j=((Le=pe==null?void 0:pe.props)==null?void 0:Le.title)||j}catch{}}}if(!P)return;let D=new Blob([P],{type:"text/markdown"}),oe=URL.createObjectURL(D),he=document.createElement("a");he.href=oe,he.download=`${j}.md`,he.click(),URL.revokeObjectURL(oe)}),Me.addEventListener("click",l=>{var I,P,j;let y=l.target.closest("[data-open-artifact]");if(!y)return;let E=y.getAttribute("data-open-artifact");!E||((j=(P=(I=n.features)==null?void 0:I.artifacts)==null?void 0:P.onArtifactAction)==null?void 0:j.call(P,{type:"open",artifactId:E}))===!0||(l.preventDefault(),l.stopPropagation(),H.selectArtifact(E),vn())}),Me.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;g.hasAttribute("data-open-artifact")&&(l.preventDefault(),g.click())});let xn=null,mt=null,sn=null,Mn=null,Lr=()=>{};function lr(){Mn==null||Mn(),Mn=null}let Pr=()=>{var P;if(!xn||!mt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((P=e.ownerDocument.defaultView)!=null?P:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){mt.style.removeProperty("position"),mt.style.removeProperty("left"),mt.style.removeProperty("top"),mt.style.removeProperty("bottom"),mt.style.removeProperty("width"),mt.style.removeProperty("z-index");return}let E=xn.firstElementChild;if(!E||E===mt)return;let L=10;mt.style.position="absolute",mt.style.top="0",mt.style.bottom="0",mt.style.width=`${L}px`,mt.style.zIndex="5";let I=E.offsetWidth-L/2;mt.style.left=`${Math.max(0,I)}px`},Jn=()=>{},vn=()=>{var y,E,L,I,P;if(!Ze||!pn(n))return;jo(e,n),zo(e,n),Jn();let l=(I=(L=(E=(y=n.features)==null?void 0:y.artifacts)==null?void 0:E.layout)==null?void 0:L.narrowHostMaxWidth)!=null?I:520,g=ue.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l),Ze.update(G),Jt?(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),(P=Ze.backdrop)==null||P.classList.add("persona-hidden")):G.artifacts.length>0&&(Ze.element.classList.remove("persona-hidden"),Ze.setMobileOpen(!0)),Lr()};if(pn(n)){ue.style.position="relative";let l=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(Q),Ze=ql(n,{onSelect:y=>{var E;return(E=Vn.current)==null?void 0:E.selectArtifact(y)},onDismiss:()=>{Jt=!0,vn()}}),Ze.element.classList.add("persona-hidden"),xn=g,g.appendChild(l),g.appendChild(Ze.element),Ze.backdrop&&ue.appendChild(Ze.backdrop),ue.appendChild(g),Lr=()=>{var E,L,I,P;if(!xn||!Ze)return;if(!(((I=(L=(E=n.features)==null?void 0:E.artifacts)==null?void 0:L.layout)==null?void 0:I.resizable)===!0)){sn==null||sn(),sn=null,lr(),mt&&(mt.remove(),mt=null),Ze.element.style.removeProperty("width"),Ze.element.style.removeProperty("maxWidth");return}if(!mt){let j=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");j.setAttribute("role","separator"),j.setAttribute("aria-orientation","vertical"),j.setAttribute("aria-label","Resize artifacts panel"),j.tabIndex=0;let D=e.ownerDocument,oe=(P=D.defaultView)!=null?P:window,he=Ce=>{var ae,Re;if(!Ze||Ce.button!==0||e.classList.contains("persona-artifact-narrow-host")||oe.innerWidth<=640)return;Ce.preventDefault(),lr();let We=Ce.clientX,Te=Ze.element.getBoundingClientRect().width,R=(Re=(ae=n.features)==null?void 0:ae.artifacts)==null?void 0:Re.layout,Le=nt=>{let qe=xn.getBoundingClientRect().width,pe=e.classList.contains("persona-artifact-appearance-seamless"),Wt=pe?0:Kl(xn,oe),lt=pe?0:j.getBoundingClientRect().width||6,Qt=Te-(nt.clientX-We),Ut=Yl(Qt,qe,Wt,lt,R==null?void 0:R.resizableMinWidth,R==null?void 0:R.resizableMaxWidth);Ze.element.style.width=`${Ut}px`,Ze.element.style.maxWidth="none",Pr()},Pe=()=>{D.removeEventListener("pointermove",Le),D.removeEventListener("pointerup",Pe),D.removeEventListener("pointercancel",Pe),Mn=null;try{j.releasePointerCapture(Ce.pointerId)}catch{}};Mn=Pe,D.addEventListener("pointermove",Le),D.addEventListener("pointerup",Pe),D.addEventListener("pointercancel",Pe);try{j.setPointerCapture(Ce.pointerId)}catch{}};j.addEventListener("pointerdown",he),mt=j,xn.insertBefore(j,Ze.element),sn=()=>{j.removeEventListener("pointerdown",he)}}if(mt){let j=G.artifacts.length>0&&!Jt;mt.classList.toggle("persona-hidden",!j),Pr()}},Jn=()=>{var oe,he,Ce,We,Te,R,Le,Pe,ae,Re,nt,qe,pe,Wt;if(!b||!Ze||((he=(oe=n.launcher)==null?void 0:oe.sidebarMode)!=null?he:!1)||_t(n)&&fn(n).reveal==="emerge")return;let E=(Ce=e.ownerDocument.defaultView)!=null?Ce:window,L=(Te=(We=n.launcher)==null?void 0:We.mobileFullscreen)!=null?Te:!0,I=(Le=(R=n.launcher)==null?void 0:R.mobileBreakpoint)!=null?Le:640;if(L&&E.innerWidth<=I||!Jl(n,b))return;let P=(Re=(ae=(Pe=n.launcher)==null?void 0:Pe.width)!=null?ae:n.launcherWidth)!=null?Re:"min(400px, calc(100vw - 24px))",j=(Wt=(pe=(qe=(nt=n.features)==null?void 0:nt.artifacts)==null?void 0:qe.layout)==null?void 0:pe.expandedPanelWidth)!=null?Wt:"min(720px, calc(100vw - 24px))";G.artifacts.length>0&&!Jt?(ue.style.width=j,ue.style.maxWidth=j):(ue.style.width=P,ue.style.maxWidth=P)},typeof ResizeObserver!="undefined"&&(nn=new ResizeObserver(()=>{vn()}),nn.observe(ue))}else ue.appendChild(Q);e.appendChild(be);let Kn=()=>{var Wt,lt,Qt,Ut,Yt,Nt,cn,Ue,vt,Co,wo,So,Ao,Eo,ns,rs,kt,To,jr;let l=_t(n),g=(lt=(Wt=n.launcher)==null?void 0:Wt.sidebarMode)!=null?lt:!1,y=l||g||((Ut=(Qt=n.launcher)==null?void 0:Qt.fullHeight)!=null?Ut:!1),E=((Yt=n.launcher)==null?void 0:Yt.enabled)===!1,L=(cn=(Nt=n.theme)==null?void 0:Nt.components)==null?void 0:cn.panel,I=Fo(n),P=(en,dn)=>{var Mo;return en==null||en===""?dn:(Mo=eo(I,en))!=null?Mo:en},j=(Ue=e.ownerDocument.defaultView)!=null?Ue:window,D=(Co=(vt=n.launcher)==null?void 0:vt.mobileFullscreen)!=null?Co:!0,oe=(So=(wo=n.launcher)==null?void 0:wo.mobileBreakpoint)!=null?So:640,he=j.innerWidth<=oe,Ce=D&&he&&b,We=(Eo=(Ao=n.launcher)==null?void 0:Ao.position)!=null?Eo:"bottom-left",Te=We==="bottom-left"||We==="top-left",R=g||Ce?"none":"1px solid var(--persona-border)",Le=Ce?"none":g?Te?"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&&!Ce&&(Le="none",R="none");let Pe=g||Ce?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ae=P(L==null?void 0:L.border,R),Re=P(L==null?void 0:L.shadow,Le),nt=P(L==null?void 0:L.borderRadius,Pe);if(e.style.cssText="",be.style.cssText="",ue.style.cssText="",Q.style.cssText="",re.style.cssText="",st.style.cssText="",Ce){be.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"),be.style.cssText=`
20
+ `,k.addEventListener("click",()=>{p=_,x.forEach((q,fe)=>{let de=fe<_;q.classList.toggle("selected",de),q.setAttribute("aria-checked",fe===_-1?"true":"false")})}),x.push(k),b.appendChild(k)}f.appendChild(b);let M=null;if(d){let _=document.createElement("div");_.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=o,M.rows=3,M.setAttribute("aria-label","Additional comments"),_.appendChild(M),f.appendChild(_)}let O=document.createElement("div");O.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=i,A.addEventListener("click",()=>{t==null||t(),u.remove()});let W=document.createElement("button");return W.type="button",W.className="persona-feedback-btn persona-feedback-btn-submit",W.textContent=a,W.addEventListener("click",async()=>{if(p===null){b.classList.add("persona-feedback-shake"),setTimeout(()=>b.classList.remove("persona-feedback-shake"),500);return}W.disabled=!0,W.textContent="Submitting...";try{let _=(M==null?void 0:M.value.trim())||void 0;await r(p,_),u.remove()}catch(_){W.disabled=!1,W.textContent=a,console.error("[CSAT Feedback] Failed to submit:",_)}}),O.appendChild(A),O.appendChild(W),f.appendChild(O),u.appendChild(f),u}function Ws(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:d=!0,lowLabel:c="Not likely",highLabel:u="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let T=document.createElement("h3");T.className="persona-feedback-title",T.textContent=n,C.appendChild(T);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=s,C.appendChild(b),m.appendChild(C);let x=document.createElement("div");x.className="persona-feedback-rating persona-feedback-rating-nps",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let O=document.createElement("span");O.className="persona-feedback-label-low",O.textContent=c;let A=document.createElement("span");A.className="persona-feedback-label-high",A.textContent=u,M.appendChild(O),M.appendChild(A);let W=document.createElement("div");W.className="persona-feedback-numbers";let _=[];for(let z=0;z<=10;z++){let ne=document.createElement("button");ne.type="button",ne.className="persona-feedback-rating-btn persona-feedback-number-btn",ne.setAttribute("role","radio"),ne.setAttribute("aria-checked","false"),ne.setAttribute("aria-label",`Rating ${z} out of 10`),ne.textContent=String(z),ne.dataset.rating=String(z),z<=6?ne.classList.add("persona-feedback-detractor"):z<=8?ne.classList.add("persona-feedback-passive"):ne.classList.add("persona-feedback-promoter"),ne.addEventListener("click",()=>{f=z,_.forEach((Ae,le)=>{Ae.classList.toggle("selected",le===z),Ae.setAttribute("aria-checked",le===z?"true":"false")})}),_.push(ne),W.appendChild(ne)}x.appendChild(M),x.appendChild(W),m.appendChild(x);let k=null;if(d){let z=document.createElement("div");z.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"),z.appendChild(k),m.appendChild(z)}let q=document.createElement("div");q.className="persona-feedback-actions";let fe=document.createElement("button");fe.type="button",fe.className="persona-feedback-btn persona-feedback-btn-skip",fe.textContent=i,fe.addEventListener("click",()=>{t==null||t(),p.remove()});let de=document.createElement("button");return de.type="button",de.className="persona-feedback-btn persona-feedback-btn-submit",de.textContent=a,de.addEventListener("click",async()=>{if(f===null){W.classList.add("persona-feedback-shake"),setTimeout(()=>W.classList.remove("persona-feedback-shake"),500);return}de.disabled=!0,de.textContent="Submitting...";try{let z=(k==null?void 0:k.value.trim())||void 0;await r(f,z),p.remove()}catch(z){de.disabled=!1,de.textContent=a,console.error("[NPS Feedback] Failed to submit:",z)}}),q.appendChild(fe),q.appendChild(de),m.appendChild(q),p.appendChild(m),p}var Mr="persona-chat-history",ep=30*1e3,tp={"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 np(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 d=(s=tp[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{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 rp(e){var r,t,n,s,o,a,i,d,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:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function op(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Rs=e=>!e||typeof e!="object"?{}:{...e},ec=e=>e.map(r=>({...r,streaming:!1})),tc=(e,r,t)=>{let n=e!=null&&e.markdown?hr(e.markdown):null,s=Yr(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,u,p;let a=(c=o.text)!=null?c:"",i=(u=o.message.rawContent)!=null?u: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 d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(p=i!=null?i:o.text)!=null?p:""}):n?d=n(a):d=Kr(a),s?s(d):d}},Hs=(e,r,t)=>{var we,at,Pt,At,Bt,It,it,ct,Mt,dt,Dt,Zt,ln,qs,Us,Vs,Js,Ks,Ys,Gs,Xs,Zs,Qs,ea,ta,na,ra,oa,sa,aa,ia,la,ca,da,pa,ua,ga,ma;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=As(r),s=qo.getForInstance(n.plugins);n.components&&jn.registerAll(n.components);let o=Zl(),a=(we=n.storageAdapter)!=null?we:Ts(),i={},d=null,c=!1,u=l=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(l);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:E}=g;return E&&(c=!0),y}return g}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")d=l.then(g=>{let y=g!=null?g:{messages:[],metadata:{}};return u(y)});else{let g=l!=null?l:{messages:[],metadata:{}},y=u(g);y.metadata&&(i=Rs(y.metadata)),(at=y.messages)!=null&&at.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=u({messages:[],metadata:{}});(Pt=l.messages)!=null&&Pt.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let p=()=>i,f=l=>{var y;i=(y=l({...i}))!=null?y:{},Dr()},m=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Uo],C=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Tr.message,Tr.messageAndClick],T=Vo({parsers:m,handlers:C,getSessionMetadata:p,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let b=(Bt=(At=n.launcher)==null?void 0:At.enabled)!=null?Bt:!0,x=(it=(It=n.launcher)==null?void 0:It.autoExpand)!=null?it:!1,M=(ct=n.autoFocusInput)!=null?ct:!1,O=x,A=b,W=(dt=(Mt=n.layout)==null?void 0:Mt.header)==null?void 0:dt.layout,_=!1,k=b?x:!0,q=!1,fe=null,de=()=>{q=!0,fe&&clearTimeout(fe),fe=setTimeout(()=>{q&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),q=!1)},1e4)},z=tc(n,T,de),ne=(Zt=(Dt=n.features)==null?void 0:Dt.showReasoning)!=null?Zt:!0,Ae=(qs=(ln=n.features)==null?void 0:ln.showToolCalls)!=null?qs:!0,le=(Vs=(Us=n.features)==null?void 0:Us.showEventStreamToggle)!=null?Vs:!1,ie=`${(Ks=typeof n.persistState=="object"?(Js=n.persistState)==null?void 0:Js.keyPrefix:void 0)!=null?Ks:"persona-"}event-stream`,K=le?new lo(ie):null,be=(Xs=(Gs=(Ys=n.features)==null?void 0:Ys.eventStream)==null?void 0:Gs.maxEvents)!=null?Xs:2e3,F=le?new io(be,K):null,U=null,he=!1,pt=null,Ct=0;K==null||K.open().then(()=>F==null?void 0:F.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ut={onCopy:l=>{var g,y;o.emit("message:copy",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.id,"copy").catch(E=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",E)}),(y=(g=n.messageActions)==null?void 0:g.onCopy)==null||y.call(g,l)},onFeedback:l=>{var g,y;o.emit("message:feedback",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.messageId,l.type).catch(E=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",E)}),(y=(g=n.messageActions)==null?void 0:g.onFeedback)==null||y.call(g,l)}},xt=(Zs=n.statusIndicator)!=null?Zs:{},Fe=l=>{var g,y,E,L;return l==="idle"?(g=xt.idleText)!=null?g:Vt.idle:l==="connecting"?(y=xt.connectingText)!=null?y:Vt.connecting:l==="connected"?(E=xt.connectedText)!=null?E:Vt.connected:l==="error"?(L=xt.errorText)!=null?L:Vt.error:Vt[l]},{wrapper:xe,panel:ge}=Rl(n),J=Hl(n,b),{container:Q,body:re,messagesWrapper:Me,suggestions:Xe,textarea:ee,sendButton:Y,sendButtonWrapper:Ve,composerForm:Ie,statusText:ft,introTitle:jt,introSubtitle:zt,closeButton:pe,iconHolder:ce,headerTitle:ot,headerSubtitle:gt,header:Je,footer:st,actionsRow:Ht,leftActions:Lt,rightActions:qt}=J,S=J.micButton,V=J.micButtonWrapper,te=J.attachmentButton,$e=J.attachmentButtonWrapper,se=J.attachmentInput,ze=J.attachmentPreviewsContainer,Se=null,He=null,ke=s.find(l=>l.renderHeader);if(ke!=null&&ke.renderHeader){let l=ke.renderHeader({config:n,defaultRenderer:()=>{let g=_n({config:n,showClose:b});return Cr(Q,g,n),g.header},onClose:()=>ht(!1,"user")});if(l){let g=Q.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),Je=l)}}let Ke=()=>{var g,y,E,L;if(!F)return;if(he=!0,!U&&F&&(U=_l({buffer:F,getFullHistory:()=>F.getAllFromStore(),onClose:()=>et(),config:n,plugins:s})),U&&(re.style.display="none",(g=st.parentNode)==null||g.insertBefore(U.element,st),U.update()),Ce){Ce.classList.remove("persona-text-persona-muted"),Ce.classList.add("persona-text-persona-accent"),Ce.style.boxShadow="inset 0 0 0 1.5px var(--persona-accent, #3b82f6)";let I=(L=(E=(y=n.features)==null?void 0:y.eventStream)==null?void 0:E.classNames)==null?void 0:L.toggleButtonActive;I&&I.split(/\s+/).forEach(P=>P&&Ce.classList.add(P))}let l=()=>{if(!he)return;let I=Date.now();I-Ct>=200&&(U==null||U.update(),Ct=I),pt=requestAnimationFrame(l)};Ct=0,pt=requestAnimationFrame(l),o.emit("eventStream:opened",{timestamp:Date.now()})},et=()=>{var l,g,y;if(he){if(he=!1,U&&U.element.remove(),re.style.display="",Ce){Ce.classList.remove("persona-text-persona-accent"),Ce.classList.add("persona-text-persona-muted"),Ce.style.boxShadow="";let E=(y=(g=(l=n.features)==null?void 0:l.eventStream)==null?void 0:g.classNames)==null?void 0:y.toggleButtonActive;E&&E.split(/\s+/).forEach(L=>L&&Ce.classList.remove(L))}pt!==null&&(cancelAnimationFrame(pt),pt=null),o.emit("eventStream:closed",{timestamp:Date.now()})}},Ce=null;if(le){let l=(ea=(Qs=n.features)==null?void 0:Qs.eventStream)==null?void 0:ea.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");Ce=h("button",g),Ce.style.width="28px",Ce.style.height="28px",Ce.type="button",Ce.setAttribute("aria-label","Event Stream"),Ce.title="Event Stream";let y=me("activity","18px","currentColor",1.5);y&&Ce.appendChild(y);let E=J.clearChatButtonWrapper,L=J.closeButtonWrapper,I=E||L;I&&I.parentNode===Je?Je.insertBefore(Ce,I):Je.appendChild(Ce),Ce.addEventListener("click",()=>{he?et():Ke()})}let qn=l=>{var E,L,I;let g=n.attachments;if(!(g!=null&&g.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 P=l.querySelector("[data-persona-composer-form]");P!=null&&P.parentNode?P.parentNode.insertBefore(y,P):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let P=h("input");P.type="file",P.accept=((E=g.allowedTypes)!=null?E:Rn).join(","),P.multiple=((L=g.maxFiles)!=null?L:4)>1,P.style.display="none",P.setAttribute("aria-label",(I=g.buttonTooltipText)!=null?I:"Attach files"),l.appendChild(P)}},bn=s.find(l=>l.renderComposer);if(bn!=null&&bn.renderComposer){let l=n.composer,g=bn.renderComposer({config:n,defaultRenderer:()=>so({config:n}).footer,onSubmit:y=>{H&&!H.isStreaming()&&H.sendMessage(y)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{se==null||se.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y}},onVoiceToggle:((ta=n.voiceRecognition)==null?void 0:ta.enabled)===!0?()=>{He==null||He()}:void 0});g&&(st.replaceWith(g),st=g)}let Un=l=>{let g=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),E=l.querySelector("[data-persona-composer-submit]"),L=l.querySelector("[data-persona-composer-mic]"),I=l.querySelector("[data-persona-composer-status]");g&&(Ie=g),y&&(ee=y),E&&(Y=E),L&&(S=L,V=L.parentElement),I&&(ft=I);let P=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");P&&(Xe=P);let j=l.querySelector(".persona-attachment-button");j&&(te=j,$e=j.parentElement),se=l.querySelector('input[type="file"]'),ze=l.querySelector(".persona-attachment-previews");let D=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");D&&(Ht=D)};qn(st),Un(st);let Bn=(na=n.layout)==null?void 0:na.contentMaxWidth;Bn&&Ie&&(Ie.style.maxWidth=Bn,Ie.style.marginLeft="auto",Ie.style.marginRight="auto"),(ra=n.attachments)!=null&&ra.enabled&&se&&ze&&(Se=vr.fromConfig(n.attachments),Se.setPreviewsContainer(ze),se.addEventListener("change",l=>{let g=l.target;Se==null||Se.handleFileSelect(g.files),g.value=""})),(()=>{var E,L;let l=(L=(E=n.layout)==null?void 0:E.slots)!=null?L:{},g=I=>{switch(I){case"body-top":return Q.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Me;case"footer-top":return Xe;case"composer":return Ie;case"footer-bottom":return ft;default:return null}},y=(I,P)=>{var j;switch(I){case"header-left":case"header-center":case"header-right":if(I==="header-left")Je.insertBefore(P,Je.firstChild);else if(I==="header-right")Je.appendChild(P);else{let D=Je.querySelector(".persona-flex-col");D?(j=D.parentNode)==null||j.insertBefore(P,D.nextSibling):Je.appendChild(P)}break;case"body-top":{let D=re.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");D?D.replaceWith(P):re.insertBefore(P,re.firstChild);break}case"body-bottom":re.appendChild(P);break;case"footer-top":Xe.replaceWith(P);break;case"footer-bottom":ft.replaceWith(P);break;default:break}};for(let[I,P]of Object.entries(l))if(P)try{let j=P({config:n,defaultContent:()=>g(I)});j&&y(I,j)}catch(j){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${I}":`,j)}})();let Dn=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let E=y.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!E)return;let L=E.getAttribute("data-message-id");if(!L)return;let I=y.getAttribute("data-bubble-type");I==="reasoning"?(Sr.has(L)?Sr.delete(L):Sr.add(L),Ol(L,E)):I==="tool"&&(Ar.has(L)?Ar.delete(L):Ar.add(L),Fl(L,E,n))};Me.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Dn(l))}),Me.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Dn(l))});let Tn=new Map;Me.addEventListener("click",l=>{var P;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.closest("[data-actions-for]");if(!E)return;let L=E.getAttribute("data-actions-for");if(!L)return;let I=y.getAttribute("data-action");if(I==="copy"){let D=H.getMessages().find(oe=>oe.id===L);if(D&&ut.onCopy){let oe=D.content||"";navigator.clipboard.writeText(oe).then(()=>{y.classList.add("persona-message-action-success");let ye=me("check",14,"currentColor",2);ye&&(y.innerHTML="",y.appendChild(ye)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ve=me("copy",14,"currentColor",2);ve&&(y.innerHTML="",y.appendChild(ve))},2e3)}).catch(ye=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ye)}),ut.onCopy(D)}}else if(I==="upvote"||I==="downvote")if(((P=Tn.get(L))!=null?P:null)===I)Tn.delete(L),y.classList.remove("persona-message-action-active");else{let oe=I==="upvote"?"downvote":"upvote",ye=E.querySelector(`[data-action="${oe}"]`);ye&&ye.classList.remove("persona-message-action-active"),Tn.set(L,I),y.classList.add("persona-message-action-active");let We=H.getMessages().find(Te=>Te.id===L);We&&ut.onFeedback&&ut.onFeedback({type:I,messageId:We.id,message:We})}}),Me.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.closest(".vanilla-approval-bubble");if(!E)return;let L=E.getAttribute("data-message-id");if(!L)return;let I=y.getAttribute("data-approval-action");if(!I)return;let P=I==="approve"?"approved":"denied",D=H.getMessages().find(ye=>ye.id===L);if(!(D!=null&&D.approval))return;let oe=E.querySelector("[data-approval-buttons]");oe&&oe.querySelectorAll("button").forEach(ve=>{ve.disabled=!0,ve.style.opacity="0.5",ve.style.cursor="not-allowed"}),H.resolveApproval(D.approval,P)});let Ze=null,nn=null,G={artifacts:[],selectedId:null},Jt=!1,Vn={current:null};Me.addEventListener("click",l=>{var ve,We,Te,R,Le;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.getAttribute("data-download-artifact");if(!E||((Te=(We=(ve=n.features)==null?void 0:ve.artifacts)==null?void 0:We.onArtifactAction)==null?void 0:Te.call(We,{type:"download",artifactId:E}))===!0)return;let I=H.getArtifactById(E),P=I==null?void 0:I.markdown,j=(I==null?void 0:I.title)||"artifact";if(!P){let Pe=y.closest("[data-open-artifact]"),ae=Pe==null?void 0:Pe.closest("[data-message-id]"),Re=ae==null?void 0:ae.getAttribute("data-message-id");if(Re){let qe=H.getMessages().find(ue=>ue.id===Re);if(qe!=null&&qe.rawContent)try{let ue=JSON.parse(qe.rawContent);P=(R=ue==null?void 0:ue.props)==null?void 0:R.markdown,j=((Le=ue==null?void 0:ue.props)==null?void 0:Le.title)||j}catch{}}}if(!P)return;let D=new Blob([P],{type:"text/markdown"}),oe=URL.createObjectURL(D),ye=document.createElement("a");ye.href=oe,ye.download=`${j}.md`,ye.click(),URL.revokeObjectURL(oe)}),Me.addEventListener("click",l=>{var I,P,j;let y=l.target.closest("[data-open-artifact]");if(!y)return;let E=y.getAttribute("data-open-artifact");!E||((j=(P=(I=n.features)==null?void 0:I.artifacts)==null?void 0:P.onArtifactAction)==null?void 0:j.call(P,{type:"open",artifactId:E}))===!0||(l.preventDefault(),l.stopPropagation(),H.selectArtifact(E),vn())}),Me.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;g.hasAttribute("data-open-artifact")&&(l.preventDefault(),g.click())});let xn=null,mt=null,sn=null,Mn=null,Lr=()=>{};function lr(){Mn==null||Mn(),Mn=null}let Pr=()=>{var P;if(!xn||!mt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((P=e.ownerDocument.defaultView)!=null?P:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){mt.style.removeProperty("position"),mt.style.removeProperty("left"),mt.style.removeProperty("top"),mt.style.removeProperty("bottom"),mt.style.removeProperty("width"),mt.style.removeProperty("z-index");return}let E=xn.firstElementChild;if(!E||E===mt)return;let L=10;mt.style.position="absolute",mt.style.top="0",mt.style.bottom="0",mt.style.width=`${L}px`,mt.style.zIndex="5";let I=E.offsetWidth-L/2;mt.style.left=`${Math.max(0,I)}px`},Jn=()=>{},vn=()=>{var y,E,L,I,P;if(!Ze||!pn(n))return;jo(e,n),zo(e,n),Jn();let l=(I=(L=(E=(y=n.features)==null?void 0:y.artifacts)==null?void 0:E.layout)==null?void 0:L.narrowHostMaxWidth)!=null?I:520,g=ge.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l),Ze.update(G),Jt?(Ze.setMobileOpen(!1),Ze.element.classList.add("persona-hidden"),(P=Ze.backdrop)==null||P.classList.add("persona-hidden")):G.artifacts.length>0&&(Ze.element.classList.remove("persona-hidden"),Ze.setMobileOpen(!0)),Lr()};if(pn(n)){ge.style.position="relative";let l=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(Q),Ze=ql(n,{onSelect:y=>{var E;return(E=Vn.current)==null?void 0:E.selectArtifact(y)},onDismiss:()=>{Jt=!0,vn()}}),Ze.element.classList.add("persona-hidden"),xn=g,g.appendChild(l),g.appendChild(Ze.element),Ze.backdrop&&ge.appendChild(Ze.backdrop),ge.appendChild(g),Lr=()=>{var E,L,I,P;if(!xn||!Ze)return;if(!(((I=(L=(E=n.features)==null?void 0:E.artifacts)==null?void 0:L.layout)==null?void 0:I.resizable)===!0)){sn==null||sn(),sn=null,lr(),mt&&(mt.remove(),mt=null),Ze.element.style.removeProperty("width"),Ze.element.style.removeProperty("maxWidth");return}if(!mt){let j=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");j.setAttribute("role","separator"),j.setAttribute("aria-orientation","vertical"),j.setAttribute("aria-label","Resize artifacts panel"),j.tabIndex=0;let D=e.ownerDocument,oe=(P=D.defaultView)!=null?P:window,ye=ve=>{var ae,Re;if(!Ze||ve.button!==0||e.classList.contains("persona-artifact-narrow-host")||oe.innerWidth<=640)return;ve.preventDefault(),lr();let We=ve.clientX,Te=Ze.element.getBoundingClientRect().width,R=(Re=(ae=n.features)==null?void 0:ae.artifacts)==null?void 0:Re.layout,Le=nt=>{let qe=xn.getBoundingClientRect().width,ue=e.classList.contains("persona-artifact-appearance-seamless"),Wt=ue?0:Kl(xn,oe),lt=ue?0:j.getBoundingClientRect().width||6,Qt=Te-(nt.clientX-We),Ut=Yl(Qt,qe,Wt,lt,R==null?void 0:R.resizableMinWidth,R==null?void 0:R.resizableMaxWidth);Ze.element.style.width=`${Ut}px`,Ze.element.style.maxWidth="none",Pr()},Pe=()=>{D.removeEventListener("pointermove",Le),D.removeEventListener("pointerup",Pe),D.removeEventListener("pointercancel",Pe),Mn=null;try{j.releasePointerCapture(ve.pointerId)}catch{}};Mn=Pe,D.addEventListener("pointermove",Le),D.addEventListener("pointerup",Pe),D.addEventListener("pointercancel",Pe);try{j.setPointerCapture(ve.pointerId)}catch{}};j.addEventListener("pointerdown",ye),mt=j,xn.insertBefore(j,Ze.element),sn=()=>{j.removeEventListener("pointerdown",ye)}}if(mt){let j=G.artifacts.length>0&&!Jt;mt.classList.toggle("persona-hidden",!j),Pr()}},Jn=()=>{var oe,ye,ve,We,Te,R,Le,Pe,ae,Re,nt,qe,ue,Wt;if(!b||!Ze||((ye=(oe=n.launcher)==null?void 0:oe.sidebarMode)!=null?ye:!1)||_t(n)&&fn(n).reveal==="emerge")return;let E=(ve=e.ownerDocument.defaultView)!=null?ve:window,L=(Te=(We=n.launcher)==null?void 0:We.mobileFullscreen)!=null?Te:!0,I=(Le=(R=n.launcher)==null?void 0:R.mobileBreakpoint)!=null?Le:640;if(L&&E.innerWidth<=I||!Jl(n,b))return;let P=(Re=(ae=(Pe=n.launcher)==null?void 0:Pe.width)!=null?ae:n.launcherWidth)!=null?Re:"min(400px, calc(100vw - 24px))",j=(Wt=(ue=(qe=(nt=n.features)==null?void 0:nt.artifacts)==null?void 0:qe.layout)==null?void 0:ue.expandedPanelWidth)!=null?Wt:"min(720px, calc(100vw - 24px))";G.artifacts.length>0&&!Jt?(ge.style.width=j,ge.style.maxWidth=j):(ge.style.width=P,ge.style.maxWidth=P)},typeof ResizeObserver!="undefined"&&(nn=new ResizeObserver(()=>{vn()}),nn.observe(ge))}else ge.appendChild(Q);e.appendChild(xe);let Kn=()=>{var Wt,lt,Qt,Ut,Yt,Nt,cn,Ue,vt,Co,wo,So,Ao,Eo,ns,rs,kt,To,jr;let l=_t(n),g=(lt=(Wt=n.launcher)==null?void 0:Wt.sidebarMode)!=null?lt:!1,y=l||g||((Ut=(Qt=n.launcher)==null?void 0:Qt.fullHeight)!=null?Ut:!1),E=((Yt=n.launcher)==null?void 0:Yt.enabled)===!1,L=(cn=(Nt=n.theme)==null?void 0:Nt.components)==null?void 0:cn.panel,I=Fo(n),P=(en,dn)=>{var Mo;return en==null||en===""?dn:(Mo=eo(I,en))!=null?Mo:en},j=(Ue=e.ownerDocument.defaultView)!=null?Ue:window,D=(Co=(vt=n.launcher)==null?void 0:vt.mobileFullscreen)!=null?Co:!0,oe=(So=(wo=n.launcher)==null?void 0:wo.mobileBreakpoint)!=null?So:640,ye=j.innerWidth<=oe,ve=D&&ye&&b,We=(Eo=(Ao=n.launcher)==null?void 0:Ao.position)!=null?Eo:"bottom-left",Te=We==="bottom-left"||We==="top-left",R=g||ve?"none":"1px solid var(--persona-border)",Le=ve?"none":g?Te?"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&&!ve&&(Le="none",R="none");let Pe=g||ve?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ae=P(L==null?void 0:L.border,R),Re=P(L==null?void 0:L.shadow,Le),nt=P(L==null?void 0:L.borderRadius,Pe);if(e.style.cssText="",xe.style.cssText="",ge.style.cssText="",Q.style.cssText="",re.style.cssText="",st.style.cssText="",ve){xe.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"),xe.style.cssText=`
21
21
  position: fixed !important;
22
22
  inset: 0 !important;
23
23
  width: 100% !important;
@@ -28,7 +28,7 @@ import{Marked as Wc}from"marked";var Rc=e=>{if(e)return e},Lo=e=>{var s,o;let r=
28
28
  display: flex !important;
29
29
  flex-direction: column !important;
30
30
  z-index: inherit !important;
31
- `,ue.style.cssText=`
31
+ `,ge.style.cssText=`
32
32
  position: relative !important;
33
33
  display: flex !important;
34
34
  flex-direction: column !important;
@@ -52,7 +52,7 @@ import{Marked as Wc}from"marked";var Rc=e=>{if(e)return e},Lo=e=>{var s,o;let r=
52
52
  overflow: hidden !important;
53
53
  border-radius: 0 !important;
54
54
  border: none !important;
55
- `,re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",st.style.flexShrink="0",_=!0;return}let qe=(rs=(ns=n==null?void 0:n.launcher)==null?void 0:ns.width)!=null?rs:n==null?void 0:n.launcherWidth,pe=qe!=null?qe:"min(400px, calc(100vw - 24px))";if(!g&&!l)E&&y?(ue.style.width="100%",ue.style.maxWidth="100%"):(ue.style.width=pe,ue.style.maxWidth=pe);else if(l)if(fn(n).reveal==="emerge"){let dn=fn(n).width;ue.style.width=dn,ue.style.maxWidth=dn}else ue.style.width="100%",ue.style.maxWidth="100%";if(Jn(),ue.style.boxShadow=Re,ue.style.borderRadius=nt,Q.style.border=ae,Q.style.borderRadius=nt,l&&!Ce&&(L==null?void 0:L.border)===void 0&&(Q.style.border="none",fn(n).side==="right"?Q.style.borderLeft="1px solid var(--persona-border)":Q.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",E&&(e.style.width="100%"),be.style.display="flex",be.style.flexDirection="column",be.style.flex="1 1 0%",be.style.minHeight="0",be.style.maxHeight="100%",be.style.height="100%",E&&(be.style.overflow="hidden"),ue.style.display="flex",ue.style.flexDirection="column",ue.style.flex="1 1 0%",ue.style.minHeight="0",ue.style.maxHeight="100%",ue.style.height="100%",ue.style.overflow="hidden",Q.style.display="flex",Q.style.flexDirection="column",Q.style.flex="1 1 0%",Q.style.minHeight="0",Q.style.maxHeight="100%",Q.style.overflow="hidden",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",st.style.flexShrink="0"),be.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"),!g&&!E&&!l&&((kt=hn[We])!=null?kt:hn["bottom-right"]).split(" ").forEach(dn=>be.classList.add(dn)),g){let en=(jr=(To=n.launcher)==null?void 0:To.sidebarWidth)!=null?jr:"420px";be.style.cssText=`
55
+ `,re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",st.style.flexShrink="0",_=!0;return}let qe=(rs=(ns=n==null?void 0:n.launcher)==null?void 0:ns.width)!=null?rs:n==null?void 0:n.launcherWidth,ue=qe!=null?qe:"min(400px, calc(100vw - 24px))";if(!g&&!l)E&&y?(ge.style.width="100%",ge.style.maxWidth="100%"):(ge.style.width=ue,ge.style.maxWidth=ue);else if(l)if(fn(n).reveal==="emerge"){let dn=fn(n).width;ge.style.width=dn,ge.style.maxWidth=dn}else ge.style.width="100%",ge.style.maxWidth="100%";if(Jn(),ge.style.boxShadow=Re,ge.style.borderRadius=nt,Q.style.border=ae,Q.style.borderRadius=nt,l&&!ve&&(L==null?void 0:L.border)===void 0&&(Q.style.border="none",fn(n).side==="right"?Q.style.borderLeft="1px solid var(--persona-border)":Q.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",E&&(e.style.width="100%"),xe.style.display="flex",xe.style.flexDirection="column",xe.style.flex="1 1 0%",xe.style.minHeight="0",xe.style.maxHeight="100%",xe.style.height="100%",E&&(xe.style.overflow="hidden"),ge.style.display="flex",ge.style.flexDirection="column",ge.style.flex="1 1 0%",ge.style.minHeight="0",ge.style.maxHeight="100%",ge.style.height="100%",ge.style.overflow="hidden",Q.style.display="flex",Q.style.flexDirection="column",Q.style.flex="1 1 0%",Q.style.minHeight="0",Q.style.maxHeight="100%",Q.style.overflow="hidden",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.overflowY="auto",st.style.flexShrink="0"),xe.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"),!g&&!E&&!l&&((kt=hn[We])!=null?kt:hn["bottom-right"]).split(" ").forEach(dn=>xe.classList.add(dn)),g){let en=(jr=(To=n.launcher)==null?void 0:To.sidebarWidth)!=null?jr:"420px";xe.style.cssText=`
56
56
  position: fixed !important;
57
57
  top: 0 !important;
58
58
  bottom: 0 !important;
@@ -64,7 +64,7 @@ import{Marked as Wc}from"marked";var Rc=e=>{if(e)return e},Lo=e=>{var s,o;let r=
64
64
  display: flex !important;
65
65
  flex-direction: column !important;
66
66
  ${Te?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
67
- `,ue.style.cssText=`
67
+ `,ge.style.cssText=`
68
68
  position: relative !important;
69
69
  display: flex !important;
70
70
  flex-direction: column !important;
@@ -77,7 +77,7 @@ import{Marked as Wc}from"marked";var Rc=e=>{if(e)return e},Lo=e=>{var s,o;let r=
77
77
  padding: 0 !important;
78
78
  box-shadow: ${Re} !important;
79
79
  border-radius: ${nt} !important;
80
- `,ue.style.setProperty("width","100%","important"),ue.style.setProperty("max-width","100%","important"),Q.style.cssText=`
80
+ `,ge.style.setProperty("width","100%","important"),ge.style.setProperty("max-width","100%","important"),Q.style.cssText=`
81
81
  display: flex !important;
82
82
  flex-direction: column !important;
83
83
  flex: 1 1 0% !important;
@@ -92,7 +92,7 @@ import{Marked as Wc}from"marked";var Rc=e=>{if(e)return e},Lo=e=>{var s,o;let r=
92
92
  flex-shrink: 0 !important;
93
93
  border-top: none !important;
94
94
  padding: 8px 16px 12px 16px !important;
95
- `}if(!E&&!l){let en="max-height: -moz-available !important; max-height: stretch !important;",dn=g?"":"padding-top: 1.25em !important;";be.style.cssText+=en+dn}};Kn(),sr(e,n),jo(e,n),zo(e,n);let wt=[];nn&&wt.push(()=>{nn==null||nn.disconnect(),nn=null}),wt.push(()=>{sn==null||sn(),sn=null,lr(),mt&&(mt.remove(),mt=null),Ze==null||Ze.element.style.removeProperty("width"),Ze==null||Ze.element.style.removeProperty("maxWidth")}),ie&&wt.push(()=>{pt!==null&&(cancelAnimationFrame(pt),pt=null),K==null||K.destroy(),K=null,F==null||F.destroy(),F=null,J=null});let Cn=null,Ir=()=>{Cn&&(Cn(),Cn=null),n.colorScheme==="auto"&&(Cn=ms(()=>{sr(e,n)}))};Ir(),wt.push(()=>{Cn&&(Cn(),Cn=null)});let Nn=$l(Xe),wn=null,H,On=!1,Fn=Tl(),Wr=0,kn=!0,Yn=0,Rr=0,Ln=null,Pn=!1,cr=0,dr=!1,co=125,po=2e3,uo=5,Hr=50,pr=new Map,je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Br=(sa=(oa=n.voiceRecognition)==null?void 0:oa.autoResume)!=null?sa:!1,an=l=>{o.emit("voice:state",{active:je.active,source:l,timestamp:Date.now()})},Xt=()=>{f(l=>({...l,voiceState:{active:je.active,timestamp:Date.now(),manuallyDeactivated:je.manuallyDeactivated}}))},go=()=>{var E,L;if(((E=n.voiceRecognition)==null?void 0:E.enabled)===!1)return;let l=Rs(i.voiceState),g=!!l.active,y=Number((L=l.timestamp)!=null?L:0);je.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-y<ep&&setTimeout(()=>{var I,P;je.active||(je.manuallyDeactivated=!1,((P=(I=n.voiceRecognition)==null?void 0:I.provider)==null?void 0:P.type)==="runtype"?H.toggleVoice().then(()=>{je.active=H.isVoiceActive(),an("restore"),H.isVoiceActive()&&$n()}):Qn("restore"))},1e3)},mo=()=>H?ec(H.getMessages()).filter(l=>!l.__skipPersist):[];function Dr(l){if(!(a!=null&&a.save))return;let y={messages:l?ec(l):H?mo():[],metadata:i};try{let E=a.save(y);E instanceof Promise&&E.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",E)}}let Gn=(l=!1)=>{if(!kn)return;let g=Date.now();Pn&&g<cr&&!l||(Pn&&g>=cr&&(Pn=!1),!(!l&&!On)&&(g-Rr<co||(Rr=g,Ln&&cancelAnimationFrame(Ln),Ln=requestAnimationFrame(()=>{Pn||!kn||(dr=!0,re.scrollTop=re.scrollHeight,Yn=re.scrollTop,requestAnimationFrame(()=>{dr=!1}),Ln=null)}))))},In=null,fo=()=>be.querySelector("#persona-scroll-container")||re,ho=(l,g=500)=>{let y=l.scrollTop,E=l.clientHeight,L=l.scrollHeight,I=L-y;if(y+E>=L-2||Math.abs(I)<5)return;In!==null&&(cancelAnimationFrame(In),In=null);let j=performance.now(),D=he=>1-Math.pow(1-he,3),oe=he=>{let Ce=l.scrollHeight;Ce!==L&&(L=Ce,I=L-y);let We=he-j,Te=Math.min(We/g,1),R=D(Te),Le=y+I*R;l.scrollTop=Le,Te<1?In=requestAnimationFrame(oe):(l.scrollTop=l.scrollHeight,In=null)};In=requestAnimationFrame(oe)},yo=l=>{let g=new Map;l.forEach(y=>{let E=pr.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!E&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(E!=null&&E.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(E?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),pr.clear(),g.forEach((y,E)=>{pr.set(E,y)})},Xn=(l,g,y)=>{var he,Ce,We,Te;let E=document.createElement("div"),I=(()=>{var Le;let R=s.find(Pe=>Pe.renderLoadingIndicator);if(R!=null&&R.renderLoadingIndicator)return R.renderLoadingIndicator;if((Le=n.loadingIndicator)!=null&&Le.render)return n.loadingIndicator.render})(),P=new Set;g.forEach(R=>{var pe,Wt;P.add(R.id);let Le=El(R,Wr),Pe=Ml(Fn,R.id,Le);if(Pe){E.appendChild(Pe.cloneNode(!0));return}let ae=null,Re=s.find(lt=>!!(R.variant==="reasoning"&&lt.renderReasoning||R.variant==="tool"&&lt.renderToolCall||R.variant==="approval"&&lt.renderApproval||!R.variant&&lt.renderMessage)),nt=(pe=n.layout)==null?void 0:pe.messages;if(Re)if(R.variant==="reasoning"&&R.reasoning&&Re.renderReasoning){if(!ne)return;ae=Re.renderReasoning({message:R,defaultRenderer:()=>ys(R),config:n})}else if(R.variant==="tool"&&R.toolCall&&Re.renderToolCall){if(!Ee)return;ae=Re.renderToolCall({message:R,defaultRenderer:()=>bs(R,n),config:n})}else if(R.variant==="approval"&&R.approval&&Re.renderApproval){if(n.approval===!1)return;ae=Re.renderApproval({message:R,defaultRenderer:()=>xs(R,n),config:n})}else Re.renderMessage&&(ae=Re.renderMessage({message:R,defaultRenderer:()=>{let lt=ao(R,y,nt,n.messageActions,ut,{loadingIndicatorRenderer:I,widgetConfig:n});return R.role!=="user"&&ws(lt,R,n,H),lt},config:n}));if(!ae&&R.role==="assistant"&&!R.variant&&n.enableComponentStreaming!==!1&&Ls(R)){let Qt=Ps(R);if(Qt){let Ut=ks(Qt,{config:n,message:R,transform:y});if(Ut)if(n.wrapComponentDirectiveInBubble!==!1){let Nt=document.createElement("div");if(Nt.className=["vanilla-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Nt.id=`bubble-${R.id}`,Nt.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let cn=document.createElement("div");cn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",cn.innerHTML=y({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Nt.appendChild(cn)}Nt.appendChild(Ut),ae=Nt}else{let Nt=document.createElement("div");if(Nt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Nt.id=`bubble-${R.id}`,Nt.setAttribute("data-message-id",R.id),Nt.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let cn=document.createElement("div");cn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",cn.innerHTML=y({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Nt.appendChild(cn)}Nt.appendChild(Ut),ae=Nt}}}if(!ae)if(R.variant==="reasoning"&&R.reasoning){if(!ne)return;ae=ys(R)}else if(R.variant==="tool"&&R.toolCall){if(!Ee)return;ae=bs(R,n)}else if(R.variant==="approval"&&R.approval){if(n.approval===!1)return;ae=xs(R,n)}else{let lt=(Wt=n.layout)==null?void 0:Wt.messages;lt!=null&&lt.renderUserMessage&&R.role==="user"?ae=lt.renderUserMessage({message:R,config:n,streaming:!!R.streaming}):lt!=null&&lt.renderAssistantMessage&&R.role==="assistant"?ae=lt.renderAssistantMessage({message:R,config:n,streaming:!!R.streaming}):ae=ao(R,y,lt,n.messageActions,ut,{loadingIndicatorRenderer:I,widgetConfig:n}),R.role!=="user"&&ae&&ws(ae,R,n,H)}let qe=document.createElement("div");qe.className="persona-flex",qe.id=`wrapper-${R.id}`,qe.setAttribute("data-wrapper-id",R.id),R.role==="user"&&qe.classList.add("persona-justify-end"),(ae==null?void 0:ae.getAttribute("data-persona-component-directive"))==="true"&&qe.classList.add("persona-w-full"),qe.appendChild(ae),kl(Fn,R.id,Le,qe),E.appendChild(qe)}),Ll(Fn,P);let j=g.some(R=>R.role==="assistant"&&R.streaming),D=g[g.length-1],oe=(D==null?void 0:D.role)==="assistant"&&!D.streaming&&D.variant!=="approval";if(On&&g.some(R=>R.role==="user")&&!j&&!oe){let R={config:n,streaming:!0,location:"standalone",defaultRenderer:wr},Le=s.find(ae=>ae.renderLoadingIndicator),Pe=null;if(Le!=null&&Le.renderLoadingIndicator&&(Pe=Le.renderLoadingIndicator(R)),Pe===null&&((he=n.loadingIndicator)!=null&&he.render)&&(Pe=n.loadingIndicator.render(R)),Pe===null&&(Pe=wr()),Pe){let ae=document.createElement("div"),Re=((Ce=n.loadingIndicator)==null?void 0:Ce.showBubble)!==!1;ae.className=Re?["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(" "),ae.setAttribute("data-typing-indicator","true"),ae.appendChild(Pe);let nt=document.createElement("div");nt.className="persona-flex",nt.id="wrapper-typing-indicator",nt.setAttribute("data-wrapper-id","typing-indicator"),nt.appendChild(ae),E.appendChild(nt)}}if(!On&&g.length>0){let R=g[g.length-1],Le={config:n,lastMessage:R,messageCount:g.length},Pe=s.find(Re=>Re.renderIdleIndicator),ae=null;if(Pe!=null&&Pe.renderIdleIndicator&&(ae=Pe.renderIdleIndicator(Le)),ae===null&&((We=n.loadingIndicator)!=null&&We.renderIdle)&&(ae=n.loadingIndicator.renderIdle(Le)),ae){let Re=document.createElement("div"),nt=((Te=n.loadingIndicator)==null?void 0:Te.showBubble)!==!1;Re.className=nt?["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(" "),Re.setAttribute("data-idle-indicator","true"),Re.appendChild(ae);let qe=document.createElement("div");qe.className="persona-flex",qe.id="wrapper-idle-indicator",qe.setAttribute("data-wrapper-id","idle-indicator"),qe.appendChild(Re),E.appendChild(qe)}}Al(l,E),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let R=fo();ho(R)})})},Zn=()=>{var D,oe,he,Ce,We;if(!b)return;let l=_t(n),g=(D=e.ownerDocument.defaultView)!=null?D:window,y=(he=(oe=n.launcher)==null?void 0:oe.mobileBreakpoint)!=null?he:640,E=(We=(Ce=n.launcher)==null?void 0:Ce.mobileFullscreen)!=null?We:!0,L=g.innerWidth<=y,I=E&&L&&b,P=fn(n).reveal;k?(be.style.removeProperty("display"),be.style.display=l?"flex":"",be.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-95","persona-opacity-0"),ue.classList.add("persona-scale-100","persona-opacity-100"),Ne?Ne.element.style.display="none":_e&&(_e.style.display="none")):(l?l&&(P==="overlay"||P==="push")&&!I?(be.style.removeProperty("display"),be.style.display="flex",be.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(be.style.setProperty("display","none","important"),be.classList.remove("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(be.style.display="",be.classList.add("persona-pointer-events-none","persona-opacity-0"),ue.classList.remove("persona-scale-100","persona-opacity-100"),ue.classList.add("persona-scale-95","persona-opacity-0")),Ne?Ne.element.style.display=l?"none":"":_e&&(_e.style.display=l?"none":""))},ht=(l,g="user")=>{if(!b||k===l)return;let y=k;k=l,Zn(),k&&(Tt(),Gn(!0));let E={open:k,source:g,timestamp:Date.now()};k&&!y?o.emit("widget:opened",E):!k&&y&&o.emit("widget:closed",E),o.emit("widget:state",{open:k,launcherEnabled:b,voiceActive:je.active,streaming:H.isStreaming()})},ur=l=>{Y.disabled=l,S&&(S.disabled=l),Nn.buttons.forEach(g=>{g.disabled=l}),st.dataset.personaComposerStreaming=l?"true":"false",st.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},gr=()=>{je.active||ee&&ee.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>gr(),200)});let Nr=()=>{var g,y,E,L,I,P,j,D,oe,he;jt.textContent=(y=(g=n.copy)==null?void 0:g.welcomeTitle)!=null?y:"Hello \u{1F44B}",zt.textContent=(L=(E=n.copy)==null?void 0:E.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",ee.placeholder=(P=(I=n.copy)==null?void 0:I.inputPlaceholder)!=null?P:"How can I help...",(D=(j=n.sendButton)==null?void 0:j.useIcon)!=null&&D||(Y.textContent=(he=(oe=n.copy)==null?void 0:oe.sendButtonLabel)!=null?he:"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))"};if(n.clientToken&&(n={...n,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(g=>({...g,sessionId:l}))}}),H=new Qr(n,{onMessagesChanged(l){Xn(Me,l,z),H&&(l.some(L=>L.role==="user")?Nn.render([],H,ee,l):Nn.render(n.suggestionChips,H,ee,l,n.suggestionChipsConfig)),Gn(!On),yo(l);let g=[...l].reverse().find(E=>E.role==="user"),y=je.lastUserMessageId;g&&g.id!==y&&(je.lastUserMessageId=g.id,o.emit("user:message",g)),je.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Dr(l)},onStatusChanged(l){var E;let g=(E=n.statusIndicator)!=null?E:{},y=L=>{var I,P,j,D;return L==="idle"?(I=g.idleText)!=null?I:Vt.idle:L==="connecting"?(P=g.connectingText)!=null?P:Vt.connecting:L==="connected"?(j=g.connectedText)!=null?j:Vt.connected:L==="error"?(D=g.errorText)!=null?D:Vt.error:Vt[L]};ft.textContent=y(l)},onStreamingChanged(l){On=l,ur(l),H&&Xn(Me,H.getMessages(),z),l||Gn(!0)},onVoiceStatusChanged(l){var g,y;if(((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype")switch(l){case"listening":break;case"processing":gn(),xo();break;case"speaking":gn(),vo();break;default:l==="idle"&&H.isBargeInActive()?(gn(),$n(),S==null||S.setAttribute("aria-label","End voice session")):(je.active=!1,gn(),an("system"),Xt());break}},onArtifactsState(l){G=l,vn()}}),Vn.current=H,((ia=(aa=n.voiceRecognition)==null?void 0:aa.provider)==null?void 0:ia.type)==="runtype")try{H.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&H.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),F&&H.setSSEEventCallback((l,g)=>{F==null||F.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})}),d&&d.then(l=>{var g;l&&(l.metadata&&(i=Rs(l.metadata),T.syncFromMetadata()),(g=l.messages)!=null&&g.length&&H.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Or=l=>{var L;l.preventDefault();let g=ee.value.trim(),y=(L=Ae==null?void 0:Ae.hasAttachments())!=null?L:!1;if(!g&&!y)return;let E;y&&(E=[],E.push(...Ae.getContentParts()),g&&E.push(ds(g))),ee.value="",ee.style.height="auto",H.sendMessage(g,{contentParts:E}),y&&Ae.clearAttachments()},Fr=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),Y.click())},$r=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!Ae)return;let g=np(l.clipboardData);g.length!==0&&(l.preventDefault(),await Ae.handleFiles(g))},Kt=null,rn=!1,Wn=null,Be=null,_r=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Qn=(l="user")=>{var I,P,j,D,oe,he,Ce,We;if(rn||H.isStreaming())return;let g=_r();if(!g)return;Kt=new g;let E=(P=((I=n.voiceRecognition)!=null?I:{}).pauseDuration)!=null?P:2e3;Kt.continuous=!0,Kt.interimResults=!0,Kt.lang="en-US";let L=ee.value;Kt.onresult=Te=>{let R="",Le="";for(let ae=0;ae<Te.results.length;ae++){let Re=Te.results[ae],nt=Re[0].transcript;Re.isFinal?R+=nt+" ":Le=nt}let Pe=L+R+Le;ee.value=Pe,Wn&&clearTimeout(Wn),(R||Le)&&(Wn=window.setTimeout(()=>{let ae=ee.value.trim();ae&&Kt&&rn&&(un(),ee.value="",ee.style.height="auto",H.sendMessage(ae,{viaVoice:!0}))},E))},Kt.onerror=Te=>{Te.error!=="no-speech"&&un()},Kt.onend=()=>{if(rn){let Te=ee.value.trim();Te&&Te!==L.trim()&&(ee.value="",ee.style.height="auto",H.sendMessage(Te,{viaVoice:!0})),un()}};try{if(Kt.start(),rn=!0,je.active=!0,l!=="system"&&(je.manuallyDeactivated=!1),an(l),Xt(),S){let Te=(j=n.voiceRecognition)!=null?j:{};Be={backgroundColor:S.style.backgroundColor,color:S.style.color,borderColor:S.style.borderColor,iconName:(D=Te.iconName)!=null?D:"mic",iconSize:parseFloat((Ce=(he=Te.iconSize)!=null?he:(oe=n.sendButton)==null?void 0:oe.size)!=null?Ce:"40")||24};let R=(We=Te.recordingBackgroundColor)!=null?We:"#ef4444",Le=Te.recordingIconColor,Pe=Te.recordingBorderColor;if(S.classList.add("persona-voice-recording"),S.style.backgroundColor=R,Le){S.style.color=Le;let ae=S.querySelector("svg");ae&&ae.setAttribute("stroke",Le)}Pe&&(S.style.borderColor=Pe),S.setAttribute("aria-label","Stop voice recognition")}}catch{un("system")}},un=(l="user")=>{if(rn){if(rn=!1,Wn&&(clearTimeout(Wn),Wn=null),Kt){try{Kt.stop()}catch{}Kt=null}if(je.active=!1,an(l),Xt(),S){if(S.classList.remove("persona-voice-recording"),Be){S.style.backgroundColor=Be.backgroundColor,S.style.color=Be.color,S.style.borderColor=Be.borderColor;let g=S.querySelector("svg");g&&g.setAttribute("stroke",Be.color||"currentColor"),Be=null}S.setAttribute("aria-label","Start voice recognition")}}},bo=(l,g)=>{var ae,Re,nt,qe,pe,Wt,lt,Qt;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),E=((ae=l==null?void 0:l.provider)==null?void 0:ae.type)==="runtype";if(!(y||E))return null;let I=h("div","persona-send-button-wrapper"),P=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");P.type="button",P.setAttribute("aria-label","Start voice recognition");let j=(Re=l==null?void 0:l.iconName)!=null?Re:"mic",D=(nt=g==null?void 0:g.size)!=null?nt:"40px",oe=(qe=l==null?void 0:l.iconSize)!=null?qe:D,he=parseFloat(oe)||24,Ce=(pe=l==null?void 0:l.backgroundColor)!=null?pe:g==null?void 0:g.backgroundColor,We=(Wt=l==null?void 0:l.iconColor)!=null?Wt:g==null?void 0:g.textColor;P.style.width=oe,P.style.height=oe,P.style.minWidth=oe,P.style.minHeight=oe,P.style.fontSize="18px",P.style.lineHeight="1";let Te=We||"currentColor",R=ge(j,he,Te,1.5);R?(P.appendChild(R),P.style.color=Te):(P.textContent="\u{1F3A4}",P.style.color=Te),Ce?P.style.backgroundColor=Ce:P.classList.add("persona-bg-persona-primary"),We?P.style.color=We:!We&&!(g!=null&&g.textColor)&&P.classList.add("persona-text-white"),l!=null&&l.borderWidth&&(P.style.borderWidth=l.borderWidth,P.style.borderStyle="solid"),l!=null&&l.borderColor&&(P.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(P.style.paddingLeft=l.paddingX,P.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(P.style.paddingTop=l.paddingY,P.style.paddingBottom=l.paddingY),I.appendChild(P);let Le=(lt=l==null?void 0:l.tooltipText)!=null?lt:"Start voice recognition";if(((Qt=l==null?void 0:l.showTooltip)!=null?Qt:!1)&&Le){let Ut=h("div","persona-send-button-tooltip");Ut.textContent=Le,I.appendChild(Ut)}return{micButton:P,micButtonWrapper:I}},mr=()=>{var g,y,E,L,I;if(!S||Be)return;let l=(g=n.voiceRecognition)!=null?g:{};Be={backgroundColor:S.style.backgroundColor,color:S.style.color,borderColor:S.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((I=(L=l.iconSize)!=null?L:(E=n.sendButton)==null?void 0:E.size)!=null?I:"40")||24}},fr=(l,g)=>{var I,P,j,D,oe;if(!S)return;let y=S.querySelector("svg");y&&y.remove();let E=(oe=Be==null?void 0:Be.iconSize)!=null?oe:parseFloat((D=(j=(I=n.voiceRecognition)==null?void 0:I.iconSize)!=null?j:(P=n.sendButton)==null?void 0:P.size)!=null?D:"40")||24,L=ge(l,E,g,1.5);L&&S.appendChild(L)},er=()=>{S&&S.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},$n=()=>{var L,I;if(!S)return;mr();let l=(L=n.voiceRecognition)!=null?L:{},g=(I=l.recordingBackgroundColor)!=null?I:"#ef4444",y=l.recordingIconColor,E=l.recordingBorderColor;if(er(),S.classList.add("persona-voice-recording"),S.style.backgroundColor=g,y){S.style.color=y;let P=S.querySelector("svg");P&&P.setAttribute("stroke",y)}E&&(S.style.borderColor=E),S.setAttribute("aria-label","Stop voice recognition")},xo=()=>{var j,D,oe,he,Ce,We,Te,R;if(!S)return;mr();let l=(j=n.voiceRecognition)!=null?j:{},g=H.getVoiceInterruptionMode(),y=(D=l.processingIconName)!=null?D:"loader",E=(he=(oe=l.processingIconColor)!=null?oe:Be==null?void 0:Be.color)!=null?he:"",L=(We=(Ce=l.processingBackgroundColor)!=null?Ce:Be==null?void 0:Be.backgroundColor)!=null?We:"",I=(R=(Te=l.processingBorderColor)!=null?Te:Be==null?void 0:Be.borderColor)!=null?R:"";er(),S.classList.add("persona-voice-processing"),S.style.backgroundColor=L,S.style.borderColor=I;let P=E||"currentColor";S.style.color=P,fr(y,P),S.setAttribute("aria-label","Processing voice input"),g==="none"&&(S.style.cursor="default")},vo=()=>{var oe,he,Ce,We,Te,R,Le,Pe,ae,Re,nt,qe;if(!S)return;mr();let l=(oe=n.voiceRecognition)!=null?oe:{},g=H.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",E=(he=l.speakingIconName)!=null?he:y,L=(R=l.speakingIconColor)!=null?R:g==="barge-in"?(We=(Ce=l.recordingIconColor)!=null?Ce:Be==null?void 0:Be.color)!=null?We:"":(Te=Be==null?void 0:Be.color)!=null?Te:"",I=(ae=l.speakingBackgroundColor)!=null?ae:g==="barge-in"?(Le=l.recordingBackgroundColor)!=null?Le:"#ef4444":(Pe=Be==null?void 0:Be.backgroundColor)!=null?Pe:"",P=(qe=l.speakingBorderColor)!=null?qe:g==="barge-in"?(Re=l.recordingBorderColor)!=null?Re:"":(nt=Be==null?void 0:Be.borderColor)!=null?nt:"";er(),S.classList.add("persona-voice-speaking"),S.style.backgroundColor=I,S.style.borderColor=P;let j=L||"currentColor";S.style.color=j,fr(E,j);let D=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";S.setAttribute("aria-label",D),g==="none"&&(S.style.cursor="default"),g==="barge-in"&&S.classList.add("persona-voice-recording")},gn=()=>{var l,g,y;S&&(er(),Be&&(S.style.backgroundColor=(l=Be.backgroundColor)!=null?l:"",S.style.color=(g=Be.color)!=null?g:"",S.style.borderColor=(y=Be.borderColor)!=null?y:"",fr(Be.iconName,Be.color||"currentColor"),Be=null),S.style.cursor="",S.setAttribute("aria-label","Start voice recognition"))},tr=()=>{var l,g;if(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"){let y=H.getVoiceStatus(),E=H.getVoiceInterruptionMode();if(E==="none"&&(y==="processing"||y==="speaking"))return;if(E==="cancel"&&(y==="processing"||y==="speaking")){H.stopVoicePlayback();return}if(H.isBargeInActive()){H.stopVoicePlayback(),H.deactivateBargeIn().then(()=>{je.active=!1,je.manuallyDeactivated=!0,Xt(),an("user"),gn()});return}H.toggleVoice().then(()=>{je.active=H.isVoiceActive(),je.manuallyDeactivated=!H.isVoiceActive(),Xt(),an("user"),H.isVoiceActive()?$n():gn()});return}if(rn){let y=ee.value.trim();je.manuallyDeactivated=!0,Xt(),un("user"),y&&(ee.value="",ee.style.height="auto",H.sendMessage(y))}else je.manuallyDeactivated=!1,Xt(),Qn("user")};He=tr,S&&(S.addEventListener("click",tr),wt.push(()=>{var l,g;((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?(H.isVoiceActive()&&H.toggleVoice(),gn()):un("system"),S&&S.removeEventListener("click",tr)}));let X=o.on("assistant:complete",()=>{Br&&(je.active||je.manuallyDeactivated||Br==="assistant"&&!je.lastUserMessageWasVoice||setTimeout(()=>{var l,g;!je.active&&!je.manuallyDeactivated&&(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?H.toggleVoice().then(()=>{je.active=H.isVoiceActive(),an("auto"),H.isVoiceActive()&&$n()}):Qn("auto"))},600))});wt.push(X);let Ye=o.on("action:resubmit",()=>{setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)});wt.push(Ye);let tt=()=>{ht(!k,"user")},Ne=null,_e=null;if(b){let l=s.find(g=>g.renderLauncher);if(l!=null&&l.renderLauncher){let g=l.renderLauncher({config:n,defaultRenderer:()=>ro(n,tt).element,onToggle:tt});g&&(_e=g)}_e||(Ne=ro(n,tt))}Ne?e.appendChild(Ne.element):_e&&e.appendChild(_e),Zn(),Nn.render(n.suggestionChips,H,ee,void 0,n.suggestionChipsConfig),Nr(),ur(H.isStreaming()),Gn(!0),go(),M&&(b?k&&setTimeout(()=>gr(),200):setTimeout(()=>gr(),0));let Tt=()=>{var D,oe,he,Ce,We,Te,R,Le,Pe,ae,Re,nt,qe;let l=_t(n),g=(oe=(D=n.launcher)==null?void 0:D.sidebarMode)!=null?oe:!1,y=l||g||((Ce=(he=n.launcher)==null?void 0:he.fullHeight)!=null?Ce:!1),E=(We=e.ownerDocument.defaultView)!=null?We:window,L=(R=(Te=n.launcher)==null?void 0:Te.mobileFullscreen)!=null?R:!0,I=(Pe=(Le=n.launcher)==null?void 0:Le.mobileBreakpoint)!=null?Pe:640,P=E.innerWidth<=I,j=L&&P&&b;try{if(j){Kn(),sr(e,n);return}if(_&&(_=!1,Kn(),sr(e,n)),!b&&!l){ue.style.height="",ue.style.width="";return}if(!g&&!l){let pe=(Re=(ae=n==null?void 0:n.launcher)==null?void 0:ae.width)!=null?Re:n==null?void 0:n.launcherWidth,Wt=pe!=null?pe:"min(400px, calc(100vw - 24px))";ue.style.width=Wt,ue.style.maxWidth=Wt}if(Jn(),!y){let pe=E.innerHeight,Wt=64,lt=(qe=(nt=n.launcher)==null?void 0:nt.heightOffset)!=null?qe:0,Qt=Math.max(200,pe-Wt),Ut=Math.min(640,Qt),Yt=Math.max(200,Ut-lt);ue.style.height=`${Yt}px`}}finally{Zn()}};Tt();let St=(la=e.ownerDocument.defaultView)!=null?la:window;St.addEventListener("resize",Tt),wt.push(()=>St.removeEventListener("resize",Tt)),Yn=re.scrollTop;let v=()=>{let l=re.scrollTop,g=re.scrollHeight,y=re.clientHeight,E=g-l-y,L=Math.abs(l-Yn);if(Yn=l,!dr&&!(L<=uo)){if(!kn&&E<Hr){Pn=!1,kn=!0;return}kn&&E>Hr&&(Pn=!0,cr=Date.now()+po,kn=!1)}};re.addEventListener("scroll",v,{passive:!0}),wt.push(()=>re.removeEventListener("scroll",v)),wt.push(()=>{Ln&&cancelAnimationFrame(Ln)});let De=()=>{de&&(wn&&(de.removeEventListener("click",wn),wn=null),b?(de.style.display="",wn=()=>{ht(!1,"user")},de.addEventListener("click",wn)):de.style.display="none")};De(),(()=>{let{clearChatButton:l}=V;l&&l.addEventListener("click",()=>{H.clearMessages(),Fn.clear();try{localStorage.removeItem(Mr),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Mr}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Mr)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 g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),a!=null&&a.clear)try{let y=a.clear();y instanceof Promise&&y.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},T.syncFromMetadata(),F==null||F.clear(),K==null||K.update()})})(),Ie&&Ie.addEventListener("submit",Or),ee==null||ee.addEventListener("keydown",Fr),ee==null||ee.addEventListener("paste",$r),wt.push(()=>{Ie&&Ie.removeEventListener("submit",Or),ee==null||ee.removeEventListener("keydown",Fr),ee==null||ee.removeEventListener("paste",$r)}),wt.push(()=>{H.cancel()}),Ne?wt.push(()=>{Ne==null||Ne.destroy()}):_e&&wt.push(()=>{_e==null||_e.remove()});let w={update(l){var fa,ha,ya,ba,xa,va,Ca,wa,Sa,Aa,Ea,Ta,Ma,ka,La,Pa,Ia,Wa,Ra,Ha,Ba,Da,Na,Oa,Fa,$a,_a,ja,za,qa,Ua,Va,Ja,Ka,Ya,Ga,Xa,Za,Qa,ei,ti,ni,ri,oi,si,ai,ii,li,ci,di,pi,ui,gi,mi,fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Pi,Ii,Wi,Ri,Hi,Bi,Di,Ni,Oi,Fi,$i,_i,ji,zi,qi,Ui,Vi,Ji,Ki,Yi,Gi,Xi,Zi,Qi,el,tl;let g=n.toolCall,y=n.messageActions,E=(fa=n.layout)==null?void 0:fa.messages,L=n.colorScheme,I=n.loadingIndicator,P=n.iterationDisplay;n={...n,...l},Kn(),sr(e,n),jo(e,n),zo(e,n),vn(),n.colorScheme!==L&&Ir();let j=qo.getForInstance(n.plugins);s.length=0,s.push(...j),b=(ya=(ha=n.launcher)==null?void 0:ha.enabled)!=null?ya:!0,x=(xa=(ba=n.launcher)==null?void 0:ba.autoExpand)!=null?xa:!1,ne=(Ca=(va=n.features)==null?void 0:va.showReasoning)!=null?Ca:!0,Ee=(Sa=(wa=n.features)==null?void 0:wa.showToolCalls)!=null?Sa:!0;let D=ie;if(ie=(Ea=(Aa=n.features)==null?void 0:Aa.showEventStreamToggle)!=null?Ea:!1,ie&&!D){if(F||(J=new lo(xe),F=new io(ve,J),J.open().then(()=>F==null?void 0:F.restore()).catch(()=>{}),H.setSSEEventCallback(($,Ge)=>{F.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:$,timestamp:Date.now(),payload:JSON.stringify(Ge)})})),!we&&Je){let $=(Ma=(Ta=n.features)==null?void 0:Ta.eventStream)==null?void 0:Ma.classNames,Ge="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+($!=null&&$.toggleButton?" "+$.toggleButton:"");we=h("button",Ge),we.style.width="28px",we.style.height="28px",we.type="button",we.setAttribute("aria-label","Event Stream"),we.title="Event Stream";let yt=ge("activity","18px","currentColor",1.5);yt&&we.appendChild(yt);let Oe=V.clearChatButtonWrapper,rt=V.closeButtonWrapper,Rt=Oe||rt;Rt&&Rt.parentNode===Je?Je.insertBefore(we,Rt):Je.appendChild(we),we.addEventListener("click",()=>{fe?et():Ke()})}}else!ie&&D&&(et(),we&&(we.remove(),we=null),F==null||F.clear(),J==null||J.destroy(),F=null,J=null);if(((ka=n.launcher)==null?void 0:ka.enabled)===!1&&Ne&&(Ne.destroy(),Ne=null),((La=n.launcher)==null?void 0:La.enabled)===!1&&_e&&(_e.remove(),_e=null),((Pa=n.launcher)==null?void 0:Pa.enabled)!==!1&&!Ne&&!_e){let $=s.find(Ge=>Ge.renderLauncher);if($!=null&&$.renderLauncher){let Ge=$.renderLauncher({config:n,defaultRenderer:()=>ro(n,tt).element,onToggle:tt});Ge&&(_e=Ge,e.appendChild(_e))}_e||(Ne=ro(n,tt),e.appendChild(Ne.element))}Ne&&Ne.update(n),ot&&((Ia=n.launcher)==null?void 0:Ia.title)!==void 0&&(ot.textContent=n.launcher.title),gt&&((Wa=n.launcher)==null?void 0:Wa.subtitle)!==void 0&&(gt.textContent=n.launcher.subtitle);let oe=(Ra=n.layout)==null?void 0:Ra.header;if((oe==null?void 0:oe.layout)!==W&&Je){let $=oe?oo(n,oe,{showClose:b,onClose:()=>ht(!1,"user")}):_n({config:n,showClose:b,onClose:()=>ht(!1,"user")});Je.replaceWith($.header),Je=$.header,le=$.iconHolder,ot=$.headerTitle,gt=$.headerSubtitle,de=$.closeButton,W=oe==null?void 0:oe.layout}else if(oe&&(le&&(le.style.display=oe.showIcon===!1?"none":""),ot&&(ot.style.display=oe.showTitle===!1?"none":""),gt&&(gt.style.display=oe.showSubtitle===!1?"none":""),de&&(de.style.display=oe.showCloseButton===!1?"none":""),V.clearChatButtonWrapper)){let $=oe.showClearChat;if($!==void 0){V.clearChatButtonWrapper.style.display=$?"":"none";let{closeButtonWrapper:Ge}=V;Ge&&!Ge.classList.contains("persona-absolute")&&($?Ge.classList.remove("persona-ml-auto"):Ge.classList.add("persona-ml-auto"))}}let Ce=((Ha=n.layout)==null?void 0:Ha.showHeader)!==!1;Je&&(Je.style.display=Ce?"":"none");let We=((Ba=n.layout)==null?void 0:Ba.showFooter)!==!1;st&&(st.style.display=We?"":"none"),b!==A?b?ht(x,"auto"):(k=!0,Zn()):x!==O&&ht(x,"auto"),O=x,A=b,Tt(),De();let Le=JSON.stringify(l.toolCall)!==JSON.stringify(g),Pe=JSON.stringify(n.messageActions)!==JSON.stringify(y),ae=JSON.stringify((Da=n.layout)==null?void 0:Da.messages)!==JSON.stringify(E),Re=((Na=n.loadingIndicator)==null?void 0:Na.render)!==(I==null?void 0:I.render)||((Oa=n.loadingIndicator)==null?void 0:Oa.renderIdle)!==(I==null?void 0:I.renderIdle)||((Fa=n.loadingIndicator)==null?void 0:Fa.showBubble)!==(I==null?void 0:I.showBubble),nt=n.iterationDisplay!==P;(Le||Pe||ae||Re||nt)&&H&&(Wr++,Xn(Me,H.getMessages(),z));let pe=($a=n.launcher)!=null?$a:{},Wt=(_a=pe.headerIconHidden)!=null?_a:!1,lt=(za=(ja=n.layout)==null?void 0:ja.header)==null?void 0:za.showIcon,Qt=Wt||lt===!1,Ut=pe.headerIconName,Yt=(qa=pe.headerIconSize)!=null?qa:"48px";if(le){let $=Q.querySelector(".persona-border-b-persona-divider"),Ge=$==null?void 0:$.querySelector(".persona-flex-col");if(Qt)le.style.display="none",$&&Ge&&!$.contains(Ge)&&$.insertBefore(Ge,$.firstChild);else{if(le.style.display="",le.style.height=Yt,le.style.width=Yt,$&&Ge&&($.contains(le)?le.nextSibling!==Ge&&(le.remove(),$.insertBefore(le,Ge)):$.insertBefore(le,Ge)),Ut){let Oe=parseFloat(Yt)||24,rt=ge(Ut,Oe*.6,"#ffffff",2);rt?le.replaceChildren(rt):le.textContent=(Ua=pe.agentIconText)!=null?Ua:"\u{1F4AC}"}else if(pe.iconUrl){let Oe=le.querySelector("img");if(Oe)Oe.src=pe.iconUrl,Oe.style.height=Yt,Oe.style.width=Yt;else{let rt=document.createElement("img");rt.src=pe.iconUrl,rt.alt="",rt.className="persona-rounded-xl persona-object-cover",rt.style.height=Yt,rt.style.width=Yt,le.replaceChildren(rt)}}else{let Oe=le.querySelector("svg"),rt=le.querySelector("img");(Oe||rt)&&le.replaceChildren(),le.textContent=(Va=pe.agentIconText)!=null?Va:"\u{1F4AC}"}let yt=le.querySelector("img");yt&&(yt.style.height=Yt,yt.style.width=Yt)}}let Nt=(Ka=(Ja=n.layout)==null?void 0:Ja.header)==null?void 0:Ka.showTitle,cn=(Ga=(Ya=n.layout)==null?void 0:Ya.header)==null?void 0:Ga.showSubtitle;if(ot&&(ot.style.display=Nt===!1?"none":""),gt&&(gt.style.display=cn===!1?"none":""),de){((Za=(Xa=n.layout)==null?void 0:Xa.header)==null?void 0:Za.showCloseButton)===!1?de.style.display="none":de.style.display="";let Ge=(Qa=pe.closeButtonSize)!=null?Qa:"32px",yt=(ei=pe.closeButtonPlacement)!=null?ei:"inline";de.style.height=Ge,de.style.width=Ge;let{closeButtonWrapper:Oe}=V,rt=yt==="top-right",Rt=Oe==null?void 0:Oe.classList.contains("persona-absolute");if(Oe&&rt!==Rt)if(Oe.remove(),rt)Oe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Q.style.position="relative",Q.appendChild(Oe);else{let Qe=(ni=(ti=pe.clearChat)==null?void 0:ti.placement)!=null?ni:"inline",Ot=(oi=(ri=pe.clearChat)==null?void 0:ri.enabled)!=null?oi:!0;Oe.className=Ot&&Qe==="inline"?"":"persona-ml-auto";let tn=Q.querySelector(".persona-border-b-persona-divider");tn&&tn.appendChild(Oe)}if(de.style.color=pe.closeButtonColor||yn.actionIconColor,pe.closeButtonBackgroundColor?(de.style.backgroundColor=pe.closeButtonBackgroundColor,de.classList.remove("hover:persona-bg-gray-100")):(de.style.backgroundColor="",de.classList.add("hover:persona-bg-gray-100")),pe.closeButtonBorderWidth||pe.closeButtonBorderColor){let Qe=pe.closeButtonBorderWidth||"0px",Ot=pe.closeButtonBorderColor||"transparent";de.style.border=`${Qe} solid ${Ot}`,de.classList.remove("persona-border-none")}else de.style.border="",de.classList.add("persona-border-none");pe.closeButtonBorderRadius?(de.style.borderRadius=pe.closeButtonBorderRadius,de.classList.remove("persona-rounded-full")):(de.style.borderRadius="",de.classList.add("persona-rounded-full")),pe.closeButtonPaddingX?(de.style.paddingLeft=pe.closeButtonPaddingX,de.style.paddingRight=pe.closeButtonPaddingX):(de.style.paddingLeft="",de.style.paddingRight=""),pe.closeButtonPaddingY?(de.style.paddingTop=pe.closeButtonPaddingY,de.style.paddingBottom=pe.closeButtonPaddingY):(de.style.paddingTop="",de.style.paddingBottom="");let $t=(si=pe.closeButtonIconName)!=null?si:"x",mn=(ai=pe.closeButtonIconText)!=null?ai:"\xD7";de.innerHTML="";let Gt=ge($t,"20px","currentColor",2);Gt?de.appendChild(Gt):de.textContent=mn;let Et=(ii=pe.closeButtonTooltipText)!=null?ii:"Close chat",on=(li=pe.closeButtonShowTooltip)!=null?li:!0;if(de.setAttribute("aria-label",Et),Oe&&(Oe._cleanupTooltip&&(Oe._cleanupTooltip(),delete Oe._cleanupTooltip),on&&Et)){let Qe=null,Ot=()=>{if(Qe||!de)return;let nr=de.ownerDocument,Vr=nr.body;if(!Vr)return;Qe=An(nr,"div","persona-clear-chat-tooltip"),Qe.textContent=Et;let Jr=An(nr,"div");Jr.className="persona-clear-chat-tooltip-arrow",Qe.appendChild(Jr);let rr=de.getBoundingClientRect();Qe.style.position="fixed",Qe.style.left=`${rr.left+rr.width/2}px`,Qe.style.top=`${rr.top-8}px`,Qe.style.transform="translate(-50%, -100%)",Vr.appendChild(Qe)},tn=()=>{Qe&&Qe.parentNode&&(Qe.parentNode.removeChild(Qe),Qe=null)};Oe.addEventListener("mouseenter",Ot),Oe.addEventListener("mouseleave",tn),de.addEventListener("focus",Ot),de.addEventListener("blur",tn),Oe._cleanupTooltip=()=>{tn(),Oe&&(Oe.removeEventListener("mouseenter",Ot),Oe.removeEventListener("mouseleave",tn)),de&&(de.removeEventListener("focus",Ot),de.removeEventListener("blur",tn))}}}let{clearChatButton:Ue,clearChatButtonWrapper:vt}=V;if(Ue){let $=(ci=pe.clearChat)!=null?ci:{},Ge=(di=$.enabled)!=null?di:!0,yt=(ui=(pi=n.layout)==null?void 0:pi.header)==null?void 0:ui.showClearChat,Oe=yt!==void 0?yt:Ge,rt=(gi=$.placement)!=null?gi:"inline";if(vt){vt.style.display=Oe?"":"none";let{closeButtonWrapper:Rt}=V;Rt&&!Rt.classList.contains("persona-absolute")&&(Oe?Rt.classList.remove("persona-ml-auto"):Rt.classList.add("persona-ml-auto"));let $t=rt==="top-right",mn=vt.classList.contains("persona-absolute");if($t!==mn&&Oe){if(vt.remove(),$t)vt.className="persona-absolute persona-top-4 persona-z-50",vt.style.right="48px",Q.style.position="relative",Q.appendChild(vt);else{vt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",vt.style.right="";let Et=Q.querySelector(".persona-border-b-persona-divider"),on=V.closeButtonWrapper;Et&&on&&on.parentElement===Et?Et.insertBefore(vt,on):Et&&Et.appendChild(vt)}let Gt=V.closeButtonWrapper;Gt&&!Gt.classList.contains("persona-absolute")&&($t?Gt.classList.add("persona-ml-auto"):Gt.classList.remove("persona-ml-auto"))}}if(Oe){let Rt=(mi=$.size)!=null?mi:"32px";Ue.style.height=Rt,Ue.style.width=Rt;let $t=(fi=$.iconName)!=null?fi:"refresh-cw",mn=(hi=$.iconColor)!=null?hi:"";Ue.style.color=mn||yn.actionIconColor,Ue.innerHTML="";let Gt=ge($t,"20px","currentColor",2);if(Gt&&Ue.appendChild(Gt),$.backgroundColor?(Ue.style.backgroundColor=$.backgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),$.borderWidth||$.borderColor){let Qe=$.borderWidth||"0px",Ot=$.borderColor||"transparent";Ue.style.border=`${Qe} solid ${Ot}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");$.borderRadius?(Ue.style.borderRadius=$.borderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),$.paddingX?(Ue.style.paddingLeft=$.paddingX,Ue.style.paddingRight=$.paddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),$.paddingY?(Ue.style.paddingTop=$.paddingY,Ue.style.paddingBottom=$.paddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let Et=(yi=$.tooltipText)!=null?yi:"Clear chat",on=(bi=$.showTooltip)!=null?bi:!0;if(Ue.setAttribute("aria-label",Et),vt&&(vt._cleanupTooltip&&(vt._cleanupTooltip(),delete vt._cleanupTooltip),on&&Et)){let Qe=null,Ot=()=>{if(Qe||!Ue)return;let nr=Ue.ownerDocument,Vr=nr.body;if(!Vr)return;Qe=An(nr,"div","persona-clear-chat-tooltip"),Qe.textContent=Et;let Jr=An(nr,"div");Jr.className="persona-clear-chat-tooltip-arrow",Qe.appendChild(Jr);let rr=Ue.getBoundingClientRect();Qe.style.position="fixed",Qe.style.left=`${rr.left+rr.width/2}px`,Qe.style.top=`${rr.top-8}px`,Qe.style.transform="translate(-50%, -100%)",Vr.appendChild(Qe)},tn=()=>{Qe&&Qe.parentNode&&(Qe.parentNode.removeChild(Qe),Qe=null)};vt.addEventListener("mouseenter",Ot),vt.addEventListener("mouseleave",tn),Ue.addEventListener("focus",Ot),Ue.addEventListener("blur",tn),vt._cleanupTooltip=()=>{tn(),vt&&(vt.removeEventListener("mouseenter",Ot),vt.removeEventListener("mouseleave",tn)),Ue&&(Ue.removeEventListener("focus",Ot),Ue.removeEventListener("blur",tn))}}}}let Co=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Uo],wo=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Tr.message,Tr.messageAndClick];T=Vo({parsers:Co,handlers:wo,getSessionMetadata:p,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),z=tc(n,T,ce),H.updateConfig(n),Xn(Me,H.getMessages(),z),Nn.render(n.suggestionChips,H,ee,void 0,n.suggestionChipsConfig),Nr(),ur(H.isStreaming());let So=((xi=n.voiceRecognition)==null?void 0:xi.enabled)===!0,Ao=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Eo=((Ci=(vi=n.voiceRecognition)==null?void 0:vi.provider)==null?void 0:Ci.type)==="runtype";if(So&&(Ao||Eo))if(!S||!U){let $=bo(n.voiceRecognition,n.sendButton);$&&(S=$.micButton,U=$.micButtonWrapper,qt.insertBefore(U,Ve),S.addEventListener("click",tr),S.disabled=H.isStreaming())}else{let $=(wi=n.voiceRecognition)!=null?wi:{},Ge=(Si=n.sendButton)!=null?Si:{},yt=(Ai=$.iconName)!=null?Ai:"mic",Oe=(Ei=Ge.size)!=null?Ei:"40px",rt=(Ti=$.iconSize)!=null?Ti:Oe,Rt=parseFloat(rt)||24;S.style.width=rt,S.style.height=rt,S.style.minWidth=rt,S.style.minHeight=rt;let $t=(ki=(Mi=$.iconColor)!=null?Mi:Ge.textColor)!=null?ki:"currentColor";S.innerHTML="";let mn=ge(yt,Rt,$t,2);mn?S.appendChild(mn):S.textContent="\u{1F3A4}";let Gt=(Li=$.backgroundColor)!=null?Li:Ge.backgroundColor;Gt?(S.style.backgroundColor=Gt,S.classList.remove("persona-bg-persona-primary")):(S.style.backgroundColor="",S.classList.add("persona-bg-persona-primary")),$t?(S.style.color=$t,S.classList.remove("persona-text-white")):!$t&&!Ge.textColor&&(S.style.color="",S.classList.add("persona-text-white")),$.borderWidth?(S.style.borderWidth=$.borderWidth,S.style.borderStyle="solid"):(S.style.borderWidth="",S.style.borderStyle=""),$.borderColor?S.style.borderColor=$.borderColor:S.style.borderColor="",$.paddingX?(S.style.paddingLeft=$.paddingX,S.style.paddingRight=$.paddingX):(S.style.paddingLeft="",S.style.paddingRight=""),$.paddingY?(S.style.paddingTop=$.paddingY,S.style.paddingBottom=$.paddingY):(S.style.paddingTop="",S.style.paddingBottom="");let Et=U==null?void 0:U.querySelector(".persona-send-button-tooltip"),on=(Pi=$.tooltipText)!=null?Pi:"Start voice recognition";if(((Ii=$.showTooltip)!=null?Ii:!1)&&on)if(Et)Et.textContent=on,Et.style.display="";else{let Ot=document.createElement("div");Ot.className="persona-send-button-tooltip",Ot.textContent=on,U==null||U.insertBefore(Ot,S)}else Et&&(Et.style.display="none");U.style.display="",S.disabled=H.isStreaming()}else S&&U&&(U.style.display="none",((Ri=(Wi=n.voiceRecognition)==null?void 0:Wi.provider)==null?void 0:Ri.type)==="runtype"?H.isVoiceActive()&&H.toggleVoice():rn&&un());if(((Hi=n.attachments)==null?void 0:Hi.enabled)===!0)if(!$e||!te){let $=(Bi=n.attachments)!=null?Bi:{},yt=(Ni=((Di=n.sendButton)!=null?Di:{}).size)!=null?Ni:"40px";ze||(ze=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ze.style.display="none",Ie.insertBefore(ze,ee)),se||(se=document.createElement("input"),se.type="file",se.accept=((Oi=$.allowedTypes)!=null?Oi:Rn).join(","),se.multiple=((Fi=$.maxFiles)!=null?Fi:4)>1,se.style.display="none",se.setAttribute("aria-label","Attach files"),Ie.insertBefore(se,ee)),$e=h("div","persona-send-button-wrapper"),te=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),te.type="button",te.setAttribute("aria-label",($i=$.buttonTooltipText)!=null?$i:"Attach file");let Oe=(_i=$.buttonIconName)!=null?_i:"paperclip",rt=yt,Rt=parseFloat(rt)||40,$t=Math.round(Rt*.6);te.style.width=rt,te.style.height=rt,te.style.minWidth=rt,te.style.minHeight=rt,te.style.fontSize="18px",te.style.lineHeight="1",te.style.backgroundColor="transparent",te.style.color="var(--persona-primary, #111827)",te.style.border="none",te.style.borderRadius="6px",te.style.transition="background-color 0.15s ease",te.addEventListener("mouseenter",()=>{te.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),te.addEventListener("mouseleave",()=>{te.style.backgroundColor="transparent"});let mn=ge(Oe,$t,"currentColor",1.5);mn?te.appendChild(mn):te.textContent="\u{1F4CE}",te.addEventListener("click",on=>{on.preventDefault(),se==null||se.click()}),$e.appendChild(te);let Gt=(ji=$.buttonTooltipText)!=null?ji:"Attach file",Et=h("div","persona-send-button-tooltip");Et.textContent=Gt,$e.appendChild(Et),Lt.append($e),!Ae&&se&&ze&&(Ae=vr.fromConfig($),Ae.setPreviewsContainer(ze),se.addEventListener("change",async()=>{Ae&&(se!=null&&se.files)&&(await Ae.handleFileSelect(se.files),se.value="")}))}else{$e.style.display="";let $=(zi=n.attachments)!=null?zi:{};se&&(se.accept=((qi=$.allowedTypes)!=null?qi:Rn).join(","),se.multiple=((Ui=$.maxFiles)!=null?Ui:4)>1),Ae&&Ae.updateConfig({allowedTypes:$.allowedTypes,maxFileSize:$.maxFileSize,maxFiles:$.maxFiles})}else $e&&($e.style.display="none"),Ae&&Ae.clearAttachments();let kt=(Vi=n.sendButton)!=null?Vi:{},To=(Ji=kt.useIcon)!=null?Ji:!1,jr=(Ki=kt.iconText)!=null?Ki:"\u2191",en=kt.iconName,dn=(Yi=kt.tooltipText)!=null?Yi:"Send message",Mo=(Gi=kt.showTooltip)!=null?Gi:!1,zr=(Xi=kt.size)!=null?Xi:"40px",ko=kt.backgroundColor,Sn=kt.textColor;if(To){if(Y.style.width=zr,Y.style.height=zr,Y.style.minWidth=zr,Y.style.minHeight=zr,Y.style.fontSize="18px",Y.style.lineHeight="1",Y.innerHTML="",en){let $=parseFloat(zr)||24,Ge=Sn&&typeof Sn=="string"&&Sn.trim()?Sn.trim():"currentColor",yt=ge(en,$,Ge,2);yt?(Y.appendChild(yt),Y.style.color=Ge):(Y.textContent=jr,Sn?Y.style.color=Sn:Y.classList.add("persona-text-white"))}else Y.textContent=jr,Sn?Y.style.color=Sn:Y.classList.add("persona-text-white");Y.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",ko?(Y.style.backgroundColor=ko,Y.classList.remove("persona-bg-persona-primary")):Y.classList.add("persona-bg-persona-primary")}else Y.textContent=(Qi=(Zi=n.copy)==null?void 0:Zi.sendButtonLabel)!=null?Qi:"Send",Y.style.width="",Y.style.height="",Y.style.minWidth="",Y.style.minHeight="",Y.style.fontSize="",Y.style.lineHeight="",Y.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",ko?(Y.style.backgroundColor=ko,Y.classList.remove("persona-bg-persona-accent")):Y.classList.add("persona-bg-persona-accent"),Sn?Y.style.color=Sn:Y.classList.add("persona-text-white");kt.borderWidth?(Y.style.borderWidth=kt.borderWidth,Y.style.borderStyle="solid"):(Y.style.borderWidth="",Y.style.borderStyle=""),kt.borderColor?Y.style.borderColor=kt.borderColor:Y.style.borderColor="",kt.paddingX?(Y.style.paddingLeft=kt.paddingX,Y.style.paddingRight=kt.paddingX):(Y.style.paddingLeft="",Y.style.paddingRight=""),kt.paddingY?(Y.style.paddingTop=kt.paddingY,Y.style.paddingBottom=kt.paddingY):(Y.style.paddingTop="",Y.style.paddingBottom="");let qr=Ve==null?void 0:Ve.querySelector(".persona-send-button-tooltip");if(Mo&&dn)if(qr)qr.textContent=dn,qr.style.display="";else{let $=document.createElement("div");$.className="persona-send-button-tooltip",$.textContent=dn,Ve==null||Ve.insertBefore($,Y)}else qr&&(qr.style.display="none");let Ur=(el=n.statusIndicator)!=null?el:{},Ic=(tl=Ur.visible)!=null?tl:!0;if(ft.style.display=Ic?"":"none",H){let $=H.getStatus(),Ge=yt=>{var Oe,rt,Rt,$t;return yt==="idle"?(Oe=Ur.idleText)!=null?Oe:Vt.idle:yt==="connecting"?(rt=Ur.connectingText)!=null?rt:Vt.connecting:yt==="connected"?(Rt=Ur.connectedText)!=null?Rt:Vt.connected:yt==="error"?($t=Ur.errorText)!=null?$t:Vt.error:Vt[yt]};ft.textContent=Ge($)}},open(){b&&ht(!0,"api")},close(){b&&ht(!1,"api")},toggle(){b&&ht(!k,"api")},clearChat(){Jt=!1,H.clearMessages(),Fn.clear();try{localStorage.removeItem(Mr),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Mr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Mr)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let g=a.clear();g instanceof Promise&&g.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}i={},T.syncFromMetadata(),F==null||F.clear(),K==null||K.update()},setMessage(l){return!ee||H.isStreaming()?!1:(!k&&b&&ht(!0,"system"),ee.value=l,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(H.isStreaming())return!1;let g=(l==null?void 0:l.trim())||ee.value.trim();return g?(!k&&b&&ht(!0,"system"),ee.value="",ee.style.height="auto",H.sendMessage(g),!0):!1},startVoiceRecognition(){var g,y;return H.isStreaming()?!1:((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype"?(H.isVoiceActive()||(!k&&b&&ht(!0,"system"),je.manuallyDeactivated=!1,Xt(),H.toggleVoice().then(()=>{je.active=H.isVoiceActive(),an("user"),H.isVoiceActive()&&$n()})),!0):rn?!0:_r()?(!k&&b&&ht(!0,"system"),je.manuallyDeactivated=!1,Xt(),Qn("user"),!0):!1},stopVoiceRecognition(){var l,g;return((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?H.isVoiceActive()?(H.toggleVoice().then(()=>{je.active=!1,je.manuallyDeactivated=!0,Xt(),an("user"),gn()}),!0):!1:rn?(je.manuallyDeactivated=!0,Xt(),un("user"),!0):!1},injectMessage(l){return!k&&b&&ht(!0,"system"),H.injectMessage(l)},injectAssistantMessage(l){!k&&b&&ht(!0,"system");let g=H.injectAssistantMessage(l);return q&&(q=!1,me&&(clearTimeout(me),me=null),setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)),g},injectUserMessage(l){return!k&&b&&ht(!0,"system"),H.injectUserMessage(l)},injectSystemMessage(l){return!k&&b&&ht(!0,"system"),H.injectSystemMessage(l)},injectMessageBatch(l){return!k&&b&&ht(!0,"system"),H.injectMessageBatch(l)},injectTestMessage(l){!k&&b&&ht(!0,"system"),H.injectTestEvent(l)},async connectStream(l,g){return H.connectStream(l,g)},__pushEventStreamEvent(l){F&&F.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!ie||!F||Ke()},hideEventStream(){fe&&et()},isEventStreamVisible(){return fe},showArtifacts(){pn(n)&&(Jt=!1,vn(),Ze==null||Ze.setMobileOpen(!0))},hideArtifacts(){pn(n)&&(Jt=!0,vn())},upsertArtifact(l){return pn(n)?(Jt=!1,H.upsertArtifact(l)):null},selectArtifact(l){pn(n)&&H.selectArtifact(l)},clearArtifacts(){pn(n)&&H.clearArtifacts()},focusInput(){return b&&!k||!ee?!1:(ee.focus(),!0)},async resolveApproval(l,g){let E=H.getMessages().find(L=>{var I;return L.variant==="approval"&&((I=L.approval)==null?void 0:I.id)===l});if(!(E!=null&&E.approval))throw new Error(`Approval not found: ${l}`);return H.resolveApproval(E.approval,g)},getMessages(){return H.getMessages()},getStatus(){return H.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){f(l)},on(l,g){return o.on(l,g)},off(l,g){o.off(l,g)},isOpen(){return b&&k},isVoiceActive(){return je.active},getState(){return{open:b&&k,launcherEnabled:b,voiceActive:je.active,streaming:H.isStreaming()}},showCSATFeedback(l){!k&&b&&ht(!0,"system");let g=Me.querySelector(".persona-feedback-container");g&&g.remove();let y=Is({onSubmit:async(E,L)=>{var I;H.isClientTokenMode()&&await H.submitCSATFeedback(E,L),(I=l==null?void 0:l.onSubmit)==null||I.call(l,E,L)},onDismiss:l==null?void 0:l.onDismiss,...l});Me.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!k&&b&&ht(!0,"system");let g=Me.querySelector(".persona-feedback-container");g&&g.remove();let y=Ws({onSubmit:async(E,L)=>{var I;H.isClientTokenMode()&&await H.submitNPSFeedback(E,L),(I=l==null?void 0:l.onSubmit)==null||I.call(l,E,L)},onDismiss:l==null?void 0:l.onDismiss,...l});Me.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return H.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return H.submitNPSFeedback(l,g)},destroy(){wt.forEach(l=>l()),be.remove(),Ne==null||Ne.destroy(),_e==null||_e.remove(),wn&&de.removeEventListener("click",wn)}};if((((ca=t==null?void 0:t.debugTools)!=null?ca:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,g={controller:w,getMessages:w.getMessages,getStatus:w.getStatus,getMetadata:w.getPersistentMetadata,updateMetadata:w.updatePersistentMetadata,clearHistory:()=>w.clearChat(),setVoiceActive:y=>y?w.startVoiceRecognition():w.stopVoiceRecognition()};window.AgentWidgetBrowser=g,wt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=j=>{let D=j.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&w.focusInput()};if(window.addEventListener("persona:focusInput",g),wt.push(()=>{window.removeEventListener("persona:focusInput",g)}),ie){let j=oe=>{let he=oe.detail;(!(he!=null&&he.instanceId)||he.instanceId===l)&&w.showEventStream()},D=oe=>{let he=oe.detail;(!(he!=null&&he.instanceId)||he.instanceId===l)&&w.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",D),wt.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",D)})}let y=j=>{let D=j.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&w.showArtifacts()},E=j=>{let D=j.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&w.hideArtifacts()},L=j=>{let D=j.detail;D!=null&&D.instanceId&&D.instanceId!==l||D!=null&&D.artifact&&w.upsertArtifact(D.artifact)},I=j=>{let D=j.detail;D!=null&&D.instanceId&&D.instanceId!==l||typeof(D==null?void 0:D.id)=="string"&&w.selectArtifact(D.id)},P=j=>{let D=j.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&w.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",E),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",I),window.addEventListener("persona:clearArtifacts",P),wt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",E),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",I),window.removeEventListener("persona:clearArtifacts",P)})}let Z=rp(n.persistState);if(Z&&b){let l=op(Z.storage),g=`${Z.keyPrefix}widget-open`,y=`${Z.keyPrefix}widget-voice`,E=`${Z.keyPrefix}widget-voice-mode`;if(l){let L=((da=Z.persist)==null?void 0:da.openState)&&l.getItem(g)==="true",I=((pa=Z.persist)==null?void 0:pa.voiceState)&&l.getItem(y)==="true",P=((ua=Z.persist)==null?void 0:ua.voiceState)&&l.getItem(E)==="true";if(L&&setTimeout(()=>{w.open(),setTimeout(()=>{var j;if(I||P)w.startVoiceRecognition();else if((j=Z.persist)!=null&&j.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(ga=Z.persist)!=null&&ga.openState&&(o.on("widget:opened",()=>{l.setItem(g,"true")}),o.on("widget:closed",()=>{l.setItem(g,"false")})),(ma=Z.persist)!=null&&ma.voiceState&&(o.on("voice:state",j=>{l.setItem(y,j.active?"true":"false")}),o.on("user:message",j=>{l.setItem(E,j.viaVoice?"true":"false")})),Z.clearOnChatClear){let j=()=>{l.removeItem(g),l.removeItem(y),l.removeItem(E)},D=()=>j();window.addEventListener("persona:clear-chat",D),wt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return c&&b&&setTimeout(()=>{w.open()},0),w};var sp=(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},nc=(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"},Os=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=""},rc=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Os(e)},Bs=e=>{e.style.transition=""},Ds=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=""},Ns=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Jo=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},ap=(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))},ip=(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)},oc=(e,r,t,n,s,o,a)=>{var C,T,b,x;let i=fn(o),d=i.reveal==="push";ap(e,r,t,n,d),ip(e,r,t,n,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",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,u=(T=(C=o==null?void 0:o.launcher)==null?void 0:C.mobileFullscreen)!=null?T:!0,p=(x=(b=o==null?void 0:o.launcher)==null?void 0:b.mobileBreakpoint)!=null?x:640,f=c!=null?c.innerWidth<=p:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Ds(r),Bs(n),rc(n),Ns(t),Jo(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="9999",n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(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"),rc(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Ds(r),Bs(n),Ns(t),Jo(s,n);let M=i.animate?"transform 180ms ease":"none",O=i.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":O;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=M,n.style.transform=A,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",Bs(n),Os(n),Jo(s,n);let M=sp(i.width,e.clientWidth),O=Math.max(0,e.clientWidth),A=i.animate?"transform 180ms ease":"none",W=i.side==="right"?a?`translateX(-${M}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${M}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=`${O+M}px`,r.style.transition=A,r.style.transform=W,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${O}px`,t.style.maxWidth=`${O}px`,t.style.minWidth=`${O}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="",Ds(r),Os(n),Ns(t),Jo(s,n);let M=i.reveal==="emerge";M?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let O=a?i.width:"0px",A=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",W=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${O}`,n.style.width=O,n.style.maxWidth=O,n.style.minWidth=O,n.style.minHeight="0",n.style.position="relative",n.style.overflow=M||W?"hidden":"visible",n.style.transition=A,M&&(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")}},lp=(e,r)=>{let t=e.ownerDocument.createElement("div");return nc(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){nc(t,n)},destroy(){t.remove()}}},cp=(e,r)=>{var M,O,A,W;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"),d=t.createElement("div"),c=t.createElement("aside"),u=t.createElement("div"),p=(O=(M=r==null?void 0:r.launcher)==null?void 0:M.enabled)==null||O?(W=(A=r==null?void 0:r.launcher)==null?void 0:A.autoExpand)!=null?W:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",c.appendChild(u),n.insertBefore(a,e),d.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},C=()=>{m(),fn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{oc(a,i,d,c,u,r,p)}),f.observe(a))},T=()=>{oc(a,i,d,c,u,r,p),C()},b=a.ownerDocument.defaultView,x=()=>{T()};return b==null||b.addEventListener("resize",x),fn(r).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),T(),{mode:"docked",host:u,shell:a,syncWidgetState(_){let k=_.launcherEnabled?_.open:!0;p!==k&&(p=k,T())},updateConfig(_){var k,q;r=_,((q=(k=r==null?void 0:r.launcher)==null?void 0:k.enabled)!=null?q:!0)===!1&&(p=!0),T()},destroy(){b==null||b.removeEventListener("resize",x),m(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},Ko=(e,r)=>_t(r)?cp(e,r):lp(e,r);var Fs={},dp=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},pp=()=>{try{if(typeof Fs!="undefined"&&Fs.url)return new URL("../widget.css",Fs.url).href}catch{}return null},sc=(e,r)=>{let t=pp(),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)}},ac=e=>{var b;let r=dp(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=Ko(r,s),a,i=[],d=(x,M)=>{var _,k;let A=!((k=(_=M==null?void 0:M.launcher)==null?void 0:_.enabled)!=null?k:!0)||_t(M),W=n.createElement("div");if(W.setAttribute("data-persona-root","true"),A&&(W.style.height="100%",W.style.display="flex",W.style.flexDirection="column",W.style.flex="1",W.style.minHeight="0"),t){let q=x.attachShadow({mode:"open"});q.appendChild(W),sc(q,n)}else x.appendChild(W),sc(x,n);return r.id&&W.setAttribute("data-persona-instance",r.id),W},c=()=>{o.syncWidgetState(a.getState())},u=()=>{i.forEach(x=>x()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},p=()=>{let x=d(o.host,s);a=Hs(x,s,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(x=>x()),i=[],a.destroy()};p(),(b=e.onReady)==null||b.call(e);let m=x=>{f(),o.destroy(),o=Ko(r,x),s=x,p()},C={update(x){var W,_,k,q,me,ce;let M={...s,...x,launcher:{...(W=s==null?void 0:s.launcher)!=null?W:{},...(_=x==null?void 0:x.launcher)!=null?_:{},dock:{...(q=(k=s==null?void 0:s.launcher)==null?void 0:k.dock)!=null?q:{},...(ce=(me=x==null?void 0:x.launcher)==null?void 0:me.dock)!=null?ce:{}}}},O=_t(s),A=_t(M);if(O!==A){m(M);return}s=M,o.updateConfig(s),a.update(x),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},T=new Proxy(C,{get(x,M,O){if(M==="host")return o.host;if(M in x)return Reflect.get(x,M,O);let A=a[M];return typeof A=="function"?A.bind(a):A}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=T),T};var pc=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),up=new Set(["button","a","input","select","textarea","details","summary"]),gp=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),$s=/\b(product|card|item|listing|result)\b/i,js=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,mp=3e3,fp=100;function uc(e){let r=typeof e.className=="string"?e.className:"";if($s.test(r)||e.id&&$s.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&$s.test(n.value))return!0}return!1}function gc(e){var r;return js.test(((r=e.textContent)!=null?r:"").trim())}function mc(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 hp(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ic(e){let r=e.match(js);return r?r[0]:null}function lc(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 yp(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 bp="commerce-card",xp="result-card";function cc(e){return!uc(e)||!gc(e)||!mc(e)&&!hp(e)?0:5200}function dc(e){var n;return!uc(e)||gc(e)||!mc(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 fc=[{id:bp,scoreElement(e){return cc(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||js.test(n)&&n.length<32)}return!0},formatSummary(e,r){var d,c,u;if(cc(e)===0)return null;let{title:t,href:n}=lc(e),s=(u=(c=ic(((d=e.textContent)!=null?d:"").trim()))!=null?c:ic(r.text))!=null?u:"",o=yp(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(`
95
+ `}if(!E&&!l){let en="max-height: -moz-available !important; max-height: stretch !important;",dn=g?"":"padding-top: 1.25em !important;";xe.style.cssText+=en+dn}};Kn(),sr(e,n),jo(e,n),zo(e,n);let wt=[];nn&&wt.push(()=>{nn==null||nn.disconnect(),nn=null}),wt.push(()=>{sn==null||sn(),sn=null,lr(),mt&&(mt.remove(),mt=null),Ze==null||Ze.element.style.removeProperty("width"),Ze==null||Ze.element.style.removeProperty("maxWidth")}),le&&wt.push(()=>{pt!==null&&(cancelAnimationFrame(pt),pt=null),U==null||U.destroy(),U=null,F==null||F.destroy(),F=null,K=null});let Cn=null,Ir=()=>{Cn&&(Cn(),Cn=null),n.colorScheme==="auto"&&(Cn=ms(()=>{sr(e,n)}))};Ir(),wt.push(()=>{Cn&&(Cn(),Cn=null)});let Nn=$l(Xe),wn=null,H,On=!1,Fn=Tl(),Wr=0,kn=!0,Yn=0,Rr=0,Ln=null,Pn=!1,cr=0,dr=!1,co=125,po=2e3,uo=5,Hr=50,pr=new Map,je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Br=(sa=(oa=n.voiceRecognition)==null?void 0:oa.autoResume)!=null?sa:!1,an=l=>{o.emit("voice:state",{active:je.active,source:l,timestamp:Date.now()})},Xt=()=>{f(l=>({...l,voiceState:{active:je.active,timestamp:Date.now(),manuallyDeactivated:je.manuallyDeactivated}}))},go=()=>{var E,L;if(((E=n.voiceRecognition)==null?void 0:E.enabled)===!1)return;let l=Rs(i.voiceState),g=!!l.active,y=Number((L=l.timestamp)!=null?L:0);je.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-y<ep&&setTimeout(()=>{var I,P;je.active||(je.manuallyDeactivated=!1,((P=(I=n.voiceRecognition)==null?void 0:I.provider)==null?void 0:P.type)==="runtype"?H.toggleVoice().then(()=>{je.active=H.isVoiceActive(),an("restore"),H.isVoiceActive()&&$n()}):Qn("restore"))},1e3)},mo=()=>H?ec(H.getMessages()).filter(l=>!l.__skipPersist):[];function Dr(l){if(!(a!=null&&a.save))return;let y={messages:l?ec(l):H?mo():[],metadata:i};try{let E=a.save(y);E instanceof Promise&&E.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",E)}}let Gn=(l=!1)=>{if(!kn)return;let g=Date.now();Pn&&g<cr&&!l||(Pn&&g>=cr&&(Pn=!1),!(!l&&!On)&&(g-Rr<co||(Rr=g,Ln&&cancelAnimationFrame(Ln),Ln=requestAnimationFrame(()=>{Pn||!kn||(dr=!0,re.scrollTop=re.scrollHeight,Yn=re.scrollTop,requestAnimationFrame(()=>{dr=!1}),Ln=null)}))))},In=null,fo=()=>xe.querySelector("#persona-scroll-container")||re,ho=(l,g=500)=>{let y=l.scrollTop,E=l.clientHeight,L=l.scrollHeight,I=L-y;if(y+E>=L-2||Math.abs(I)<5)return;In!==null&&(cancelAnimationFrame(In),In=null);let j=performance.now(),D=ye=>1-Math.pow(1-ye,3),oe=ye=>{let ve=l.scrollHeight;ve!==L&&(L=ve,I=L-y);let We=ye-j,Te=Math.min(We/g,1),R=D(Te),Le=y+I*R;l.scrollTop=Le,Te<1?In=requestAnimationFrame(oe):(l.scrollTop=l.scrollHeight,In=null)};In=requestAnimationFrame(oe)},yo=l=>{let g=new Map;l.forEach(y=>{let E=pr.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!E&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(E!=null&&E.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(E?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),pr.clear(),g.forEach((y,E)=>{pr.set(E,y)})},Xn=(l,g,y)=>{var ye,ve,We,Te;let E=document.createElement("div"),I=(()=>{var Le;let R=s.find(Pe=>Pe.renderLoadingIndicator);if(R!=null&&R.renderLoadingIndicator)return R.renderLoadingIndicator;if((Le=n.loadingIndicator)!=null&&Le.render)return n.loadingIndicator.render})(),P=new Set;g.forEach(R=>{var ue,Wt;P.add(R.id);let Le=El(R,Wr),Pe=Ml(Fn,R.id,Le);if(Pe){E.appendChild(Pe.cloneNode(!0));return}let ae=null,Re=s.find(lt=>!!(R.variant==="reasoning"&&lt.renderReasoning||R.variant==="tool"&&lt.renderToolCall||R.variant==="approval"&&lt.renderApproval||!R.variant&&lt.renderMessage)),nt=(ue=n.layout)==null?void 0:ue.messages;if(Re)if(R.variant==="reasoning"&&R.reasoning&&Re.renderReasoning){if(!ne)return;ae=Re.renderReasoning({message:R,defaultRenderer:()=>ys(R),config:n})}else if(R.variant==="tool"&&R.toolCall&&Re.renderToolCall){if(!Ae)return;ae=Re.renderToolCall({message:R,defaultRenderer:()=>bs(R,n),config:n})}else if(R.variant==="approval"&&R.approval&&Re.renderApproval){if(n.approval===!1)return;ae=Re.renderApproval({message:R,defaultRenderer:()=>xs(R,n),config:n})}else Re.renderMessage&&(ae=Re.renderMessage({message:R,defaultRenderer:()=>{let lt=ao(R,y,nt,n.messageActions,ut,{loadingIndicatorRenderer:I,widgetConfig:n});return R.role!=="user"&&ws(lt,R,n,H),lt},config:n}));if(!ae&&R.role==="assistant"&&!R.variant&&n.enableComponentStreaming!==!1&&Ls(R)){let Qt=Ps(R);if(Qt){let Ut=ks(Qt,{config:n,message:R,transform:y});if(Ut)if(n.wrapComponentDirectiveInBubble!==!1){let Nt=document.createElement("div");if(Nt.className=["vanilla-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Nt.id=`bubble-${R.id}`,Nt.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let cn=document.createElement("div");cn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",cn.innerHTML=y({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Nt.appendChild(cn)}Nt.appendChild(Ut),ae=Nt}else{let Nt=document.createElement("div");if(Nt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Nt.id=`bubble-${R.id}`,Nt.setAttribute("data-message-id",R.id),Nt.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let cn=document.createElement("div");cn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",cn.innerHTML=y({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),Nt.appendChild(cn)}Nt.appendChild(Ut),ae=Nt}}}if(!ae)if(R.variant==="reasoning"&&R.reasoning){if(!ne)return;ae=ys(R)}else if(R.variant==="tool"&&R.toolCall){if(!Ae)return;ae=bs(R,n)}else if(R.variant==="approval"&&R.approval){if(n.approval===!1)return;ae=xs(R,n)}else{let lt=(Wt=n.layout)==null?void 0:Wt.messages;lt!=null&&lt.renderUserMessage&&R.role==="user"?ae=lt.renderUserMessage({message:R,config:n,streaming:!!R.streaming}):lt!=null&&lt.renderAssistantMessage&&R.role==="assistant"?ae=lt.renderAssistantMessage({message:R,config:n,streaming:!!R.streaming}):ae=ao(R,y,lt,n.messageActions,ut,{loadingIndicatorRenderer:I,widgetConfig:n}),R.role!=="user"&&ae&&ws(ae,R,n,H)}let qe=document.createElement("div");qe.className="persona-flex",qe.id=`wrapper-${R.id}`,qe.setAttribute("data-wrapper-id",R.id),R.role==="user"&&qe.classList.add("persona-justify-end"),(ae==null?void 0:ae.getAttribute("data-persona-component-directive"))==="true"&&qe.classList.add("persona-w-full"),qe.appendChild(ae),kl(Fn,R.id,Le,qe),E.appendChild(qe)}),Ll(Fn,P);let j=g.some(R=>R.role==="assistant"&&R.streaming),D=g[g.length-1],oe=(D==null?void 0:D.role)==="assistant"&&!D.streaming&&D.variant!=="approval";if(On&&g.some(R=>R.role==="user")&&!j&&!oe){let R={config:n,streaming:!0,location:"standalone",defaultRenderer:wr},Le=s.find(ae=>ae.renderLoadingIndicator),Pe=null;if(Le!=null&&Le.renderLoadingIndicator&&(Pe=Le.renderLoadingIndicator(R)),Pe===null&&((ye=n.loadingIndicator)!=null&&ye.render)&&(Pe=n.loadingIndicator.render(R)),Pe===null&&(Pe=wr()),Pe){let ae=document.createElement("div"),Re=((ve=n.loadingIndicator)==null?void 0:ve.showBubble)!==!1;ae.className=Re?["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(" "),ae.setAttribute("data-typing-indicator","true"),ae.appendChild(Pe);let nt=document.createElement("div");nt.className="persona-flex",nt.id="wrapper-typing-indicator",nt.setAttribute("data-wrapper-id","typing-indicator"),nt.appendChild(ae),E.appendChild(nt)}}if(!On&&g.length>0){let R=g[g.length-1],Le={config:n,lastMessage:R,messageCount:g.length},Pe=s.find(Re=>Re.renderIdleIndicator),ae=null;if(Pe!=null&&Pe.renderIdleIndicator&&(ae=Pe.renderIdleIndicator(Le)),ae===null&&((We=n.loadingIndicator)!=null&&We.renderIdle)&&(ae=n.loadingIndicator.renderIdle(Le)),ae){let Re=document.createElement("div"),nt=((Te=n.loadingIndicator)==null?void 0:Te.showBubble)!==!1;Re.className=nt?["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(" "),Re.setAttribute("data-idle-indicator","true"),Re.appendChild(ae);let qe=document.createElement("div");qe.className="persona-flex",qe.id="wrapper-idle-indicator",qe.setAttribute("data-wrapper-id","idle-indicator"),qe.appendChild(Re),E.appendChild(qe)}}Al(l,E),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let R=fo();ho(R)})})},Zn=()=>{var D,oe,ye,ve,We;if(!b)return;let l=_t(n),g=(D=e.ownerDocument.defaultView)!=null?D:window,y=(ye=(oe=n.launcher)==null?void 0:oe.mobileBreakpoint)!=null?ye:640,E=(We=(ve=n.launcher)==null?void 0:ve.mobileFullscreen)!=null?We:!0,L=g.innerWidth<=y,I=E&&L&&b,P=fn(n).reveal;k?(xe.style.removeProperty("display"),xe.style.display=l?"flex":"",xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-95","persona-opacity-0"),ge.classList.add("persona-scale-100","persona-opacity-100"),Ne?Ne.element.style.display="none":_e&&(_e.style.display="none")):(l?l&&(P==="overlay"||P==="push")&&!I?(xe.style.removeProperty("display"),xe.style.display="flex",xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(xe.style.setProperty("display","none","important"),xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(xe.style.display="",xe.classList.add("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-100","persona-opacity-100"),ge.classList.add("persona-scale-95","persona-opacity-0")),Ne?Ne.element.style.display=l?"none":"":_e&&(_e.style.display=l?"none":""))},ht=(l,g="user")=>{if(!b||k===l)return;let y=k;k=l,Zn(),k&&(Tt(),Gn(!0));let E={open:k,source:g,timestamp:Date.now()};k&&!y?o.emit("widget:opened",E):!k&&y&&o.emit("widget:closed",E),o.emit("widget:state",{open:k,launcherEnabled:b,voiceActive:je.active,streaming:H.isStreaming()})},ur=l=>{Y.disabled=l,S&&(S.disabled=l),Nn.buttons.forEach(g=>{g.disabled=l}),st.dataset.personaComposerStreaming=l?"true":"false",st.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},gr=()=>{je.active||ee&&ee.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>gr(),200)});let Nr=()=>{var g,y,E,L,I,P,j,D,oe,ye;jt.textContent=(y=(g=n.copy)==null?void 0:g.welcomeTitle)!=null?y:"Hello \u{1F44B}",zt.textContent=(L=(E=n.copy)==null?void 0:E.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",ee.placeholder=(P=(I=n.copy)==null?void 0:I.inputPlaceholder)!=null?P:"How can I help...",(D=(j=n.sendButton)==null?void 0:j.useIcon)!=null&&D||(Y.textContent=(ye=(oe=n.copy)==null?void 0:oe.sendButtonLabel)!=null?ye:"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))"};if(n.clientToken&&(n={...n,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(g=>({...g,sessionId:l}))}}),H=new Qr(n,{onMessagesChanged(l){Xn(Me,l,z),H&&(l.some(L=>L.role==="user")?Nn.render([],H,ee,l):Nn.render(n.suggestionChips,H,ee,l,n.suggestionChipsConfig)),Gn(!On),yo(l);let g=[...l].reverse().find(E=>E.role==="user"),y=je.lastUserMessageId;g&&g.id!==y&&(je.lastUserMessageId=g.id,o.emit("user:message",g)),je.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Dr(l)},onStatusChanged(l){var E;let g=(E=n.statusIndicator)!=null?E:{},y=L=>{var I,P,j,D;return L==="idle"?(I=g.idleText)!=null?I:Vt.idle:L==="connecting"?(P=g.connectingText)!=null?P:Vt.connecting:L==="connected"?(j=g.connectedText)!=null?j:Vt.connected:L==="error"?(D=g.errorText)!=null?D:Vt.error:Vt[L]};ft.textContent=y(l)},onStreamingChanged(l){On=l,ur(l),H&&Xn(Me,H.getMessages(),z),l||Gn(!0)},onVoiceStatusChanged(l){var g,y;if(((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype")switch(l){case"listening":break;case"processing":gn(),xo();break;case"speaking":gn(),vo();break;default:l==="idle"&&H.isBargeInActive()?(gn(),$n(),S==null||S.setAttribute("aria-label","End voice session")):(je.active=!1,gn(),an("system"),Xt());break}},onArtifactsState(l){G=l,vn()}}),Vn.current=H,((ia=(aa=n.voiceRecognition)==null?void 0:aa.provider)==null?void 0:ia.type)==="runtype")try{H.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&H.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),F&&H.setSSEEventCallback((l,g)=>{F==null||F.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})}),d&&d.then(l=>{var g;l&&(l.metadata&&(i=Rs(l.metadata),T.syncFromMetadata()),(g=l.messages)!=null&&g.length&&H.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Or=l=>{var L;l.preventDefault();let g=ee.value.trim(),y=(L=Se==null?void 0:Se.hasAttachments())!=null?L:!1;if(!g&&!y)return;let E;y&&(E=[],E.push(...Se.getContentParts()),g&&E.push(ds(g))),ee.value="",ee.style.height="auto",H.sendMessage(g,{contentParts:E}),y&&Se.clearAttachments()},Fr=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),Y.click())},$r=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!Se)return;let g=np(l.clipboardData);g.length!==0&&(l.preventDefault(),await Se.handleFiles(g))},Kt=null,rn=!1,Wn=null,Be=null,_r=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Qn=(l="user")=>{var I,P,j,D,oe,ye,ve,We;if(rn||H.isStreaming())return;let g=_r();if(!g)return;Kt=new g;let E=(P=((I=n.voiceRecognition)!=null?I:{}).pauseDuration)!=null?P:2e3;Kt.continuous=!0,Kt.interimResults=!0,Kt.lang="en-US";let L=ee.value;Kt.onresult=Te=>{let R="",Le="";for(let ae=0;ae<Te.results.length;ae++){let Re=Te.results[ae],nt=Re[0].transcript;Re.isFinal?R+=nt+" ":Le=nt}let Pe=L+R+Le;ee.value=Pe,Wn&&clearTimeout(Wn),(R||Le)&&(Wn=window.setTimeout(()=>{let ae=ee.value.trim();ae&&Kt&&rn&&(un(),ee.value="",ee.style.height="auto",H.sendMessage(ae,{viaVoice:!0}))},E))},Kt.onerror=Te=>{Te.error!=="no-speech"&&un()},Kt.onend=()=>{if(rn){let Te=ee.value.trim();Te&&Te!==L.trim()&&(ee.value="",ee.style.height="auto",H.sendMessage(Te,{viaVoice:!0})),un()}};try{if(Kt.start(),rn=!0,je.active=!0,l!=="system"&&(je.manuallyDeactivated=!1),an(l),Xt(),S){let Te=(j=n.voiceRecognition)!=null?j:{};Be={backgroundColor:S.style.backgroundColor,color:S.style.color,borderColor:S.style.borderColor,iconName:(D=Te.iconName)!=null?D:"mic",iconSize:parseFloat((ve=(ye=Te.iconSize)!=null?ye:(oe=n.sendButton)==null?void 0:oe.size)!=null?ve:"40")||24};let R=(We=Te.recordingBackgroundColor)!=null?We:"#ef4444",Le=Te.recordingIconColor,Pe=Te.recordingBorderColor;if(S.classList.add("persona-voice-recording"),S.style.backgroundColor=R,Le){S.style.color=Le;let ae=S.querySelector("svg");ae&&ae.setAttribute("stroke",Le)}Pe&&(S.style.borderColor=Pe),S.setAttribute("aria-label","Stop voice recognition")}}catch{un("system")}},un=(l="user")=>{if(rn){if(rn=!1,Wn&&(clearTimeout(Wn),Wn=null),Kt){try{Kt.stop()}catch{}Kt=null}if(je.active=!1,an(l),Xt(),S){if(S.classList.remove("persona-voice-recording"),Be){S.style.backgroundColor=Be.backgroundColor,S.style.color=Be.color,S.style.borderColor=Be.borderColor;let g=S.querySelector("svg");g&&g.setAttribute("stroke",Be.color||"currentColor"),Be=null}S.setAttribute("aria-label","Start voice recognition")}}},bo=(l,g)=>{var ae,Re,nt,qe,ue,Wt,lt,Qt;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),E=((ae=l==null?void 0:l.provider)==null?void 0:ae.type)==="runtype";if(!(y||E))return null;let I=h("div","persona-send-button-wrapper"),P=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");P.type="button",P.setAttribute("aria-label","Start voice recognition");let j=(Re=l==null?void 0:l.iconName)!=null?Re:"mic",D=(nt=g==null?void 0:g.size)!=null?nt:"40px",oe=(qe=l==null?void 0:l.iconSize)!=null?qe:D,ye=parseFloat(oe)||24,ve=(ue=l==null?void 0:l.backgroundColor)!=null?ue:g==null?void 0:g.backgroundColor,We=(Wt=l==null?void 0:l.iconColor)!=null?Wt:g==null?void 0:g.textColor;P.style.width=oe,P.style.height=oe,P.style.minWidth=oe,P.style.minHeight=oe,P.style.fontSize="18px",P.style.lineHeight="1";let Te=We||"currentColor",R=me(j,ye,Te,1.5);R?(P.appendChild(R),P.style.color=Te):(P.textContent="\u{1F3A4}",P.style.color=Te),ve?P.style.backgroundColor=ve:P.classList.add("persona-bg-persona-primary"),We?P.style.color=We:!We&&!(g!=null&&g.textColor)&&P.classList.add("persona-text-white"),l!=null&&l.borderWidth&&(P.style.borderWidth=l.borderWidth,P.style.borderStyle="solid"),l!=null&&l.borderColor&&(P.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(P.style.paddingLeft=l.paddingX,P.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(P.style.paddingTop=l.paddingY,P.style.paddingBottom=l.paddingY),I.appendChild(P);let Le=(lt=l==null?void 0:l.tooltipText)!=null?lt:"Start voice recognition";if(((Qt=l==null?void 0:l.showTooltip)!=null?Qt:!1)&&Le){let Ut=h("div","persona-send-button-tooltip");Ut.textContent=Le,I.appendChild(Ut)}return{micButton:P,micButtonWrapper:I}},mr=()=>{var g,y,E,L,I;if(!S||Be)return;let l=(g=n.voiceRecognition)!=null?g:{};Be={backgroundColor:S.style.backgroundColor,color:S.style.color,borderColor:S.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((I=(L=l.iconSize)!=null?L:(E=n.sendButton)==null?void 0:E.size)!=null?I:"40")||24}},fr=(l,g)=>{var I,P,j,D,oe;if(!S)return;let y=S.querySelector("svg");y&&y.remove();let E=(oe=Be==null?void 0:Be.iconSize)!=null?oe:parseFloat((D=(j=(I=n.voiceRecognition)==null?void 0:I.iconSize)!=null?j:(P=n.sendButton)==null?void 0:P.size)!=null?D:"40")||24,L=me(l,E,g,1.5);L&&S.appendChild(L)},er=()=>{S&&S.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},$n=()=>{var L,I;if(!S)return;mr();let l=(L=n.voiceRecognition)!=null?L:{},g=(I=l.recordingBackgroundColor)!=null?I:"#ef4444",y=l.recordingIconColor,E=l.recordingBorderColor;if(er(),S.classList.add("persona-voice-recording"),S.style.backgroundColor=g,y){S.style.color=y;let P=S.querySelector("svg");P&&P.setAttribute("stroke",y)}E&&(S.style.borderColor=E),S.setAttribute("aria-label","Stop voice recognition")},xo=()=>{var j,D,oe,ye,ve,We,Te,R;if(!S)return;mr();let l=(j=n.voiceRecognition)!=null?j:{},g=H.getVoiceInterruptionMode(),y=(D=l.processingIconName)!=null?D:"loader",E=(ye=(oe=l.processingIconColor)!=null?oe:Be==null?void 0:Be.color)!=null?ye:"",L=(We=(ve=l.processingBackgroundColor)!=null?ve:Be==null?void 0:Be.backgroundColor)!=null?We:"",I=(R=(Te=l.processingBorderColor)!=null?Te:Be==null?void 0:Be.borderColor)!=null?R:"";er(),S.classList.add("persona-voice-processing"),S.style.backgroundColor=L,S.style.borderColor=I;let P=E||"currentColor";S.style.color=P,fr(y,P),S.setAttribute("aria-label","Processing voice input"),g==="none"&&(S.style.cursor="default")},vo=()=>{var oe,ye,ve,We,Te,R,Le,Pe,ae,Re,nt,qe;if(!S)return;mr();let l=(oe=n.voiceRecognition)!=null?oe:{},g=H.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",E=(ye=l.speakingIconName)!=null?ye:y,L=(R=l.speakingIconColor)!=null?R:g==="barge-in"?(We=(ve=l.recordingIconColor)!=null?ve:Be==null?void 0:Be.color)!=null?We:"":(Te=Be==null?void 0:Be.color)!=null?Te:"",I=(ae=l.speakingBackgroundColor)!=null?ae:g==="barge-in"?(Le=l.recordingBackgroundColor)!=null?Le:"#ef4444":(Pe=Be==null?void 0:Be.backgroundColor)!=null?Pe:"",P=(qe=l.speakingBorderColor)!=null?qe:g==="barge-in"?(Re=l.recordingBorderColor)!=null?Re:"":(nt=Be==null?void 0:Be.borderColor)!=null?nt:"";er(),S.classList.add("persona-voice-speaking"),S.style.backgroundColor=I,S.style.borderColor=P;let j=L||"currentColor";S.style.color=j,fr(E,j);let D=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";S.setAttribute("aria-label",D),g==="none"&&(S.style.cursor="default"),g==="barge-in"&&S.classList.add("persona-voice-recording")},gn=()=>{var l,g,y;S&&(er(),Be&&(S.style.backgroundColor=(l=Be.backgroundColor)!=null?l:"",S.style.color=(g=Be.color)!=null?g:"",S.style.borderColor=(y=Be.borderColor)!=null?y:"",fr(Be.iconName,Be.color||"currentColor"),Be=null),S.style.cursor="",S.setAttribute("aria-label","Start voice recognition"))},tr=()=>{var l,g;if(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"){let y=H.getVoiceStatus(),E=H.getVoiceInterruptionMode();if(E==="none"&&(y==="processing"||y==="speaking"))return;if(E==="cancel"&&(y==="processing"||y==="speaking")){H.stopVoicePlayback();return}if(H.isBargeInActive()){H.stopVoicePlayback(),H.deactivateBargeIn().then(()=>{je.active=!1,je.manuallyDeactivated=!0,Xt(),an("user"),gn()});return}H.toggleVoice().then(()=>{je.active=H.isVoiceActive(),je.manuallyDeactivated=!H.isVoiceActive(),Xt(),an("user"),H.isVoiceActive()?$n():gn()});return}if(rn){let y=ee.value.trim();je.manuallyDeactivated=!0,Xt(),un("user"),y&&(ee.value="",ee.style.height="auto",H.sendMessage(y))}else je.manuallyDeactivated=!1,Xt(),Qn("user")};He=tr,S&&(S.addEventListener("click",tr),wt.push(()=>{var l,g;((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?(H.isVoiceActive()&&H.toggleVoice(),gn()):un("system"),S&&S.removeEventListener("click",tr)}));let X=o.on("assistant:complete",()=>{Br&&(je.active||je.manuallyDeactivated||Br==="assistant"&&!je.lastUserMessageWasVoice||setTimeout(()=>{var l,g;!je.active&&!je.manuallyDeactivated&&(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?H.toggleVoice().then(()=>{je.active=H.isVoiceActive(),an("auto"),H.isVoiceActive()&&$n()}):Qn("auto"))},600))});wt.push(X);let Ye=o.on("action:resubmit",()=>{setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)});wt.push(Ye);let tt=()=>{ht(!k,"user")},Ne=null,_e=null;if(b){let l=s.find(g=>g.renderLauncher);if(l!=null&&l.renderLauncher){let g=l.renderLauncher({config:n,defaultRenderer:()=>ro(n,tt).element,onToggle:tt});g&&(_e=g)}_e||(Ne=ro(n,tt))}Ne?e.appendChild(Ne.element):_e&&e.appendChild(_e),Zn(),Nn.render(n.suggestionChips,H,ee,void 0,n.suggestionChipsConfig),Nr(),ur(H.isStreaming()),Gn(!0),go(),M&&(b?k&&setTimeout(()=>gr(),200):setTimeout(()=>gr(),0));let Tt=()=>{var D,oe,ye,ve,We,Te,R,Le,Pe,ae,Re,nt,qe;let l=_t(n),g=(oe=(D=n.launcher)==null?void 0:D.sidebarMode)!=null?oe:!1,y=l||g||((ve=(ye=n.launcher)==null?void 0:ye.fullHeight)!=null?ve:!1),E=(We=e.ownerDocument.defaultView)!=null?We:window,L=(R=(Te=n.launcher)==null?void 0:Te.mobileFullscreen)!=null?R:!0,I=(Pe=(Le=n.launcher)==null?void 0:Le.mobileBreakpoint)!=null?Pe:640,P=E.innerWidth<=I,j=L&&P&&b;try{if(j){Kn(),sr(e,n);return}if(_&&(_=!1,Kn(),sr(e,n)),!b&&!l){ge.style.height="",ge.style.width="";return}if(!g&&!l){let ue=(Re=(ae=n==null?void 0:n.launcher)==null?void 0:ae.width)!=null?Re:n==null?void 0:n.launcherWidth,Wt=ue!=null?ue:"min(400px, calc(100vw - 24px))";ge.style.width=Wt,ge.style.maxWidth=Wt}if(Jn(),!y){let ue=E.innerHeight,Wt=64,lt=(qe=(nt=n.launcher)==null?void 0:nt.heightOffset)!=null?qe:0,Qt=Math.max(200,ue-Wt),Ut=Math.min(640,Qt),Yt=Math.max(200,Ut-lt);ge.style.height=`${Yt}px`}}finally{Zn()}};Tt();let St=(la=e.ownerDocument.defaultView)!=null?la:window;St.addEventListener("resize",Tt),wt.push(()=>St.removeEventListener("resize",Tt)),Yn=re.scrollTop;let v=()=>{let l=re.scrollTop,g=re.scrollHeight,y=re.clientHeight,E=g-l-y,L=Math.abs(l-Yn);if(Yn=l,!dr&&!(L<=uo)){if(!kn&&E<Hr){Pn=!1,kn=!0;return}kn&&E>Hr&&(Pn=!0,cr=Date.now()+po,kn=!1)}};re.addEventListener("scroll",v,{passive:!0}),wt.push(()=>re.removeEventListener("scroll",v)),wt.push(()=>{Ln&&cancelAnimationFrame(Ln)});let De=()=>{pe&&(wn&&(pe.removeEventListener("click",wn),wn=null),b?(pe.style.display="",wn=()=>{ht(!1,"user")},pe.addEventListener("click",wn)):pe.style.display="none")};De(),(()=>{let{clearChatButton:l}=J;l&&l.addEventListener("click",()=>{H.clearMessages(),Fn.clear();try{localStorage.removeItem(Mr),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Mr}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Mr)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 g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),a!=null&&a.clear)try{let y=a.clear();y instanceof Promise&&y.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},T.syncFromMetadata(),F==null||F.clear(),U==null||U.update()})})(),Ie&&Ie.addEventListener("submit",Or),ee==null||ee.addEventListener("keydown",Fr),ee==null||ee.addEventListener("paste",$r),wt.push(()=>{Ie&&Ie.removeEventListener("submit",Or),ee==null||ee.removeEventListener("keydown",Fr),ee==null||ee.removeEventListener("paste",$r)}),wt.push(()=>{H.cancel()}),Ne?wt.push(()=>{Ne==null||Ne.destroy()}):_e&&wt.push(()=>{_e==null||_e.remove()});let w={update(l){var fa,ha,ya,ba,xa,va,Ca,wa,Sa,Aa,Ea,Ta,Ma,ka,La,Pa,Ia,Wa,Ra,Ha,Ba,Da,Na,Oa,Fa,$a,_a,ja,za,qa,Ua,Va,Ja,Ka,Ya,Ga,Xa,Za,Qa,ei,ti,ni,ri,oi,si,ai,ii,li,ci,di,pi,ui,gi,mi,fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Pi,Ii,Wi,Ri,Hi,Bi,Di,Ni,Oi,Fi,$i,_i,ji,zi,qi,Ui,Vi,Ji,Ki,Yi,Gi,Xi,Zi,Qi,el,tl;let g=n.toolCall,y=n.messageActions,E=(fa=n.layout)==null?void 0:fa.messages,L=n.colorScheme,I=n.loadingIndicator,P=n.iterationDisplay;n={...n,...l},Kn(),sr(e,n),jo(e,n),zo(e,n),vn(),n.colorScheme!==L&&Ir();let j=qo.getForInstance(n.plugins);s.length=0,s.push(...j),b=(ya=(ha=n.launcher)==null?void 0:ha.enabled)!=null?ya:!0,x=(xa=(ba=n.launcher)==null?void 0:ba.autoExpand)!=null?xa:!1,ne=(Ca=(va=n.features)==null?void 0:va.showReasoning)!=null?Ca:!0,Ae=(Sa=(wa=n.features)==null?void 0:wa.showToolCalls)!=null?Sa:!0;let D=le;if(le=(Ea=(Aa=n.features)==null?void 0:Aa.showEventStreamToggle)!=null?Ea:!1,le&&!D){if(F||(K=new lo(ie),F=new io(be,K),K.open().then(()=>F==null?void 0:F.restore()).catch(()=>{}),H.setSSEEventCallback(($,Ge)=>{F.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:$,timestamp:Date.now(),payload:JSON.stringify(Ge)})})),!Ce&&Je){let $=(Ma=(Ta=n.features)==null?void 0:Ta.eventStream)==null?void 0:Ma.classNames,Ge="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+($!=null&&$.toggleButton?" "+$.toggleButton:"");Ce=h("button",Ge),Ce.style.width="28px",Ce.style.height="28px",Ce.type="button",Ce.setAttribute("aria-label","Event Stream"),Ce.title="Event Stream";let yt=me("activity","18px","currentColor",1.5);yt&&Ce.appendChild(yt);let Oe=J.clearChatButtonWrapper,rt=J.closeButtonWrapper,Rt=Oe||rt;Rt&&Rt.parentNode===Je?Je.insertBefore(Ce,Rt):Je.appendChild(Ce),Ce.addEventListener("click",()=>{he?et():Ke()})}}else!le&&D&&(et(),Ce&&(Ce.remove(),Ce=null),F==null||F.clear(),K==null||K.destroy(),F=null,K=null);if(((ka=n.launcher)==null?void 0:ka.enabled)===!1&&Ne&&(Ne.destroy(),Ne=null),((La=n.launcher)==null?void 0:La.enabled)===!1&&_e&&(_e.remove(),_e=null),((Pa=n.launcher)==null?void 0:Pa.enabled)!==!1&&!Ne&&!_e){let $=s.find(Ge=>Ge.renderLauncher);if($!=null&&$.renderLauncher){let Ge=$.renderLauncher({config:n,defaultRenderer:()=>ro(n,tt).element,onToggle:tt});Ge&&(_e=Ge,e.appendChild(_e))}_e||(Ne=ro(n,tt),e.appendChild(Ne.element))}Ne&&Ne.update(n),ot&&((Ia=n.launcher)==null?void 0:Ia.title)!==void 0&&(ot.textContent=n.launcher.title),gt&&((Wa=n.launcher)==null?void 0:Wa.subtitle)!==void 0&&(gt.textContent=n.launcher.subtitle);let oe=(Ra=n.layout)==null?void 0:Ra.header;if((oe==null?void 0:oe.layout)!==W&&Je){let $=oe?oo(n,oe,{showClose:b,onClose:()=>ht(!1,"user")}):_n({config:n,showClose:b,onClose:()=>ht(!1,"user")});Je.replaceWith($.header),Je=$.header,ce=$.iconHolder,ot=$.headerTitle,gt=$.headerSubtitle,pe=$.closeButton,W=oe==null?void 0:oe.layout}else if(oe&&(ce&&(ce.style.display=oe.showIcon===!1?"none":""),ot&&(ot.style.display=oe.showTitle===!1?"none":""),gt&&(gt.style.display=oe.showSubtitle===!1?"none":""),pe&&(pe.style.display=oe.showCloseButton===!1?"none":""),J.clearChatButtonWrapper)){let $=oe.showClearChat;if($!==void 0){J.clearChatButtonWrapper.style.display=$?"":"none";let{closeButtonWrapper:Ge}=J;Ge&&!Ge.classList.contains("persona-absolute")&&($?Ge.classList.remove("persona-ml-auto"):Ge.classList.add("persona-ml-auto"))}}let ve=((Ha=n.layout)==null?void 0:Ha.showHeader)!==!1;Je&&(Je.style.display=ve?"":"none");let We=((Ba=n.layout)==null?void 0:Ba.showFooter)!==!1;st&&(st.style.display=We?"":"none"),b!==A?b?ht(x,"auto"):(k=!0,Zn()):x!==O&&ht(x,"auto"),O=x,A=b,Tt(),De();let Le=JSON.stringify(l.toolCall)!==JSON.stringify(g),Pe=JSON.stringify(n.messageActions)!==JSON.stringify(y),ae=JSON.stringify((Da=n.layout)==null?void 0:Da.messages)!==JSON.stringify(E),Re=((Na=n.loadingIndicator)==null?void 0:Na.render)!==(I==null?void 0:I.render)||((Oa=n.loadingIndicator)==null?void 0:Oa.renderIdle)!==(I==null?void 0:I.renderIdle)||((Fa=n.loadingIndicator)==null?void 0:Fa.showBubble)!==(I==null?void 0:I.showBubble),nt=n.iterationDisplay!==P;(Le||Pe||ae||Re||nt)&&H&&(Wr++,Xn(Me,H.getMessages(),z));let ue=($a=n.launcher)!=null?$a:{},Wt=(_a=ue.headerIconHidden)!=null?_a:!1,lt=(za=(ja=n.layout)==null?void 0:ja.header)==null?void 0:za.showIcon,Qt=Wt||lt===!1,Ut=ue.headerIconName,Yt=(qa=ue.headerIconSize)!=null?qa:"48px";if(ce){let $=Q.querySelector(".persona-border-b-persona-divider"),Ge=$==null?void 0:$.querySelector(".persona-flex-col");if(Qt)ce.style.display="none",$&&Ge&&!$.contains(Ge)&&$.insertBefore(Ge,$.firstChild);else{if(ce.style.display="",ce.style.height=Yt,ce.style.width=Yt,$&&Ge&&($.contains(ce)?ce.nextSibling!==Ge&&(ce.remove(),$.insertBefore(ce,Ge)):$.insertBefore(ce,Ge)),Ut){let Oe=parseFloat(Yt)||24,rt=me(Ut,Oe*.6,"#ffffff",2);rt?ce.replaceChildren(rt):ce.textContent=(Ua=ue.agentIconText)!=null?Ua:"\u{1F4AC}"}else if(ue.iconUrl){let Oe=ce.querySelector("img");if(Oe)Oe.src=ue.iconUrl,Oe.style.height=Yt,Oe.style.width=Yt;else{let rt=document.createElement("img");rt.src=ue.iconUrl,rt.alt="",rt.className="persona-rounded-xl persona-object-cover",rt.style.height=Yt,rt.style.width=Yt,ce.replaceChildren(rt)}}else{let Oe=ce.querySelector("svg"),rt=ce.querySelector("img");(Oe||rt)&&ce.replaceChildren(),ce.textContent=(Va=ue.agentIconText)!=null?Va:"\u{1F4AC}"}let yt=ce.querySelector("img");yt&&(yt.style.height=Yt,yt.style.width=Yt)}}let Nt=(Ka=(Ja=n.layout)==null?void 0:Ja.header)==null?void 0:Ka.showTitle,cn=(Ga=(Ya=n.layout)==null?void 0:Ya.header)==null?void 0:Ga.showSubtitle;if(ot&&(ot.style.display=Nt===!1?"none":""),gt&&(gt.style.display=cn===!1?"none":""),pe){((Za=(Xa=n.layout)==null?void 0:Xa.header)==null?void 0:Za.showCloseButton)===!1?pe.style.display="none":pe.style.display="";let Ge=(Qa=ue.closeButtonSize)!=null?Qa:"32px",yt=(ei=ue.closeButtonPlacement)!=null?ei:"inline";pe.style.height=Ge,pe.style.width=Ge;let{closeButtonWrapper:Oe}=J,rt=yt==="top-right",Rt=Oe==null?void 0:Oe.classList.contains("persona-absolute");if(Oe&&rt!==Rt)if(Oe.remove(),rt)Oe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",Q.style.position="relative",Q.appendChild(Oe);else{let Qe=(ni=(ti=ue.clearChat)==null?void 0:ti.placement)!=null?ni:"inline",Ot=(oi=(ri=ue.clearChat)==null?void 0:ri.enabled)!=null?oi:!0;Oe.className=Ot&&Qe==="inline"?"":"persona-ml-auto";let tn=Q.querySelector(".persona-border-b-persona-divider");tn&&tn.appendChild(Oe)}if(pe.style.color=ue.closeButtonColor||yn.actionIconColor,ue.closeButtonBackgroundColor?(pe.style.backgroundColor=ue.closeButtonBackgroundColor,pe.classList.remove("hover:persona-bg-gray-100")):(pe.style.backgroundColor="",pe.classList.add("hover:persona-bg-gray-100")),ue.closeButtonBorderWidth||ue.closeButtonBorderColor){let Qe=ue.closeButtonBorderWidth||"0px",Ot=ue.closeButtonBorderColor||"transparent";pe.style.border=`${Qe} solid ${Ot}`,pe.classList.remove("persona-border-none")}else pe.style.border="",pe.classList.add("persona-border-none");ue.closeButtonBorderRadius?(pe.style.borderRadius=ue.closeButtonBorderRadius,pe.classList.remove("persona-rounded-full")):(pe.style.borderRadius="",pe.classList.add("persona-rounded-full")),ue.closeButtonPaddingX?(pe.style.paddingLeft=ue.closeButtonPaddingX,pe.style.paddingRight=ue.closeButtonPaddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),ue.closeButtonPaddingY?(pe.style.paddingTop=ue.closeButtonPaddingY,pe.style.paddingBottom=ue.closeButtonPaddingY):(pe.style.paddingTop="",pe.style.paddingBottom="");let $t=(si=ue.closeButtonIconName)!=null?si:"x",mn=(ai=ue.closeButtonIconText)!=null?ai:"\xD7";pe.innerHTML="";let Gt=me($t,"20px","currentColor",2);Gt?pe.appendChild(Gt):pe.textContent=mn;let Et=(ii=ue.closeButtonTooltipText)!=null?ii:"Close chat",on=(li=ue.closeButtonShowTooltip)!=null?li:!0;if(pe.setAttribute("aria-label",Et),Oe&&(Oe._cleanupTooltip&&(Oe._cleanupTooltip(),delete Oe._cleanupTooltip),on&&Et)){let Qe=null,Ot=()=>{if(Qe||!pe)return;let nr=pe.ownerDocument,Vr=nr.body;if(!Vr)return;Qe=An(nr,"div","persona-clear-chat-tooltip"),Qe.textContent=Et;let Jr=An(nr,"div");Jr.className="persona-clear-chat-tooltip-arrow",Qe.appendChild(Jr);let rr=pe.getBoundingClientRect();Qe.style.position="fixed",Qe.style.left=`${rr.left+rr.width/2}px`,Qe.style.top=`${rr.top-8}px`,Qe.style.transform="translate(-50%, -100%)",Vr.appendChild(Qe)},tn=()=>{Qe&&Qe.parentNode&&(Qe.parentNode.removeChild(Qe),Qe=null)};Oe.addEventListener("mouseenter",Ot),Oe.addEventListener("mouseleave",tn),pe.addEventListener("focus",Ot),pe.addEventListener("blur",tn),Oe._cleanupTooltip=()=>{tn(),Oe&&(Oe.removeEventListener("mouseenter",Ot),Oe.removeEventListener("mouseleave",tn)),pe&&(pe.removeEventListener("focus",Ot),pe.removeEventListener("blur",tn))}}}let{clearChatButton:Ue,clearChatButtonWrapper:vt}=J;if(Ue){let $=(ci=ue.clearChat)!=null?ci:{},Ge=(di=$.enabled)!=null?di:!0,yt=(ui=(pi=n.layout)==null?void 0:pi.header)==null?void 0:ui.showClearChat,Oe=yt!==void 0?yt:Ge,rt=(gi=$.placement)!=null?gi:"inline";if(vt){vt.style.display=Oe?"":"none";let{closeButtonWrapper:Rt}=J;Rt&&!Rt.classList.contains("persona-absolute")&&(Oe?Rt.classList.remove("persona-ml-auto"):Rt.classList.add("persona-ml-auto"));let $t=rt==="top-right",mn=vt.classList.contains("persona-absolute");if($t!==mn&&Oe){if(vt.remove(),$t)vt.className="persona-absolute persona-top-4 persona-z-50",vt.style.right="48px",Q.style.position="relative",Q.appendChild(vt);else{vt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",vt.style.right="";let Et=Q.querySelector(".persona-border-b-persona-divider"),on=J.closeButtonWrapper;Et&&on&&on.parentElement===Et?Et.insertBefore(vt,on):Et&&Et.appendChild(vt)}let Gt=J.closeButtonWrapper;Gt&&!Gt.classList.contains("persona-absolute")&&($t?Gt.classList.add("persona-ml-auto"):Gt.classList.remove("persona-ml-auto"))}}if(Oe){let Rt=(mi=$.size)!=null?mi:"32px";Ue.style.height=Rt,Ue.style.width=Rt;let $t=(fi=$.iconName)!=null?fi:"refresh-cw",mn=(hi=$.iconColor)!=null?hi:"";Ue.style.color=mn||yn.actionIconColor,Ue.innerHTML="";let Gt=me($t,"20px","currentColor",2);if(Gt&&Ue.appendChild(Gt),$.backgroundColor?(Ue.style.backgroundColor=$.backgroundColor,Ue.classList.remove("hover:persona-bg-gray-100")):(Ue.style.backgroundColor="",Ue.classList.add("hover:persona-bg-gray-100")),$.borderWidth||$.borderColor){let Qe=$.borderWidth||"0px",Ot=$.borderColor||"transparent";Ue.style.border=`${Qe} solid ${Ot}`,Ue.classList.remove("persona-border-none")}else Ue.style.border="",Ue.classList.add("persona-border-none");$.borderRadius?(Ue.style.borderRadius=$.borderRadius,Ue.classList.remove("persona-rounded-full")):(Ue.style.borderRadius="",Ue.classList.add("persona-rounded-full")),$.paddingX?(Ue.style.paddingLeft=$.paddingX,Ue.style.paddingRight=$.paddingX):(Ue.style.paddingLeft="",Ue.style.paddingRight=""),$.paddingY?(Ue.style.paddingTop=$.paddingY,Ue.style.paddingBottom=$.paddingY):(Ue.style.paddingTop="",Ue.style.paddingBottom="");let Et=(yi=$.tooltipText)!=null?yi:"Clear chat",on=(bi=$.showTooltip)!=null?bi:!0;if(Ue.setAttribute("aria-label",Et),vt&&(vt._cleanupTooltip&&(vt._cleanupTooltip(),delete vt._cleanupTooltip),on&&Et)){let Qe=null,Ot=()=>{if(Qe||!Ue)return;let nr=Ue.ownerDocument,Vr=nr.body;if(!Vr)return;Qe=An(nr,"div","persona-clear-chat-tooltip"),Qe.textContent=Et;let Jr=An(nr,"div");Jr.className="persona-clear-chat-tooltip-arrow",Qe.appendChild(Jr);let rr=Ue.getBoundingClientRect();Qe.style.position="fixed",Qe.style.left=`${rr.left+rr.width/2}px`,Qe.style.top=`${rr.top-8}px`,Qe.style.transform="translate(-50%, -100%)",Vr.appendChild(Qe)},tn=()=>{Qe&&Qe.parentNode&&(Qe.parentNode.removeChild(Qe),Qe=null)};vt.addEventListener("mouseenter",Ot),vt.addEventListener("mouseleave",tn),Ue.addEventListener("focus",Ot),Ue.addEventListener("blur",tn),vt._cleanupTooltip=()=>{tn(),vt&&(vt.removeEventListener("mouseenter",Ot),vt.removeEventListener("mouseleave",tn)),Ue&&(Ue.removeEventListener("focus",Ot),Ue.removeEventListener("blur",tn))}}}}let Co=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Uo],wo=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Tr.message,Tr.messageAndClick];T=Vo({parsers:Co,handlers:wo,getSessionMetadata:p,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),z=tc(n,T,de),H.updateConfig(n),Xn(Me,H.getMessages(),z),Nn.render(n.suggestionChips,H,ee,void 0,n.suggestionChipsConfig),Nr(),ur(H.isStreaming());let So=((xi=n.voiceRecognition)==null?void 0:xi.enabled)===!0,Ao=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Eo=((Ci=(vi=n.voiceRecognition)==null?void 0:vi.provider)==null?void 0:Ci.type)==="runtype";if(So&&(Ao||Eo))if(!S||!V){let $=bo(n.voiceRecognition,n.sendButton);$&&(S=$.micButton,V=$.micButtonWrapper,qt.insertBefore(V,Ve),S.addEventListener("click",tr),S.disabled=H.isStreaming())}else{let $=(wi=n.voiceRecognition)!=null?wi:{},Ge=(Si=n.sendButton)!=null?Si:{},yt=(Ai=$.iconName)!=null?Ai:"mic",Oe=(Ei=Ge.size)!=null?Ei:"40px",rt=(Ti=$.iconSize)!=null?Ti:Oe,Rt=parseFloat(rt)||24;S.style.width=rt,S.style.height=rt,S.style.minWidth=rt,S.style.minHeight=rt;let $t=(ki=(Mi=$.iconColor)!=null?Mi:Ge.textColor)!=null?ki:"currentColor";S.innerHTML="";let mn=me(yt,Rt,$t,2);mn?S.appendChild(mn):S.textContent="\u{1F3A4}";let Gt=(Li=$.backgroundColor)!=null?Li:Ge.backgroundColor;Gt?(S.style.backgroundColor=Gt,S.classList.remove("persona-bg-persona-primary")):(S.style.backgroundColor="",S.classList.add("persona-bg-persona-primary")),$t?(S.style.color=$t,S.classList.remove("persona-text-white")):!$t&&!Ge.textColor&&(S.style.color="",S.classList.add("persona-text-white")),$.borderWidth?(S.style.borderWidth=$.borderWidth,S.style.borderStyle="solid"):(S.style.borderWidth="",S.style.borderStyle=""),$.borderColor?S.style.borderColor=$.borderColor:S.style.borderColor="",$.paddingX?(S.style.paddingLeft=$.paddingX,S.style.paddingRight=$.paddingX):(S.style.paddingLeft="",S.style.paddingRight=""),$.paddingY?(S.style.paddingTop=$.paddingY,S.style.paddingBottom=$.paddingY):(S.style.paddingTop="",S.style.paddingBottom="");let Et=V==null?void 0:V.querySelector(".persona-send-button-tooltip"),on=(Pi=$.tooltipText)!=null?Pi:"Start voice recognition";if(((Ii=$.showTooltip)!=null?Ii:!1)&&on)if(Et)Et.textContent=on,Et.style.display="";else{let Ot=document.createElement("div");Ot.className="persona-send-button-tooltip",Ot.textContent=on,V==null||V.insertBefore(Ot,S)}else Et&&(Et.style.display="none");V.style.display="",S.disabled=H.isStreaming()}else S&&V&&(V.style.display="none",((Ri=(Wi=n.voiceRecognition)==null?void 0:Wi.provider)==null?void 0:Ri.type)==="runtype"?H.isVoiceActive()&&H.toggleVoice():rn&&un());if(((Hi=n.attachments)==null?void 0:Hi.enabled)===!0)if(!$e||!te){let $=(Bi=n.attachments)!=null?Bi:{},yt=(Ni=((Di=n.sendButton)!=null?Di:{}).size)!=null?Ni:"40px";ze||(ze=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ze.style.display="none",Ie.insertBefore(ze,ee)),se||(se=document.createElement("input"),se.type="file",se.accept=((Oi=$.allowedTypes)!=null?Oi:Rn).join(","),se.multiple=((Fi=$.maxFiles)!=null?Fi:4)>1,se.style.display="none",se.setAttribute("aria-label","Attach files"),Ie.insertBefore(se,ee)),$e=h("div","persona-send-button-wrapper"),te=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),te.type="button",te.setAttribute("aria-label",($i=$.buttonTooltipText)!=null?$i:"Attach file");let Oe=(_i=$.buttonIconName)!=null?_i:"paperclip",rt=yt,Rt=parseFloat(rt)||40,$t=Math.round(Rt*.6);te.style.width=rt,te.style.height=rt,te.style.minWidth=rt,te.style.minHeight=rt,te.style.fontSize="18px",te.style.lineHeight="1",te.style.backgroundColor="transparent",te.style.color="var(--persona-primary, #111827)",te.style.border="none",te.style.borderRadius="6px",te.style.transition="background-color 0.15s ease",te.addEventListener("mouseenter",()=>{te.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),te.addEventListener("mouseleave",()=>{te.style.backgroundColor="transparent"});let mn=me(Oe,$t,"currentColor",1.5);mn?te.appendChild(mn):te.textContent="\u{1F4CE}",te.addEventListener("click",on=>{on.preventDefault(),se==null||se.click()}),$e.appendChild(te);let Gt=(ji=$.buttonTooltipText)!=null?ji:"Attach file",Et=h("div","persona-send-button-tooltip");Et.textContent=Gt,$e.appendChild(Et),Lt.append($e),!Se&&se&&ze&&(Se=vr.fromConfig($),Se.setPreviewsContainer(ze),se.addEventListener("change",async()=>{Se&&(se!=null&&se.files)&&(await Se.handleFileSelect(se.files),se.value="")}))}else{$e.style.display="";let $=(zi=n.attachments)!=null?zi:{};se&&(se.accept=((qi=$.allowedTypes)!=null?qi:Rn).join(","),se.multiple=((Ui=$.maxFiles)!=null?Ui:4)>1),Se&&Se.updateConfig({allowedTypes:$.allowedTypes,maxFileSize:$.maxFileSize,maxFiles:$.maxFiles})}else $e&&($e.style.display="none"),Se&&Se.clearAttachments();let kt=(Vi=n.sendButton)!=null?Vi:{},To=(Ji=kt.useIcon)!=null?Ji:!1,jr=(Ki=kt.iconText)!=null?Ki:"\u2191",en=kt.iconName,dn=(Yi=kt.tooltipText)!=null?Yi:"Send message",Mo=(Gi=kt.showTooltip)!=null?Gi:!1,zr=(Xi=kt.size)!=null?Xi:"40px",ko=kt.backgroundColor,Sn=kt.textColor;if(To){if(Y.style.width=zr,Y.style.height=zr,Y.style.minWidth=zr,Y.style.minHeight=zr,Y.style.fontSize="18px",Y.style.lineHeight="1",Y.innerHTML="",en){let $=parseFloat(zr)||24,Ge=Sn&&typeof Sn=="string"&&Sn.trim()?Sn.trim():"currentColor",yt=me(en,$,Ge,2);yt?(Y.appendChild(yt),Y.style.color=Ge):(Y.textContent=jr,Sn?Y.style.color=Sn:Y.classList.add("persona-text-white"))}else Y.textContent=jr,Sn?Y.style.color=Sn:Y.classList.add("persona-text-white");Y.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",ko?(Y.style.backgroundColor=ko,Y.classList.remove("persona-bg-persona-primary")):Y.classList.add("persona-bg-persona-primary")}else Y.textContent=(Qi=(Zi=n.copy)==null?void 0:Zi.sendButtonLabel)!=null?Qi:"Send",Y.style.width="",Y.style.height="",Y.style.minWidth="",Y.style.minHeight="",Y.style.fontSize="",Y.style.lineHeight="",Y.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",ko?(Y.style.backgroundColor=ko,Y.classList.remove("persona-bg-persona-accent")):Y.classList.add("persona-bg-persona-accent"),Sn?Y.style.color=Sn:Y.classList.add("persona-text-white");kt.borderWidth?(Y.style.borderWidth=kt.borderWidth,Y.style.borderStyle="solid"):(Y.style.borderWidth="",Y.style.borderStyle=""),kt.borderColor?Y.style.borderColor=kt.borderColor:Y.style.borderColor="",kt.paddingX?(Y.style.paddingLeft=kt.paddingX,Y.style.paddingRight=kt.paddingX):(Y.style.paddingLeft="",Y.style.paddingRight=""),kt.paddingY?(Y.style.paddingTop=kt.paddingY,Y.style.paddingBottom=kt.paddingY):(Y.style.paddingTop="",Y.style.paddingBottom="");let qr=Ve==null?void 0:Ve.querySelector(".persona-send-button-tooltip");if(Mo&&dn)if(qr)qr.textContent=dn,qr.style.display="";else{let $=document.createElement("div");$.className="persona-send-button-tooltip",$.textContent=dn,Ve==null||Ve.insertBefore($,Y)}else qr&&(qr.style.display="none");let Ur=(el=n.statusIndicator)!=null?el:{},Ic=(tl=Ur.visible)!=null?tl:!0;if(ft.style.display=Ic?"":"none",H){let $=H.getStatus(),Ge=yt=>{var Oe,rt,Rt,$t;return yt==="idle"?(Oe=Ur.idleText)!=null?Oe:Vt.idle:yt==="connecting"?(rt=Ur.connectingText)!=null?rt:Vt.connecting:yt==="connected"?(Rt=Ur.connectedText)!=null?Rt:Vt.connected:yt==="error"?($t=Ur.errorText)!=null?$t:Vt.error:Vt[yt]};ft.textContent=Ge($)}},open(){b&&ht(!0,"api")},close(){b&&ht(!1,"api")},toggle(){b&&ht(!k,"api")},clearChat(){Jt=!1,H.clearMessages(),Fn.clear();try{localStorage.removeItem(Mr),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Mr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Mr)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let g=a.clear();g instanceof Promise&&g.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}i={},T.syncFromMetadata(),F==null||F.clear(),U==null||U.update()},setMessage(l){return!ee||H.isStreaming()?!1:(!k&&b&&ht(!0,"system"),ee.value=l,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(H.isStreaming())return!1;let g=(l==null?void 0:l.trim())||ee.value.trim();return g?(!k&&b&&ht(!0,"system"),ee.value="",ee.style.height="auto",H.sendMessage(g),!0):!1},startVoiceRecognition(){var g,y;return H.isStreaming()?!1:((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype"?(H.isVoiceActive()||(!k&&b&&ht(!0,"system"),je.manuallyDeactivated=!1,Xt(),H.toggleVoice().then(()=>{je.active=H.isVoiceActive(),an("user"),H.isVoiceActive()&&$n()})),!0):rn?!0:_r()?(!k&&b&&ht(!0,"system"),je.manuallyDeactivated=!1,Xt(),Qn("user"),!0):!1},stopVoiceRecognition(){var l,g;return((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?H.isVoiceActive()?(H.toggleVoice().then(()=>{je.active=!1,je.manuallyDeactivated=!0,Xt(),an("user"),gn()}),!0):!1:rn?(je.manuallyDeactivated=!0,Xt(),un("user"),!0):!1},injectMessage(l){return!k&&b&&ht(!0,"system"),H.injectMessage(l)},injectAssistantMessage(l){!k&&b&&ht(!0,"system");let g=H.injectAssistantMessage(l);return q&&(q=!1,fe&&(clearTimeout(fe),fe=null),setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)),g},injectUserMessage(l){return!k&&b&&ht(!0,"system"),H.injectUserMessage(l)},injectSystemMessage(l){return!k&&b&&ht(!0,"system"),H.injectSystemMessage(l)},injectMessageBatch(l){return!k&&b&&ht(!0,"system"),H.injectMessageBatch(l)},injectTestMessage(l){!k&&b&&ht(!0,"system"),H.injectTestEvent(l)},async connectStream(l,g){return H.connectStream(l,g)},__pushEventStreamEvent(l){F&&F.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!le||!F||Ke()},hideEventStream(){he&&et()},isEventStreamVisible(){return he},showArtifacts(){pn(n)&&(Jt=!1,vn(),Ze==null||Ze.setMobileOpen(!0))},hideArtifacts(){pn(n)&&(Jt=!0,vn())},upsertArtifact(l){return pn(n)?(Jt=!1,H.upsertArtifact(l)):null},selectArtifact(l){pn(n)&&H.selectArtifact(l)},clearArtifacts(){pn(n)&&H.clearArtifacts()},focusInput(){return b&&!k||!ee?!1:(ee.focus(),!0)},async resolveApproval(l,g){let E=H.getMessages().find(L=>{var I;return L.variant==="approval"&&((I=L.approval)==null?void 0:I.id)===l});if(!(E!=null&&E.approval))throw new Error(`Approval not found: ${l}`);return H.resolveApproval(E.approval,g)},getMessages(){return H.getMessages()},getStatus(){return H.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){f(l)},on(l,g){return o.on(l,g)},off(l,g){o.off(l,g)},isOpen(){return b&&k},isVoiceActive(){return je.active},getState(){return{open:b&&k,launcherEnabled:b,voiceActive:je.active,streaming:H.isStreaming()}},showCSATFeedback(l){!k&&b&&ht(!0,"system");let g=Me.querySelector(".persona-feedback-container");g&&g.remove();let y=Is({onSubmit:async(E,L)=>{var I;H.isClientTokenMode()&&await H.submitCSATFeedback(E,L),(I=l==null?void 0:l.onSubmit)==null||I.call(l,E,L)},onDismiss:l==null?void 0:l.onDismiss,...l});Me.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!k&&b&&ht(!0,"system");let g=Me.querySelector(".persona-feedback-container");g&&g.remove();let y=Ws({onSubmit:async(E,L)=>{var I;H.isClientTokenMode()&&await H.submitNPSFeedback(E,L),(I=l==null?void 0:l.onSubmit)==null||I.call(l,E,L)},onDismiss:l==null?void 0:l.onDismiss,...l});Me.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return H.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return H.submitNPSFeedback(l,g)},destroy(){wt.forEach(l=>l()),xe.remove(),Ne==null||Ne.destroy(),_e==null||_e.remove(),wn&&pe.removeEventListener("click",wn)}};if((((ca=t==null?void 0:t.debugTools)!=null?ca:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,g={controller:w,getMessages:w.getMessages,getStatus:w.getStatus,getMetadata:w.getPersistentMetadata,updateMetadata:w.updatePersistentMetadata,clearHistory:()=>w.clearChat(),setVoiceActive:y=>y?w.startVoiceRecognition():w.stopVoiceRecognition()};window.AgentWidgetBrowser=g,wt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=j=>{let D=j.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&w.focusInput()};if(window.addEventListener("persona:focusInput",g),wt.push(()=>{window.removeEventListener("persona:focusInput",g)}),le){let j=oe=>{let ye=oe.detail;(!(ye!=null&&ye.instanceId)||ye.instanceId===l)&&w.showEventStream()},D=oe=>{let ye=oe.detail;(!(ye!=null&&ye.instanceId)||ye.instanceId===l)&&w.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",D),wt.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",D)})}let y=j=>{let D=j.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&w.showArtifacts()},E=j=>{let D=j.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&w.hideArtifacts()},L=j=>{let D=j.detail;D!=null&&D.instanceId&&D.instanceId!==l||D!=null&&D.artifact&&w.upsertArtifact(D.artifact)},I=j=>{let D=j.detail;D!=null&&D.instanceId&&D.instanceId!==l||typeof(D==null?void 0:D.id)=="string"&&w.selectArtifact(D.id)},P=j=>{let D=j.detail;(!(D!=null&&D.instanceId)||D.instanceId===l)&&w.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",E),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",I),window.addEventListener("persona:clearArtifacts",P),wt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",E),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",I),window.removeEventListener("persona:clearArtifacts",P)})}let Z=rp(n.persistState);if(Z&&b){let l=op(Z.storage),g=`${Z.keyPrefix}widget-open`,y=`${Z.keyPrefix}widget-voice`,E=`${Z.keyPrefix}widget-voice-mode`;if(l){let L=((da=Z.persist)==null?void 0:da.openState)&&l.getItem(g)==="true",I=((pa=Z.persist)==null?void 0:pa.voiceState)&&l.getItem(y)==="true",P=((ua=Z.persist)==null?void 0:ua.voiceState)&&l.getItem(E)==="true";if(L&&setTimeout(()=>{w.open(),setTimeout(()=>{var j;if(I||P)w.startVoiceRecognition();else if((j=Z.persist)!=null&&j.focusInput){let D=e.querySelector("textarea");D&&D.focus()}},100)},0),(ga=Z.persist)!=null&&ga.openState&&(o.on("widget:opened",()=>{l.setItem(g,"true")}),o.on("widget:closed",()=>{l.setItem(g,"false")})),(ma=Z.persist)!=null&&ma.voiceState&&(o.on("voice:state",j=>{l.setItem(y,j.active?"true":"false")}),o.on("user:message",j=>{l.setItem(E,j.viaVoice?"true":"false")})),Z.clearOnChatClear){let j=()=>{l.removeItem(g),l.removeItem(y),l.removeItem(E)},D=()=>j();window.addEventListener("persona:clear-chat",D),wt.push(()=>{window.removeEventListener("persona:clear-chat",D)})}}}return c&&b&&setTimeout(()=>{w.open()},0),w};var sp=(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},nc=(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"},Os=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=""},rc=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Os(e)},Bs=e=>{e.style.transition=""},Ds=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=""},Ns=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Jo=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},ap=(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))},ip=(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)},oc=(e,r,t,n,s,o,a)=>{var C,T,b,x;let i=fn(o),d=i.reveal==="push";ap(e,r,t,n,d),ip(e,r,t,n,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",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,u=(T=(C=o==null?void 0:o.launcher)==null?void 0:C.mobileFullscreen)!=null?T:!0,p=(x=(b=o==null?void 0:o.launcher)==null?void 0:b.mobileBreakpoint)!=null?x:640,f=c!=null?c.innerWidth<=p:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Ds(r),Bs(n),rc(n),Ns(t),Jo(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="9999",n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(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"),rc(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Ds(r),Bs(n),Ns(t),Jo(s,n);let M=i.animate?"transform 180ms ease":"none",O=i.side==="right"?"translateX(100%)":"translateX(-100%)",A=a?"translateX(0)":O;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=M,n.style.transform=A,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",Bs(n),Os(n),Jo(s,n);let M=sp(i.width,e.clientWidth),O=Math.max(0,e.clientWidth),A=i.animate?"transform 180ms ease":"none",W=i.side==="right"?a?`translateX(-${M}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${M}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=`${O+M}px`,r.style.transition=A,r.style.transform=W,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${O}px`,t.style.maxWidth=`${O}px`,t.style.minWidth=`${O}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="",Ds(r),Os(n),Ns(t),Jo(s,n);let M=i.reveal==="emerge";M?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let O=a?i.width:"0px",A=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",W=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${O}`,n.style.width=O,n.style.maxWidth=O,n.style.minWidth=O,n.style.minHeight="0",n.style.position="relative",n.style.overflow=M||W?"hidden":"visible",n.style.transition=A,M&&(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")}},lp=(e,r)=>{let t=e.ownerDocument.createElement("div");return nc(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){nc(t,n)},destroy(){t.remove()}}},cp=(e,r)=>{var M,O,A,W;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"),d=t.createElement("div"),c=t.createElement("aside"),u=t.createElement("div"),p=(O=(M=r==null?void 0:r.launcher)==null?void 0:M.enabled)==null||O?(W=(A=r==null?void 0:r.launcher)==null?void 0:A.autoExpand)!=null?W:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",c.appendChild(u),n.insertBefore(a,e),d.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},C=()=>{m(),fn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{oc(a,i,d,c,u,r,p)}),f.observe(a))},T=()=>{oc(a,i,d,c,u,r,p),C()},b=a.ownerDocument.defaultView,x=()=>{T()};return b==null||b.addEventListener("resize",x),fn(r).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),T(),{mode:"docked",host:u,shell:a,syncWidgetState(_){let k=_.launcherEnabled?_.open:!0;p!==k&&(p=k,T())},updateConfig(_){var k,q;r=_,((q=(k=r==null?void 0:r.launcher)==null?void 0:k.enabled)!=null?q:!0)===!1&&(p=!0),T()},destroy(){b==null||b.removeEventListener("resize",x),m(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},Ko=(e,r)=>_t(r)?cp(e,r):lp(e,r);var Fs={},dp=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},pp=()=>{try{if(typeof Fs!="undefined"&&Fs.url)return new URL("../widget.css",Fs.url).href}catch{}return null},sc=(e,r)=>{let t=pp(),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)}},ac=e=>{var b;let r=dp(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=Ko(r,s),a,i=[],d=(x,M)=>{var _,k;let A=!((k=(_=M==null?void 0:M.launcher)==null?void 0:_.enabled)!=null?k:!0)||_t(M),W=n.createElement("div");if(W.setAttribute("data-persona-root","true"),A&&(W.style.height="100%",W.style.display="flex",W.style.flexDirection="column",W.style.flex="1",W.style.minHeight="0"),t){let q=x.attachShadow({mode:"open"});q.appendChild(W),sc(q,n)}else x.appendChild(W),sc(x,n);return r.id&&W.setAttribute("data-persona-instance",r.id),W},c=()=>{o.syncWidgetState(a.getState())},u=()=>{i.forEach(x=>x()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},p=()=>{let x=d(o.host,s);a=Hs(x,s,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(x=>x()),i=[],a.destroy()};p(),(b=e.onReady)==null||b.call(e);let m=x=>{f(),o.destroy(),o=Ko(r,x),s=x,p()},C={update(x){var W,_,k,q,fe,de;let M={...s,...x,launcher:{...(W=s==null?void 0:s.launcher)!=null?W:{},...(_=x==null?void 0:x.launcher)!=null?_:{},dock:{...(q=(k=s==null?void 0:s.launcher)==null?void 0:k.dock)!=null?q:{},...(de=(fe=x==null?void 0:x.launcher)==null?void 0:fe.dock)!=null?de:{}}}},O=_t(s),A=_t(M);if(O!==A){m(M);return}s=M,o.updateConfig(s),a.update(x),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},T=new Proxy(C,{get(x,M,O){if(M==="host")return o.host;if(M in x)return Reflect.get(x,M,O);let A=a[M];return typeof A=="function"?A.bind(a):A}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=T),T};var pc=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),up=new Set(["button","a","input","select","textarea","details","summary"]),gp=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),$s=/\b(product|card|item|listing|result)\b/i,js=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,mp=3e3,fp=100;function uc(e){let r=typeof e.className=="string"?e.className:"";if($s.test(r)||e.id&&$s.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&$s.test(n.value))return!0}return!1}function gc(e){var r;return js.test(((r=e.textContent)!=null?r:"").trim())}function mc(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 hp(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ic(e){let r=e.match(js);return r?r[0]:null}function lc(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 yp(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 bp="commerce-card",xp="result-card";function cc(e){return!uc(e)||!gc(e)||!mc(e)&&!hp(e)?0:5200}function dc(e){var n;return!uc(e)||gc(e)||!mc(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 fc=[{id:bp,scoreElement(e){return cc(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||js.test(n)&&n.length<32)}return!0},formatSummary(e,r){var d,c,u;if(cc(e)===0)return null;let{title:t,href:n}=lc(e),s=(u=(c=ic(((d=e.textContent)!=null?d:"").trim()))!=null?c:ic(r.text))!=null?u:"",o=yp(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(`
96
96
  `)}},{id:xp,scoreElement(e){return dc(e)},formatSummary(e,r){if(dc(e)===0)return null;let{title:t,href:n}=lc(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
97
97
  `)}}];function vp(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Cp(e){var u,p,f,m,C,T,b,x,M,O,A,W,_;let r=(u=e.options)!=null?u:{},t=(f=(p=r.maxElements)!=null?p:e.maxElements)!=null?f:80,n=(C=(m=r.excludeSelector)!=null?m:e.excludeSelector)!=null?C:".persona-host",s=(b=(T=r.maxTextLength)!=null?T:e.maxTextLength)!=null?b:200,o=(M=(x=r.visibleOnly)!=null?x:e.visibleOnly)!=null?M:!0,a=(O=r.root)!=null?O:e.root,i=(A=r.mode)!=null?A:"structured",d=(W=r.maxCandidates)!=null?W:Math.max(500,t*10),c=(_=e.rules)!=null?_:fc;return i==="simple"&&e.rules&&e.rules.length>0?(vp(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:n,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function _s(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var wp=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Sp(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"||up.has(r)||t&&gp.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function hc(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 Ap(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 d=e.getAttribute("role");d&&(r.role=d);for(let c=0;c<e.attributes.length;c++){let u=e.attributes[c];u.name.startsWith("data-")&&(r[u.name]=u.value)}return r}function yc(e){let r=e.tagName.toLowerCase();if(e.id){let s=`#${_s(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of wp){let o=e.getAttribute(s);if(o){let a=`${r}[${s}="${_s(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=>_s(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 d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}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 Ep(e){return e==="static"?fp:mp}function bc(e,r){var s;let t=e.tagName.toLowerCase(),n=((s=e.textContent)!=null?s:"").trim().substring(0,r);return{selector:yc(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:Sp(e),attributes:Ap(e)}}function Tp(e,r,t,n){let s=Ep(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 Mp(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 kp(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,u=c.tagName.toLowerCase();if(pc.has(u)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!hc(c)){i=a.nextNode();continue}let p=bc(c,e.maxTextLength),f=p.text.length>0,m=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(b=>b==="role");if(!f&&!m){i=a.nextNode();continue}if(n.has(p.selector)){i=a.nextNode();continue}n.add(p.selector);let{score:C,formattingRule:T}=Tp(c,p,e.rules,t);s.push({el:c,domIndex:o,enriched:p,score:C,formattingRule:T}),o+=1}i=a.nextNode()}s.sort((c,u)=>{let p=c.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:u.score!==c.score?u.score-c.score:c.domIndex-u.domIndex});let d=[];for(let c of s){if(d.length>=e.maxElements)break;Mp(d,c)||d.push(c)}return d.sort((c,u)=>{let p=c.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:p===1&&u.score!==c.score?u.score-c.score:c.domIndex-u.domIndex}),d.map(c=>{var f;let u;if((f=c.formattingRule)!=null&&f.formatSummary){let m=c.formattingRule.formatSummary(c.el,c.enriched,t);m&&(u=m)}let p={...c.enriched};return u&&(p.formattedSummary=u),p})}function Lp(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 d=o,c=d.tagName.toLowerCase();if(pc.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!hc(d)){o=s.nextNode();continue}let u=bc(d,e.maxTextLength),p=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(m=>m==="role");if(!p&&!f){o=s.nextNode();continue}n.has(u.selector)||(n.add(u.selector),t.push(u))}o=s.nextNode()}let a=[],i=[];for(let d of t)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function Pp(e={}){var n;let r=Cp(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?Lp(r,t):kp(r,t):[]}var Yo=100;function Ip(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:
98
98
  ${a.map(i=>`- ${i.split(`
@@ -108,7 +108,7 @@ ${a.join(`
108
108
  ${a.join(`
109
109
  `)}`)}return n.join(`
110
110
 
111
- `)}var xc={name:"@runtypelabs/persona",version:"3.1.1",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"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && npm run build:styles && npm run build:client && npm run build:installer","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 kr=xc.version;function Hn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function Rp(e){if(e)return{getHeaders:Hn(e.getHeaders),onFeedback:Hn(e.onFeedback),onCopy:Hn(e.onCopy),requestMiddleware:Hn(e.requestMiddleware),actionHandlers:Hn(e.actionHandlers),actionParsers:Hn(e.actionParsers),postprocessMessage:Hn(e.postprocessMessage),contextProviders:Hn(e.contextProviders),streamParser:Hn(e.streamParser)}}var vc=`({ text, message }: any) => {
111
+ `)}var xc={name:"@runtypelabs/persona",version:"3.2.1",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"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer","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 kr=xc.version;function Hn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function Rp(e){if(e)return{getHeaders:Hn(e.getHeaders),onFeedback:Hn(e.onFeedback),onCopy:Hn(e.onCopy),requestMiddleware:Hn(e.requestMiddleware),actionHandlers:Hn(e.actionHandlers),actionParsers:Hn(e.actionParsers),postprocessMessage:Hn(e.postprocessMessage),contextProviders:Hn(e.contextProviders),streamParser:Hn(e.streamParser)}}var vc=`({ text, message }: any) => {
112
112
  const jsonSource = (message as any).rawContent || text || message.content;
113
113
  if (!jsonSource || typeof jsonSource !== 'string') return null;
114
114
  let cleanJson = jsonSource