@runtypelabs/persona 3.8.2 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import{Marked as yd}from"marked";var bd=e=>{if(e)return e},Oo=e=>{var s,o;let r=e==null?void 0:e.markedOptions,t=new yd({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=bd(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),a=>t.parse(a)},jr=e=>e?Oo({markedOptions:e.options,renderer:e.renderer}):Oo(),xd=Oo(),Dl=e=>xd(e),mo=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Fl=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Bl=e=>`%%FORM_PLACEHOLDER_${e}%%`,Nl=(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=Bl(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=Bl(r.length);return r.push({token:o,type:s}),o}),t},vd=e=>{let r=jr(e);return t=>{let n=[],s=Nl(t,n),o=r(s);return n.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Fl(i)}"></div>`;o=o.replace(d,p)}),o}},Cd=e=>{let r=[],t=Nl(e,r),n=Dl(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="${Fl(o)}"></div>`;n=n.replace(a,d)}),n};import wd from"dompurify";var Sd={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"]},Ad=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Ol=()=>{let e=wd(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:")&&!Ad.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,Sd)},fo=e=>e===!1?null:typeof e=="function"?e:Ol();import{parse as $l,STR as _l,OBJ as jl}from"partial-json";var $o=e=>e.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ho=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)}},Ed=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`},zl=e=>e.status==="complete"?Ed(e):e.status==="pending"?"Waiting":"",Td=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 Vl=e=>e.status==="complete"?Td(e):"Using tool...",Md=()=>{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,`
1
+ import{Marked as xd}from"marked";var vd=e=>{if(e)return e},zo=e=>{var s,o;let r=e==null?void 0:e.markedOptions,t=new xd({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=vd(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),a=>t.parse(a)},Vr=e=>e?zo({markedOptions:e.options,renderer:e.renderer}):zo(),Cd=zo(),Nl=e=>Cd(e),bo=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;"),Fl=e=>`%%FORM_PLACEHOLDER_${e}%%`,$l=(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=Fl(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=Fl(r.length);return r.push({token:o,type:s}),o}),t},wd=e=>{let r=Vr(e);return t=>{let n=[],s=$l(t,n),o=r(s);return n.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${Ol(i)}"></div>`;o=o.replace(d,p)}),o}},Sd=e=>{let r=[],t=$l(e,r),n=Nl(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 Ad from"dompurify";var Ed={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"]},Td=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,_l=()=>{let e=Ad(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:")&&!Td.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,Ed)},xo=e=>e===!1?null:typeof e=="function"?e:_l();import{parse as jl,STR as zl,OBJ as Ul}from"partial-json";var Uo=e=>e.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),vo=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)}},Md=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`},Vl=e=>e.status==="complete"?Md(e):e.status==="pending"?"Waiting":"",kd=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 ql=e=>e.status==="complete"?kd(e):"Using tool...",Ld=()=>{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()=>{}}},_o=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},hs=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ys=()=>{var r;let e=Md();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)}},bs=()=>{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=$l(t,_l|jl);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?$o(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=$o(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},kd=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?$o(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?$o(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=$l(o,_l|jl),d=s(i);d!==null&&(r=d)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},xs=()=>{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 Ld="https://api.runtype.com/v1/dispatch",vs="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 Id(e){switch(e){case"json":return bs;case"regex-json":return ys;case"xml":return xs;default:return hs}}var zr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:Ld,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:Id(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$/,""))||vs;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$/,""))||vs}/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),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,u={sessionId:d.sessionId,messages:r.messages.filter(Cs).map(m=>{var C,M,b;return{id:m.id,role:m.role,content:(b=(M=(C=m.contentParts)!=null?C:m.llmContent)!=null?M:m.rawContent)!=null?b:m.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",u);let h=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u),signal:n.signal});if(!h.ok){let m=await h.json().catch(()=>({error:"Chat request failed"}));if(h.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let M=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:M}),M}if(h.status===429){let M=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:M}),M}let C=new Error(m.error||"Failed to send message");throw t({type:"error",error:C}),C}if(!h.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(h.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$/,""))||vs}/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,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return n.current=u,s(u),u},c=p=>n.current?n.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,s(n.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(n.current&&(n.current.streaming=!1,s(n.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(r,t,n){var Ie,Re,ot,At,j,U,re,_,z,Q,lt,K,X,wt,st,Pt,Jt,Be,ie,ke,Et,Tt,Qe,et,en,Zt,tn,O,Ee,le,dt,He,G,he,Pe,mt,Nt,at,Ot,pt,Je,ut,Ne,$t,_n,Yn,Rn,Xe,wr,jn,Sr,zn,Wr,or,Kn,tt,xn,Hn,an,sr,vn,bt,ln,Mn,ar,Xn,ir,Vn,Cn,qn,xt,Wt,Rt,wn,lr,Bn,Sn,H,Dn,kn,cr,gn,An,ee,Fn,Rr,to,Hr,Ye,no,Ln,mn,Wo,Ro,ro,Gn,Ho,Br,Dr,Zn,oo,dr,pr,Bo,Do,fs,Ar,Er,Mt,Fr,Nr,so,ao,io,lo,cn,En,Qn,Oe;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,p=Z=>{let qe=Z.reasoning?{...Z.reasoning,chunks:[...Z.reasoning.chunks]}:void 0,nt=Z.toolCall?{...Z.toolCall,chunks:Z.toolCall.chunks?[...Z.toolCall.chunks]:void 0}:void 0,_t=Z.tools?Z.tools.map(jt=>({...jt,chunks:jt.chunks?[...jt.chunks]:void 0})):void 0;return{...Z,reasoning:qe,toolCall:nt,tools:_t}},u=Z=>{t({type:"message",message:p(Z)})},h=null,m={current:null},C={current:null},M=new Map,b=new Map,x={lastId:null,byStep:new Map},S={lastId:null,byCall:new Map},F=Z=>{if(Z==null)return null;try{return String(Z)}catch{return null}},w=Z=>{var qe,nt,_t,jt,Yt;return F((Yt=(jt=(_t=(nt=(qe=Z.stepId)!=null?qe:Z.step_id)!=null?nt:Z.step)!=null?_t:Z.parentId)!=null?jt:Z.flowStepId)!=null?Yt:Z.flow_step_id)},L=Z=>{var qe,nt,_t,jt,Yt,kt,v;return F((v=(kt=(Yt=(jt=(_t=(nt=(qe=Z.callId)!=null?qe:Z.call_id)!=null?nt:Z.requestId)!=null?_t:Z.request_id)!=null?jt:Z.toolCallId)!=null?Yt:Z.tool_call_id)!=null?kt:Z.stepId)!=null?v:Z.step_id)},R=()=>h||(h={id:n!=null?n:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},u(h),h),T=(Z,qe)=>{x.lastId=qe,Z&&x.byStep.set(Z,qe)},Y=(Z,qe)=>{var Yt;let nt=(Yt=Z.reasoningId)!=null?Yt:Z.id,_t=w(Z);if(nt){let kt=String(nt);return T(_t,kt),kt}if(_t){let kt=x.byStep.get(_t);if(kt)return x.lastId=kt,kt}if(x.lastId&&!qe)return x.lastId;if(!qe)return null;let jt=`reason-${c()}`;return T(_t,jt),jt},ue=Z=>{let qe=M.get(Z);if(qe)return qe;let nt={id:`reason-${Z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:Z,status:"streaming",chunks:[]}};return M.set(Z,nt),u(nt),nt},se=(Z,qe)=>{S.lastId=qe,Z&&S.byCall.set(Z,qe)},$=new Set,te=new Map,Ae=new Set,ne=new Map,Ce=Z=>{if(!Z)return!1;let qe=Z.replace(/_+/g,"_").replace(/^_|_$/g,"");return qe==="emit_artifact_markdown"||qe==="emit_artifact_component"},Me=(Z,qe)=>{var Yt;let nt=(Yt=Z.toolId)!=null?Yt:Z.id,_t=L(Z);if(nt){let kt=String(nt);return se(_t,kt),kt}if(_t){let kt=S.byCall.get(_t);if(kt)return S.lastId=kt,kt}if(S.lastId&&!qe)return S.lastId;if(!qe)return null;let jt=`tool-${c()}`;return se(_t,jt),jt},de=Z=>{let qe=b.get(Z);if(qe)return qe;let nt={id:`tool-${Z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:Z,status:"pending"}};return b.set(Z,nt),u(nt),nt},fe=Z=>{if(typeof Z=="number"&&Number.isFinite(Z))return Z;if(typeof Z=="string"){let qe=Number(Z);if(!Number.isNaN(qe)&&Number.isFinite(qe))return qe;let nt=Date.parse(Z);if(!Number.isNaN(nt))return nt}return Date.now()},Se=Z=>{if(typeof Z=="string")return Z;if(Z==null)return"";try{return JSON.stringify(Z)}catch{return String(Z)}},J=new Map,ae=new Map,ge=null,De=new Map,Le=(Ie=this.config.iterationDisplay)!=null?Ie:"separate";for(;;){let{done:Z,value:qe}=await s.read();if(Z)break;a+=o.decode(qe,{stream:!0});let nt=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()=>{}}},Vo=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},vs=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Cs=()=>{var r;let e=Ld();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)}},ws=()=>{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=jl(t,zl|Ul);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Uo(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Uo(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Id=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Uo(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Uo(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=jl(o,zl|Ul),d=s(i);d!==null&&(r=d)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},Ss=()=>{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 Pd="https://api.runtype.com/v1/dispatch",As="https://api.runtype.com",Es=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 Wd(e){switch(e){case"json":return ws;case"regex-json":return Cs;case"xml":return Ss;default:return vs}}var qr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:Pd,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:Wd(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$/,""))||As;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$/,""))||As}/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),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,u={sessionId:d.sessionId,messages:r.messages.filter(Es).map(m=>{var v,M,b;return{id:m.id,role:m.role,content:(b=(M=(v=m.contentParts)!=null?v:m.llmContent)!=null?M:m.rawContent)!=null?b:m.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",u);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u),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 M=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:M}),M}if(f.status===429){let M=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:M}),M}let v=new Error(m.error||"Failed to send message");throw t({type:"error",error:v}),v}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$/,""))||As}/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(Es).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(Es).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(r,t,n,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return n.current=u,s(u),u},c=p=>n.current?n.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,s(n.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(n.current&&(n.current.streaming=!1,s(n.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(r,t,n){var wt,j,q,se,_,z,Q,Fe,J,K,xt,tt,Lt,Ut,Ne,le,Ie,St,At,Ze,Qe,Kt,Gt,Zt,O,Le,pe,at,Be,Z,ye,Pe,dt,Ot,nt,$t,it,qe,lt,_e,_t,Un,Xn,Bn,Xe,Ar,Vn,Er,Mn,Br,ir,Kn,et,xn,Dn,an,lr,vn,ft,ln,kn,cr,Zn,dr,qn,Cn,Jn,ht,Wt,Rt,wn,pr,Fn,Sn,D,Nn,Ln,ur,gn,An,ee,On,Dr,oo,Fr,Je,so,In,mn,Do,Fo,ao,Qn,No,Nr,Or,er,io,gr,mr,Oo,$o,xs,Tr,Mr,Et,$r,_r,lo,co,po,uo,cn,En,tr,je,go,kr,$n;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,p=X=>{let Ye=X.reasoning?{...X.reasoning,chunks:[...X.reasoning.chunks]}:void 0,pt=X.toolCall?{...X.toolCall,chunks:X.toolCall.chunks?[...X.toolCall.chunks]:void 0}:void 0,It=X.tools?X.tools.map(Pt=>({...Pt,chunks:Pt.chunks?[...Pt.chunks]:void 0})):void 0;return{...X,reasoning:Ye,toolCall:pt,tools:It}},u=X=>{t({type:"message",message:p(X)})},f=null,m={current:null},v={current:null},M=!1,b=new Map,C=new Map,S={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},w=X=>{if(X==null)return null;try{return String(X)}catch{return null}},L=X=>{var Ye,pt,It,Pt,Qt;return w((Qt=(Pt=(It=(pt=(Ye=X.stepId)!=null?Ye:X.step_id)!=null?pt:X.step)!=null?It:X.parentId)!=null?Pt:X.flowStepId)!=null?Qt:X.flow_step_id)},B=X=>{var Ye,pt,It,Pt,Qt,Ht,x;return w((x=(Ht=(Qt=(Pt=(It=(pt=(Ye=X.callId)!=null?Ye:X.call_id)!=null?pt:X.requestId)!=null?It:X.request_id)!=null?Pt:X.toolCallId)!=null?Qt:X.tool_call_id)!=null?Ht:X.stepId)!=null?x:X.step_id)},T=n,Y=!1,ue=()=>{if(f)return f;let X;return!Y&&T?(X=T,Y=!0):T&&v.current?X=`${T}_${v.current}`:X=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:X,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},u(f),f},ce=(X,Ye)=>{S.lastId=Ye,X&&S.byStep.set(X,Ye)},$=(X,Ye)=>{var Qt;let pt=(Qt=X.reasoningId)!=null?Qt:X.id,It=L(X);if(pt){let Ht=String(pt);return ce(It,Ht),Ht}if(It){let Ht=S.byStep.get(It);if(Ht)return S.lastId=Ht,Ht}if(S.lastId&&!Ye)return S.lastId;if(!Ye)return null;let Pt=`reason-${c()}`;return ce(It,Pt),Pt},te=X=>{let Ye=b.get(X);if(Ye)return Ye;let pt={id:`reason-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:X,status:"streaming",chunks:[]}};return b.set(X,pt),u(pt),pt},Te=(X,Ye)=>{R.lastId=Ye,X&&R.byCall.set(X,Ye)},ne=new Set,Se=new Map,He=new Set,he=new Map,Me=X=>{if(!X)return!1;let Ye=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ye==="emit_artifact_markdown"||Ye==="emit_artifact_component"},ke=(X,Ye)=>{var Qt;let pt=(Qt=X.toolId)!=null?Qt:X.id,It=B(X);if(pt){let Ht=String(pt);return Te(It,Ht),Ht}if(It){let Ht=R.byCall.get(It);if(Ht)return R.lastId=Ht,Ht}if(R.lastId&&!Ye)return R.lastId;if(!Ye)return null;let Pt=`tool-${c()}`;return Te(It,Pt),Pt},re=X=>{let Ye=C.get(X);if(Ye)return Ye;let pt={id:`tool-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:X,status:"pending"}};return C.set(X,pt),u(pt),pt},be=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 pt=Date.parse(X);if(!Number.isNaN(pt))return pt}return Date.now()},$e=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},ge=new Map,de=new Map,oe=null,De=new Map,ot=(wt=this.config.iterationDisplay)!=null?wt:"separate";for(;;){let{done:X,value:Ye}=await s.read();if(X)break;a+=o.decode(Ye,{stream:!0});let pt=a.split(`
5
5
 
6
- `);a=(Re=nt.pop())!=null?Re:"";for(let _t of nt){let jt=_t.split(`
7
- `),Yt="message",kt="";for(let D of jt)D.startsWith("event:")?Yt=D.replace("event:","").trim():D.startsWith("data:")&&(kt+=D.replace("data:","").trim());if(!kt)continue;let v;try{v=JSON.parse(kt)}catch(D){t({type:"error",error:D instanceof Error?D:new Error("Failed to parse chat stream payload")});continue}let _e=Yt!=="message"?Yt:(ot=v.type)!=null?ot:"message";if((At=this.onSSEEvent)==null||At.call(this,_e,v),this.parseSSEEvent){m.current=h;let D=await this.handleCustomSSEEvent(v,t,m,u,c,C);if(m.current&&m.current!==h&&(h=m.current),D)continue}if(_e==="reason_start"){let D=(j=Y(v,!0))!=null?j:`reason-${c()}`,A=ue(D);A.reasoning=(U=A.reasoning)!=null?U:{id:D,status:"streaming",chunks:[]},A.reasoning.startedAt=(_=A.reasoning.startedAt)!=null?_:fe((re=v.startedAt)!=null?re:v.timestamp),A.reasoning.completedAt=void 0,A.reasoning.durationMs=void 0,A.streaming=!0,A.reasoning.status="streaming",u(A)}else if(_e==="reason_delta"||_e==="reason_chunk"){let D=(Q=(z=Y(v,!1))!=null?z:Y(v,!0))!=null?Q:`reason-${c()}`,A=ue(D);A.reasoning=(lt=A.reasoning)!=null?lt:{id:D,status:"streaming",chunks:[]},A.reasoning.startedAt=(X=A.reasoning.startedAt)!=null?X:fe((K=v.startedAt)!=null?K:v.timestamp);let N=(Pt=(st=(wt=v.reasoningText)!=null?wt:v.text)!=null?st:v.delta)!=null?Pt:"";if(N&&v.hidden!==!0&&A.reasoning.chunks.push(String(N)),A.reasoning.status=v.done?"complete":"streaming",v.done){A.reasoning.completedAt=fe((Jt=v.completedAt)!=null?Jt:v.timestamp);let ce=(Be=A.reasoning.startedAt)!=null?Be:Date.now();A.reasoning.durationMs=Math.max(0,((ie=A.reasoning.completedAt)!=null?ie:Date.now())-ce)}A.streaming=A.reasoning.status!=="complete",u(A)}else if(_e==="reason_complete"){let D=(Et=(ke=Y(v,!1))!=null?ke:Y(v,!0))!=null?Et:`reason-${c()}`,A=M.get(D);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=fe((Tt=v.completedAt)!=null?Tt:v.timestamp);let ce=(Qe=A.reasoning.startedAt)!=null?Qe:Date.now();A.reasoning.durationMs=Math.max(0,((et=A.reasoning.completedAt)!=null?et:Date.now())-ce),A.streaming=!1,u(A)}let N=w(v);N&&x.byStep.delete(N)}else if(_e==="tool_start"){let D=(en=Me(v,!0))!=null?en:`tool-${c()}`,A=(Zt=v.toolName)!=null?Zt:v.name;if(Ce(A)){$.add(D);continue}let N=de(D),ce=(tn=N.toolCall)!=null?tn:{id:D,status:"pending"};ce.name=A!=null?A:ce.name,ce.status="running",v.args!==void 0?ce.args=v.args:v.parameters!==void 0&&(ce.args=v.parameters),ce.startedAt=(Ee=ce.startedAt)!=null?Ee:fe((O=v.startedAt)!=null?O:v.timestamp),ce.completedAt=void 0,ce.durationMs=void 0,N.toolCall=ce,N.streaming=!0;let Te=v.agentContext;(Te||v.executionId)&&(N.agentMetadata={executionId:(le=Te==null?void 0:Te.executionId)!=null?le:v.executionId,iteration:(dt=Te==null?void 0:Te.iteration)!=null?dt:v.iteration}),u(N)}else if(_e==="tool_chunk"||_e==="tool_delta"){let D=(G=(He=Me(v,!1))!=null?He:Me(v,!0))!=null?G:`tool-${c()}`;if($.has(D))continue;let A=de(D),N=(he=A.toolCall)!=null?he:{id:D,status:"running"};N.startedAt=(mt=N.startedAt)!=null?mt:fe((Pe=v.startedAt)!=null?Pe:v.timestamp);let ce=(Ot=(at=(Nt=v.text)!=null?Nt:v.delta)!=null?at:v.message)!=null?Ot:"";ce&&(N.chunks=(pt=N.chunks)!=null?pt:[],N.chunks.push(String(ce))),N.status="running",A.toolCall=N,A.streaming=!0;let Te=v.agentContext;(Te||v.executionId)&&(A.agentMetadata=(Ne=A.agentMetadata)!=null?Ne:{executionId:(Je=Te==null?void 0:Te.executionId)!=null?Je:v.executionId,iteration:(ut=Te==null?void 0:Te.iteration)!=null?ut:v.iteration}),u(A)}else if(_e==="tool_complete"){let D=(_n=($t=Me(v,!1))!=null?$t:Me(v,!0))!=null?_n:`tool-${c()}`;if($.has(D)){$.delete(D);continue}let A=de(D),N=(Yn=A.toolCall)!=null?Yn:{id:D,status:"running"};N.status="complete",v.result!==void 0&&(N.result=v.result),typeof v.duration=="number"&&(N.duration=v.duration),N.completedAt=fe((Rn=v.completedAt)!=null?Rn:v.timestamp);let ce=(Xe=v.duration)!=null?Xe:v.executionTime;if(typeof ce=="number")N.durationMs=ce;else{let Ue=(wr=N.startedAt)!=null?wr:Date.now();N.durationMs=Math.max(0,((jn=N.completedAt)!=null?jn:Date.now())-Ue)}A.toolCall=N,A.streaming=!1;let Te=v.agentContext;(Te||v.executionId)&&(A.agentMetadata=(Wr=A.agentMetadata)!=null?Wr:{executionId:(Sr=Te==null?void 0:Te.executionId)!=null?Sr:v.executionId,iteration:(zn=Te==null?void 0:Te.iteration)!=null?zn:v.iteration}),u(A);let rt=L(v);rt&&S.byCall.delete(rt)}else if(_e==="step_chunk"||_e==="step_delta"){let D=v.stepType,A=v.executionType;if(D==="tool"||A==="context")continue;let N=R(),ce=(xn=(tt=(Kn=(or=v.text)!=null?or:v.delta)!=null?Kn:v.content)!=null?tt:v.chunk)!=null?xn:"";if(ce){let rt=((Hn=ae.get(N.id))!=null?Hn:"")+ce;N.rawContent=rt,J.has(N.id)||J.set(N.id,this.createStreamParser());let Ue=J.get(N.id),$e=rt.trim().startsWith("{")||rt.trim().startsWith("[");if($e&&ae.set(N.id,rt),Ue.__isPlainTextParser===!0){N.content+=ce,ae.delete(N.id),J.delete(N.id),N.rawContent=void 0,u(N);continue}let qt=Ue.processChunk(rt);if(qt instanceof Promise)qt.then(ft=>{var zt;let vt=typeof ft=="string"?ft:(zt=ft==null?void 0:ft.text)!=null?zt:null;if(vt!==null&&vt.trim()!==""){let Ct=h;Ct&&Ct.id===N.id&&(Ct.content=vt,u(Ct))}else if(!$e&&!rt.trim().startsWith("<")){let Ct=h;Ct&&Ct.id===N.id&&(Ct.content+=ce,ae.delete(Ct.id),J.delete(Ct.id),Ct.rawContent=void 0,u(Ct))}}).catch(()=>{N.content+=ce,ae.delete(N.id),J.delete(N.id),N.rawContent=void 0,u(N)});else{let ft=typeof qt=="string"?qt:(an=qt==null?void 0:qt.text)!=null?an:null;ft!==null&&ft.trim()!==""?(N.content=ft,u(N)):!$e&&!rt.trim().startsWith("<")&&(N.content+=ce,ae.delete(N.id),J.delete(N.id),N.rawContent=void 0,u(N))}}if(v.isComplete){let Te=(vn=(sr=v.result)==null?void 0:sr.response)!=null?vn:N.content;if(Te){let rt=ae.get(N.id),Ue=rt!=null?rt:Se(Te);N.rawContent=Ue;let $e=J.get(N.id),Ht=null,qt=!1;if($e&&(Ht=$e.getExtractedText(),Ht===null&&(Ht=_o(Ue)),Ht===null)){let ft=$e.processChunk(Ue);ft instanceof Promise?(qt=!0,ft.then(vt=>{var Ct;let zt=typeof vt=="string"?vt:(Ct=vt==null?void 0:vt.text)!=null?Ct:null;if(zt!==null){let Ze=h;Ze&&Ze.id===N.id&&(Ze.content=zt,Ze.streaming=!1,J.delete(Ze.id),ae.delete(Ze.id),u(Ze))}})):Ht=typeof ft=="string"?ft:(bt=ft==null?void 0:ft.text)!=null?bt:null}if(!qt){Ht!==null&&Ht.trim()!==""?N.content=Ht:ae.has(N.id)||(N.content=Se(Te));let ft=J.get(N.id);if(ft){let vt=(ln=ft.close)==null?void 0:ln.call(ft);vt instanceof Promise&&vt.catch(()=>{}),J.delete(N.id)}ae.delete(N.id),N.streaming=!1,u(N)}}}}else if(_e==="step_complete"){let D=v.stepType,A=v.executionType;if(D==="tool"||A==="context")continue;let N=(Mn=v.result)==null?void 0:Mn.response,ce=R();if(N!=null){let Te=J.get(ce.id),rt=!1,Ue=!1;if(Te){let $e=Te.getExtractedText(),Ht=ae.get(ce.id),qt=Ht!=null?Ht:Se(N);if(ce.rawContent=qt,$e!==null&&$e.trim()!=="")ce.content=$e,rt=!0;else{let ft=_o(qt);if(ft!==null)ce.content=ft,rt=!0;else{let vt=Te.processChunk(qt);if(vt instanceof Promise)Ue=!0,vt.then(zt=>{var Ze;let Ct=typeof zt=="string"?zt:(Ze=zt==null?void 0:zt.text)!=null?Ze:null;if(Ct!==null&&Ct.trim()!==""){let In=h;In&&In.id===ce.id&&(In.content=Ct,In.streaming=!1,J.delete(In.id),ae.delete(In.id),u(In))}else{let In=Te.getExtractedText(),Bt=h;Bt&&Bt.id===ce.id&&(In!==null&&In.trim()!==""?Bt.content=In:ae.has(Bt.id)||(Bt.content=Se(N)),Bt.streaming=!1,J.delete(Bt.id),ae.delete(Bt.id),u(Bt))}});else{let zt=typeof vt=="string"?vt:(ar=vt==null?void 0:vt.text)!=null?ar:null;if(zt!==null&&zt.trim()!=="")ce.content=zt,rt=!0;else{let Ct=Te.getExtractedText();Ct!==null&&Ct.trim()!==""&&(ce.content=Ct,rt=!0)}}}}}if(!Ue){if(!ce.rawContent){let $e=ae.get(ce.id);ce.rawContent=$e!=null?$e:Se(N)}if(!rt&&!ae.has(ce.id)&&(ce.content=Se(N)),Te){let $e=(Xn=Te.close)==null?void 0:Xn.call(Te);$e instanceof Promise&&$e.catch(()=>{})}J.delete(ce.id),ae.delete(ce.id),ce.streaming=!1,u(ce)}}else J.delete(ce.id),ae.delete(ce.id),ce.streaming=!1,u(ce)}else if(_e==="flow_complete"){let D=(ir=v.result)==null?void 0:ir.response;if(D!=null){let A=R(),N=ae.get(A.id),ce=N!=null?N:Se(D);A.rawContent=ce;let Te=Se(D),rt=J.get(A.id);if(rt){let Ht=_o(ce);if(Ht!==null)Te=Ht;else{let qt=rt.processChunk(ce);qt instanceof Promise&&qt.then(vt=>{var Ct;let zt=typeof vt=="string"?vt:(Ct=vt==null?void 0:vt.text)!=null?Ct:null;if(zt!==null){let Ze=h;Ze&&Ze.id===A.id&&(Ze.content=zt,Ze.streaming=!1,u(Ze))}});let ft=rt.getExtractedText();ft!==null&&(Te=ft)}}J.delete(A.id),ae.delete(A.id);let Ue=Te!==A.content,$e=A.streaming!==!1;Ue&&(A.content=Te),A.streaming=!1,(Ue||$e)&&u(A)}else if(h!==null){let A=h;J.delete(A.id),ae.delete(A.id),A.streaming!==!1&&(A.streaming=!1,u(A))}t({type:"status",status:"idle"})}else if(_e==="agent_start")ge={executionId:v.executionId,agentId:(Vn=v.agentId)!=null?Vn:"virtual",agentName:(Cn=v.agentName)!=null?Cn:"",status:"running",currentIteration:0,maxTurns:(qn=v.maxTurns)!=null?qn:1,startedAt:fe(v.startedAt)};else if(_e==="agent_iteration_start"){if(ge&&(ge.currentIteration=v.iteration),Le==="separate"&&v.iteration>1){let D=h;D&&(D.streaming=!1,u(D),De.set(v.iteration-1,D),h=null)}}else if(_e!=="agent_turn_start"){if(_e==="agent_turn_delta"){if(v.contentType==="text"){let D=R();D.content+=(xt=v.delta)!=null?xt:"",D.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:v.turnId,agentName:ge==null?void 0:ge.agentName},u(D)}else if(v.contentType==="thinking"){let D=(Wt=v.turnId)!=null?Wt:`agent-think-${v.iteration}`,A=ue(D);A.reasoning=(Rt=A.reasoning)!=null?Rt:{id:D,status:"streaming",chunks:[]},A.reasoning.chunks.push((wn=v.delta)!=null?wn:""),A.agentMetadata={executionId:v.executionId,iteration:v.iteration,turnId:v.turnId},u(A)}else if(v.contentType==="tool_input"){let D=(lr=v.toolCallId)!=null?lr:S.lastId;if(D){let A=b.get(D);A!=null&&A.toolCall&&(A.toolCall.chunks=(Bn=A.toolCall.chunks)!=null?Bn:[],A.toolCall.chunks.push((Sn=v.delta)!=null?Sn:""),u(A))}}}else if(_e==="agent_turn_complete"){let D=v.turnId;if(D){let A=M.get(D);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=fe(v.completedAt);let N=(H=A.reasoning.startedAt)!=null?H:Date.now();A.reasoning.durationMs=Math.max(0,((Dn=A.reasoning.completedAt)!=null?Dn:Date.now())-N),A.streaming=!1,u(A)}}}else if(_e==="agent_tool_start"){let D=(kn=v.toolCallId)!=null?kn:`agent-tool-${c()}`;se(L(v),D);let A=de(D),N=(cr=A.toolCall)!=null?cr:{id:D,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=(An=(gn=v.toolName)!=null?gn:v.name)!=null?An:N.name,N.status="running",v.parameters!==void 0&&(N.args=v.parameters),N.startedAt=fe((ee=v.startedAt)!=null?ee:v.timestamp),A.toolCall=N,A.streaming=!0,A.agentMetadata={executionId:v.executionId,iteration:v.iteration},u(A)}else if(_e==="agent_tool_delta"){let D=(Fn=v.toolCallId)!=null?Fn:S.lastId;if(D){let A=(Rr=b.get(D))!=null?Rr:de(D);A.toolCall&&(A.toolCall.chunks=(to=A.toolCall.chunks)!=null?to:[],A.toolCall.chunks.push((Hr=v.delta)!=null?Hr:""),A.toolCall.status="running",A.streaming=!0,u(A))}}else if(_e==="agent_tool_complete"){let D=(Ye=v.toolCallId)!=null?Ye:S.lastId;if(D){let A=(no=b.get(D))!=null?no:de(D);if(A.toolCall){A.toolCall.status="complete",v.result!==void 0&&(A.toolCall.result=v.result),typeof v.executionTime=="number"&&(A.toolCall.durationMs=v.executionTime),A.toolCall.completedAt=fe((Ln=v.completedAt)!=null?Ln:v.timestamp),A.streaming=!1,u(A);let N=L(v);N&&S.byCall.delete(N)}}}else if(_e!=="agent_iteration_complete"){if(_e==="agent_reflection"||_e==="agent_reflect"){let D=`agent-reflection-${v.executionId}-${v.iteration}`,A={id:D,role:"assistant",content:(mn=v.reflection)!=null?mn:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:D,status:"complete",chunks:[(Wo=v.reflection)!=null?Wo:""]},agentMetadata:{executionId:v.executionId,iteration:v.iteration}};u(A)}else if(_e==="agent_complete"){ge&&(ge.status=v.success?"complete":"error",ge.completedAt=fe(v.completedAt),ge.stopReason=v.stopReason);let D=h;D&&(D.streaming=!1,u(D)),t({type:"status",status:"idle"})}else if(_e==="agent_error"){let D=typeof v.error=="string"?v.error:(ro=(Ro=v.error)==null?void 0:Ro.message)!=null?ro:"Agent execution error";v.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",D):t({type:"error",error:new Error(D)})}else if(_e!=="agent_ping")if(_e==="agent_approval_start"){let D=(Gn=v.approvalId)!=null?Gn:`approval-${c()}`,A={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:"pending",agentId:(Ho=ge==null?void 0:ge.agentId)!=null?Ho:"virtual",executionId:(Dr=(Br=v.executionId)!=null?Br:ge==null?void 0:ge.executionId)!=null?Dr:"",toolName:(Zn=v.toolName)!=null?Zn:"",toolType:v.toolType,description:(dr=v.description)!=null?dr:`Execute ${(oo=v.toolName)!=null?oo:"tool"}`,parameters:v.parameters}};u(A)}else if(_e==="step_await"&&v.awaitReason==="approval_required"){let D=(pr=v.approvalId)!=null?pr:`approval-${c()}`,A={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:"pending",agentId:(Bo=ge==null?void 0:ge.agentId)!=null?Bo:"virtual",executionId:(fs=(Do=v.executionId)!=null?Do:ge==null?void 0:ge.executionId)!=null?fs:"",toolName:(Ar=v.toolName)!=null?Ar:"",toolType:v.toolType,description:(Mt=v.description)!=null?Mt:`Execute ${(Er=v.toolName)!=null?Er:"tool"}`,parameters:v.parameters}};u(A)}else if(_e==="agent_approval_complete"){let D=v.approvalId;if(D){let N={id:`approval-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:D,status:(Fr=v.decision)!=null?Fr:"approved",agentId:(Nr=ge==null?void 0:ge.agentId)!=null?Nr:"virtual",executionId:(ao=(so=v.executionId)!=null?so:ge==null?void 0:ge.executionId)!=null?ao:"",toolName:(io=v.toolName)!=null?io:"",description:(lo=v.description)!=null?lo:"",resolvedAt:Date.now()}};u(N)}}else if(_e==="artifact_start"||_e==="artifact_delta"||_e==="artifact_update"||_e==="artifact_complete"){if(_e==="artifact_start"){let D=v.artifactType,A=String(v.id),N=typeof v.title=="string"?v.title:void 0;if(t({type:"artifact_start",id:A,artifactType:D,title:N,component:typeof v.component=="string"?v.component:void 0}),ne.set(A,{markdown:"",title:N}),!Ae.has(A)){Ae.add(A);let ce={id:`artifact-ref-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:A,title:N,artifactType:D,status:"streaming"}})};te.set(A,ce),u(ce)}}else if(_e==="artifact_delta"){let D=String(v.id),A=typeof v.delta=="string"?v.delta:String((cn=v.delta)!=null?cn:"");t({type:"artifact_delta",id:D,artDelta:A});let N=ne.get(D);N&&(N.markdown+=A)}else if(_e==="artifact_update"){let D=v.props&&typeof v.props=="object"&&!Array.isArray(v.props)?v.props:{};t({type:"artifact_update",id:String(v.id),props:D,component:typeof v.component=="string"?v.component:void 0})}else if(_e==="artifact_complete"){let D=String(v.id);t({type:"artifact_complete",id:D});let A=te.get(D);if(A){A.streaming=!1;try{let N=JSON.parse((En=A.rawContent)!=null?En:"{}");if(N.props){N.props.status="complete";let ce=ne.get(D);ce!=null&&ce.markdown&&(N.props.markdown=ce.markdown)}A.rawContent=JSON.stringify(N)}catch{}ne.delete(D),u(A),te.delete(D)}}}else if(_e==="transcript_insert"){let D=v.message;if(!D||typeof D!="object")continue;let A=String((Qn=D.id)!=null?Qn:`msg-${c()}`),N=D.role,Te={id:A,role:N==="user"?"user":N==="system"?"system":"assistant",content:typeof D.content=="string"?D.content:"",rawContent:typeof D.rawContent=="string"?D.rawContent:void 0,createdAt:typeof D.createdAt=="string"?D.createdAt:new Date().toISOString(),streaming:D.streaming===!0,...typeof D.variant=="string"?{variant:D.variant}:{},sequence:c()};if(u(Te),Te.rawContent)try{let rt=JSON.parse(Te.rawContent),Ue=(Oe=rt==null?void 0:rt.props)==null?void 0:Oe.artifactId;typeof Ue=="string"&&Ae.add(Ue)}catch{}h=null,m.current=null,J.delete(A),ae.delete(A)}else _e==="error"&&v.error&&t({type:"error",error:v.error instanceof Error?v.error:new Error(String(v.error))})}}}}}};function Pd(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function yo(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function Vr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var jo="[Image]";function Wd(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Rd(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function Hd(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Bd(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function ws(e){return{type:"text",text:e}}function Dd(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 Fd(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 Nd(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 ql=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Od=["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"],nr=[...ql,...Od];function $d(e){return ql.includes(e)||e.startsWith("image/")}function zo(e){return $d(e.type)}async function Ul(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;zo(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 Jl(e,r=nr,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 _d(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function Yl(e,r){let t=_d(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 Vo=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 qo=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,n,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=r.createMediaStreamSource(t),this.analyserNode=r.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let 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 bo=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 qo;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 p=`${o}//${a}/ws/agents/${i}/voice?token=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((h,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let C=!1,M=x=>{C||(C=!0,clearTimeout(b),m(new Error(x)))},b=setTimeout(()=>M("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(b),h())},{once:!0}),this.ws.addEventListener("error",()=>{M("WebSocket connection failed to "+p+"."+u)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!C){let S=x.code!==1006?` (code ${x.code})`:"";M("WebSocket connection failed"+S+"."+u)}},{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 Vo(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(h=>h("processing")),this.processingStartCallbacks.forEach(h=>h());let p=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:p});await this.sendAudio(u),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 Lr=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 qr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new bo(e.runtype);case"browser":if(!Lr.isSupported())throw new Error("Browser speech recognition not supported");return new Lr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ss(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return qr({type:"runtype",runtype:e.runtype});if(Lr.isSupported())return qr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Uo(e){try{return Ss(e),!0}catch{return!1}}var xo=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 zr(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 Uo((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,s;try{let o=r||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=qr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",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 p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var p,u,h,m,C,M;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=c.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=c.transcript)!=null&&u.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((h=c.text)!=null&&h.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=(M=this.pendingVoiceAssistantMessageId)!=null?M:(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 p,u;this.voiceStatus=c,this.voiceActive=c==="listening",(u=(p=this.callbacks).onVoiceStatusChanged)==null||u.call(p,c)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,s,o,a,i,d,c,p;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((s=r.runtype)==null?void 0:s.clientToken)||"",host:(o=r.runtype)==null?void 0:o.host,voiceId:(a=r.runtype)==null?void 0:a.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(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:(p=r.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new zr(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:p}=r,h={id:a!=null?a:t==="user"?yo():t==="assistant"?Vr():`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},...p!==void 0&&{voiceProcessing:p}};return this.upsertMessage(h),h}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:p,streaming:u=!1}=n,m={id:d!=null?d:s==="user"?yo():s==="assistant"?Vr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...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,p,u,h,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=yo(),o=Vr(),a={id:s,role:"user",content:n||jo,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 M=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!M){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,M||(C instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,C):(m=(h=this.callbacks).onError)==null||m.call(h,new Error(String(C))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=Vr();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:r},this.handleEvent)}catch(c){let p={id:r,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(p),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(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,p;let n=`approval-${r.id}`,s={...r,status:t,resolvedAt:Date.now()},o={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let u;if(i?u=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):u=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),u){let h=null;if(u instanceof Response){if(!u.ok){let m=await u.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Approval request failed: ${u.status}`)}h=u.body}else u instanceof ReadableStream&&(h=u);h?await this.connectStream(h):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(u){(p=(c=this.callbacks).onError)==null||p.call(c,u instanceof Error?u:new Error(String(u)))}}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 f=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},Un=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};import*as jd from"lucide";var pe=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=jd[s];return o?zd(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 zd(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,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),s.appendChild(d)}}}),s}var Jo={allowedTypes:nr,maxFileSize:10*1024*1024,maxFiles:4};function Vd(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function qd(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 Ur=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:Jo.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:Jo.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:Jo.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:Jo.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 p=Jl(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,u);continue}try{let u=await Ul(c),h=zo(c)?URL.createObjectURL(c):null,m={id:Vd(),file:c,previewUrl:h,contentPart:u};this.attachments.push(m),this.renderPreview(m)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}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=zo(r.file),n=f("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=f("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=f("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=qd(r.file.type),d=pe(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=f("span");c.textContent=Yl(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=f("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=pe("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 Kl={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},Xl={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Gl={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:"min(400px, calc(100vw - 24px))",maxWidth:"400px",height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function vo(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."))?vo(e,n):n}function As(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=vo(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 Zl(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 Ql(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]=Ql(o,s):t[n]=s}return t}function Ud(e,r){return r?Ql(e,r):e}function Co(e,r={}){var s,o,a,i,d,c,p,u,h,m,C,M,b;let t={palette:Kl,semantic:Xl,components:Gl},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,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...t.semantic.colors.interactive,...(h=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:h.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,...(M=e==null?void 0:e.semantic)==null?void 0:M.spacing},typography:{...t.semantic.typography,...(b=e==null?void 0:e.semantic)==null?void 0:b.typography}},components:Ud(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let x=Zl(n);if(!x.valid)throw new Error(`Theme validation failed: ${x.errors.map(S=>S.message).join(", ")}`)}if(r.plugins)for(let x of r.plugins)n=x.transform(n);return n}function Es(e){var C,M,b,x,S,F,w,L,R,T,Y,ue,se,$,te,Ae,ne,Ce,Me,de,fe,Se,J,ae,ge,De,Le,Ie,Re,ot,At,j,U,re,_,z,Q,lt,K,X,wt,st,Pt,Jt,Be,ie,ke,Et,Tt,Qe,et,en,Zt,tn,O,Ee,le,dt,He,G,he,Pe,mt,Nt,at,Ot,pt,Je,ut,Ne,$t,_n,Yn,Rn,Xe,wr,jn,Sr,zn,Wr,or,Kn,tt,xn,Hn,an,sr,vn,bt,ln,Mn,ar,Xn,ir,Vn,Cn,qn,xt,Wt,Rt,wn,lr,Bn,Sn,H,Dn,kn,cr,gn,An;let r=As(e),t={};for(let[ee,Fn]of Object.entries(r)){let Rr=ee.replace(/\./g,"-");t[`--persona-${Rr}`]=Fn.value}t["--persona-primary"]=(C=t["--persona-semantic-colors-primary"])!=null?C:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(M=t["--persona-semantic-colors-secondary"])!=null?M:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(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"]=(S=t["--persona-semantic-colors-background"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(F=t["--persona-semantic-colors-container"])!=null?F:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(w=t["--persona-semantic-colors-text"])!=null?w:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(L=t["--persona-semantic-colors-text-muted"])!=null?L:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(R=t["--persona-semantic-colors-text-inverse"])!=null?R:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(T=t["--persona-semantic-colors-border"])!=null?T:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(Y=t["--persona-semantic-colors-divider"])!=null?Y:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(ue=t["--persona-components-voice-recording-indicator"])!=null?ue:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(se=t["--persona-components-voice-recording-background"])!=null?se:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=($=t["--persona-components-voice-processing-icon"])!=null?$:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(te=t["--persona-components-voice-speaking-icon"])!=null?te: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"]=(ne=t["--persona-components-approval-requested-border"])!=null?ne:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Ce=t["--persona-components-approval-requested-text"])!=null?Ce:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(Me=t["--persona-components-approval-approve-background"])!=null?Me:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(de=t["--persona-components-approval-deny-background"])!=null?de:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(fe=t["--persona-components-attachment-image-background"])!=null?fe:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Se=t["--persona-components-attachment-image-border"])!=null?Se:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(J=t["--persona-semantic-typography-fontFamily"])!=null?J:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ae=t["--persona-semantic-typography-fontSize"])!=null?ae:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(ge=t["--persona-semantic-typography-fontWeight"])!=null?ge:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(De=t["--persona-semantic-typography-lineHeight"])!=null?De: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"]=(Le=t["--persona-palette-radius-sm"])!=null?Le:"0.125rem",t["--persona-radius-md"]=(Ie=t["--persona-palette-radius-md"])!=null?Ie:"0.375rem",t["--persona-radius-lg"]=(Re=t["--persona-palette-radius-lg"])!=null?Re:"0.5rem",t["--persona-radius-xl"]=(ot=t["--persona-palette-radius-xl"])!=null?ot:"0.75rem",t["--persona-radius-full"]=(At=t["--persona-palette-radius-full"])!=null?At:"9999px",t["--persona-launcher-radius"]=(U=(j=t["--persona-components-launcher-borderRadius"])!=null?j:t["--persona-palette-radius-full"])!=null?U:"9999px",t["--persona-launcher-bg"]=(re=t["--persona-components-launcher-background"])!=null?re:t["--persona-primary"],t["--persona-launcher-fg"]=(_=t["--persona-components-launcher-foreground"])!=null?_:t["--persona-text-inverse"],t["--persona-launcher-border"]=(z=t["--persona-components-launcher-border"])!=null?z:t["--persona-border"],t["--persona-button-primary-bg"]=(Q=t["--persona-components-button-primary-background"])!=null?Q:t["--persona-primary"],t["--persona-button-primary-fg"]=(lt=t["--persona-components-button-primary-foreground"])!=null?lt:t["--persona-text-inverse"],t["--persona-button-radius"]=(X=(K=t["--persona-components-button-primary-borderRadius"])!=null?K:t["--persona-palette-radius-full"])!=null?X:"9999px",t["--persona-panel-radius"]=(st=(wt=t["--persona-components-panel-borderRadius"])!=null?wt:t["--persona-radius-xl"])!=null?st:"0.75rem",t["--persona-panel-border"]=(Pt=t["--persona-components-panel-border"])!=null?Pt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Be=(Jt=t["--persona-components-panel-shadow"])!=null?Jt:t["--persona-palette-shadows-xl"])!=null?Be:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(ke=(ie=t["--persona-components-input-borderRadius"])!=null?ie:t["--persona-radius-lg"])!=null?ke:"0.5rem",t["--persona-message-user-radius"]=(Tt=(Et=t["--persona-components-message-user-borderRadius"])!=null?Et:t["--persona-radius-lg"])!=null?Tt:"0.5rem",t["--persona-message-assistant-radius"]=(et=(Qe=t["--persona-components-message-assistant-borderRadius"])!=null?Qe:t["--persona-radius-lg"])!=null?et:"0.5rem",t["--persona-header-bg"]=(en=t["--persona-components-header-background"])!=null?en:t["--persona-surface"],t["--persona-header-border"]=(Zt=t["--persona-components-header-border"])!=null?Zt:t["--persona-divider"],t["--persona-header-icon-bg"]=(tn=t["--persona-components-header-iconBackground"])!=null?tn:t["--persona-primary"],t["--persona-header-icon-fg"]=(O=t["--persona-components-header-iconForeground"])!=null?O:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Ee=t["--persona-components-header-titleForeground"])!=null?Ee:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(le=t["--persona-components-header-subtitleForeground"])!=null?le:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(dt=t["--persona-components-header-actionIconForeground"])!=null?dt:t["--persona-muted"];let n=(He=e.components)==null?void 0:He.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-input-background"]=(G=t["--persona-components-input-background"])!=null?G:t["--persona-surface"],t["--persona-input-placeholder"]=(he=t["--persona-components-input-placeholder"])!=null?he:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Pe=t["--persona-components-message-user-background"])!=null?Pe:t["--persona-accent"],t["--persona-message-user-text"]=(mt=t["--persona-components-message-user-text"])!=null?mt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Nt=t["--persona-components-message-user-shadow"])!=null?Nt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(at=t["--persona-components-message-assistant-background"])!=null?at:t["--persona-surface"],t["--persona-message-assistant-text"]=(Ot=t["--persona-components-message-assistant-text"])!=null?Ot:t["--persona-text"],t["--persona-message-assistant-border"]=(pt=t["--persona-components-message-assistant-border"])!=null?pt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Je=t["--persona-components-message-assistant-shadow"])!=null?Je:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(Ne=(ut=t["--persona-components-scrollToBottom-background"])!=null?ut:t["--persona-button-primary-bg"])!=null?Ne:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(_n=($t=t["--persona-components-scrollToBottom-foreground"])!=null?$t:t["--persona-button-primary-fg"])!=null?_n:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Yn=t["--persona-components-scrollToBottom-border"])!=null?Yn:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(Rn=t["--persona-components-scrollToBottom-size"])!=null?Rn:"40px",t["--persona-scroll-to-bottom-radius"]=(jn=(wr=(Xe=t["--persona-components-scrollToBottom-borderRadius"])!=null?Xe:t["--persona-button-radius"])!=null?wr:t["--persona-radius-full"])!=null?jn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(zn=(Sr=t["--persona-components-scrollToBottom-shadow"])!=null?Sr:t["--persona-palette-shadows-sm"])!=null?zn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Wr=t["--persona-components-scrollToBottom-padding"])!=null?Wr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(or=t["--persona-components-scrollToBottom-gap"])!=null?or:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(tt=(Kn=t["--persona-components-scrollToBottom-fontSize"])!=null?Kn:t["--persona-palette-typography-fontSize-sm"])!=null?tt:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(xn=t["--persona-components-scrollToBottom-iconSize"])!=null?xn:"14px",t["--persona-tool-bubble-shadow"]=(Hn=t["--persona-components-toolBubble-shadow"])!=null?Hn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(an=t["--persona-components-reasoningBubble-shadow"])!=null?an:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(sr=t["--persona-components-composer-shadow"])!=null?sr:"none",t["--persona-md-inline-code-bg"]=(vn=t["--persona-components-markdown-inlineCode-background"])!=null?vn:t["--persona-container"],t["--persona-md-inline-code-color"]=(bt=t["--persona-components-markdown-inlineCode-foreground"])!=null?bt:t["--persona-text"],t["--persona-md-link-color"]=(Mn=(ln=t["--persona-components-markdown-link-foreground"])!=null?ln:t["--persona-accent"])!=null?Mn:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let d=t["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(t["--persona-md-prose-font-family"]=d),t["--persona-md-code-block-bg"]=(ar=t["--persona-components-markdown-codeBlock-background"])!=null?ar:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Xn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Xn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(ir=t["--persona-components-markdown-codeBlock-textColor"])!=null?ir:"inherit",t["--persona-md-table-header-bg"]=(Vn=t["--persona-components-markdown-table-headerBackground"])!=null?Vn:t["--persona-container"],t["--persona-md-table-border-color"]=(Cn=t["--persona-components-markdown-table-borderColor"])!=null?Cn:t["--persona-border"],t["--persona-md-hr-color"]=(qn=t["--persona-components-markdown-hr-color"])!=null?qn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(xt=t["--persona-components-markdown-blockquote-borderColor"])!=null?xt:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Wt=t["--persona-components-markdown-blockquote-background"])!=null?Wt:"transparent",t["--persona-md-blockquote-text-color"]=(Rt=t["--persona-components-markdown-blockquote-textColor"])!=null?Rt:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(wn=t["--persona-components-collapsibleWidget-container"])!=null?wn:t["--persona-surface"],t["--cw-surface"]=(lr=t["--persona-components-collapsibleWidget-surface"])!=null?lr:t["--persona-surface"],t["--cw-border"]=(Bn=t["--persona-components-collapsibleWidget-border"])!=null?Bn:t["--persona-border"],t["--persona-message-border"]=(Sn=t["--persona-components-message-border"])!=null?Sn:t["--persona-border"];let c=e.components,p=c==null?void 0:c.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let u=c==null?void 0:c.labelButton;u&&(u.background&&(t["--persona-label-btn-bg"]=u.background),u.border&&(t["--persona-label-btn-border"]=u.border),u.color&&(t["--persona-label-btn-color"]=u.color),u.padding&&(t["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(t["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(t["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(t["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(t["--persona-label-btn-gap"]=u.gap));let h=c==null?void 0:c.toggleGroup;h&&(h.gap&&(t["--persona-toggle-group-gap"]=h.gap),h.borderRadius&&(t["--persona-toggle-group-radius"]=h.borderRadius));let m=c==null?void 0:c.artifact;if(m!=null&&m.toolbar){let ee=m.toolbar;ee.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=ee.iconHoverColor),ee.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=ee.iconHoverBackground),ee.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=ee.iconPadding),ee.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=ee.iconBorderRadius),ee.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=ee.iconBorder),ee.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=ee.toggleGroupGap),ee.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=ee.toggleBorderRadius),ee.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=ee.copyBackground),ee.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=ee.copyBorder),ee.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=ee.copyColor),ee.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=ee.copyBorderRadius),ee.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=ee.copyPadding),ee.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=ee.copyMenuBackground,t["--persona-dropdown-bg"]=(H=t["--persona-dropdown-bg"])!=null?H:ee.copyMenuBackground),ee.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ee.copyMenuBorder,t["--persona-dropdown-border"]=(Dn=t["--persona-dropdown-border"])!=null?Dn:ee.copyMenuBorder),ee.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ee.copyMenuShadow,t["--persona-dropdown-shadow"]=(kn=t["--persona-dropdown-shadow"])!=null?kn:ee.copyMenuShadow),ee.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ee.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(cr=t["--persona-dropdown-radius"])!=null?cr:ee.copyMenuBorderRadius),ee.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ee.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(gn=t["--persona-dropdown-item-hover-bg"])!=null?gn:ee.copyMenuItemHoverBackground),ee.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ee.iconBackground),ee.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ee.toolbarBorder)}if(m!=null&&m.tab){let ee=m.tab;ee.background&&(t["--persona-artifact-tab-bg"]=ee.background),ee.activeBackground&&(t["--persona-artifact-tab-active-bg"]=ee.activeBackground),ee.activeBorder&&(t["--persona-artifact-tab-active-border"]=ee.activeBorder),ee.borderRadius&&(t["--persona-artifact-tab-radius"]=ee.borderRadius),ee.textColor&&(t["--persona-artifact-tab-color"]=ee.textColor),ee.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=ee.hoverBackground),ee.listBackground&&(t["--persona-artifact-tab-list-bg"]=ee.listBackground),ee.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=ee.listBorderColor),ee.listPadding&&(t["--persona-artifact-tab-list-padding"]=ee.listPadding)}if(m!=null&&m.pane){let ee=m.pane;if(ee.toolbarBackground){let Fn=(An=vo(e,ee.toolbarBackground))!=null?An:ee.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Fn}}return t}var Jd={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 ec=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function wo(e,r){if(!e)return r;if(!r)return e;let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];ec(o)&&ec(s)?t[n]=wo(o,s):t[n]=s}return t}var Yd={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},tc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Yo=()=>{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"},Kd=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":Yo()},nc=e=>Kd(e),Xd=e=>Co(e),Gd=e=>{var t;let r=Co(void 0,{validate:!1});return Co({...e,palette:{...r.palette,colors:{...Yd.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Ko=e=>{let r=nc(e),t=tc(e==null?void 0:e.theme),n=tc(e==null?void 0:e.darkTheme);return r==="dark"?Gd(wo(t!=null?t:{},n!=null?n:{})):Xd(t)},Zd=e=>Es(e),Ir=(e,r)=>{var o;let t=Ko(r),n=Zd(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)},Ts=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Yo())});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(Yo());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 Qd}from"idiomorph";var rc=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;Qd.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 oc(e,r){var t,n,s,o,a,i,d,c,p,u,h,m,C,M,b,x,S,F;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,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(h=(u=e.approval)==null?void 0:u.status)!=null?h:"",(C=(m=e.toolCall)==null?void 0:m.status)!=null?C:"",(x=(b=(M=e.reasoning)==null?void 0:M.chunks)==null?void 0:b.length)!=null?x:0,(F=(S=e.contentParts)==null?void 0:S.length)!=null?F:0,r].join("\0")}function sc(){return new Map}function ac(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function ic(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function lc(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function Xo(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function So(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Ao(e,r){return So(e)-e.scrollTop<=r}function Go(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=t-n;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:t}:!r&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:r&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:r&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function Zo(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:s=!1}=e;return r&&t<0?"pause":!r&&s&&t>0&&n?"resume":"none"}var sn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},yn=1e5,yr=yn+1;function Ms(e,r=yn){let t=e.style.position,n=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(r),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=n,e.style.isolation=s}}var Eo=0,br=null;function ks(e=document){var t;if(Eo++,Eo===1){let n=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;br={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:o},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${o}px`,n.style.width="100%"}let r=!1;return()=>{var n;if(!r&&(r=!0,Eo=Math.max(0,Eo-1),Eo===0&&br)){let s=e.body,o=(n=e.defaultView)!=null?n:window;s.style.overflow=br.originalOverflow,s.style.position=br.originalPosition,s.style.top=br.originalTop,s.style.width=br.originalWidth,o.scrollTo(0,br.scrollY),br=null}}}var Qo={side:"right",width:"420px",animate:!0,reveal:"resize"},Gt=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},On=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:Qo.side,width:(s=r==null?void 0:r.width)!=null?s:Qo.width,animate:(o=r==null?void 0:r.animate)!=null?o:Qo.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:Qo.reveal}};var $n={"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 To=(e,r)=>{let t=f("button");t.type="button",t.innerHTML=`
6
+ `);a=(j=pt.pop())!=null?j:"";for(let It of pt){let Pt=It.split(`
7
+ `),Qt="message",Ht="";for(let I of Pt)I.startsWith("event:")?Qt=I.replace("event:","").trim():I.startsWith("data:")&&(Ht+=I.replace("data:","").trim());if(!Ht)continue;let x;try{x=JSON.parse(Ht)}catch(I){t({type:"error",error:I instanceof Error?I:new Error("Failed to parse chat stream payload")});continue}let We=Qt!=="message"?Qt:(q=x.type)!=null?q:"message";if((se=this.onSSEEvent)==null||se.call(this,We,x),this.parseSSEEvent){m.current=f;let I=await this.handleCustomSSEEvent(x,t,m,u,c,v);if(m.current&&m.current!==f&&(f=m.current),I)continue}if(We==="reason_start"){let I=(_=$(x,!0))!=null?_:`reason-${c()}`,A=te(I);A.reasoning=(z=A.reasoning)!=null?z:{id:I,status:"streaming",chunks:[]},A.reasoning.startedAt=(Fe=A.reasoning.startedAt)!=null?Fe:be((Q=x.startedAt)!=null?Q:x.timestamp),A.reasoning.completedAt=void 0,A.reasoning.durationMs=void 0,A.streaming=!0,A.reasoning.status="streaming",u(A)}else if(We==="reason_delta"||We==="reason_chunk"){let I=(K=(J=$(x,!1))!=null?J:$(x,!0))!=null?K:`reason-${c()}`,A=te(I);A.reasoning=(xt=A.reasoning)!=null?xt:{id:I,status:"streaming",chunks:[]},A.reasoning.startedAt=(Lt=A.reasoning.startedAt)!=null?Lt:be((tt=x.startedAt)!=null?tt:x.timestamp);let G=(le=(Ne=(Ut=x.reasoningText)!=null?Ut:x.text)!=null?Ne:x.delta)!=null?le:"";if(G&&x.hidden!==!0&&A.reasoning.chunks.push(String(G)),A.reasoning.status=x.done?"complete":"streaming",x.done){A.reasoning.completedAt=be((Ie=x.completedAt)!=null?Ie:x.timestamp);let N=(St=A.reasoning.startedAt)!=null?St:Date.now();A.reasoning.durationMs=Math.max(0,((At=A.reasoning.completedAt)!=null?At:Date.now())-N)}A.streaming=A.reasoning.status!=="complete",u(A)}else if(We==="reason_complete"){let I=(Qe=(Ze=$(x,!1))!=null?Ze:$(x,!0))!=null?Qe:`reason-${c()}`,A=b.get(I);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=be((Kt=x.completedAt)!=null?Kt:x.timestamp);let N=(Gt=A.reasoning.startedAt)!=null?Gt:Date.now();A.reasoning.durationMs=Math.max(0,((Zt=A.reasoning.completedAt)!=null?Zt:Date.now())-N),A.streaming=!1,u(A)}let G=L(x);G&&S.byStep.delete(G)}else if(We==="tool_start"){let I=(O=ke(x,!0))!=null?O:`tool-${c()}`,A=(Le=x.toolName)!=null?Le:x.name;if(Me(A)){ne.add(I);continue}let G=re(I),N=(pe=G.toolCall)!=null?pe:{id:I,status:"pending"};N.name=A!=null?A:N.name,N.status="running",x.args!==void 0?N.args=x.args:x.parameters!==void 0&&(N.args=x.parameters),N.startedAt=(Be=N.startedAt)!=null?Be:be((at=x.startedAt)!=null?at:x.timestamp),N.completedAt=void 0,N.durationMs=void 0,G.toolCall=N,G.streaming=!0;let ie=x.agentContext;(ie||x.executionId)&&(G.agentMetadata={executionId:(Z=ie==null?void 0:ie.executionId)!=null?Z:x.executionId,iteration:(ye=ie==null?void 0:ie.iteration)!=null?ye:x.iteration}),u(G)}else if(We==="tool_chunk"||We==="tool_delta"){let I=(dt=(Pe=ke(x,!1))!=null?Pe:ke(x,!0))!=null?dt:`tool-${c()}`;if(ne.has(I))continue;let A=re(I),G=(Ot=A.toolCall)!=null?Ot:{id:I,status:"running"};G.startedAt=($t=G.startedAt)!=null?$t:be((nt=x.startedAt)!=null?nt:x.timestamp);let N=(lt=(qe=(it=x.text)!=null?it:x.delta)!=null?qe:x.message)!=null?lt:"";N&&(G.chunks=(_e=G.chunks)!=null?_e:[],G.chunks.push(String(N))),G.status="running",A.toolCall=G,A.streaming=!0;let ie=x.agentContext;(ie||x.executionId)&&(A.agentMetadata=(Xn=A.agentMetadata)!=null?Xn:{executionId:(_t=ie==null?void 0:ie.executionId)!=null?_t:x.executionId,iteration:(Un=ie==null?void 0:ie.iteration)!=null?Un:x.iteration}),u(A)}else if(We==="tool_complete"){let I=(Xe=(Bn=ke(x,!1))!=null?Bn:ke(x,!0))!=null?Xe:`tool-${c()}`;if(ne.has(I)){ne.delete(I);continue}let A=re(I),G=(Ar=A.toolCall)!=null?Ar:{id:I,status:"running"};G.status="complete",x.result!==void 0&&(G.result=x.result),typeof x.duration=="number"&&(G.duration=x.duration),G.completedAt=be((Vn=x.completedAt)!=null?Vn:x.timestamp);let N=(Er=x.duration)!=null?Er:x.executionTime;if(typeof N=="number")G.durationMs=N;else{let Tt=(Mn=G.startedAt)!=null?Mn:Date.now();G.durationMs=Math.max(0,((Br=G.completedAt)!=null?Br:Date.now())-Tt)}A.toolCall=G,A.streaming=!1;let ie=x.agentContext;(ie||x.executionId)&&(A.agentMetadata=(et=A.agentMetadata)!=null?et:{executionId:(ir=ie==null?void 0:ie.executionId)!=null?ir:x.executionId,iteration:(Kn=ie==null?void 0:ie.iteration)!=null?Kn:x.iteration}),u(A);let ut=B(x);ut&&R.byCall.delete(ut)}else if(We==="text_start"){let I=x.partId;if(I!==void 0&&v.current!==null&&I!==v.current){let A=f;A&&(A.streaming=!1,u(A),f=null,M=!0)}I!==void 0&&(v.current=I)}else if(We==="text_end"){let I=f;I&&(I.streaming=!1,u(I),f=null,M=!0)}else if(We==="step_chunk"||We==="step_delta"){let I=x.stepType,A=x.executionType;if(I==="tool"||A==="context")continue;let G=x.partId;if(G!==void 0&&v.current!==null&&G!==v.current){let ut=f;ut&&(ut.streaming=!1,u(ut),f=null,M=!0)}G!==void 0&&(v.current=G);let N=ue();G!==void 0&&!N.partId&&(N.partId=G);let ie=(lr=(an=(Dn=(xn=x.text)!=null?xn:x.delta)!=null?Dn:x.content)!=null?an:x.chunk)!=null?lr:"";if(ie){let Tt=((vn=de.get(N.id))!=null?vn:"")+ie;N.rawContent=Tt,ge.has(N.id)||ge.set(N.id,this.createStreamParser());let Bt=ge.get(N.id),en=Tt.trim().startsWith("{")||Tt.trim().startsWith("[");if(en&&de.set(N.id,Tt),Bt.__isPlainTextParser===!0){N.content+=ie,de.delete(N.id),ge.delete(N.id),N.rawContent=void 0,u(N);continue}let tn=Bt.processChunk(Tt);if(tn instanceof Promise)tn.then(Ae=>{var yt;let vt=typeof Ae=="string"?Ae:(yt=Ae==null?void 0:Ae.text)!=null?yt:null;if(vt!==null&&vt.trim()!==""){let bt=f;bt&&bt.id===N.id&&(bt.content=vt,u(bt))}else if(!en&&!Tt.trim().startsWith("<")){let bt=f;bt&&bt.id===N.id&&(bt.content+=ie,de.delete(bt.id),ge.delete(bt.id),bt.rawContent=void 0,u(bt))}}).catch(()=>{N.content+=ie,de.delete(N.id),ge.delete(N.id),N.rawContent=void 0,u(N)});else{let Ae=typeof tn=="string"?tn:(ft=tn==null?void 0:tn.text)!=null?ft:null;Ae!==null&&Ae.trim()!==""?(N.content=Ae,u(N)):!en&&!Tt.trim().startsWith("<")&&(N.content+=ie,de.delete(N.id),ge.delete(N.id),N.rawContent=void 0,u(N))}}if(x.isComplete){let ut=(kn=(ln=x.result)==null?void 0:ln.response)!=null?kn:N.content;if(ut){let Tt=de.get(N.id),Bt=Tt!=null?Tt:$e(ut);N.rawContent=Bt;let en=ge.get(N.id),Vt=null,tn=!1;if(en&&(Vt=en.getExtractedText(),Vt===null&&(Vt=Vo(Bt)),Vt===null)){let Ae=en.processChunk(Bt);Ae instanceof Promise?(tn=!0,Ae.then(vt=>{var bt;let yt=typeof vt=="string"?vt:(bt=vt==null?void 0:vt.text)!=null?bt:null;if(yt!==null){let Dt=f;Dt&&Dt.id===N.id&&(Dt.content=yt,Dt.streaming=!1,ge.delete(Dt.id),de.delete(Dt.id),u(Dt))}})):Vt=typeof Ae=="string"?Ae:(cr=Ae==null?void 0:Ae.text)!=null?cr:null}if(!tn){Vt!==null&&Vt.trim()!==""?N.content=Vt:de.has(N.id)||(N.content=$e(ut));let Ae=ge.get(N.id);if(Ae){let vt=(Zn=Ae.close)==null?void 0:Zn.call(Ae);vt instanceof Promise&&vt.catch(()=>{}),ge.delete(N.id)}de.delete(N.id),N.streaming=!1,u(N)}}}}else if(We==="step_complete"){let I=x.stepType,A=x.executionType;if(I==="tool"||A==="context")continue;let G=(dr=x.result)==null?void 0:dr.response,N=ue();if(G!=null){let ie=ge.get(N.id),ut=!1,Tt=!1;if(ie){let Bt=ie.getExtractedText(),en=de.get(N.id),Vt=en!=null?en:$e(G);if(N.rawContent=Vt,Bt!==null&&Bt.trim()!=="")N.content=Bt,ut=!0;else{let tn=Vo(Vt);if(tn!==null)N.content=tn,ut=!0;else{let Ae=ie.processChunk(Vt);if(Ae instanceof Promise)Tt=!0,Ae.then(vt=>{var bt;let yt=typeof vt=="string"?vt:(bt=vt==null?void 0:vt.text)!=null?bt:null;if(yt!==null&&yt.trim()!==""){let Dt=f;Dt&&Dt.id===N.id&&(Dt.content=yt,Dt.streaming=!1,ge.delete(Dt.id),de.delete(Dt.id),u(Dt))}else{let Dt=ie.getExtractedText(),Pn=f;Pn&&Pn.id===N.id&&(Dt!==null&&Dt.trim()!==""?Pn.content=Dt:de.has(Pn.id)||(Pn.content=$e(G)),Pn.streaming=!1,ge.delete(Pn.id),de.delete(Pn.id),u(Pn))}});else{let vt=typeof Ae=="string"?Ae:(qn=Ae==null?void 0:Ae.text)!=null?qn:null;if(vt!==null&&vt.trim()!=="")N.content=vt,ut=!0;else{let yt=ie.getExtractedText();yt!==null&&yt.trim()!==""&&(N.content=yt,ut=!0)}}}}}if(!Tt){if(!N.rawContent){let Bt=de.get(N.id);N.rawContent=Bt!=null?Bt:$e(G)}if(!ut&&!de.has(N.id)&&(N.content=$e(G)),ie){let Bt=(Cn=ie.close)==null?void 0:Cn.call(ie);Bt instanceof Promise&&Bt.catch(()=>{})}ge.delete(N.id),de.delete(N.id),N.streaming=!1,u(N)}}else ge.delete(N.id),de.delete(N.id),N.streaming=!1,u(N)}else if(We==="flow_complete"){let I=(Jn=x.result)==null?void 0:Jn.response;if(M){if(f!==null){let A=f;ge.delete(A.id),de.delete(A.id),A.streaming!==!1&&(A.streaming=!1,u(A))}}else if(I!=null){let A=ue(),G=de.get(A.id),N=G!=null?G:$e(I);A.rawContent=N;let ie=$e(I),ut=ge.get(A.id);if(ut){let en=Vo(N);if(en!==null)ie=en;else{let Vt=ut.processChunk(N);Vt instanceof Promise&&Vt.then(Ae=>{var yt;let vt=typeof Ae=="string"?Ae:(yt=Ae==null?void 0:Ae.text)!=null?yt:null;if(vt!==null){let bt=f;bt&&bt.id===A.id&&(bt.content=vt,bt.streaming=!1,u(bt))}});let tn=ut.getExtractedText();tn!==null&&(ie=tn)}}ge.delete(A.id),de.delete(A.id);let Tt=ie!==A.content,Bt=A.streaming!==!1;Tt&&(A.content=ie),A.streaming=!1,(Tt||Bt)&&u(A)}else if(f!==null){let A=f;ge.delete(A.id),de.delete(A.id),A.streaming!==!1&&(A.streaming=!1,u(A))}t({type:"status",status:"idle"})}else if(We==="agent_start")oe={executionId:x.executionId,agentId:(ht=x.agentId)!=null?ht:"virtual",agentName:(Wt=x.agentName)!=null?Wt:"",status:"running",currentIteration:0,maxTurns:(Rt=x.maxTurns)!=null?Rt:1,startedAt:be(x.startedAt)};else if(We==="agent_iteration_start"){if(oe&&(oe.currentIteration=x.iteration),ot==="separate"&&x.iteration>1){let I=f;I&&(I.streaming=!1,u(I),De.set(x.iteration-1,I),f=null)}}else if(We!=="agent_turn_start"){if(We==="agent_turn_delta"){if(x.contentType==="text"){let I=ue();I.content+=(wn=x.delta)!=null?wn:"",I.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:x.turnId,agentName:oe==null?void 0:oe.agentName},u(I)}else if(x.contentType==="thinking"){let I=(pr=x.turnId)!=null?pr:`agent-think-${x.iteration}`,A=te(I);A.reasoning=(Fn=A.reasoning)!=null?Fn:{id:I,status:"streaming",chunks:[]},A.reasoning.chunks.push((Sn=x.delta)!=null?Sn:""),A.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:x.turnId},u(A)}else if(x.contentType==="tool_input"){let I=(D=x.toolCallId)!=null?D:R.lastId;if(I){let A=C.get(I);A!=null&&A.toolCall&&(A.toolCall.chunks=(Nn=A.toolCall.chunks)!=null?Nn:[],A.toolCall.chunks.push((Ln=x.delta)!=null?Ln:""),u(A))}}}else if(We==="agent_turn_complete"){let I=x.turnId;if(I){let A=b.get(I);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=be(x.completedAt);let G=(ur=A.reasoning.startedAt)!=null?ur:Date.now();A.reasoning.durationMs=Math.max(0,((gn=A.reasoning.completedAt)!=null?gn:Date.now())-G),A.streaming=!1,u(A)}}}else if(We==="agent_tool_start"){let I=(An=x.toolCallId)!=null?An:`agent-tool-${c()}`;Te(B(x),I);let A=re(I),G=(ee=A.toolCall)!=null?ee:{id:I,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};G.name=(Dr=(On=x.toolName)!=null?On:x.name)!=null?Dr:G.name,G.status="running",x.parameters!==void 0&&(G.args=x.parameters),G.startedAt=be((oo=x.startedAt)!=null?oo:x.timestamp),A.toolCall=G,A.streaming=!0,A.agentMetadata={executionId:x.executionId,iteration:x.iteration},u(A)}else if(We==="agent_tool_delta"){let I=(Fr=x.toolCallId)!=null?Fr:R.lastId;if(I){let A=(Je=C.get(I))!=null?Je:re(I);A.toolCall&&(A.toolCall.chunks=(so=A.toolCall.chunks)!=null?so:[],A.toolCall.chunks.push((In=x.delta)!=null?In:""),A.toolCall.status="running",A.streaming=!0,u(A))}}else if(We==="agent_tool_complete"){let I=(mn=x.toolCallId)!=null?mn:R.lastId;if(I){let A=(Do=C.get(I))!=null?Do:re(I);if(A.toolCall){A.toolCall.status="complete",x.result!==void 0&&(A.toolCall.result=x.result),typeof x.executionTime=="number"&&(A.toolCall.durationMs=x.executionTime),A.toolCall.completedAt=be((Fo=x.completedAt)!=null?Fo:x.timestamp),A.streaming=!1,u(A);let G=B(x);G&&R.byCall.delete(G)}}}else if(We!=="agent_iteration_complete"){if(We==="agent_reflection"||We==="agent_reflect"){let I=`agent-reflection-${x.executionId}-${x.iteration}`,A={id:I,role:"assistant",content:(ao=x.reflection)!=null?ao:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:I,status:"complete",chunks:[(Qn=x.reflection)!=null?Qn:""]},agentMetadata:{executionId:x.executionId,iteration:x.iteration}};u(A)}else if(We==="agent_complete"){oe&&(oe.status=x.success?"complete":"error",oe.completedAt=be(x.completedAt),oe.stopReason=x.stopReason);let I=f;I&&(I.streaming=!1,u(I)),t({type:"status",status:"idle"})}else if(We==="agent_error"){let I=typeof x.error=="string"?x.error:(Nr=(No=x.error)==null?void 0:No.message)!=null?Nr:"Agent execution error";x.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",I):t({type:"error",error:new Error(I)})}else if(We!=="agent_ping")if(We==="agent_approval_start"){let I=(Or=x.approvalId)!=null?Or:`approval-${c()}`,A={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:"pending",agentId:(er=oe==null?void 0:oe.agentId)!=null?er:"virtual",executionId:(gr=(io=x.executionId)!=null?io:oe==null?void 0:oe.executionId)!=null?gr:"",toolName:(mr=x.toolName)!=null?mr:"",toolType:x.toolType,description:($o=x.description)!=null?$o:`Execute ${(Oo=x.toolName)!=null?Oo:"tool"}`,parameters:x.parameters}};u(A)}else if(We==="step_await"&&x.awaitReason==="approval_required"){let I=(xs=x.approvalId)!=null?xs:`approval-${c()}`,A={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:"pending",agentId:(Tr=oe==null?void 0:oe.agentId)!=null?Tr:"virtual",executionId:(Et=(Mr=x.executionId)!=null?Mr:oe==null?void 0:oe.executionId)!=null?Et:"",toolName:($r=x.toolName)!=null?$r:"",toolType:x.toolType,description:(lo=x.description)!=null?lo:`Execute ${(_r=x.toolName)!=null?_r:"tool"}`,parameters:x.parameters}};u(A)}else if(We==="agent_approval_complete"){let I=x.approvalId;if(I){let G={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:(co=x.decision)!=null?co:"approved",agentId:(po=oe==null?void 0:oe.agentId)!=null?po:"virtual",executionId:(cn=(uo=x.executionId)!=null?uo:oe==null?void 0:oe.executionId)!=null?cn:"",toolName:(En=x.toolName)!=null?En:"",description:(tr=x.description)!=null?tr:"",resolvedAt:Date.now()}};u(G)}}else if(We==="artifact_start"||We==="artifact_delta"||We==="artifact_update"||We==="artifact_complete"){if(We==="artifact_start"){let I=x.artifactType,A=String(x.id),G=typeof x.title=="string"?x.title:void 0;if(t({type:"artifact_start",id:A,artifactType:I,title:G,component:typeof x.component=="string"?x.component:void 0}),he.set(A,{markdown:"",title:G}),!He.has(A)){He.add(A);let N={id:`artifact-ref-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:A,title:G,artifactType:I,status:"streaming"}})};Se.set(A,N),u(N)}}else if(We==="artifact_delta"){let I=String(x.id),A=typeof x.delta=="string"?x.delta:String((je=x.delta)!=null?je:"");t({type:"artifact_delta",id:I,artDelta:A});let G=he.get(I);G&&(G.markdown+=A)}else if(We==="artifact_update"){let I=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};t({type:"artifact_update",id:String(x.id),props:I,component:typeof x.component=="string"?x.component:void 0})}else if(We==="artifact_complete"){let I=String(x.id);t({type:"artifact_complete",id:I});let A=Se.get(I);if(A){A.streaming=!1;try{let G=JSON.parse((go=A.rawContent)!=null?go:"{}");if(G.props){G.props.status="complete";let N=he.get(I);N!=null&&N.markdown&&(G.props.markdown=N.markdown)}A.rawContent=JSON.stringify(G)}catch{}he.delete(I),u(A),Se.delete(I)}}}else if(We==="transcript_insert"){let I=x.message;if(!I||typeof I!="object")continue;let A=String((kr=I.id)!=null?kr:`msg-${c()}`),G=I.role,ie={id:A,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof I.content=="string"?I.content:"",rawContent:typeof I.rawContent=="string"?I.rawContent:void 0,createdAt:typeof I.createdAt=="string"?I.createdAt:new Date().toISOString(),streaming:I.streaming===!0,...typeof I.variant=="string"?{variant:I.variant}:{},sequence:c()};if(u(ie),ie.rawContent)try{let ut=JSON.parse(ie.rawContent),Tt=($n=ut==null?void 0:ut.props)==null?void 0:$n.artifactId;typeof Tt=="string"&&He.add(Tt)}catch{}f=null,m.current=null,ge.delete(A),de.delete(A)}else We==="error"&&x.error&&t({type:"error",error:x.error instanceof Error?x.error:new Error(String(x.error))})}}}}}};function Rd(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function Co(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function Jr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var qo="[Image]";function Hd(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Bd(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function Dd(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Fd(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function Ts(e){return{type:"text",text:e}}function Nd(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 Od(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 $d(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 Jl=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],_d=["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"],sr=[...Jl,..._d];function jd(e){return Jl.includes(e)||e.startsWith("image/")}function Jo(e){return jd(e.type)}async function Yl(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;Jo(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 Gl(e,r=sr,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 zd(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function Xl(e,r){let t=zd(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 Yo=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 Go=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,n,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=r.createMediaStreamSource(t),this.analyserNode=r.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let 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 wo=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 Go;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 p=`${o}//${a}/ws/agents/${i}/voice?token=...`,u=" 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 v=!1,M=C=>{v||(v=!0,clearTimeout(b),m(new Error(C)))},b=setTimeout(()=>M("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(b),f())},{once:!0}),this.ws.addEventListener("error",()=>{M("WebSocket connection failed to "+p+"."+u)},{once:!0}),this.ws.addEventListener("close",C=>{if(!C.wasClean&&!v){let S=C.code!==1006?` (code ${C.code})`:"";M("WebSocket connection failed"+S+"."+u)}},{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 Yo(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 p=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:p});await this.sendAudio(u),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 Wr=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 Yr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new wo(e.runtype);case"browser":if(!Wr.isSupported())throw new Error("Browser speech recognition not supported");return new Wr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ms(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Yr({type:"runtype",runtype:e.runtype});if(Wr.isSupported())return Yr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Xo(e){try{return Ms(e),!0}catch{return!1}}var So=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 qr(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 Xo((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=Yr(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 p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var p,u,f,m,v,M;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=c.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=c.transcript)!=null&&u.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=(M=this.pendingVoiceAssistantMessageId)!=null?M:(v=[...this.messages].reverse().find(C=>C.role==="assistant"))==null?void 0:v.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 p,u;this.voiceStatus=c,this.voiceActive=c==="listening",(u=(p=this.callbacks).onVoiceStatusChanged)==null||u.call(p,c)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,s,o,a,i,d,c,p;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((s=r.runtype)==null?void 0:s.clientToken)||"",host:(o=r.runtype)==null?void 0:o.host,voiceId:(a=r.runtype)==null?void 0:a.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(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:(p=r.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new qr(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:p}=r,f={id:a!=null?a:t==="user"?Co():t==="assistant"?Jr():`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},...p!==void 0&&{voiceProcessing:p}};return this.upsertMessage(f),f}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:u=!1}=n,m={id:d!=null?d:s==="user"?Co():s==="assistant"?Jr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...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,p,u,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=Co(),o=Jr(),a={id:s,role:"user",content:n||qo,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(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!M){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,M||(v instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,v):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=Jr();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:r},this.handleEvent)}catch(c){let p={id:r,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(p),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(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,p;let n=`approval-${r.id}`,s={...r,status:t,resolvedAt:Date.now()},o={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let u;if(i?u=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):u=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),u){let f=null;if(u instanceof Response){if(!u.ok){let m=await u.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Approval request failed: ${u.status}`)}f=u.body}else u instanceof ReadableStream&&(f=u);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(u){(p=(c=this.callbacks).onError)==null||p.call(c,u instanceof Error?u:new Error(String(u)))}}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},Yn=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};import*as Ud 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=Ud[s];return o?Vd(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 Vd(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,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),s.appendChild(d)}}}),s}var Ko={allowedTypes:sr,maxFileSize:10*1024*1024,maxFiles:4};function qd(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Jd(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 Gr=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:Ko.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:Ko.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:Ko.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:Ko.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 p=Gl(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,u);continue}try{let u=await Yl(c),f=Jo(c)?URL.createObjectURL(c):null,m={id:qd(),file:c,previewUrl:f,contentPart:u};this.attachments.push(m),this.renderPreview(m)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}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=Jo(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=Jd(r.file.type),d=me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=h("span");c.textContent=Xl(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 Kl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ao(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];Kl(o)&&Kl(s)?t[n]=Ao(o,s):t[n]=s}return t}var Rn="min(440px, calc(100vw - 24px))",ks="440px",Ct={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}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Rn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""}},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 Zl(e,r){if(!(!e&&!r))return e?r?Ao(e,r):e:r}function Ls(e){var r,t,n,s,o,a,i,d,c,p,u,f,m,v,M,b,C,S,R,w,L;return e?{...Ct,...e,theme:Zl(Ct.theme,e.theme),darkTheme:Zl(Ct.darkTheme,e.darkTheme),launcher:{...Ct.launcher,...e.launcher,dock:{...(r=Ct.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=Ct.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Ct.copy,...e.copy},sendButton:{...Ct.sendButton,...e.sendButton},statusIndicator:{...Ct.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ct.voiceRecognition,...e.voiceRecognition},features:(()=>{var te,Te,ne,Se;let B=(te=Ct.features)==null?void 0:te.artifacts,T=(Te=e.features)==null?void 0:Te.artifacts,Y=(ne=Ct.features)==null?void 0:ne.scrollToBottom,ue=(Se=e.features)==null?void 0:Se.scrollToBottom,ce=B===void 0&&T===void 0?void 0:{...B,...T,layout:{...B==null?void 0:B.layout,...T==null?void 0:T.layout}},$=Y===void 0&&ue===void 0?void 0:{...Y,...ue};return{...Ct.features,...e.features,...$!==void 0?{scrollToBottom:$}:{},...ce!==void 0?{artifacts:ce}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Ct.suggestionChips,suggestionChipsConfig:{...Ct.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ct.layout,...e.layout,header:{...(a=Ct.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Ct.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(u=(p=Ct.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(M=(v=Ct.layout)==null?void 0:v.messages)==null?void 0:M.timestamp,...(C=(b=e.layout)==null?void 0:b.messages)==null?void 0:C.timestamp}},slots:{...(S=Ct.layout)==null?void 0:S.slots,...(R=e.layout)==null?void 0:R.slots}},markdown:{...Ct.markdown,...e.markdown,options:{...(w=Ct.markdown)==null?void 0:w.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...Ct.messageActions,...e.messageActions}}:Ct}var Ql={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},ec={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},tc={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Rn,maxWidth:ks,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function 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 Is(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 nc(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 rc(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]=rc(o,s):t[n]=s}return t}function Yd(e,r){return r?rc(e,r):e}function To(e,r={}){var s,o,a,i,d,c,p,u,f,m,v,M,b;let t={palette:Ql,semantic:ec,components:tc},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,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...t.semantic.colors.interactive,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(v=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(M=e==null?void 0:e.semantic)==null?void 0:M.spacing},typography:{...t.semantic.typography,...(b=e==null?void 0:e.semantic)==null?void 0:b.typography}},components:Yd(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let C=nc(n);if(!C.valid)throw new Error(`Theme validation failed: ${C.errors.map(S=>S.message).join(", ")}`)}if(r.plugins)for(let C of r.plugins)n=C.transform(n);return n}function Ps(e){var v,M,b,C,S,R,w,L,B,T,Y,ue,ce,$,te,Te,ne,Se,He,he,Me,ke,re,be,$e,ge,de,oe,De,ot,wt,j,q,se,_,z,Q,Fe,J,K,xt,tt,Lt,Ut,Ne,le,Ie,St,At,Ze,Qe,Kt,Gt,Zt,O,Le,pe,at,Be,Z,ye,Pe,dt,Ot,nt,$t,it,qe,lt,_e,_t,Un,Xn,Bn,Xe,Ar,Vn,Er,Mn,Br,ir,Kn,et,xn,Dn,an,lr,vn,ft,ln,kn,cr,Zn,dr,qn,Cn,Jn,ht,Wt,Rt,wn,pr,Fn,Sn,D,Nn,Ln,ur,gn,An;let r=Is(e),t={};for(let[ee,On]of Object.entries(r)){let Dr=ee.replace(/\./g,"-");t[`--persona-${Dr}`]=On.value}t["--persona-primary"]=(v=t["--persona-semantic-colors-primary"])!=null?v:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(M=t["--persona-semantic-colors-secondary"])!=null?M:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(b=t["--persona-semantic-colors-accent"])!=null?b:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(C=t["--persona-semantic-colors-surface"])!=null?C:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(S=t["--persona-semantic-colors-background"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(R=t["--persona-semantic-colors-container"])!=null?R:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(w=t["--persona-semantic-colors-text"])!=null?w:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(L=t["--persona-semantic-colors-text-muted"])!=null?L:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(B=t["--persona-semantic-colors-text-inverse"])!=null?B:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(T=t["--persona-semantic-colors-border"])!=null?T:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(Y=t["--persona-semantic-colors-divider"])!=null?Y:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(ue=t["--persona-components-voice-recording-indicator"])!=null?ue: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"]=($=t["--persona-components-voice-processing-icon"])!=null?$:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(te=t["--persona-components-voice-speaking-icon"])!=null?te:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Te=t["--persona-components-approval-requested-background"])!=null?Te:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(ne=t["--persona-components-approval-requested-border"])!=null?ne:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Se=t["--persona-components-approval-requested-text"])!=null?Se:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(He=t["--persona-components-approval-approve-background"])!=null?He:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(he=t["--persona-components-approval-deny-background"])!=null?he:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Me=t["--persona-components-attachment-image-background"])!=null?Me:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(ke=t["--persona-components-attachment-image-border"])!=null?ke:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(re=t["--persona-semantic-typography-fontFamily"])!=null?re:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(be=t["--persona-semantic-typography-fontSize"])!=null?be:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=($e=t["--persona-semantic-typography-fontWeight"])!=null?$e:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(ge=t["--persona-semantic-typography-lineHeight"])!=null?ge: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"]=(de=t["--persona-palette-radius-sm"])!=null?de:"0.125rem",t["--persona-radius-md"]=(oe=t["--persona-palette-radius-md"])!=null?oe:"0.375rem",t["--persona-radius-lg"]=(De=t["--persona-palette-radius-lg"])!=null?De:"0.5rem",t["--persona-radius-xl"]=(ot=t["--persona-palette-radius-xl"])!=null?ot:"0.75rem",t["--persona-radius-full"]=(wt=t["--persona-palette-radius-full"])!=null?wt:"9999px",t["--persona-launcher-radius"]=(q=(j=t["--persona-components-launcher-borderRadius"])!=null?j:t["--persona-palette-radius-full"])!=null?q:"9999px",t["--persona-launcher-bg"]=(se=t["--persona-components-launcher-background"])!=null?se:t["--persona-primary"],t["--persona-launcher-fg"]=(_=t["--persona-components-launcher-foreground"])!=null?_:t["--persona-text-inverse"],t["--persona-launcher-border"]=(z=t["--persona-components-launcher-border"])!=null?z:t["--persona-border"],t["--persona-button-primary-bg"]=(Q=t["--persona-components-button-primary-background"])!=null?Q:t["--persona-primary"],t["--persona-button-primary-fg"]=(Fe=t["--persona-components-button-primary-foreground"])!=null?Fe:t["--persona-text-inverse"],t["--persona-button-radius"]=(K=(J=t["--persona-components-button-primary-borderRadius"])!=null?J:t["--persona-palette-radius-full"])!=null?K:"9999px",t["--persona-panel-radius"]=(tt=(xt=t["--persona-components-panel-borderRadius"])!=null?xt:t["--persona-radius-xl"])!=null?tt:"0.75rem",t["--persona-panel-border"]=(Lt=t["--persona-components-panel-border"])!=null?Lt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Ne=(Ut=t["--persona-components-panel-shadow"])!=null?Ut:t["--persona-palette-shadows-xl"])!=null?Ne:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Ie=(le=t["--persona-components-input-borderRadius"])!=null?le:t["--persona-radius-lg"])!=null?Ie:"0.5rem",t["--persona-message-user-radius"]=(At=(St=t["--persona-components-message-user-borderRadius"])!=null?St:t["--persona-radius-lg"])!=null?At:"0.5rem",t["--persona-message-assistant-radius"]=(Qe=(Ze=t["--persona-components-message-assistant-borderRadius"])!=null?Ze:t["--persona-radius-lg"])!=null?Qe:"0.5rem",t["--persona-header-bg"]=(Kt=t["--persona-components-header-background"])!=null?Kt:t["--persona-surface"],t["--persona-header-border"]=(Gt=t["--persona-components-header-border"])!=null?Gt:t["--persona-divider"],t["--persona-header-icon-bg"]=(Zt=t["--persona-components-header-iconBackground"])!=null?Zt:t["--persona-primary"],t["--persona-header-icon-fg"]=(O=t["--persona-components-header-iconForeground"])!=null?O:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Le=t["--persona-components-header-titleForeground"])!=null?Le:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(pe=t["--persona-components-header-subtitleForeground"])!=null?pe:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(at=t["--persona-components-header-actionIconForeground"])!=null?at:t["--persona-muted"];let n=(Be=e.components)==null?void 0:Be.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-input-background"]=(Z=t["--persona-components-input-background"])!=null?Z:t["--persona-surface"],t["--persona-input-placeholder"]=(ye=t["--persona-components-input-placeholder"])!=null?ye:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Pe=t["--persona-components-message-user-background"])!=null?Pe:t["--persona-accent"],t["--persona-message-user-text"]=(dt=t["--persona-components-message-user-text"])!=null?dt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Ot=t["--persona-components-message-user-shadow"])!=null?Ot:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(nt=t["--persona-components-message-assistant-background"])!=null?nt:t["--persona-surface"],t["--persona-message-assistant-text"]=($t=t["--persona-components-message-assistant-text"])!=null?$t:t["--persona-text"],t["--persona-message-assistant-border"]=(it=t["--persona-components-message-assistant-border"])!=null?it:t["--persona-border"],t["--persona-message-assistant-shadow"]=(qe=t["--persona-components-message-assistant-shadow"])!=null?qe:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(_e=(lt=t["--persona-components-scrollToBottom-background"])!=null?lt:t["--persona-button-primary-bg"])!=null?_e:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Un=(_t=t["--persona-components-scrollToBottom-foreground"])!=null?_t:t["--persona-button-primary-fg"])!=null?Un:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Xn=t["--persona-components-scrollToBottom-border"])!=null?Xn:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(Bn=t["--persona-components-scrollToBottom-size"])!=null?Bn:"40px",t["--persona-scroll-to-bottom-radius"]=(Vn=(Ar=(Xe=t["--persona-components-scrollToBottom-borderRadius"])!=null?Xe:t["--persona-button-radius"])!=null?Ar:t["--persona-radius-full"])!=null?Vn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Mn=(Er=t["--persona-components-scrollToBottom-shadow"])!=null?Er:t["--persona-palette-shadows-sm"])!=null?Mn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Br=t["--persona-components-scrollToBottom-padding"])!=null?Br:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(ir=t["--persona-components-scrollToBottom-gap"])!=null?ir:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(et=(Kn=t["--persona-components-scrollToBottom-fontSize"])!=null?Kn:t["--persona-palette-typography-fontSize-sm"])!=null?et:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(xn=t["--persona-components-scrollToBottom-iconSize"])!=null?xn:"14px",t["--persona-tool-bubble-shadow"]=(Dn=t["--persona-components-toolBubble-shadow"])!=null?Dn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(an=t["--persona-components-reasoningBubble-shadow"])!=null?an:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(lr=t["--persona-components-composer-shadow"])!=null?lr:"none",t["--persona-md-inline-code-bg"]=(vn=t["--persona-components-markdown-inlineCode-background"])!=null?vn:t["--persona-container"],t["--persona-md-inline-code-color"]=(ft=t["--persona-components-markdown-inlineCode-foreground"])!=null?ft:t["--persona-text"],t["--persona-md-link-color"]=(kn=(ln=t["--persona-components-markdown-link-foreground"])!=null?ln:t["--persona-accent"])!=null?kn:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let d=t["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(t["--persona-md-prose-font-family"]=d),t["--persona-md-code-block-bg"]=(cr=t["--persona-components-markdown-codeBlock-background"])!=null?cr:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Zn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Zn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(dr=t["--persona-components-markdown-codeBlock-textColor"])!=null?dr:"inherit",t["--persona-md-table-header-bg"]=(qn=t["--persona-components-markdown-table-headerBackground"])!=null?qn:t["--persona-container"],t["--persona-md-table-border-color"]=(Cn=t["--persona-components-markdown-table-borderColor"])!=null?Cn:t["--persona-border"],t["--persona-md-hr-color"]=(Jn=t["--persona-components-markdown-hr-color"])!=null?Jn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(ht=t["--persona-components-markdown-blockquote-borderColor"])!=null?ht:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Wt=t["--persona-components-markdown-blockquote-background"])!=null?Wt:"transparent",t["--persona-md-blockquote-text-color"]=(Rt=t["--persona-components-markdown-blockquote-textColor"])!=null?Rt:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(wn=t["--persona-components-collapsibleWidget-container"])!=null?wn:t["--persona-surface"],t["--cw-surface"]=(pr=t["--persona-components-collapsibleWidget-surface"])!=null?pr:t["--persona-surface"],t["--cw-border"]=(Fn=t["--persona-components-collapsibleWidget-border"])!=null?Fn:t["--persona-border"],t["--persona-message-border"]=(Sn=t["--persona-components-message-border"])!=null?Sn:t["--persona-border"];let c=e.components,p=c==null?void 0:c.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let u=c==null?void 0:c.labelButton;u&&(u.background&&(t["--persona-label-btn-bg"]=u.background),u.border&&(t["--persona-label-btn-border"]=u.border),u.color&&(t["--persona-label-btn-color"]=u.color),u.padding&&(t["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(t["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(t["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(t["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(t["--persona-label-btn-gap"]=u.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 ee=m.toolbar;ee.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=ee.iconHoverColor),ee.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=ee.iconHoverBackground),ee.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=ee.iconPadding),ee.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=ee.iconBorderRadius),ee.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=ee.iconBorder),ee.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=ee.toggleGroupGap),ee.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=ee.toggleBorderRadius),ee.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=ee.copyBackground),ee.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=ee.copyBorder),ee.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=ee.copyColor),ee.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=ee.copyBorderRadius),ee.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=ee.copyPadding),ee.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=ee.copyMenuBackground,t["--persona-dropdown-bg"]=(D=t["--persona-dropdown-bg"])!=null?D:ee.copyMenuBackground),ee.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ee.copyMenuBorder,t["--persona-dropdown-border"]=(Nn=t["--persona-dropdown-border"])!=null?Nn:ee.copyMenuBorder),ee.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ee.copyMenuShadow,t["--persona-dropdown-shadow"]=(Ln=t["--persona-dropdown-shadow"])!=null?Ln:ee.copyMenuShadow),ee.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ee.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(ur=t["--persona-dropdown-radius"])!=null?ur:ee.copyMenuBorderRadius),ee.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ee.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(gn=t["--persona-dropdown-item-hover-bg"])!=null?gn:ee.copyMenuItemHoverBackground),ee.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ee.iconBackground),ee.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ee.toolbarBorder)}if(m!=null&&m.tab){let ee=m.tab;ee.background&&(t["--persona-artifact-tab-bg"]=ee.background),ee.activeBackground&&(t["--persona-artifact-tab-active-bg"]=ee.activeBackground),ee.activeBorder&&(t["--persona-artifact-tab-active-border"]=ee.activeBorder),ee.borderRadius&&(t["--persona-artifact-tab-radius"]=ee.borderRadius),ee.textColor&&(t["--persona-artifact-tab-color"]=ee.textColor),ee.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=ee.hoverBackground),ee.listBackground&&(t["--persona-artifact-tab-list-bg"]=ee.listBackground),ee.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=ee.listBorderColor),ee.listPadding&&(t["--persona-artifact-tab-list-padding"]=ee.listPadding)}if(m!=null&&m.pane){let ee=m.pane;if(ee.toolbarBackground){let On=(An=Eo(e,ee.toolbarBackground))!=null?An:ee.toolbarBackground;t["--persona-artifact-toolbar-bg"]=On}}return t}var Gd={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 Xd={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},oc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Zo=()=>{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"},Kd=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":Zo()},sc=e=>Kd(e),Zd=e=>To(e),Qd=e=>{var t;let r=To(void 0,{validate:!1});return To({...e,palette:{...r.palette,colors:{...Xd.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Qo=e=>{let r=sc(e),t=oc(e==null?void 0:e.theme),n=oc(e==null?void 0:e.darkTheme);return r==="dark"?Qd(Ao(t!=null?t:{},n!=null?n:{})):Zd(t)},ep=e=>Ps(e),Rr=(e,r)=>{var o;let t=Qo(r),n=ep(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)},Ws=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Zo())});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(Zo());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 tp}from"idiomorph";var ac=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;tp.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 ic(e,r){var t,n,s,o,a,i,d,c,p,u,f,m,v,M,b,C,S,R;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,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(v=(m=e.toolCall)==null?void 0:m.status)!=null?v:"",(C=(b=(M=e.reasoning)==null?void 0:M.chunks)==null?void 0:b.length)!=null?C:0,(R=(S=e.contentParts)==null?void 0:S.length)!=null?R:0,r].join("\0")}function lc(){return new Map}function cc(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function dc(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function pc(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function es(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function Mo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ko(e,r){return Mo(e)-e.scrollTop<=r}function ts(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=t-n;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:t}:!r&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:r&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:r&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function ns(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:s=!1}=e;return r&&t<0?"pause":!r&&s&&t>0&&n?"resume":"none"}var sn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},yn=1e5,xr=yn+1;function Rs(e,r=yn){let t=e.style.position,n=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(r),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=n,e.style.isolation=s}}var Lo=0,vr=null;function Hs(e=document){var t;if(Lo++,Lo===1){let n=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;vr={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:o},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${o}px`,n.style.width="100%"}let r=!1;return()=>{var n;if(!r&&(r=!0,Lo=Math.max(0,Lo-1),Lo===0&&vr)){let s=e.body,o=(n=e.defaultView)!=null?n:window;s.style.overflow=vr.originalOverflow,s.style.position=vr.originalPosition,s.style.top=vr.originalTop,s.style.width=vr.originalWidth,o.scrollTo(0,vr.scrollY),vr=null}}}var rs={side:"right",width:"420px",animate:!0,reveal:"resize"},Yt=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},jn=e=>{var t,n,s,o,a;let r=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(n=r==null?void 0:r.side)!=null?n:rs.side,width:(s=r==null?void 0:r.width)!=null?s:rs.width,animate:(o=r==null?void 0:r.animate)!=null?o:rs.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:rs.reveal}};var zn={"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 Io=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
8
8
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
9
9
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
10
10
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -12,12 +12,12 @@ import{Marked as yd}from"marked";var bd=e=>{if(e)return e},Oo=e=>{var s,o;let r=
12
12
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
13
13
  </span>
14
14
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
15
- `,t.addEventListener("click",r);let n=o=>{var F,w,L,R,T,Y,ue,se,$,te,Ae,ne,Ce,Me;let a=(F=o.launcher)!=null?F:{},i=Gt(o),d=t.querySelector("[data-role='launcher-title']");if(d){let de=(w=a.title)!=null?w:"Chat Assistant";d.textContent=de,d.setAttribute("title",de)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let de=(L=a.subtitle)!=null?L:"Get answers fast";c.textContent=de,c.setAttribute("title",de)}let p=t.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=t.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let de=(R=a.agentIconSize)!=null?R:"40px";if(u.style.height=de,u.style.width=de,u.innerHTML="",a.agentIconName){let fe=parseFloat(de)||24,Se=pe(a.agentIconName,fe*.6,"var(--persona-text-inverse, #ffffff)",2);Se?(u.appendChild(Se),u.style.display=""):(u.textContent=(T=a.agentIconText)!=null?T:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(Y=a.agentIconText)!=null?Y:"\u{1F4AC}",u.style.display="")}let h=t.querySelector("[data-role='launcher-image']");if(h){let de=(ue=a.agentIconSize)!=null?ue:"40px";h.style.height=de,h.style.width=de,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(h.src=a.iconUrl,h.style.display="block"):h.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let de=(se=a.callToActionIconSize)!=null?se:"32px";m.style.height=de,m.style.width=de,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let fe=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,fe=(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 Se=parseFloat(de)||24,J=Math.max(Se-fe,8),ae=pe(a.callToActionIconName,J,"currentColor",2);ae?m.appendChild(ae):m.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}else m.textContent=(te=a.callToActionIconText)!=null?te:"\u2197"}let C=a.position&&$n[a.position]?$n[a.position]:$n["bottom-right"],M="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",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:`${M} ${C}`,i||(t.style.zIndex=String((Ae=a.zIndex)!=null?Ae:yn));let x="1px solid var(--persona-border, #e5e7eb)",S="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=(ne=a.border)!=null?ne:x,t.style.boxShadow=(Ce=a.shadow)!=null?Ce:S,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=(Me=a.collapsedMaxWidth)!=null?Me:"",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 bn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},xr=e=>{var se,$,te,Ae,ne,Ce,Me,de,fe,Se,J,ae,ge,De,Le,Ie,Re,ot,At,j,U,re,_,z,Q,lt,K,X,wt,st,Pt,Jt;let{config:r,showClose:t=!0}=e,n=f("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=(se=r==null?void 0:r.launcher)!=null?se:{},o=($=s.headerIconSize)!=null?$:"48px",a=(te=s.closeButtonSize)!=null?te:"32px",i=(Ae=s.closeButtonPlacement)!=null?Ae:"inline",d=(ne=s.headerIconHidden)!=null?ne:!1,c=s.headerIconName,p=f("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(p.style.height=o,p.style.width=o,p.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",p.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!d)if(c){let Be=parseFloat(o)||24,ie=pe(c,Be*.6,"currentColor",1);ie?p.replaceChildren(ie):p.textContent=(Me=(Ce=r==null?void 0:r.launcher)==null?void 0:Ce.agentIconText)!=null?Me:"\u{1F4AC}"}else if((de=r==null?void 0:r.launcher)!=null&&de.iconUrl){let Be=f("img");Be.src=r.launcher.iconUrl,Be.alt="",Be.className="persona-rounded-xl persona-object-cover",Be.style.height=o,Be.style.width=o,p.replaceChildren(Be)}else p.textContent=(Se=(fe=r==null?void 0:r.launcher)==null?void 0:fe.agentIconText)!=null?Se:"\u{1F4AC}";let u=f("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),h=f("span","persona-text-base persona-font-semibold");h.style.color=bn.titleColor,h.textContent=(ae=(J=r==null?void 0:r.launcher)==null?void 0:J.title)!=null?ae:"Chat Assistant";let m=f("span","persona-text-xs");m.style.color=bn.subtitleColor,m.textContent=(De=(ge=r==null?void 0:r.launcher)==null?void 0:ge.subtitle)!=null?De:"Here to help you get answers fast",u.append(h,m),d?n.append(u):n.append(p,u);let C=(Le=s.clearChat)!=null?Le:{},M=(Ie=C.enabled)!=null?Ie:!0,b=(Re=C.placement)!=null?Re:"inline",x=null,S=null;if(M){let Be=(ot=C.size)!=null?ot:"32px",ie=(At=C.iconName)!=null?At:"refresh-cw",ke=(j=C.iconColor)!=null?j:"",Et=(U=C.backgroundColor)!=null?U:"",Tt=(re=C.borderWidth)!=null?re:"",Qe=(_=C.borderColor)!=null?_:"",et=(z=C.borderRadius)!=null?z:"",en=(Q=C.paddingX)!=null?Q:"",Zt=(lt=C.paddingY)!=null?lt:"",tn=(K=C.tooltipText)!=null?K:"Clear chat",O=(X=C.showTooltip)!=null?X:!0;S=f("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"&&(S.style.right="48px"),x=f("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=Be,x.style.width=Be,x.type="button",x.setAttribute("aria-label",tn),x.style.color=ke||bn.actionIconColor;let Ee=pe(ie,"20px","currentColor",1);if(Ee&&x.appendChild(Ee),Et&&(x.style.backgroundColor=Et,x.classList.remove("hover:persona-bg-gray-100")),Tt||Qe){let le=Tt||"0px",dt=Qe||"transparent";x.style.border=`${le} solid ${dt}`,x.classList.remove("persona-border-none")}if(et&&(x.style.borderRadius=et,x.classList.remove("persona-rounded-full")),en?(x.style.paddingLeft=en,x.style.paddingRight=en):(x.style.paddingLeft="",x.style.paddingRight=""),Zt?(x.style.paddingTop=Zt,x.style.paddingBottom=Zt):(x.style.paddingTop="",x.style.paddingBottom=""),S.appendChild(x),O&&tn&&x&&S){let le=null,dt=()=>{if(le||!x)return;let G=x.ownerDocument,he=G.body;if(!he)return;le=Un(G,"div","persona-clear-chat-tooltip"),le.textContent=tn;let Pe=Un(G,"div");Pe.className="persona-clear-chat-tooltip-arrow",le.appendChild(Pe);let mt=x.getBoundingClientRect();le.style.position="fixed",le.style.zIndex=String(yr),le.style.left=`${mt.left+mt.width/2}px`,le.style.top=`${mt.top-8}px`,le.style.transform="translate(-50%, -100%)",he.appendChild(le)},He=()=>{le&&le.parentNode&&(le.parentNode.removeChild(le),le=null)};S.addEventListener("mouseenter",dt),S.addEventListener("mouseleave",He),x.addEventListener("focus",dt),x.addEventListener("blur",He),S._cleanupTooltip=()=>{He(),S&&(S.removeEventListener("mouseenter",dt),S.removeEventListener("mouseleave",He)),x&&(x.removeEventListener("focus",dt),x.removeEventListener("blur",He))}}b==="inline"&&n.appendChild(S)}let F=f("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":M&&b==="inline"?"":"persona-ml-auto"),w=f("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");w.style.height=a,w.style.width=a,w.type="button";let L=(wt=s.closeButtonTooltipText)!=null?wt:"Close chat",R=(st=s.closeButtonShowTooltip)!=null?st:!0;w.setAttribute("aria-label",L),w.style.display=t?"":"none";let T=(Pt=s.closeButtonIconName)!=null?Pt:"x",Y=(Jt=s.closeButtonIconText)!=null?Jt:"\xD7";w.style.color=s.closeButtonColor||bn.actionIconColor;let ue=pe(T,"20px","currentColor",1);if(ue?w.appendChild(ue):w.textContent=Y,s.closeButtonBackgroundColor?(w.style.backgroundColor=s.closeButtonBackgroundColor,w.classList.remove("hover:persona-bg-gray-100")):(w.style.backgroundColor="",w.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let Be=s.closeButtonBorderWidth||"0px",ie=s.closeButtonBorderColor||"transparent";w.style.border=`${Be} solid ${ie}`,w.classList.remove("persona-border-none")}else w.style.border="",w.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(w.style.borderRadius=s.closeButtonBorderRadius,w.classList.remove("persona-rounded-full")):(w.style.borderRadius="",w.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(w.style.paddingLeft=s.closeButtonPaddingX,w.style.paddingRight=s.closeButtonPaddingX):(w.style.paddingLeft="",w.style.paddingRight=""),s.closeButtonPaddingY?(w.style.paddingTop=s.closeButtonPaddingY,w.style.paddingBottom=s.closeButtonPaddingY):(w.style.paddingTop="",w.style.paddingBottom=""),F.appendChild(w),R&&L){let Be=null,ie=()=>{if(Be)return;let Et=w.ownerDocument,Tt=Et.body;if(!Tt)return;Be=Un(Et,"div","persona-clear-chat-tooltip"),Be.textContent=L;let Qe=Un(Et,"div");Qe.className="persona-clear-chat-tooltip-arrow",Be.appendChild(Qe);let et=w.getBoundingClientRect();Be.style.position="fixed",Be.style.zIndex=String(yr),Be.style.left=`${et.left+et.width/2}px`,Be.style.top=`${et.top-8}px`,Be.style.transform="translate(-50%, -100%)",Tt.appendChild(Be)},ke=()=>{Be&&Be.parentNode&&(Be.parentNode.removeChild(Be),Be=null)};F.addEventListener("mouseenter",ie),F.addEventListener("mouseleave",ke),w.addEventListener("focus",ie),w.addEventListener("blur",ke),F._cleanupTooltip=()=>{ke(),F.removeEventListener("mouseenter",ie),F.removeEventListener("mouseleave",ke),w.removeEventListener("focus",ie),w.removeEventListener("blur",ke)}}return i!=="top-right"&&n.appendChild(F),{header:n,iconHolder:p,headerTitle:h,headerSubtitle:m,closeButton:w,closeButtonWrapper:F,clearChatButton:x,clearChatButtonWrapper:S}},Jr=(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 Pr(e){let{items:r,onSelect:t,anchor:n,position:s="bottom-left",portal:o}=e,a=f("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(yr)):(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=pe(m.icon,16,"currentColor",1.5);b&&C.appendChild(b)}let M=document.createElement("span");M.textContent=m.label,C.appendChild(M),C.addEventListener("click",b=>{b.stopPropagation(),p(),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)&&p()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?c():p()}function h(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:p,toggle:u,destroy:h}}function It(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=f("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=pe(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function es(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 p=f("button",c);if(p.type="button",p.setAttribute("aria-label",t),r){let h=pe(r,o!=null?o:14,"currentColor",2);h&&p.appendChild(h)}let u=f("span");if(u.textContent=t,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[h,m]of Object.entries(d))p.setAttribute(h,m);return p}function ts(e){let{items:r,selectedId:t,onSelect:n,className:s}=e,o=f("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of r){let u;p.icon?u=It({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),n(p.id)}}):(u=f("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),n(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),o.appendChild(u)}function c(p){a=p,d()}return{element:o,setSelected:c}}function Ls(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=f("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",r);let p=f("span","persona-combo-btn-label");p.textContent=r,c.appendChild(p);let u=pe(t,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),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 M,b;c.style.backgroundColor=(M=d.background)!=null?M:"",c.style.borderColor=(b=d.border)!=null?b:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let h=Pr({items:n,onSelect:M=>{c.setAttribute("aria-expanded","false"),s(M)},anchor:c,position:o,portal:a});return a||c.appendChild(h.element),c.addEventListener("click",M=>{M.stopPropagation();let b=!h.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",b?"false":"true"),h.toggle()}),c.addEventListener("keydown",M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),c.click())}),{element:c,setLabel:M=>{p.textContent=M,c.setAttribute("aria-label",M)},open:()=>{c.setAttribute("aria-expanded","true"),h.show()},close:()=>{c.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let M=!h.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",M?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),c.remove()}}}var cc=e=>{var n;let r=xr({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 ep(e,r,t){var n,s,o;if(r!=null&&r.length)for(let a of r){let i=f("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=pe(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=f("div","persona-relative");d.appendChild(i);let c=Pr({items:a.menuItems,onSelect:p=>t==null?void 0:t(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var dc=e=>{var S,F,w,L,R,T,Y,ue,se;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(S=r==null?void 0:r.launcher)!=null?S:{},i=f("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,p;if(d)c=Ls({label:(F=a.title)!=null?F:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=bn.titleColor,p=(w=c.querySelector(".persona-combo-btn-label"))!=null?w:c;else{if(c=f("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=f("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=bn.titleColor,p.textContent=(L=a.title)!=null?L:"Chat Assistant",c.appendChild(p),ep(c,s==null?void 0:s.trailingActions,(R=s==null?void 0:s.onAction)!=null?R:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let te=s.onTitleClick;c.addEventListener("click",Ae=>{Ae.target.closest("button")||te()}),c.addEventListener("keydown",Ae=>{(Ae.key==="Enter"||Ae.key===" ")&&(Ae.preventDefault(),te())})}let $=s==null?void 0:s.titleRowHover;$&&(c.style.borderRadius=(T=$.borderRadius)!=null?T:"10px",c.style.padding=(Y=$.padding)!=null?Y:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var te,Ae;c.style.backgroundColor=(te=$.background)!=null?te:"",c.style.borderColor=(Ae=$.border)!=null?Ae:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let u=(ue=a.closeButtonSize)!=null?ue:"32px",h=f("div",""),m=f("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=u,m.style.width=u,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||bn.actionIconColor;let C=(se=a.closeButtonIconName)!=null?se:"x",M=pe(C,"20px","currentColor",2);M?m.appendChild(M):m.textContent="\xD7",n&&m.addEventListener("click",n),h.appendChild(m),i.appendChild(h);let b=f("div");b.style.display="none";let x=f("span");return x.style.display="none",{header:i,iconHolder:b,headerTitle:p,headerSubtitle:x,closeButton:m,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}},Is={default:cc,minimal:dc},pc=e=>{var r;return(r=Is[e])!=null?r:Is.default},Mo=(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}),p=f("div");p.style.display="none";let u=f("span"),h=f("span"),m=f("button");m.style.display="none";let C=f("div");return C.style.display="none",{header:c,iconHolder:p,headerTitle:u,headerSubtitle:h,closeButton:m,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=pc(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 ko=e=>{var Re,ot,At,j,U,re,_,z,Q,lt,K,X,wt,st,Pt,Jt,Be,ie,ke,Et,Tt,Qe,et,en,Zt,tn,O;let{config:r}=e,t=f("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=f("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2"),s=f("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=f("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=(ot=(Re=r==null?void 0:r.copy)==null?void 0:Re.inputPlaceholder)!=null?ot:"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 Ee=Math.min(o.scrollHeight,d);o.style.height=`${Ee}px`};o.addEventListener("input",c),o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"});let p=(At=r==null?void 0:r.sendButton)!=null?At:{},u=(j=p.useIcon)!=null?j:!1,h=(U=p.iconText)!=null?U:"\u2191",m=p.iconName,C=(re=p.tooltipText)!=null?re:"Send message",M=(_=p.showTooltip)!=null?_:!1,b=(z=p.size)!=null?z:"40px",x=p.backgroundColor,S=p.textColor,F=f("div","persona-send-button-wrapper"),w=f("button",u?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");if(w.type="submit",w.setAttribute("data-persona-composer-submit",""),u){if(w.style.width=b,w.style.height=b,w.style.minWidth=b,w.style.minHeight=b,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",S?w.style.color=S:w.style.color="var(--persona-button-primary-fg, #ffffff)",m){let Ee=parseFloat(b)||24,le=(S==null?void 0:S.trim())||"currentColor",dt=pe(m,Ee,le,2);dt?w.appendChild(dt):w.textContent=h}else w.textContent=h;x?w.style.backgroundColor=x:w.classList.add("persona-bg-persona-primary")}else w.textContent=(lt=(Q=r==null?void 0:r.copy)==null?void 0:Q.sendButtonLabel)!=null?lt:"Send",S?w.style.color=S:w.classList.add("persona-text-white");if(p.borderWidth&&(w.style.borderWidth=p.borderWidth,w.style.borderStyle="solid"),p.borderColor&&(w.style.borderColor=p.borderColor),p.paddingX?(w.style.paddingLeft=p.paddingX,w.style.paddingRight=p.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),p.paddingY?(w.style.paddingTop=p.paddingY,w.style.paddingBottom=p.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),M&&C){let Ee=f("div","persona-send-button-tooltip");Ee.textContent=C,F.appendChild(Ee)}F.appendChild(w);let L=(K=r==null?void 0:r.voiceRecognition)!=null?K:{},R=L.enabled===!0,T=null,Y=null,ue=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),se=((X=L.provider)==null?void 0:X.type)==="runtype";if(R&&(ue||se)){Y=f("div","persona-send-button-wrapper"),T=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),T.type="button",T.setAttribute("data-persona-composer-mic",""),T.setAttribute("aria-label","Start voice recognition");let Ee=(wt=L.iconName)!=null?wt:"mic",le=(st=L.iconSize)!=null?st:b,dt=parseFloat(le)||24,He=(Pt=L.backgroundColor)!=null?Pt:x,G=(Jt=L.iconColor)!=null?Jt:S;T.style.width=le,T.style.height=le,T.style.minWidth=le,T.style.minHeight=le,T.style.fontSize="18px",T.style.lineHeight="1",G?T.style.color=G:T.style.color="var(--persona-text, #111827)";let Pe=pe(Ee,dt,G||"currentColor",1.5);Pe?T.appendChild(Pe):T.textContent="\u{1F3A4}",He&&(T.style.backgroundColor=He),L.borderWidth&&(T.style.borderWidth=L.borderWidth,T.style.borderStyle="solid"),L.borderColor&&(T.style.borderColor=L.borderColor),L.paddingX&&(T.style.paddingLeft=L.paddingX,T.style.paddingRight=L.paddingX),L.paddingY&&(T.style.paddingTop=L.paddingY,T.style.paddingBottom=L.paddingY),Y.appendChild(T);let mt=(Be=L.tooltipText)!=null?Be:"Start voice recognition";if(((ie=L.showTooltip)!=null?ie:!1)&&mt){let at=f("div","persona-send-button-tooltip");at.textContent=mt,Y.appendChild(at)}}let te=(ke=r==null?void 0:r.attachments)!=null?ke:{},Ae=te.enabled===!0,ne=null,Ce=null,Me=null,de=null;if(Ae){de=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),de.style.display="none",Me=f("input"),Me.type="file",Me.accept=((Et=te.allowedTypes)!=null?Et:nr).join(","),Me.multiple=((Tt=te.maxFiles)!=null?Tt:4)>1,Me.style.display="none",Me.setAttribute("aria-label","Attach files"),Ce=f("div","persona-send-button-wrapper"),ne=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ne.type="button",ne.setAttribute("aria-label",(Qe=te.buttonTooltipText)!=null?Qe:"Attach file");let Ee=(et=te.buttonIconName)!=null?et:"paperclip",le=b,dt=parseFloat(le)||40,He=Math.round(dt*.6);ne.style.width=le,ne.style.height=le,ne.style.minWidth=le,ne.style.minHeight=le,ne.style.fontSize="18px",ne.style.lineHeight="1",ne.style.backgroundColor="transparent",ne.style.color="var(--persona-primary, #111827)",ne.style.border="none",ne.style.borderRadius="6px",ne.style.transition="background-color 0.15s ease",ne.addEventListener("mouseenter",()=>{ne.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ne.addEventListener("mouseleave",()=>{ne.style.backgroundColor="transparent"});let G=pe(Ee,He,"currentColor",1.5);G?ne.appendChild(G):ne.textContent="\u{1F4CE}",ne.addEventListener("click",mt=>{mt.preventDefault(),Me==null||Me.click()}),Ce.appendChild(ne);let he=(en=te.buttonTooltipText)!=null?en:"Attach file",Pe=f("div","persona-send-button-tooltip");Pe.textContent=he,Ce.appendChild(Pe)}s.addEventListener("click",Ee=>{Ee.target!==w&&Ee.target!==F&&Ee.target!==T&&Ee.target!==Y&&Ee.target!==ne&&Ee.target!==Ce&&o.focus()}),de&&(de.style.gap="8px",s.append(de)),Me&&s.append(Me),s.append(o);let fe=f("div","persona-flex persona-items-center persona-justify-between persona-w-full"),Se=f("div","persona-flex persona-items-center persona-gap-2");Ce&&Se.append(Ce);let J=f("div","persona-flex persona-items-center persona-gap-1");Y&&J.append(Y),J.append(F),fe.append(Se,J),s.append(fe);let ae=(Zt=r==null?void 0:r.statusIndicator)!=null?Zt:{},ge=ae.align==="left"?"persona-text-left":ae.align==="center"?"persona-text-center":"persona-text-right",De=f("div",`persona-mt-2 ${ge} persona-text-xs persona-text-persona-muted`);De.setAttribute("data-persona-composer-status","");let Le=(tn=ae.visible)!=null?tn:!0;De.style.display=Le?"":"none";let Ie=(O=ae.idleText)!=null?O:"Online";if(ae.idleLink){let Ee=f("a");Ee.href=ae.idleLink,Ee.target="_blank",Ee.rel="noopener noreferrer",Ee.textContent=Ie,Ee.style.color="inherit",Ee.style.textDecoration="none",De.appendChild(Ee)}else De.textContent=Ie;return t.append(n,s,De),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:F,micButton:T,micButtonWrapper:Y,statusText:De,attachmentButton:ne,attachmentButtonWrapper:Ce,attachmentInput:Me,attachmentPreviewsContainer:de,actionsRow:fe,leftActions:Se,rightActions:J}};var uc=e=>{var c,p,u,h,m,C,M,b,x;let r=(p=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?p:!0;if(Gt(e)){let S=f("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),F=f("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return S.appendChild(F),{wrapper:S,panel:F}}if(!r){let S=f("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),F=f("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=(h=(u=e==null?void 0:e.launcher)==null?void 0:u.width)!=null?h:"100%";return S.style.width=w,F.style.width="100%",S.appendChild(F),{wrapper:S,panel:F}}let n=(m=e==null?void 0:e.launcher)!=null?m:{},s=n.position&&$n[n.position]?$n[n.position]:$n["bottom-right"],o=f("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);o.style.zIndex=String((M=(C=e==null?void 0:e.launcher)==null?void 0:C.zIndex)!=null?M:yn);let a=f("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(x=(b=e==null?void 0:e.launcher)==null?void 0:b.width)!=null?x: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}},gc=(e,r=!0)=>{var b,x,S,F,w,L,R,T,Y;let t=f("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?Mo(e,n,{showClose:r}):xr({config:e,showClose:r}),a=f("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=Gt(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=f("div",i),c=f("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(F=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeTitle)!=null?F:"Hello \u{1F44B}";let p=f("p","persona-mt-2 persona-text-sm persona-text-persona-muted");p.textContent=(L=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",d.append(c,p);let u=f("div","persona-flex persona-flex-col persona-gap-3"),h=(R=e==null?void 0:e.layout)==null?void 0:R.contentMaxWidth;h&&(u.style.maxWidth=h,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),d.setAttribute("data-persona-intro-card",""),((T=e==null?void 0:e.copy)==null?void 0:T.showWelcomeCard)!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,u);let C=ko({config:e}),M=((Y=e==null?void 0:e.layout)==null?void 0:Y.showFooter)!==!1;return s?Jr(t,o,e):(o.header.style.display="none",Jr(t,o,e)),t.append(a),M||(C.footer.style.display="none"),t.append(C.footer),{container:t,body:a,messagesWrapper:u,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:p,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:C.footer,attachmentButton:C.attachmentButton,attachmentButtonWrapper:C.attachmentButtonWrapper,attachmentInput:C.attachmentInput,attachmentPreviewsContainer:C.attachmentPreviewsContainer,actionsRow:C.actionsRow,leftActions:C.leftActions,rightActions:C.rightActions}};var tp=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},np=320,rp=320,op=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),sp=(e,r,t)=>{if(e.length===0)return null;try{let n=f("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 u;let c=f("img");c.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${np}px`,c.style.maxHeight=`${rp}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,c.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{p=!0}),tp(i.image)?(c.src=i.image,n.appendChild(c)):(p=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},Yr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(s),e},fc=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Yr};if(r){let s=r(n);if(s!==null)return s}return Yr()},ap=(e,r)=>{let t=f("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=f("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},mc=(e,r)=>{let t=f("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},ip=(e,r="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(r){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},hc=(e,r,t)=>{var m,C,M,b,x,S;let n=(m=r.showCopy)!=null?m:!0,s=(C=r.showUpvote)!=null?C:!0,o=(M=r.showDownvote)!=null?M:!0;if(!n&&!s&&!o){let F=f("div");return F.style.display="none",F.id=`actions-${e.id}`,F.setAttribute("data-actions-for",e.id),F}let a=(b=r.visibility)!=null?b:"hover",i=(x=r.align)!=null?x:"right",d=(S=r.layout)!=null?S:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],u=f("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let h=(F,w,L)=>{let R=It({icon:F,label:w,size:14,className:"persona-message-action-btn"});return R.setAttribute("data-action",L),R};return n&&u.appendChild(h("copy","Copy message","copy")),s&&u.appendChild(h("thumbs-up","Upvote","upvote")),o&&u.appendChild(h("thumbs-down","Downvote","downvote")),u},Lo=(e,r,t,n,s,o)=>{var se,$,te,Ae,ne,Ce,Me;let a=t!=null?t:{},i=(se=a.layout)!=null?se:"bubble",d=a.avatar,c=a.timestamp,p=($=d==null?void 0:d.show)!=null?$:!1,u=(te=c==null?void 0:c.show)!=null?te:!1,h=(Ae=d==null?void 0:d.position)!=null?Ae:"left",m=(ne=c==null?void 0:c.position)!=null?ne:"below",C=ip(e.role,i),M=f("div",C.join(" "));M.id=`bubble-${e.id}`,M.setAttribute("data-message-id",e.id),M.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(M.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",M.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(M.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",M.style.color="var(--persona-message-assistant-text, var(--persona-text))");let b=op(e),x=(Me=(Ce=e.content)==null?void 0:Ce.trim())!=null?Me:"",F=b.length>0&&x===jo,w=document.createElement("div");w.classList.add("persona-message-content");let L=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),R=null;if(F?(R=document.createElement("div"),R.innerHTML=L,R.style.display="none",w.appendChild(R)):w.innerHTML=L,u&&m==="inline"&&e.createdAt){let de=mc(e,c);de.classList.add("persona-ml-2","persona-inline"),w.appendChild(de)}if(b.length>0){let de=sp(b,!F&&!!x,()=>{F&&R&&(R.style.display="")});de?M.appendChild(de):F&&R&&(R.style.display="")}if(M.appendChild(w),u&&m==="below"&&e.createdAt){let de=mc(e,c);de.classList.add("persona-mt-1"),M.appendChild(de)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let de=fc("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);de&&M.appendChild(de)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let de=hc(e,n,s);M.appendChild(de)}if(!p||e.role==="system")return M;let Y=f("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ue=ap(d,e.role);return h==="right"||h==="left"&&e.role==="user"?Y.append(M,ue):Y.append(ue,M),M.classList.remove("persona-max-w-[85%]"),M.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Y},lp=(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}):Lo(e,r,t,n,s,o)};var Kr=new Set,yc=(e,r)=>{let t=Kr.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=pe(t?"chevron-up":"chevron-down",16,"currentColor",2);d?a.appendChild(d):a.textContent=t?"Hide":"Show"}s.style.display=t?"":"none"},Ps=e=>{let r=e.reasoning,t=f("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),!r)return t;let n=Kr.has(e.id),s=f("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=f("div","persona-flex persona-flex-col persona-text-left"),a=f("span","persona-text-xs persona-text-persona-primary");a.textContent="Thinking...",o.appendChild(a);let i=f("span","persona-text-xs persona-text-persona-primary");i.textContent=zl(r),o.appendChild(i),r.status==="complete"?a.style.display="none":a.style.display="";let d=f("div","persona-flex persona-items-center"),p=pe(n?"chevron-up":"chevron-down",16,"currentColor",2);p?d.appendChild(p):d.textContent=n?"Hide":"Show";let u=f("div","persona-flex persona-items-center persona-ml-auto");u.append(d),s.append(o,u);let h=f("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");h.style.display=n?"":"none";let m=r.chunks.join(""),C=f("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"),h.appendChild(C),(()=>{s.setAttribute("aria-expanded",n?"true":"false"),d.innerHTML="";let x=pe(n?"chevron-up":"chevron-down",16,"currentColor",2);x?d.appendChild(x):d.textContent=n?"Hide":"Show",h.style.display=n?"":"none"})(),t.append(s,h),t};var Xr=new Set,bc=(e,r,t)=>{var c;let n=Xr.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 p=s.toggleTextColor||s.headerTextColor||"currentColor",u=pe(n?"chevron-up":"chevron-down",16,p,2);u?d.appendChild(u):d.textContent=n?"Hide":"Show"}a.style.display=n?"":"none"},Ws=(e,r)=>{var M;let t=e.toolCall,n=(M=r==null?void 0:r.toolCall)!=null?M:{},s=f("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),n.backgroundColor&&(s.style.backgroundColor=n.backgroundColor),n.borderColor&&(s.style.borderColor=n.borderColor),n.borderWidth&&(s.style.borderWidth=n.borderWidth),n.borderRadius&&(s.style.borderRadius=n.borderRadius),!t)return s;let o=Xr.has(e.id),a=f("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=f("div","persona-flex persona-flex-col persona-text-left"),d=f("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(d.style.color=n.headerTextColor),d.textContent=Vl(t),i.appendChild(d);let c=f("div","persona-flex persona-items-center"),p=n.toggleTextColor||n.headerTextColor||"currentColor",u=pe(o?"chevron-up":"chevron-down",16,p,2);u?c.appendChild(u):c.textContent=o?"Hide":"Show";let h=f("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");h.append(c),a.append(i,h);let m=f("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=f("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=f("div","persona-space-y-1"),x=f("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Arguments";let S=f("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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(S.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(S.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(S.style.color=n.codeBlockTextColor),S.textContent=ho(t.args),b.append(x,S),m.appendChild(b)}if(t.chunks&&t.chunks.length){let b=f("div","persona-space-y-1"),x=f("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Activity";let S=f("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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(S.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(S.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(S.style.color=n.codeBlockTextColor),S.textContent=t.chunks.join(`
16
- `),b.append(x,S),m.appendChild(b)}if(t.status==="complete"&&t.result!==void 0){let b=f("div","persona-space-y-1"),x=f("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Result";let S=f("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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(S.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(S.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(S.style.color=n.codeBlockTextColor),S.textContent=ho(t.result),b.append(x,S),m.appendChild(b)}if(t.status==="complete"&&typeof t.duration=="number"){let b=f("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=pe(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 Rs=(e,r)=>{var M,b,x,S,F,w,L,R,T,Y,ue,se;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=f("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(M=n==null?void 0:n.backgroundColor)!=null?M:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(b=n==null?void 0:n.borderColor)!=null?b:"var(--persona-approval-border, #fef08a)",!t)return o;let a=f("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=f("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",p=pe(d,20,c,2);p&&i.appendChild(p);let u=f("div","persona-flex-1 persona-min-w-0"),h=f("div","persona-flex persona-items-center persona-gap-2"),m=f("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(m.style.color=n.titleColor),m.textContent=(S=n==null?void 0:n.title)!=null?S:"Approval Required",h.appendChild(m),!s){let $=f("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");$.setAttribute("data-approval-status",t.status),t.status==="approved"?($.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",$.style.color="var(--persona-palette-colors-success-700, #15803d)",$.textContent="Approved"):t.status==="denied"?($.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",$.style.color="var(--persona-palette-colors-error-700, #b91c1c)",$.textContent="Denied"):t.status==="timeout"&&($.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",$.style.color="var(--persona-palette-colors-warning-700, #b45309)",$.textContent="Timeout"),h.appendChild($)}u.appendChild(h);let C=f("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,u.appendChild(C),t.parameters){let $=f("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&&($.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&($.style.color=n.parameterTextColor),$.style.fontSize="0.75rem",$.style.lineHeight="1rem",$.textContent=ho(t.parameters),u.appendChild($)}if(s){let $=f("div","persona-flex persona-gap-2 persona-mt-2");$.setAttribute("data-approval-buttons","true");let te=f("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");te.type="button",te.style.backgroundColor=(F=n==null?void 0:n.approveButtonColor)!=null?F:"var(--persona-approval-approve-bg, #22c55e)",te.style.color=(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",te.setAttribute("data-approval-action","approve");let Ae=pe("shield-check",14,(L=n==null?void 0:n.approveButtonTextColor)!=null?L:"#ffffff",2);Ae&&(Ae.style.marginRight="4px",te.appendChild(Ae));let ne=document.createTextNode((R=n==null?void 0:n.approveLabel)!=null?R:"Approve");te.appendChild(ne);let Ce=f("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");Ce.type="button",Ce.style.backgroundColor=(T=n==null?void 0:n.denyButtonColor)!=null?T:"transparent",Ce.style.color=(Y=n==null?void 0:n.denyButtonTextColor)!=null?Y:"var(--persona-feedback-error, #dc2626)",Ce.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Ce.setAttribute("data-approval-action","deny");let Me=pe("shield-x",14,(ue=n==null?void 0:n.denyButtonTextColor)!=null?ue:"var(--persona-feedback-error, #dc2626)",2);Me&&(Me.style.marginRight="4px",Ce.appendChild(Me));let de=document.createTextNode((se=n==null?void 0:n.denyLabel)!=null?se:"Deny");Ce.appendChild(de),$.append(te,Ce),u.appendChild($)}return a.append(i,u),o.appendChild(a),o};var xc=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 p=document.createDocumentFragment(),u=s?s.isStreaming():!1,h=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=f("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");C.type="button",C.textContent=m,C.disabled=u,i!=null&&i.fontFamily&&(C.style.fontFamily=h(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))}),p.appendChild(C),r.push(C)}),e.appendChild(p)}}};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 Po=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 Gr(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var cp={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},dp={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},pp=["flowName","stepName","reasoningText","text","name","tool","toolName"],up=100;function gp(e,r){let t={...cp,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return dp}function mp(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function fp(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 hp(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 yp(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 bp(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 xp(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=f("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=f("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 Hs(e,r,t,n,s,o,a,i){var h;let d=s.has(e.id),c=f("div","persona-border-b persona-border-persona-divider persona-text-xs");Gr(c,(h=n.classNames)==null?void 0:h.eventRow);let p=a.find(m=>m.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let m=p.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(u()),c;function u(){var te,Ae;let m=f("div",""),C=f("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 M=f("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),b=pe(d?"chevron-down":"chevron-right","14px","currentColor",2);b&&M.appendChild(b);let x=f("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),S=(te=n.timestampFormat)!=null?te:"relative";x.textContent=S==="relative"?mp(e.timestamp,t):fp(e.timestamp);let F=null;n.showSequenceNumbers!==!1&&(F=f("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),F.textContent=String(r+1));let w=gp(e.type,n.badgeColors),L=f("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");L.style.backgroundColor=w.bg,L.style.color=w.text,L.style.borderColor=w.text+"50",L.textContent=e.type;let R=(Ae=n.descriptionFields)!=null?Ae:pp,T=hp(e.payload,R),Y=null;T&&(Y=f("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),Y.textContent=T);let ue=f("div","persona-flex-1 persona-min-w-0"),se=f("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"),$=pe("clipboard","12px","currentColor",1.5);return $&&se.appendChild($),se.addEventListener("click",async ne=>{ne.stopPropagation(),await yp(bp(e)),se.innerHTML="";let Ce=pe("check","12px","currentColor",1.5);Ce&&se.appendChild(Ce),setTimeout(()=>{se.innerHTML="";let Me=pe("clipboard","12px","currentColor",1.5);Me&&se.appendChild(Me)},1500)}),C.appendChild(M),C.appendChild(x),F&&C.appendChild(F),C.appendChild(L),Y&&C.appendChild(Y),C.appendChild(ue),C.appendChild(se),m.appendChild(C),d&&m.appendChild(xp(e,a,i)),m}}function vc(e){var m,C,M,b,x;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(m=s==null?void 0:s.features)==null?void 0:m.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,d=(C=a==null?void 0:a.iconName)!=null?C:"arrow-down",c=(M=a==null?void 0:a.label)!=null?M:"",p=(x=(b=s==null?void 0:s.features)==null?void 0:b.eventStream)!=null?x:{},u=o.find(S=>S.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&s){let S=u.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>h().element,onClose:n});if(S)return{element:S,update:()=>{},destroy:()=>{}}}return h();function h(){let S=p.classNames,F=f("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Gr(F,S==null?void 0:S.panel);let w=[],L="",R="",T=null,Y=[],ue={},se=0,$=Xo(),te=0,Ae=0,ne=!1,Ce=null,Me=!1,de=0,fe=new Set,Se=new Map,J="",ae="",ge=null,De,Le,Ie,Re,ot;function At(){let G=f("div","persona-flex persona-flex-col persona-flex-shrink-0"),he=f("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");Gr(he,S==null?void 0:S.headerBar);let Pe=f("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Pe.textContent="Events",De=f("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"),De.textContent="0";let mt=f("div","persona-flex-1");Le=f("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 Nt=f("option","");Nt.value="",Nt.textContent="All events",Le.appendChild(Nt),Ie=f("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"),Ie.type="button",Ie.title="Copy All";let Ot=pe("clipboard-copy","12px","currentColor",1.5);Ot&&Ie.appendChild(Ot);let pt=f("span","persona-text-xs");pt.textContent="Copy All",Ie.appendChild(pt),he.appendChild(Pe),he.appendChild(De),he.appendChild(mt),he.appendChild(Le),he.appendChild(Ie);let Je=f("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Gr(Je,S==null?void 0:S.searchBar);let ut=pe("search","14px","var(--persona-muted, #9ca3af)",1.5),Ne=f("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");ut&&Ne.appendChild(ut),Re=f("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"),Gr(Re,S==null?void 0:S.searchInput),Re.type="text",Re.placeholder="Search event payloads...",ot=f("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"),ot.type="button",ot.style.display="none";let $t=pe("x","12px","currentColor",2);return $t&&ot.appendChild($t),Je.appendChild(Ne),Je.appendChild(Re),Je.appendChild(ot),G.appendChild(he),G.appendChild(Je),G}let j,U=o.find(G=>G.renderEventStreamToolbar);if(U!=null&&U.renderEventStreamToolbar&&s){let G=U.renderEventStreamToolbar({config:s,defaultRenderer:()=>At(),eventCount:r.getSize(),filteredCount:0,onFilterChange:he=>{L=he,Jt(),ke()},onSearchChange:he=>{R=he,Jt(),ke()}});j=G!=null?G:At()}else j=At();let re=f("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");re.style.display="none";let _=f("div","persona-flex-1 persona-min-h-0 persona-relative"),z=f("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");z.style.height="100%";let Q=f("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Gr(Q,S==null?void 0:S.scrollIndicator),Q.style.display="none",Q.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let lt=pe(d,"14px","currentColor",2);lt&&Q.appendChild(lt);let K=f("span","");K.textContent=c,Q.appendChild(K);let X=f("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");X.style.display="none",_.appendChild(z),_.appendChild(X),_.appendChild(Q),F.setAttribute("tabindex","0"),F.appendChild(j),F.appendChild(re),F.appendChild(_);function wt(){let G=r.getAll(),he={};for(let pt of G)he[pt.type]=(he[pt.type]||0)+1;let Pe=Object.keys(he).sort(),mt=Pe.length!==Y.length||!Pe.every((pt,Je)=>pt===Y[Je]),Nt=!mt&&Pe.some(pt=>he[pt]!==ue[pt]),at=G.length!==Object.values(ue).reduce((pt,Je)=>pt+Je,0);if(!mt&&!Nt&&!at||(Y=Pe,ue=he,!Le))return;let Ot=Le.value;if(Le.options[0].textContent="All events",mt){for(;Le.options.length>1;)Le.remove(1);for(let pt of Pe){let Je=f("option","");Je.value=pt,Je.textContent=`${pt} (${he[pt]||0})`,Le.appendChild(Je)}Ot&&Pe.includes(Ot)?Le.value=Ot:Ot&&(Le.value="",L="")}else for(let pt=1;pt<Le.options.length;pt++){let Je=Le.options[pt];Je.textContent=`${Je.value} (${he[Je.value]||0})`}}function st(){let G=r.getAll();if(L&&(G=G.filter(he=>he.type===L)),R){let he=R.toLowerCase();G=G.filter(Pe=>Pe.type.toLowerCase().includes(he)||Pe.payload.toLowerCase().includes(he))}return G}function Pt(){return L!==""||R!==""}function Jt(){se=0,te=0,$.resume(),Q.style.display="none"}function Be(G){fe.has(G)?fe.delete(G):fe.add(G),ge=G;let he=z.scrollTop,Pe=$.isFollowing();Me=!0,$.pause(),ke(),z.scrollTop=he,Pe&&$.resume(),Me=!1}function ie(){return Ao(z,50)}function ke(){Ae=Date.now(),ne=!1,wt();let G=r.getEvictedCount();G>0?(re.textContent=`${G.toLocaleString()} older events truncated`,re.style.display=""):re.style.display="none",w=st();let he=w.length,Pe=r.getSize()>0;De&&(De.textContent=String(r.getSize())),he===0&&Pe&&Pt()?(X.textContent=R?`No events matching '${R}'`:"No events matching filter",X.style.display="",z.style.display="none"):(X.style.display="none",z.style.display=""),Ie&&(Ie.title=Pt()?`Copy Filtered (${he})`:"Copy All"),i&&!$.isFollowing()&&he>se&&(te+=he-se,K.textContent=c?`${c}${te>0?` (${te})`:""}`:"",Q.style.display=""),se=he;let mt=r.getAll(),Nt=mt.length>0?mt[0].timestamp:0,at=new Set(w.map(Je=>Je.id));for(let Je of fe)at.has(Je)||fe.delete(Je);let Ot=L!==J||R!==ae,pt=Se.size===0&&w.length>0;if(Ot||pt||w.length===0){z.innerHTML="",Se.clear();let Je=document.createDocumentFragment();for(let ut=0;ut<w.length;ut++){let Ne=Hs(w[ut],ut,Nt,p,fe,Be,o,s);Se.set(w[ut].id,Ne),Je.appendChild(Ne)}z.appendChild(Je),J=L,ae=R,ge=null}else{if(ge!==null){let ut=Se.get(ge);if(ut&&ut.parentNode===z){let Ne=w.findIndex($t=>$t.id===ge);if(Ne>=0){let $t=Hs(w[Ne],Ne,Nt,p,fe,Be,o,s);z.insertBefore($t,ut),ut.remove(),Se.set(ge,$t)}}ge=null}let Je=new Set(w.map(ut=>ut.id));for(let[ut,Ne]of Se)Je.has(ut)||(Ne.remove(),Se.delete(ut));for(let ut=0;ut<w.length;ut++){let Ne=w[ut];if(!Se.has(Ne.id)){let $t=Hs(Ne,ut,Nt,p,fe,Be,o,s);Se.set(Ne.id,$t),z.appendChild($t)}}}$.isFollowing()&&(z.scrollTop=z.scrollHeight)}function Et(){if(Date.now()-Ae>=up){Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),ke();return}ne||(ne=!0,Ce=requestAnimationFrame(()=>{Ce=null,ke()}))}let Tt=(G,he)=>{if(!Ie)return;Ie.innerHTML="";let Pe=pe(G,"12px","currentColor",1.5);Pe&&Ie.appendChild(Pe);let mt=f("span","persona-text-xs");mt.textContent="Copy All",Ie.appendChild(mt),setTimeout(()=>{Ie.innerHTML="";let Nt=pe("clipboard-copy","12px","currentColor",1.5);Nt&&Ie.appendChild(Nt);let at=f("span","persona-text-xs");at.textContent="Copy All",Ie.appendChild(at),Ie.disabled=!1},he)},Qe=async()=>{if(Ie){Ie.disabled=!0;try{let G;Pt()?G=w:t?(G=await t(),G.length===0&&(G=r.getAll())):G=r.getAll();let he=G.map(Pe=>{try{return JSON.parse(Pe.payload)}catch{return Pe.payload}});await navigator.clipboard.writeText(JSON.stringify(he,null,2)),Tt("check",1500)}catch{Tt("x",1500)}}},et=()=>{Le&&(L=Le.value,Jt(),ke())},en=()=>{!Re||!ot||(ot.style.display=Re.value?"":"none",T&&clearTimeout(T),T=setTimeout(()=>{R=Re.value,Jt(),ke()},150))},Zt=()=>{!Re||!ot||(Re.value="",R="",ot.style.display="none",T&&clearTimeout(T),Jt(),ke())},tn=()=>{if(Me)return;let G=z.scrollTop,{action:he,nextLastScrollTop:Pe}=Go({following:$.isFollowing(),currentScrollTop:G,lastScrollTop:de,nearBottom:ie(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});de=Pe,he==="resume"?($.resume(),te=0,Q.style.display="none"):he==="pause"&&($.pause(),i&&(K.textContent=c,Q.style.display=""))},O=G=>{let he=Zo({following:$.isFollowing(),deltaY:G.deltaY,nearBottom:ie(),resumeWhenNearBottom:!0});he==="pause"?($.pause(),i&&(K.textContent=c,Q.style.display="")):he==="resume"&&($.resume(),te=0,Q.style.display="none")},Ee=()=>{i&&(z.scrollTop=z.scrollHeight,$.resume(),te=0,Q.style.display="none")},le=G=>{let he=G.target;if(!he||he.closest("button"))return;let Pe=he.closest("[data-event-id]");if(!Pe)return;let mt=Pe.getAttribute("data-event-id");mt&&Be(mt)},dt=G=>{if((G.metaKey||G.ctrlKey)&&G.key==="f"){G.preventDefault(),Re==null||Re.focus(),Re==null||Re.select();return}G.key==="Escape"&&(Re&&document.activeElement===Re?(Zt(),Re.blur(),F.focus()):n&&n())};Ie&&Ie.addEventListener("click",Qe),Le&&Le.addEventListener("change",et),Re&&Re.addEventListener("input",en),ot&&ot.addEventListener("click",Zt),z.addEventListener("scroll",tn),z.addEventListener("wheel",O,{passive:!0}),z.addEventListener("click",le),Q.addEventListener("click",Ee),F.addEventListener("keydown",dt);function He(){T&&clearTimeout(T),Ce!==null&&(cancelAnimationFrame(Ce),Ce=null),ne=!1,Se.clear(),Ie&&Ie.removeEventListener("click",Qe),Le&&Le.removeEventListener("change",et),Re&&Re.removeEventListener("input",en),ot&&ot.removeEventListener("click",Zt),z.removeEventListener("scroll",tn),z.removeEventListener("wheel",O),z.removeEventListener("click",le),Q.removeEventListener("click",Ee),F.removeEventListener("keydown",dt)}return{element:F,update:Et,destroy:He}}}function Cc(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=t;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let h=document.createElement("span");h.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",h.style.backgroundColor="var(--persona-primary, #171717)",h.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(h);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(m)}else u.textContent=a;if(c.append(p,u),i.append(d,c),s==="complete"){let h=document.createElement("button");h.type="button",h.textContent="Download",h.title=`Download ${t}`,h.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",h.style.border="1px solid var(--persona-border, #e5e7eb)",h.style.color="var(--persona-text, #1f2937)",h.style.backgroundColor="transparent",h.style.cursor="pointer",h.setAttribute("data-download-artifact",n),i.append(h)}return i}var wc=(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",p=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:r.config,defaultRenderer:()=>Cc(e,r)});if(p)return p}return Cc(e,r)};var Bs=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)})}},vr=new Bs;vr.register("PersonaArtifactCard",wc);function vp(e){var s;let r=f("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=f("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let n=f("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 Sc(e,r){var Ie,Re,ot,At;let t=(Re=(Ie=e.features)==null?void 0:Ie.artifacts)==null?void 0:Re.layout,s=((ot=t==null?void 0:t.toolbarPreset)!=null?ot:"default")==="document",o=(At=t==null?void 0:t.panePadding)==null?void 0:At.trim(),a=e.markdown?jr(e.markdown):null,i=fo(e.sanitize),d=j=>{let U=a?a(j):mo(j);return i?i(U):U},c=typeof document!="undefined"?f("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{c==null||c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),$==null||$.hide()};c&&c.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let u=f("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");u.setAttribute("data-persona-theme-zone","artifact-pane"),s&&u.classList.add("persona-artifact-pane-document");let h=f("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");h.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&h.classList.add("persona-artifact-toolbar-document");let m=f("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let C=f("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;p(),(j=r.onDismiss)==null||j.call(r)});let M="rendered",b=f("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),x=s?It({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):It({icon:"eye",label:"Rendered view"}),S=s?It({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):It({icon:"code-2",label:"Source"}),F=f("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),w=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,L=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,R=t==null?void 0:t.documentToolbarCopyMenuItems,T=!!(L&&R&&R.length>0),Y=null,ue,se=null,$=null;if(s&&(w||L)&&!T){if(ue=w?es({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):It({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let j=pe("chevron-down",14,"currentColor",2);j&&ue.appendChild(j)}}else s&&T?(Y=f("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),ue=w?es({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):It({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),se=It({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),Y.append(ue,se)):s?ue=It({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):ue=It({icon:"copy",label:"Copy"});let te=s?It({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):It({icon:"refresh-cw",label:"Refresh"}),Ae=s?It({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):It({icon:"x",label:"Close"}),ne=()=>{var z,Q,lt;let j=(z=J.find(K=>K.id===ae))!=null?z:J[J.length-1],U=(Q=j==null?void 0:j.id)!=null?Q:null,re=(j==null?void 0:j.artifactType)==="markdown"&&(lt=j.markdown)!=null?lt:"",_=j?JSON.stringify({component:j.component,props:j.props},null,2):"";return{markdown:re,jsonPayload:_,id:U}},Ce=async()=>{var z;let{markdown:j,jsonPayload:U}=ne(),re=(z=J.find(Q=>Q.id===ae))!=null?z:J[J.length-1],_=(re==null?void 0:re.artifactType)==="markdown"?j:re?U:"";try{await navigator.clipboard.writeText(_)}catch{}};if(ue.addEventListener("click",async()=>{let j=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(j&&T){let{markdown:U,jsonPayload:re,id:_}=ne();try{await j({actionId:"primary",artifactId:_,markdown:U,jsonPayload:re})}catch{}return}await Ce()}),se&&(R!=null&&R.length)){let j=()=>{var re;return(re=u.closest("[data-persona-root]"))!=null?re:document.body},U=()=>{$=Pr({items:R.map(re=>({id:re.id,label:re.label})),onSelect:async re=>{let{markdown:_,jsonPayload:z,id:Q}=ne(),lt=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{lt?await lt({actionId:re,artifactId:Q,markdown:_,jsonPayload:z}):re==="markdown"||re==="md"?await navigator.clipboard.writeText(_):re==="json"||re==="source"?await navigator.clipboard.writeText(z):await navigator.clipboard.writeText(_||z)}catch{}},anchor:Y!=null?Y:se,position:"bottom-right",portal:j()})};u.isConnected?U():requestAnimationFrame(U),se.addEventListener("click",re=>{re.stopPropagation(),$==null||$.toggle()})}te.addEventListener("click",async()=>{var j;try{await((j=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:j.call(t))}catch{}De()}),Ae.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let Me=()=>{s&&(x.setAttribute("aria-pressed",M==="rendered"?"true":"false"),S.setAttribute("aria-pressed",M==="source"?"true":"false"))};x.addEventListener("click",()=>{M="rendered",Me(),De()}),S.addEventListener("click",()=>{M="source",Me(),De()});let de=f("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?(h.replaceChildren(),b.append(x,S),Y?F.append(Y,te,Ae):F.append(ue,te,Ae),h.append(b,de,F),Me()):(h.appendChild(m),h.appendChild(C)),o&&(h.style.paddingLeft=o,h.style.paddingRight=o);let fe=f("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"),Se=f("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(fe.style.paddingLeft=o,fe.style.paddingRight=o,Se.style.padding=o),u.appendChild(h),u.appendChild(fe),u.appendChild(Se);let J=[],ae=null,ge=!1,De=()=>{var _,z,Q,lt;let j=s&&J.length<=1;fe.classList.toggle("persona-hidden",j),fe.replaceChildren();for(let K of J){let X=f("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");X.type="button",X.textContent=K.title||K.id.slice(0,8),K.id===ae&&X.classList.add("persona-bg-persona-container","persona-border-persona-border"),X.addEventListener("click",()=>r.onSelect(K.id)),fe.appendChild(X)}Se.replaceChildren();let U=ae&&J.find(K=>K.id===ae)||J[J.length-1];if(!U)return;if(s){let K=U.artifactType==="markdown"?"MD":(_=U.component)!=null?_:"Component",wt=(U.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";de.textContent=`${wt} \xB7 ${K}`}else m.textContent="Artifacts";if(U.artifactType==="markdown"){if(s&&M==="source"){let X=f("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");X.textContent=(z=U.markdown)!=null?z:"",Se.appendChild(X);return}let K=f("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");K.innerHTML=d((Q=U.markdown)!=null?Q:""),Se.appendChild(K);return}let re=U.component?vr.get(U.component):void 0;if(re){let X={message:{id:U.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let wt=re((lt=U.props)!=null?lt:{},X);if(wt){Se.appendChild(wt);return}}catch{}}Se.appendChild(vp(U))},Le=()=>{var U;let j=J.length>0;if(u.classList.toggle("persona-hidden",!j),c){let re=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,z=((U=re==null?void 0:re.classList.contains("persona-artifact-narrow-host"))!=null?U:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;j&&z&&ge?(c.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:c,update(j){var U,re,_;J=j.artifacts,ae=(_=(re=j.selectedId)!=null?re:(U=j.artifacts[j.artifacts.length-1])==null?void 0:U.id)!=null?_:null,J.length>0&&(ge=!0),De(),Le()},setMobileOpen(j){ge=j,!j&&c?(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):Le()}}}function Wn(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 Ac(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"),!Wn(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 Cp(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 ns(e,r){var d,c,p,u,h,m,C,M,b,x;if(!Wn(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"),Cp(e),Ac(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",(p=t==null?void 0:t.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=t==null?void 0:t.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(h=t==null?void 0:t.paneMaxWidth)!=null?h:"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=(M=t==null?void 0:t.documentToolbarIconColor)==null?void 0:M.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(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"),Ac(e,r)}var Ec=["panel","seamless"];function rs(e,r){var i,d,c,p,u,h;for(let m of Ec)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"),!Wn(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=Ec.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=t==null?void 0:t.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(u=t==null?void 0:t.paneShadow)==null?void 0:u.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=((h=t.unifiedSplitOuterRadius)==null?void 0:h.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Tc(e,r){var t,n,s;return!r||!Wn(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function wp(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 Sp(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 Ap(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function Ep(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function Mc(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 kc(e,r,t,n,s,o){let a=wp(s,200),i=Ep(r,t,n,200);i=Math.max(a,i);let d=Sp(o);return d!==null&&(i=Math.min(i,d)),Ap(e,a,i)}var Lc={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"}},Ds=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var C,M,b;if(o.dataset.enhanced==="true")return;let a=(C=o.dataset.tvForm)!=null?C:"init";o.dataset.enhanced="true";let i=(M=Lc[a])!=null?M:Lc.init;o.classList.add("persona-form-card","persona-space-y-4");let d=f("div","persona-space-y-1"),c=f("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let x=f("p","persona-text-sm persona-text-persona-muted");x.textContent=i.description,d.appendChild(x)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(x=>{var R,T;let S=f("label","persona-form-field persona-flex persona-flex-col persona-gap-1");S.htmlFor=`${r.id}-${a}-${x.name}`;let F=f("span","persona-text-xs persona-font-medium persona-text-persona-muted");F.textContent=x.label,S.appendChild(F);let w=(R=x.type)!=null?R:"text",L;w==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=w),L.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",L.id=`${r.id}-${a}-${x.name}`,L.name=x.name,L.placeholder=(T=x.placeholder)!=null?T:"",x.required&&(L.required=!0),S.appendChild(L),p.appendChild(S)});let u=f("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),h=f("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=f("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",u.appendChild(h),u.appendChild(m),p.appendChild(u),o.replaceChildren(d,p),p.addEventListener("submit",async x=>{var L,R;x.preventDefault();let S=(L=t.formEndpoint)!=null?L:"/form",F=new FormData(p),w={};F.forEach((T,Y)=>{w[Y]=T}),w.type=a,m.disabled=!0,h.textContent="Submitting\u2026";try{let T=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!T.ok)throw new Error(`Form submission failed (${T.status})`);let Y=await T.json();h.textContent=(R=Y.message)!=null?R:"Thanks! We'll be in touch soon.",Y.success&&Y.nextPrompt&&await n.sendMessage(String(Y.nextPrompt))}catch(T){h.textContent=T instanceof Error?T.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Fs=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()}},os=new Fs;var St={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}",agentIconName:"bot",headerIconName:"bot",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:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""}},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 Ic(e,r){if(!(!e&&!r))return e?r?wo(e,r):e:r}function Ns(e){var r,t,n,s,o,a,i,d,c,p,u,h,m,C,M,b,x,S,F,w,L;return e?{...St,...e,theme:Ic(St.theme,e.theme),darkTheme:Ic(St.darkTheme,e.darkTheme),launcher:{...St.launcher,...e.launcher,dock:{...(r=St.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=St.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...St.copy,...e.copy},sendButton:{...St.sendButton,...e.sendButton},statusIndicator:{...St.statusIndicator,...e.statusIndicator},voiceRecognition:{...St.voiceRecognition,...e.voiceRecognition},features:(()=>{var te,Ae,ne,Ce;let R=(te=St.features)==null?void 0:te.artifacts,T=(Ae=e.features)==null?void 0:Ae.artifacts,Y=(ne=St.features)==null?void 0:ne.scrollToBottom,ue=(Ce=e.features)==null?void 0:Ce.scrollToBottom,se=R===void 0&&T===void 0?void 0:{...R,...T,layout:{...R==null?void 0:R.layout,...T==null?void 0:T.layout}},$=Y===void 0&&ue===void 0?void 0:{...Y,...ue};return{...St.features,...e.features,...$!==void 0?{scrollToBottom:$}:{},...se!==void 0?{artifacts:se}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:St.suggestionChips,suggestionChipsConfig:{...St.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...St.layout,...e.layout,header:{...(a=St.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=St.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(u=(p=St.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(m=(h=e.layout)==null?void 0:h.messages)==null?void 0:m.avatar},timestamp:{...(M=(C=St.layout)==null?void 0:C.messages)==null?void 0:M.timestamp,...(x=(b=e.layout)==null?void 0:b.messages)==null?void 0:x.timestamp}},slots:{...(S=St.layout)==null?void 0:S.slots,...(F=e.layout)==null?void 0:F.slots}},markdown:{...St.markdown,...e.markdown,options:{...(w=St.markdown)==null?void 0:w.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...St.messageActions,...e.messageActions}}:St}var Pc=()=>{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 Tp=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},Mp=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},ss=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=Tp(e),t=Mp(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}},Os=e=>typeof e=="string"?e:e==null?"":String(e),Zr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Os(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=Os(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:Os(t.text)}}},Wc=e=>Array.isArray(e)?e.map(r=>String(r)):[],as=e=>{let r=new Set(Wc(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(Wc(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let o=Array.from(r);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||r.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((c,p)=>c||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let d={action:i,message:o.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",d)},u=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let h=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:h,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:t}};var kp=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}},Lp=e=>e.map(r=>({...r,streaming:!1})),$s=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?kp(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?Lp(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 Ip,STR as Pp,OBJ as Wp}from"partial-json";function Rp(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function Hp(e,r){if(!Rp(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 _s(){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=Ip(t,Pp|Wp),o=Hp(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Bp(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function js(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=vr.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 Dp(){let e=_s();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function zs(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 Vs(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 Fp=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function qs(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=Fp}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,h=document.createElement("div");h.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 M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=s,m.appendChild(M),h.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 R=1;R<=5;R++){let T=document.createElement("button");T.type="button",T.className="persona-feedback-rating-btn persona-feedback-star-btn",T.setAttribute("role","radio"),T.setAttribute("aria-checked","false"),T.setAttribute("aria-label",`${R} star${R>1?"s":""}: ${c[R-1]}`),T.title=c[R-1],T.dataset.rating=String(R),T.innerHTML=`
15
+ `,t.addEventListener("click",r);let n=o=>{var R,w,L,B,T,Y,ue,ce,$,te,Te,ne,Se,He;let a=(R=o.launcher)!=null?R:{},i=Yt(o),d=t.querySelector("[data-role='launcher-title']");if(d){let he=(w=a.title)!=null?w:"Chat Assistant";d.textContent=he,d.setAttribute("title",he)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let he=(L=a.subtitle)!=null?L:"Get answers fast";c.textContent=he,c.setAttribute("title",he)}let p=t.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=t.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let he=(B=a.agentIconSize)!=null?B:"40px";if(u.style.height=he,u.style.width=he,u.innerHTML="",a.agentIconName){let Me=parseFloat(he)||24,ke=me(a.agentIconName,Me*.6,"var(--persona-text-inverse, #ffffff)",2);ke?(u.appendChild(ke),u.style.display=""):(u.textContent=(T=a.agentIconText)!=null?T:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(Y=a.agentIconText)!=null?Y:"\u{1F4AC}",u.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let he=(ue=a.agentIconSize)!=null?ue:"40px";f.style.height=he,f.style.width=he,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 he=(ce=a.callToActionIconSize)!=null?ce:"32px";m.style.height=he,m.style.width=he,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Me=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Me=(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 ke=parseFloat(he)||24,re=Math.max(ke-Me,8),be=me(a.callToActionIconName,re,"currentColor",2);be?m.appendChild(be):m.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}else m.textContent=(te=a.callToActionIconText)!=null?te:"\u2197"}let v=a.position&&zn[a.position]?zn[a.position]:zn["bottom-right"],M="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",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:`${M} ${v}`,i||(t.style.zIndex=String((Te=a.zIndex)!=null?Te:yn));let C="1px solid var(--persona-border, #e5e7eb)",S="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=(ne=a.border)!=null?ne:C,t.style.boxShadow=(Se=a.shadow)!=null?Se:S,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=(He=a.collapsedMaxWidth)!=null?He:"",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 bn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Cr=e=>{var ce,$,te,Te,ne,Se,He,he,Me,ke,re,be,$e,ge,de,oe,De,ot,wt,j,q,se,_,z,Q,Fe,J,K,xt,tt,Lt,Ut;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=($=s.headerIconSize)!=null?$:"48px",a=(te=s.closeButtonSize)!=null?te:"32px",i=(Te=s.closeButtonPlacement)!=null?Te:"inline",d=(ne=s.headerIconHidden)!=null?ne:!1,c=s.headerIconName,p=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(p.style.height=o,p.style.width=o,p.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",p.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!d)if(c){let Ne=parseFloat(o)||24,le=me(c,Ne*.6,"currentColor",1);le?p.replaceChildren(le):p.textContent=(He=(Se=r==null?void 0:r.launcher)==null?void 0:Se.agentIconText)!=null?He:"\u{1F4AC}"}else if((he=r==null?void 0:r.launcher)!=null&&he.iconUrl){let Ne=h("img");Ne.src=r.launcher.iconUrl,Ne.alt="",Ne.className="persona-rounded-xl persona-object-cover",Ne.style.height=o,Ne.style.width=o,p.replaceChildren(Ne)}else p.textContent=(ke=(Me=r==null?void 0:r.launcher)==null?void 0:Me.agentIconText)!=null?ke:"\u{1F4AC}";let u=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=h("span","persona-text-base persona-font-semibold");f.style.color=bn.titleColor,f.textContent=(be=(re=r==null?void 0:r.launcher)==null?void 0:re.title)!=null?be:"Chat Assistant";let m=h("span","persona-text-xs");m.style.color=bn.subtitleColor,m.textContent=(ge=($e=r==null?void 0:r.launcher)==null?void 0:$e.subtitle)!=null?ge:"Here to help you get answers fast",u.append(f,m),d?n.append(u):n.append(p,u);let v=(de=s.clearChat)!=null?de:{},M=(oe=v.enabled)!=null?oe:!0,b=(De=v.placement)!=null?De:"inline",C=null,S=null;if(M){let Ne=(ot=v.size)!=null?ot:"32px",le=(wt=v.iconName)!=null?wt:"refresh-cw",Ie=(j=v.iconColor)!=null?j:"",St=(q=v.backgroundColor)!=null?q:"",At=(se=v.borderWidth)!=null?se:"",Ze=(_=v.borderColor)!=null?_:"",Qe=(z=v.borderRadius)!=null?z:"",Kt=(Q=v.paddingX)!=null?Q:"",Gt=(Fe=v.paddingY)!=null?Fe:"",Zt=(J=v.tooltipText)!=null?J:"Clear chat",O=(K=v.showTooltip)!=null?K:!0;S=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"&&(S.style.right="48px"),C=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"),C.style.height=Ne,C.style.width=Ne,C.type="button",C.setAttribute("aria-label",Zt),C.style.color=Ie||bn.actionIconColor;let Le=me(le,"20px","currentColor",1);if(Le&&C.appendChild(Le),St&&(C.style.backgroundColor=St,C.classList.remove("hover:persona-bg-gray-100")),At||Ze){let pe=At||"0px",at=Ze||"transparent";C.style.border=`${pe} solid ${at}`,C.classList.remove("persona-border-none")}if(Qe&&(C.style.borderRadius=Qe,C.classList.remove("persona-rounded-full")),Kt?(C.style.paddingLeft=Kt,C.style.paddingRight=Kt):(C.style.paddingLeft="",C.style.paddingRight=""),Gt?(C.style.paddingTop=Gt,C.style.paddingBottom=Gt):(C.style.paddingTop="",C.style.paddingBottom=""),S.appendChild(C),O&&Zt&&C&&S){let pe=null,at=()=>{if(pe||!C)return;let Z=C.ownerDocument,ye=Z.body;if(!ye)return;pe=Yn(Z,"div","persona-clear-chat-tooltip"),pe.textContent=Zt;let Pe=Yn(Z,"div");Pe.className="persona-clear-chat-tooltip-arrow",pe.appendChild(Pe);let dt=C.getBoundingClientRect();pe.style.position="fixed",pe.style.zIndex=String(xr),pe.style.left=`${dt.left+dt.width/2}px`,pe.style.top=`${dt.top-8}px`,pe.style.transform="translate(-50%, -100%)",ye.appendChild(pe)},Be=()=>{pe&&pe.parentNode&&(pe.parentNode.removeChild(pe),pe=null)};S.addEventListener("mouseenter",at),S.addEventListener("mouseleave",Be),C.addEventListener("focus",at),C.addEventListener("blur",Be),S._cleanupTooltip=()=>{Be(),S&&(S.removeEventListener("mouseenter",at),S.removeEventListener("mouseleave",Be)),C&&(C.removeEventListener("focus",at),C.removeEventListener("blur",Be))}}b==="inline"&&n.appendChild(S)}let R=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":M&&b==="inline"?"":"persona-ml-auto"),w=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");w.style.height=a,w.style.width=a,w.type="button";let L=(xt=s.closeButtonTooltipText)!=null?xt:"Close chat",B=(tt=s.closeButtonShowTooltip)!=null?tt:!0;w.setAttribute("aria-label",L),w.style.display=t?"":"none";let T=(Lt=s.closeButtonIconName)!=null?Lt:"x",Y=(Ut=s.closeButtonIconText)!=null?Ut:"\xD7";w.style.color=s.closeButtonColor||bn.actionIconColor;let ue=me(T,"20px","currentColor",1);if(ue?w.appendChild(ue):w.textContent=Y,s.closeButtonBackgroundColor?(w.style.backgroundColor=s.closeButtonBackgroundColor,w.classList.remove("hover:persona-bg-gray-100")):(w.style.backgroundColor="",w.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let Ne=s.closeButtonBorderWidth||"0px",le=s.closeButtonBorderColor||"transparent";w.style.border=`${Ne} solid ${le}`,w.classList.remove("persona-border-none")}else w.style.border="",w.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(w.style.borderRadius=s.closeButtonBorderRadius,w.classList.remove("persona-rounded-full")):(w.style.borderRadius="",w.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(w.style.paddingLeft=s.closeButtonPaddingX,w.style.paddingRight=s.closeButtonPaddingX):(w.style.paddingLeft="",w.style.paddingRight=""),s.closeButtonPaddingY?(w.style.paddingTop=s.closeButtonPaddingY,w.style.paddingBottom=s.closeButtonPaddingY):(w.style.paddingTop="",w.style.paddingBottom=""),R.appendChild(w),B&&L){let Ne=null,le=()=>{if(Ne)return;let St=w.ownerDocument,At=St.body;if(!At)return;Ne=Yn(St,"div","persona-clear-chat-tooltip"),Ne.textContent=L;let Ze=Yn(St,"div");Ze.className="persona-clear-chat-tooltip-arrow",Ne.appendChild(Ze);let Qe=w.getBoundingClientRect();Ne.style.position="fixed",Ne.style.zIndex=String(xr),Ne.style.left=`${Qe.left+Qe.width/2}px`,Ne.style.top=`${Qe.top-8}px`,Ne.style.transform="translate(-50%, -100%)",At.appendChild(Ne)},Ie=()=>{Ne&&Ne.parentNode&&(Ne.parentNode.removeChild(Ne),Ne=null)};R.addEventListener("mouseenter",le),R.addEventListener("mouseleave",Ie),w.addEventListener("focus",le),w.addEventListener("blur",Ie),R._cleanupTooltip=()=>{Ie(),R.removeEventListener("mouseenter",le),R.removeEventListener("mouseleave",Ie),w.removeEventListener("focus",le),w.removeEventListener("blur",Ie)}}return i!=="top-right"&&n.appendChild(R),{header:n,iconHolder:p,headerTitle:f,headerSubtitle:m,closeButton:w,closeButtonWrapper:R,clearChatButton:C,clearChatButtonWrapper:S}},Xr=(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 Hr(e){let{items:r,onSelect:t,anchor:n,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(xr)):(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 v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let b=me(m.icon,16,"currentColor",1.5);b&&v.appendChild(b)}let M=document.createElement("span");M.textContent=m.label,v.appendChild(M),v.addEventListener("click",b=>{b.stopPropagation(),p(),t(m.id)}),a.appendChild(v)}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=v=>{!a.contains(v.target)&&!n.contains(v.target)&&p()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:p,toggle:u,destroy:f}}function kt(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[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function os(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 p=h("button",c);if(p.type="button",p.setAttribute("aria-label",t),r){let f=me(r,o!=null?o:14,"currentColor",2);f&&p.appendChild(f)}let u=h("span");if(u.textContent=t,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))p.setAttribute(f,m);return p}function ss(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 p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of r){let u;p.icon?u=kt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),n(p.id)}}):(u=h("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),n(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),o.appendChild(u)}function c(p){a=p,d()}return{element:o,setSelected:c}}function Bs(e){var m,v;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 p=h("span","persona-combo-btn-label");p.textContent=r,c.appendChild(p);let u=me(t,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",c.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var M,b;c.style.backgroundColor=(M=d.background)!=null?M:"",c.style.borderColor=(b=d.border)!=null?b:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=Hr({items:n,onSelect:M=>{c.setAttribute("aria-expanded","false"),s(M)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",M=>{M.stopPropagation();let b=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",b?"false":"true"),f.toggle()}),c.addEventListener("keydown",M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),c.click())}),{element:c,setLabel:M=>{p.textContent=M,c.setAttribute("aria-label",M)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let M=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",M?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var uc=e=>{var n;let r=Cr({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 np(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=Hr({items:a.menuItems,onSelect:p=>t==null?void 0:t(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var gc=e=>{var S,R,w,L,B,T,Y,ue,ce;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(S=r==null?void 0:r.launcher)!=null?S:{},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,p;if(d)c=Bs({label:(R=a.title)!=null?R:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=bn.titleColor,p=(w=c.querySelector(".persona-combo-btn-label"))!=null?w:c;else{if(c=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=h("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=bn.titleColor,p.textContent=(L=a.title)!=null?L:"Chat Assistant",c.appendChild(p),np(c,s==null?void 0:s.trailingActions,(B=s==null?void 0:s.onAction)!=null?B:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let te=s.onTitleClick;c.addEventListener("click",Te=>{Te.target.closest("button")||te()}),c.addEventListener("keydown",Te=>{(Te.key==="Enter"||Te.key===" ")&&(Te.preventDefault(),te())})}let $=s==null?void 0:s.titleRowHover;$&&(c.style.borderRadius=(T=$.borderRadius)!=null?T:"10px",c.style.padding=(Y=$.padding)!=null?Y:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var te,Te;c.style.backgroundColor=(te=$.background)!=null?te:"",c.style.borderColor=(Te=$.border)!=null?Te:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let u=(ue=a.closeButtonSize)!=null?ue:"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=u,m.style.width=u,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||bn.actionIconColor;let v=(ce=a.closeButtonIconName)!=null?ce:"x",M=me(v,"20px","currentColor",2);M?m.appendChild(M):m.textContent="\xD7",n&&m.addEventListener("click",n),f.appendChild(m),i.appendChild(f);let b=h("div");b.style.display="none";let C=h("span");return C.style.display="none",{header:i,iconHolder:b,headerTitle:p,headerSubtitle:C,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Ds={default:uc,minimal:gc},mc=e=>{var r;return(r=Ds[e])!=null?r:Ds.default},Po=(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}),p=h("div");p.style.display="none";let u=h("span"),f=h("span"),m=h("button");m.style.display="none";let v=h("div");return v.style.display="none",{header:c,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=mc(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 Wo=e=>{var De,ot,wt,j,q,se,_,z,Q,Fe,J,K,xt,tt,Lt,Ut,Ne,le,Ie,St,At,Ze,Qe,Kt,Gt,Zt,O;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=(ot=(De=r==null?void 0:r.copy)==null?void 0:De.inputPlaceholder)!=null?ot:"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 Le=Math.min(o.scrollHeight,d);o.style.height=`${Le}px`};o.addEventListener("input",c),o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"});let p=(wt=r==null?void 0:r.sendButton)!=null?wt:{},u=(j=p.useIcon)!=null?j:!1,f=(q=p.iconText)!=null?q:"\u2191",m=p.iconName,v=(se=p.tooltipText)!=null?se:"Send message",M=(_=p.showTooltip)!=null?_:!1,b=(z=p.size)!=null?z:"40px",C=p.backgroundColor,S=p.textColor,R=h("div","persona-send-button-wrapper"),w=h("button",u?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");if(w.type="submit",w.setAttribute("data-persona-composer-submit",""),u){if(w.style.width=b,w.style.height=b,w.style.minWidth=b,w.style.minHeight=b,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",S?w.style.color=S:w.style.color="var(--persona-button-primary-fg, #ffffff)",m){let Le=parseFloat(b)||24,pe=(S==null?void 0:S.trim())||"currentColor",at=me(m,Le,pe,2);at?w.appendChild(at):w.textContent=f}else w.textContent=f;C?w.style.backgroundColor=C:w.classList.add("persona-bg-persona-primary")}else w.textContent=(Fe=(Q=r==null?void 0:r.copy)==null?void 0:Q.sendButtonLabel)!=null?Fe:"Send",S?w.style.color=S:w.classList.add("persona-text-white");if(p.borderWidth&&(w.style.borderWidth=p.borderWidth,w.style.borderStyle="solid"),p.borderColor&&(w.style.borderColor=p.borderColor),p.paddingX?(w.style.paddingLeft=p.paddingX,w.style.paddingRight=p.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),p.paddingY?(w.style.paddingTop=p.paddingY,w.style.paddingBottom=p.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),M&&v){let Le=h("div","persona-send-button-tooltip");Le.textContent=v,R.appendChild(Le)}R.appendChild(w);let L=(J=r==null?void 0:r.voiceRecognition)!=null?J:{},B=L.enabled===!0,T=null,Y=null,ue=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ce=((K=L.provider)==null?void 0:K.type)==="runtype";if(B&&(ue||ce)){Y=h("div","persona-send-button-wrapper"),T=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),T.type="button",T.setAttribute("data-persona-composer-mic",""),T.setAttribute("aria-label","Start voice recognition");let Le=(xt=L.iconName)!=null?xt:"mic",pe=(tt=L.iconSize)!=null?tt:b,at=parseFloat(pe)||24,Be=(Lt=L.backgroundColor)!=null?Lt:C,Z=(Ut=L.iconColor)!=null?Ut:S;T.style.width=pe,T.style.height=pe,T.style.minWidth=pe,T.style.minHeight=pe,T.style.fontSize="18px",T.style.lineHeight="1",Z?T.style.color=Z:T.style.color="var(--persona-text, #111827)";let Pe=me(Le,at,Z||"currentColor",1.5);Pe?T.appendChild(Pe):T.textContent="\u{1F3A4}",Be&&(T.style.backgroundColor=Be),L.borderWidth&&(T.style.borderWidth=L.borderWidth,T.style.borderStyle="solid"),L.borderColor&&(T.style.borderColor=L.borderColor),L.paddingX&&(T.style.paddingLeft=L.paddingX,T.style.paddingRight=L.paddingX),L.paddingY&&(T.style.paddingTop=L.paddingY,T.style.paddingBottom=L.paddingY),Y.appendChild(T);let dt=(Ne=L.tooltipText)!=null?Ne:"Start voice recognition";if(((le=L.showTooltip)!=null?le:!1)&&dt){let nt=h("div","persona-send-button-tooltip");nt.textContent=dt,Y.appendChild(nt)}}let te=(Ie=r==null?void 0:r.attachments)!=null?Ie:{},Te=te.enabled===!0,ne=null,Se=null,He=null,he=null;if(Te){he=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),he.style.display="none",He=h("input"),He.type="file",He.accept=((St=te.allowedTypes)!=null?St:sr).join(","),He.multiple=((At=te.maxFiles)!=null?At:4)>1,He.style.display="none",He.setAttribute("aria-label","Attach files"),Se=h("div","persona-send-button-wrapper"),ne=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ne.type="button",ne.setAttribute("aria-label",(Ze=te.buttonTooltipText)!=null?Ze:"Attach file");let Le=(Qe=te.buttonIconName)!=null?Qe:"paperclip",pe=b,at=parseFloat(pe)||40,Be=Math.round(at*.6);ne.style.width=pe,ne.style.height=pe,ne.style.minWidth=pe,ne.style.minHeight=pe,ne.style.fontSize="18px",ne.style.lineHeight="1",ne.style.backgroundColor="transparent",ne.style.color="var(--persona-primary, #111827)",ne.style.border="none",ne.style.borderRadius="6px",ne.style.transition="background-color 0.15s ease",ne.addEventListener("mouseenter",()=>{ne.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ne.addEventListener("mouseleave",()=>{ne.style.backgroundColor="transparent"});let Z=me(Le,Be,"currentColor",1.5);Z?ne.appendChild(Z):ne.textContent="\u{1F4CE}",ne.addEventListener("click",dt=>{dt.preventDefault(),He==null||He.click()}),Se.appendChild(ne);let ye=(Kt=te.buttonTooltipText)!=null?Kt:"Attach file",Pe=h("div","persona-send-button-tooltip");Pe.textContent=ye,Se.appendChild(Pe)}s.addEventListener("click",Le=>{Le.target!==w&&Le.target!==R&&Le.target!==T&&Le.target!==Y&&Le.target!==ne&&Le.target!==Se&&o.focus()}),he&&(he.style.gap="8px",s.append(he)),He&&s.append(He),s.append(o);let Me=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),ke=h("div","persona-flex persona-items-center persona-gap-2");Se&&ke.append(Se);let re=h("div","persona-flex persona-items-center persona-gap-1");Y&&re.append(Y),re.append(R),Me.append(ke,re),s.append(Me);let be=(Gt=r==null?void 0:r.statusIndicator)!=null?Gt:{},$e=be.align==="left"?"persona-text-left":be.align==="center"?"persona-text-center":"persona-text-right",ge=h("div",`persona-mt-2 ${$e} persona-text-xs persona-text-persona-muted`);ge.setAttribute("data-persona-composer-status","");let de=(Zt=be.visible)!=null?Zt:!0;ge.style.display=de?"":"none";let oe=(O=be.idleText)!=null?O:"Online";if(be.idleLink){let Le=h("a");Le.href=be.idleLink,Le.target="_blank",Le.rel="noopener noreferrer",Le.textContent=oe,Le.style.color="inherit",Le.style.textDecoration="none",ge.appendChild(Le)}else ge.textContent=oe;return t.append(n,s,ge),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:R,micButton:T,micButtonWrapper:Y,statusText:ge,attachmentButton:ne,attachmentButtonWrapper:Se,attachmentInput:He,attachmentPreviewsContainer:he,actionsRow:Me,leftActions:ke,rightActions:re}};var fc=e=>{var c,p,u,f,m,v,M,b,C;let r=(p=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?p:!0;if(Yt(e)){let S=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),R=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return S.appendChild(R),{wrapper:S,panel:R}}if(!r){let S=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),R=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=(f=(u=e==null?void 0:e.launcher)==null?void 0:u.width)!=null?f:"100%";return S.style.width=w,R.style.width="100%",S.appendChild(R),{wrapper:S,panel:R}}let n=(m=e==null?void 0:e.launcher)!=null?m:{},s=n.position&&zn[n.position]?zn[n.position]:zn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);o.style.zIndex=String((M=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?M:yn);let a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(C=(b=e==null?void 0:e.launcher)==null?void 0:b.width)!=null?C:e==null?void 0:e.launcherWidth,d=i!=null?i:Rn;return a.style.width=d,a.style.maxWidth=d,o.appendChild(a),{wrapper:o,panel:a}},hc=(e,r=!0)=>{var b,C,S,R,w,L,B,T,Y;let t=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-bg-persona-surface persona-text-persona-primary persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let n=(b=e==null?void 0:e.layout)==null?void 0:b.header,s=((C=e==null?void 0:e.layout)==null?void 0:C.showHeader)!==!1,o=n?Po(e,n,{showClose:r}):Cr({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=Yt(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=(R=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeTitle)!=null?R:"Hello \u{1F44B}";let p=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");p.textContent=(L=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",d.append(c,p);let u=h("div","persona-flex persona-flex-col persona-gap-3"),f=(B=e==null?void 0:e.layout)==null?void 0:B.contentMaxWidth;f&&(u.style.maxWidth=f,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),d.setAttribute("data-persona-intro-card",""),((T=e==null?void 0:e.copy)==null?void 0:T.showWelcomeCard)!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,u);let v=Wo({config:e}),M=((Y=e==null?void 0:e.layout)==null?void 0:Y.showFooter)!==!1;return s?Xr(t,o,e):(o.header.style.display="none",Xr(t,o,e)),t.append(a),M||(v.footer.style.display="none"),t.append(v.footer),{container:t,body:a,messagesWrapper:u,suggestions:v.suggestions,textarea:v.textarea,sendButton:v.sendButton,sendButtonWrapper:v.sendButtonWrapper,micButton:v.micButton,micButtonWrapper:v.micButtonWrapper,composerForm:v.composerForm,statusText:v.statusText,introTitle:c,introSubtitle:p,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:v.footer,attachmentButton:v.attachmentButton,attachmentButtonWrapper:v.attachmentButtonWrapper,attachmentInput:v.attachmentInput,attachmentPreviewsContainer:v.attachmentPreviewsContainer,actionsRow:v.actionsRow,leftActions:v.leftActions,rightActions:v.rightActions}};var rp=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},op=320,sp=320,ap=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),ip=(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 u;let c=h("img");c.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${op}px`,c.style.maxHeight=`${sp}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;s+=1,c.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{p=!0}),rp(i.image)?(c.src=i.image,n.appendChild(c)):(p=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},Kr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(s),e},bc=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Kr};if(r){let s=r(n);if(s!==null)return s}return Kr()},lp=(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},yc=(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},cp=(e,r="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(r){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},xc=(e,r,t)=>{var m,v,M,b,C,S;let n=(m=r.showCopy)!=null?m:!0,s=(v=r.showUpvote)!=null?v:!0,o=(M=r.showDownvote)!=null?M:!0;if(!n&&!s&&!o){let R=h("div");return R.style.display="none",R.id=`actions-${e.id}`,R.setAttribute("data-actions-for",e.id),R}let a=(b=r.visibility)!=null?b:"hover",i=(C=r.align)!=null?C:"right",d=(S=r.layout)!=null?S:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],u=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let f=(R,w,L)=>{let B=kt({icon:R,label:w,size:14,className:"persona-message-action-btn"});return B.setAttribute("data-action",L),B};return n&&u.appendChild(f("copy","Copy message","copy")),s&&u.appendChild(f("thumbs-up","Upvote","upvote")),o&&u.appendChild(f("thumbs-down","Downvote","downvote")),u},Ro=(e,r,t,n,s,o)=>{var ce,$,te,Te,ne,Se,He;let a=t!=null?t:{},i=(ce=a.layout)!=null?ce:"bubble",d=a.avatar,c=a.timestamp,p=($=d==null?void 0:d.show)!=null?$:!1,u=(te=c==null?void 0:c.show)!=null?te:!1,f=(Te=d==null?void 0:d.position)!=null?Te:"left",m=(ne=c==null?void 0:c.position)!=null?ne:"below",v=cp(e.role,i),M=h("div",v.join(" "));M.id=`bubble-${e.id}`,M.setAttribute("data-message-id",e.id),M.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(M.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",M.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(M.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",M.style.color="var(--persona-message-assistant-text, var(--persona-text))");let b=ap(e),C=(He=(Se=e.content)==null?void 0:Se.trim())!=null?He:"",R=b.length>0&&C===qo,w=document.createElement("div");w.classList.add("persona-message-content");let L=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),B=null;if(R?(B=document.createElement("div"),B.innerHTML=L,B.style.display="none",w.appendChild(B)):w.innerHTML=L,u&&m==="inline"&&e.createdAt){let he=yc(e,c);he.classList.add("persona-ml-2","persona-inline"),w.appendChild(he)}if(b.length>0){let he=ip(b,!R&&!!C,()=>{R&&B&&(B.style.display="")});he?M.appendChild(he):R&&B&&(B.style.display="")}if(M.appendChild(w),u&&m==="below"&&e.createdAt){let he=yc(e,c);he.classList.add("persona-mt-1"),M.appendChild(he)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let he=bc("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);he&&M.appendChild(he)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let he=xc(e,n,s);M.appendChild(he)}if(!p||e.role==="system")return M;let Y=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ue=lp(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Y.append(M,ue):Y.append(ue,M),M.classList.remove("persona-max-w-[85%]"),M.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Y},dp=(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}):Ro(e,r,t,n,s,o)};var Zr=new Set,vc=(e,r)=>{let t=Zr.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"},Fs=e=>{let r=e.reasoning,t=h("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),!r)return t;let n=Zr.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=Vl(r),o.appendChild(i),r.status==="complete"?a.style.display="none":a.style.display="";let d=h("div","persona-flex persona-items-center"),p=me(n?"chevron-up":"chevron-down",16,"currentColor",2);p?d.appendChild(p):d.textContent=n?"Hide":"Show";let u=h("div","persona-flex persona-items-center persona-ml-auto");u.append(d),s.append(o,u);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(""),v=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return v.textContent=m||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(v),(()=>{s.setAttribute("aria-expanded",n?"true":"false"),d.innerHTML="";let C=me(n?"chevron-up":"chevron-down",16,"currentColor",2);C?d.appendChild(C):d.textContent=n?"Hide":"Show",f.style.display=n?"":"none"})(),t.append(s,f),t};var Qr=new Set,Cc=(e,r,t)=>{var c;let n=Qr.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 p=s.toggleTextColor||s.headerTextColor||"currentColor",u=me(n?"chevron-up":"chevron-down",16,p,2);u?d.appendChild(u):d.textContent=n?"Hide":"Show"}a.style.display=n?"":"none"},Ns=(e,r)=>{var M;let t=e.toolCall,n=(M=r==null?void 0:r.toolCall)!=null?M:{},s=h("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),n.backgroundColor&&(s.style.backgroundColor=n.backgroundColor),n.borderColor&&(s.style.borderColor=n.borderColor),n.borderWidth&&(s.style.borderWidth=n.borderWidth),n.borderRadius&&(s.style.borderRadius=n.borderRadius),!t)return s;let o=Qr.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=ql(t),i.appendChild(d);let c=h("div","persona-flex persona-items-center"),p=n.toggleTextColor||n.headerTextColor||"currentColor",u=me(o?"chevron-up":"chevron-down",16,p,2);u?c.appendChild(u):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"),C=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(C.style.color=n.labelTextColor),C.textContent="Arguments";let S=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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(S.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(S.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(S.style.color=n.codeBlockTextColor),S.textContent=vo(t.args),b.append(C,S),m.appendChild(b)}if(t.chunks&&t.chunks.length){let b=h("div","persona-space-y-1"),C=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(C.style.color=n.labelTextColor),C.textContent="Activity";let S=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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(S.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(S.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(S.style.color=n.codeBlockTextColor),S.textContent=t.chunks.join(`
16
+ `),b.append(C,S),m.appendChild(b)}if(t.status==="complete"&&t.result!==void 0){let b=h("div","persona-space-y-1"),C=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(C.style.color=n.labelTextColor),C.textContent="Result";let S=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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(S.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(S.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(S.style.color=n.codeBlockTextColor),S.textContent=vo(t.result),b.append(C,S),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",C=me(o?"chevron-up":"chevron-down",16,b,2);C?c.appendChild(C):c.textContent=o?"Hide":"Show",m.style.display=o?"":"none"})(),s.append(a,m),s};var Os=(e,r)=>{var M,b,C,S,R,w,L,B,T,Y,ue,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-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(M=n==null?void 0:n.backgroundColor)!=null?M:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(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)":(C=n==null?void 0:n.titleColor)!=null?C:"currentColor",p=me(d,20,c,2);p&&i.appendChild(p);let u=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=(S=n==null?void 0:n.title)!=null?S:"Approval Required",f.appendChild(m),!s){let $=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");$.setAttribute("data-approval-status",t.status),t.status==="approved"?($.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",$.style.color="var(--persona-palette-colors-success-700, #15803d)",$.textContent="Approved"):t.status==="denied"?($.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",$.style.color="var(--persona-palette-colors-error-700, #b91c1c)",$.textContent="Denied"):t.status==="timeout"&&($.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",$.style.color="var(--persona-palette-colors-warning-700, #b45309)",$.textContent="Timeout"),f.appendChild($)}u.appendChild(f);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(v.style.color=n.descriptionColor),v.textContent=t.description,u.appendChild(v),t.parameters){let $=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&&($.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&($.style.color=n.parameterTextColor),$.style.fontSize="0.75rem",$.style.lineHeight="1rem",$.textContent=vo(t.parameters),u.appendChild($)}if(s){let $=h("div","persona-flex persona-gap-2 persona-mt-2");$.setAttribute("data-approval-buttons","true");let te=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");te.type="button",te.style.backgroundColor=(R=n==null?void 0:n.approveButtonColor)!=null?R:"var(--persona-approval-approve-bg, #22c55e)",te.style.color=(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",te.setAttribute("data-approval-action","approve");let Te=me("shield-check",14,(L=n==null?void 0:n.approveButtonTextColor)!=null?L:"#ffffff",2);Te&&(Te.style.marginRight="4px",te.appendChild(Te));let ne=document.createTextNode((B=n==null?void 0:n.approveLabel)!=null?B:"Approve");te.appendChild(ne);let Se=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");Se.type="button",Se.style.backgroundColor=(T=n==null?void 0:n.denyButtonColor)!=null?T:"transparent",Se.style.color=(Y=n==null?void 0:n.denyButtonTextColor)!=null?Y:"var(--persona-feedback-error, #dc2626)",Se.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Se.setAttribute("data-approval-action","deny");let He=me("shield-x",14,(ue=n==null?void 0:n.denyButtonTextColor)!=null?ue:"var(--persona-feedback-error, #dc2626)",2);He&&(He.style.marginRight="4px",Se.appendChild(He));let he=document.createTextNode((ce=n==null?void 0:n.denyLabel)!=null?ce:"Deny");Se.appendChild(he),$.append(te,Se),u.appendChild($)}return a.append(i,u),o.appendChild(a),o};var wc=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 p=document.createDocumentFragment(),u=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 v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=m,v.disabled=u,i!=null&&i.fontFamily&&(v.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),p.appendChild(v),r.push(v)}),e.appendChild(p)}}};var Ho=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 Bo=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 eo(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var pp={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},up={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},gp=["flowName","stepName","reasoningText","text","name","tool","toolName"],mp=100;function fp(e,r){let t={...pp,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return up}function hp(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function yp(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 bp(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 xp(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 vp(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 Cp(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 $s(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");eo(c,(f=n.classNames)==null?void 0:f.eventRow);let p=a.find(m=>m.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let m=p.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(u()),c;function u(){var te,Te;let m=h("div",""),v=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",e.id);let M=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),b=me(d?"chevron-down":"chevron-right","14px","currentColor",2);b&&M.appendChild(b);let C=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),S=(te=n.timestampFormat)!=null?te:"relative";C.textContent=S==="relative"?hp(e.timestamp,t):yp(e.timestamp);let R=null;n.showSequenceNumbers!==!1&&(R=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),R.textContent=String(r+1));let w=fp(e.type,n.badgeColors),L=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");L.style.backgroundColor=w.bg,L.style.color=w.text,L.style.borderColor=w.text+"50",L.textContent=e.type;let B=(Te=n.descriptionFields)!=null?Te:gp,T=bp(e.payload,B),Y=null;T&&(Y=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),Y.textContent=T);let ue=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"),$=me("clipboard","12px","currentColor",1.5);return $&&ce.appendChild($),ce.addEventListener("click",async ne=>{ne.stopPropagation(),await xp(vp(e)),ce.innerHTML="";let Se=me("check","12px","currentColor",1.5);Se&&ce.appendChild(Se),setTimeout(()=>{ce.innerHTML="";let He=me("clipboard","12px","currentColor",1.5);He&&ce.appendChild(He)},1500)}),v.appendChild(M),v.appendChild(C),R&&v.appendChild(R),v.appendChild(L),Y&&v.appendChild(Y),v.appendChild(ue),v.appendChild(ce),m.appendChild(v),d&&m.appendChild(Cp(e,a,i)),m}}function Sc(e){var m,v,M,b,C;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(m=s==null?void 0:s.features)==null?void 0:m.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,d=(v=a==null?void 0:a.iconName)!=null?v:"arrow-down",c=(M=a==null?void 0:a.label)!=null?M:"",p=(C=(b=s==null?void 0:s.features)==null?void 0:b.eventStream)!=null?C:{},u=o.find(S=>S.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&s){let S=u.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>f().element,onClose:n});if(S)return{element:S,update:()=>{},destroy:()=>{}}}return f();function f(){let S=p.classNames,R=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");eo(R,S==null?void 0:S.panel);let w=[],L="",B="",T=null,Y=[],ue={},ce=0,$=es(),te=0,Te=0,ne=!1,Se=null,He=!1,he=0,Me=new Set,ke=new Map,re="",be="",$e=null,ge,de,oe,De,ot;function wt(){let Z=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),ye=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");eo(ye,S==null?void 0:S.headerBar);let Pe=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Pe.textContent="Events",ge=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"),ge.textContent="0";let dt=h("div","persona-flex-1");de=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 Ot=h("option","");Ot.value="",Ot.textContent="All events",de.appendChild(Ot),oe=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"),oe.type="button",oe.title="Copy All";let $t=me("clipboard-copy","12px","currentColor",1.5);$t&&oe.appendChild($t);let it=h("span","persona-text-xs");it.textContent="Copy All",oe.appendChild(it),ye.appendChild(Pe),ye.appendChild(ge),ye.appendChild(dt),ye.appendChild(de),ye.appendChild(oe);let qe=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");eo(qe,S==null?void 0:S.searchBar);let lt=me("search","14px","var(--persona-muted, #9ca3af)",1.5),_e=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");lt&&_e.appendChild(lt),De=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"),eo(De,S==null?void 0:S.searchInput),De.type="text",De.placeholder="Search event payloads...",ot=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"),ot.type="button",ot.style.display="none";let _t=me("x","12px","currentColor",2);return _t&&ot.appendChild(_t),qe.appendChild(_e),qe.appendChild(De),qe.appendChild(ot),Z.appendChild(ye),Z.appendChild(qe),Z}let j,q=o.find(Z=>Z.renderEventStreamToolbar);if(q!=null&&q.renderEventStreamToolbar&&s){let Z=q.renderEventStreamToolbar({config:s,defaultRenderer:()=>wt(),eventCount:r.getSize(),filteredCount:0,onFilterChange:ye=>{L=ye,Ut(),Ie()},onSearchChange:ye=>{B=ye,Ut(),Ie()}});j=Z!=null?Z:wt()}else j=wt();let se=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");se.style.display="none";let _=h("div","persona-flex-1 persona-min-h-0 persona-relative"),z=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");z.style.height="100%";let Q=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");eo(Q,S==null?void 0:S.scrollIndicator),Q.style.display="none",Q.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Fe=me(d,"14px","currentColor",2);Fe&&Q.appendChild(Fe);let J=h("span","");J.textContent=c,Q.appendChild(J);let K=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");K.style.display="none",_.appendChild(z),_.appendChild(K),_.appendChild(Q),R.setAttribute("tabindex","0"),R.appendChild(j),R.appendChild(se),R.appendChild(_);function xt(){let Z=r.getAll(),ye={};for(let it of Z)ye[it.type]=(ye[it.type]||0)+1;let Pe=Object.keys(ye).sort(),dt=Pe.length!==Y.length||!Pe.every((it,qe)=>it===Y[qe]),Ot=!dt&&Pe.some(it=>ye[it]!==ue[it]),nt=Z.length!==Object.values(ue).reduce((it,qe)=>it+qe,0);if(!dt&&!Ot&&!nt||(Y=Pe,ue=ye,!de))return;let $t=de.value;if(de.options[0].textContent="All events",dt){for(;de.options.length>1;)de.remove(1);for(let it of Pe){let qe=h("option","");qe.value=it,qe.textContent=`${it} (${ye[it]||0})`,de.appendChild(qe)}$t&&Pe.includes($t)?de.value=$t:$t&&(de.value="",L="")}else for(let it=1;it<de.options.length;it++){let qe=de.options[it];qe.textContent=`${qe.value} (${ye[qe.value]||0})`}}function tt(){let Z=r.getAll();if(L&&(Z=Z.filter(ye=>ye.type===L)),B){let ye=B.toLowerCase();Z=Z.filter(Pe=>Pe.type.toLowerCase().includes(ye)||Pe.payload.toLowerCase().includes(ye))}return Z}function Lt(){return L!==""||B!==""}function Ut(){ce=0,te=0,$.resume(),Q.style.display="none"}function Ne(Z){Me.has(Z)?Me.delete(Z):Me.add(Z),$e=Z;let ye=z.scrollTop,Pe=$.isFollowing();He=!0,$.pause(),Ie(),z.scrollTop=ye,Pe&&$.resume(),He=!1}function le(){return ko(z,50)}function Ie(){Te=Date.now(),ne=!1,xt();let Z=r.getEvictedCount();Z>0?(se.textContent=`${Z.toLocaleString()} older events truncated`,se.style.display=""):se.style.display="none",w=tt();let ye=w.length,Pe=r.getSize()>0;ge&&(ge.textContent=String(r.getSize())),ye===0&&Pe&&Lt()?(K.textContent=B?`No events matching '${B}'`:"No events matching filter",K.style.display="",z.style.display="none"):(K.style.display="none",z.style.display=""),oe&&(oe.title=Lt()?`Copy Filtered (${ye})`:"Copy All"),i&&!$.isFollowing()&&ye>ce&&(te+=ye-ce,J.textContent=c?`${c}${te>0?` (${te})`:""}`:"",Q.style.display=""),ce=ye;let dt=r.getAll(),Ot=dt.length>0?dt[0].timestamp:0,nt=new Set(w.map(qe=>qe.id));for(let qe of Me)nt.has(qe)||Me.delete(qe);let $t=L!==re||B!==be,it=ke.size===0&&w.length>0;if($t||it||w.length===0){z.innerHTML="",ke.clear();let qe=document.createDocumentFragment();for(let lt=0;lt<w.length;lt++){let _e=$s(w[lt],lt,Ot,p,Me,Ne,o,s);ke.set(w[lt].id,_e),qe.appendChild(_e)}z.appendChild(qe),re=L,be=B,$e=null}else{if($e!==null){let lt=ke.get($e);if(lt&&lt.parentNode===z){let _e=w.findIndex(_t=>_t.id===$e);if(_e>=0){let _t=$s(w[_e],_e,Ot,p,Me,Ne,o,s);z.insertBefore(_t,lt),lt.remove(),ke.set($e,_t)}}$e=null}let qe=new Set(w.map(lt=>lt.id));for(let[lt,_e]of ke)qe.has(lt)||(_e.remove(),ke.delete(lt));for(let lt=0;lt<w.length;lt++){let _e=w[lt];if(!ke.has(_e.id)){let _t=$s(_e,lt,Ot,p,Me,Ne,o,s);ke.set(_e.id,_t),z.appendChild(_t)}}}$.isFollowing()&&(z.scrollTop=z.scrollHeight)}function St(){if(Date.now()-Te>=mp){Se!==null&&(cancelAnimationFrame(Se),Se=null),Ie();return}ne||(ne=!0,Se=requestAnimationFrame(()=>{Se=null,Ie()}))}let At=(Z,ye)=>{if(!oe)return;oe.innerHTML="";let Pe=me(Z,"12px","currentColor",1.5);Pe&&oe.appendChild(Pe);let dt=h("span","persona-text-xs");dt.textContent="Copy All",oe.appendChild(dt),setTimeout(()=>{oe.innerHTML="";let Ot=me("clipboard-copy","12px","currentColor",1.5);Ot&&oe.appendChild(Ot);let nt=h("span","persona-text-xs");nt.textContent="Copy All",oe.appendChild(nt),oe.disabled=!1},ye)},Ze=async()=>{if(oe){oe.disabled=!0;try{let Z;Lt()?Z=w:t?(Z=await t(),Z.length===0&&(Z=r.getAll())):Z=r.getAll();let ye=Z.map(Pe=>{try{return JSON.parse(Pe.payload)}catch{return Pe.payload}});await navigator.clipboard.writeText(JSON.stringify(ye,null,2)),At("check",1500)}catch{At("x",1500)}}},Qe=()=>{de&&(L=de.value,Ut(),Ie())},Kt=()=>{!De||!ot||(ot.style.display=De.value?"":"none",T&&clearTimeout(T),T=setTimeout(()=>{B=De.value,Ut(),Ie()},150))},Gt=()=>{!De||!ot||(De.value="",B="",ot.style.display="none",T&&clearTimeout(T),Ut(),Ie())},Zt=()=>{if(He)return;let Z=z.scrollTop,{action:ye,nextLastScrollTop:Pe}=ts({following:$.isFollowing(),currentScrollTop:Z,lastScrollTop:he,nearBottom:le(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});he=Pe,ye==="resume"?($.resume(),te=0,Q.style.display="none"):ye==="pause"&&($.pause(),i&&(J.textContent=c,Q.style.display=""))},O=Z=>{let ye=ns({following:$.isFollowing(),deltaY:Z.deltaY,nearBottom:le(),resumeWhenNearBottom:!0});ye==="pause"?($.pause(),i&&(J.textContent=c,Q.style.display="")):ye==="resume"&&($.resume(),te=0,Q.style.display="none")},Le=()=>{i&&(z.scrollTop=z.scrollHeight,$.resume(),te=0,Q.style.display="none")},pe=Z=>{let ye=Z.target;if(!ye||ye.closest("button"))return;let Pe=ye.closest("[data-event-id]");if(!Pe)return;let dt=Pe.getAttribute("data-event-id");dt&&Ne(dt)},at=Z=>{if((Z.metaKey||Z.ctrlKey)&&Z.key==="f"){Z.preventDefault(),De==null||De.focus(),De==null||De.select();return}Z.key==="Escape"&&(De&&document.activeElement===De?(Gt(),De.blur(),R.focus()):n&&n())};oe&&oe.addEventListener("click",Ze),de&&de.addEventListener("change",Qe),De&&De.addEventListener("input",Kt),ot&&ot.addEventListener("click",Gt),z.addEventListener("scroll",Zt),z.addEventListener("wheel",O,{passive:!0}),z.addEventListener("click",pe),Q.addEventListener("click",Le),R.addEventListener("keydown",at);function Be(){T&&clearTimeout(T),Se!==null&&(cancelAnimationFrame(Se),Se=null),ne=!1,ke.clear(),oe&&oe.removeEventListener("click",Ze),de&&de.removeEventListener("change",Qe),De&&De.removeEventListener("input",Kt),ot&&ot.removeEventListener("click",Gt),z.removeEventListener("scroll",Zt),z.removeEventListener("wheel",O),z.removeEventListener("click",pe),Q.removeEventListener("click",Le),R.removeEventListener("keydown",at)}return{element:R,update:St,destroy:Be}}}function Ac(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=t;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(m)}else u.textContent=a;if(c.append(p,u),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 Ec=(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",p=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:r.config,defaultRenderer:()=>Ac(e,r)});if(p)return p}return Ac(e,r)};var _s=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)})}},wr=new _s;wr.register("PersonaArtifactCard",Ec);function wp(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 Tc(e,r){var oe,De,ot,wt;let t=(De=(oe=e.features)==null?void 0:oe.artifacts)==null?void 0:De.layout,s=((ot=t==null?void 0:t.toolbarPreset)!=null?ot:"default")==="document",o=(wt=t==null?void 0:t.panePadding)==null?void 0:wt.trim(),a=e.markdown?Vr(e.markdown):null,i=xo(e.sanitize),d=j=>{let q=a?a(j):bo(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,p=()=>{c==null||c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),$==null||$.hide()};c&&c.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let u=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");u.setAttribute("data-persona-theme-zone","artifact-pane"),s&&u.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 v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let M="rendered",b=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),C=s?kt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):kt({icon:"eye",label:"Rendered view"}),S=s?kt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):kt({icon:"code-2",label:"Source"}),R=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),w=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,L=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,B=t==null?void 0:t.documentToolbarCopyMenuItems,T=!!(L&&B&&B.length>0),Y=null,ue,ce=null,$=null;if(s&&(w||L)&&!T){if(ue=w?os({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let j=me("chevron-down",14,"currentColor",2);j&&ue.appendChild(j)}}else s&&T?(Y=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),ue=w?os({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),ce=kt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),Y.append(ue,ce)):s?ue=kt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):ue=kt({icon:"copy",label:"Copy"});let te=s?kt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):kt({icon:"refresh-cw",label:"Refresh"}),Te=s?kt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):kt({icon:"x",label:"Close"}),ne=()=>{var z,Q,Fe;let j=(z=re.find(J=>J.id===be))!=null?z:re[re.length-1],q=(Q=j==null?void 0:j.id)!=null?Q:null,se=(j==null?void 0:j.artifactType)==="markdown"&&(Fe=j.markdown)!=null?Fe:"",_=j?JSON.stringify({component:j.component,props:j.props},null,2):"";return{markdown:se,jsonPayload:_,id:q}},Se=async()=>{var z;let{markdown:j,jsonPayload:q}=ne(),se=(z=re.find(Q=>Q.id===be))!=null?z:re[re.length-1],_=(se==null?void 0:se.artifactType)==="markdown"?j:se?q:"";try{await navigator.clipboard.writeText(_)}catch{}};if(ue.addEventListener("click",async()=>{let j=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(j&&T){let{markdown:q,jsonPayload:se,id:_}=ne();try{await j({actionId:"primary",artifactId:_,markdown:q,jsonPayload:se})}catch{}return}await Se()}),ce&&(B!=null&&B.length)){let j=()=>{var se;return(se=u.closest("[data-persona-root]"))!=null?se:document.body},q=()=>{$=Hr({items:B.map(se=>({id:se.id,label:se.label})),onSelect:async se=>{let{markdown:_,jsonPayload:z,id:Q}=ne(),Fe=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Fe?await Fe({actionId:se,artifactId:Q,markdown:_,jsonPayload:z}):se==="markdown"||se==="md"?await navigator.clipboard.writeText(_):se==="json"||se==="source"?await navigator.clipboard.writeText(z):await navigator.clipboard.writeText(_||z)}catch{}},anchor:Y!=null?Y:ce,position:"bottom-right",portal:j()})};u.isConnected?q():requestAnimationFrame(q),ce.addEventListener("click",se=>{se.stopPropagation(),$==null||$.toggle()})}te.addEventListener("click",async()=>{var j;try{await((j=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:j.call(t))}catch{}ge()}),Te.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let He=()=>{s&&(C.setAttribute("aria-pressed",M==="rendered"?"true":"false"),S.setAttribute("aria-pressed",M==="source"?"true":"false"))};C.addEventListener("click",()=>{M="rendered",He(),ge()}),S.addEventListener("click",()=>{M="source",He(),ge()});let he=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(C,S),Y?R.append(Y,te,Te):R.append(ue,te,Te),f.append(b,he,R),He()):(f.appendChild(m),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let Me=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"),ke=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(Me.style.paddingLeft=o,Me.style.paddingRight=o,ke.style.padding=o),u.appendChild(f),u.appendChild(Me),u.appendChild(ke);let re=[],be=null,$e=!1,ge=()=>{var _,z,Q,Fe;let j=s&&re.length<=1;Me.classList.toggle("persona-hidden",j),Me.replaceChildren();for(let J of re){let K=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");K.type="button",K.textContent=J.title||J.id.slice(0,8),J.id===be&&K.classList.add("persona-bg-persona-container","persona-border-persona-border"),K.addEventListener("click",()=>r.onSelect(J.id)),Me.appendChild(K)}ke.replaceChildren();let q=be&&re.find(J=>J.id===be)||re[re.length-1];if(!q)return;if(s){let J=q.artifactType==="markdown"?"MD":(_=q.component)!=null?_:"Component",xt=(q.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";he.textContent=`${xt} \xB7 ${J}`}else m.textContent="Artifacts";if(q.artifactType==="markdown"){if(s&&M==="source"){let K=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");K.textContent=(z=q.markdown)!=null?z:"",ke.appendChild(K);return}let J=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");J.innerHTML=d((Q=q.markdown)!=null?Q:""),ke.appendChild(J);return}let se=q.component?wr.get(q.component):void 0;if(se){let K={message:{id:q.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let xt=se((Fe=q.props)!=null?Fe:{},K);if(xt){ke.appendChild(xt);return}}catch{}}ke.appendChild(wp(q))},de=()=>{var q;let j=re.length>0;if(u.classList.toggle("persona-hidden",!j),c){let se=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,z=((q=se==null?void 0:se.classList.contains("persona-artifact-narrow-host"))!=null?q:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;j&&z&&$e?(c.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:c,update(j){var q,se,_;re=j.artifacts,be=(_=(se=j.selectedId)!=null?se:(q=j.artifacts[j.artifacts.length-1])==null?void 0:q.id)!=null?_:null,re.length>0&&($e=!0),ge(),de()},setMobileOpen(j){$e=j,!j&&c?(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):de()}}}function Hn(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 Mc(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"),!Hn(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 Sp(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 as(e,r){var d,c,p,u,f,m,v,M,b,C;if(!Hn(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"),Sp(e),Mc(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",(p=t==null?void 0:t.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=t==null?void 0:t.paneWidth)!=null?u:"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=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(M=t==null?void 0:t.documentToolbarIconColor)==null?void 0:M.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(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=(C=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:C.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Mc(e,r)}var kc=["panel","seamless"];function is(e,r){var i,d,c,p,u,f;for(let m of kc)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"),!Hn(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=kc.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=t==null?void 0:t.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(u=t==null?void 0:t.paneShadow)==null?void 0:u.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 Lc(e,r){var t,n,s;return!r||!Hn(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Ap(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 Ep(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 Tp(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function Mp(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function Ic(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 Pc(e,r,t,n,s,o){let a=Ap(s,200),i=Mp(r,t,n,200);i=Math.max(a,i);let d=Ep(o);return d!==null&&(i=Math.min(i,d)),Tp(e,a,i)}var Wc={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"}},js=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,M,b;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(M=Wc[a])!=null?M:Wc.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 C=h("p","persona-text-sm persona-text-persona-muted");C.textContent=i.description,d.appendChild(C)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(C=>{var B,T;let S=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");S.htmlFor=`${r.id}-${a}-${C.name}`;let R=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");R.textContent=C.label,S.appendChild(R);let w=(B=C.type)!=null?B:"text",L;w==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=w),L.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",L.id=`${r.id}-${a}-${C.name}`,L.name=C.name,L.placeholder=(T=C.placeholder)!=null?T:"",C.required&&(L.required=!0),S.appendChild(L),p.appendChild(S)});let u=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",u.appendChild(f),u.appendChild(m),p.appendChild(u),o.replaceChildren(d,p),p.addEventListener("submit",async C=>{var L,B;C.preventDefault();let S=(L=t.formEndpoint)!=null?L:"/form",R=new FormData(p),w={};R.forEach((T,Y)=>{w[Y]=T}),w.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let T=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!T.ok)throw new Error(`Form submission failed (${T.status})`);let Y=await T.json();f.textContent=(B=Y.message)!=null?B:"Thanks! We'll be in touch soon.",Y.success&&Y.nextPrompt&&await n.sendMessage(String(Y.nextPrompt))}catch(T){f.textContent=T instanceof Error?T.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var zs=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()}},ls=new zs;var Rc=()=>{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 kp=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},Lp=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},cs=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=kp(e),t=Lp(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}},Us=e=>typeof e=="string"?e:e==null?"":String(e),to={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Us(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=Us(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:Us(t.text)}}},Hc=e=>Array.isArray(e)?e.map(r=>String(r)):[],ds=e=>{let r=new Set(Hc(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(Hc(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let o=Array.from(r);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||r.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((c,p)=>c||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let d={action:i,message:o.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",d)},u=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:t}};var Ip=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}},Pp=e=>e.map(r=>({...r,streaming:!1})),Vs=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?Ip(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?Pp(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 Wp,STR as Rp,OBJ as Hp}from"partial-json";function Bp(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function Dp(e,r){if(!Bp(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 qs(){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=Wp(t,Rp|Hp),o=Dp(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Fp(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Js(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=wr.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 Np(){let e=qs();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ys(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 Gs(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 Op=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Xs(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=Op}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=n,m.appendChild(v);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=s,m.appendChild(M),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 C=[];for(let B=1;B<=5;B++){let T=document.createElement("button");T.type="button",T.className="persona-feedback-rating-btn persona-feedback-star-btn",T.setAttribute("role","radio"),T.setAttribute("aria-checked","false"),T.setAttribute("aria-label",`${B} star${B>1?"s":""}: ${c[B-1]}`),T.title=c[B-1],T.dataset.rating=String(B),T.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
- `,T.addEventListener("click",()=>{u=R,x.forEach((Y,ue)=>{let se=ue<R;Y.classList.toggle("selected",se),Y.setAttribute("aria-checked",ue===R-1?"true":"false")})}),x.push(T),b.appendChild(T)}h.appendChild(b);let S=null;if(d){let R=document.createElement("div");R.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=o,S.rows=3,S.setAttribute("aria-label","Additional comments"),R.appendChild(S),h.appendChild(R)}let F=document.createElement("div");F.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=i,w.addEventListener("click",()=>{t==null||t(),p.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(u===null){b.classList.add("persona-feedback-shake"),setTimeout(()=>b.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let R=(S==null?void 0:S.value.trim())||void 0;await r(u,R),p.remove()}catch(R){L.disabled=!1,L.textContent=a,console.error("[CSAT Feedback] Failed to submit:",R)}}),F.appendChild(w),F.appendChild(L),h.appendChild(F),p.appendChild(h),p}function Us(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:p="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let h=null,m=document.createElement("div");m.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let M=document.createElement("h3");M.className="persona-feedback-title",M.textContent=n,C.appendChild(M);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 S=document.createElement("div");S.className="persona-feedback-labels";let F=document.createElement("span");F.className="persona-feedback-label-low",F.textContent=c;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=p,S.appendChild(F),S.appendChild(w);let L=document.createElement("div");L.className="persona-feedback-numbers";let R=[];for(let $=0;$<=10;$++){let te=document.createElement("button");te.type="button",te.className="persona-feedback-rating-btn persona-feedback-number-btn",te.setAttribute("role","radio"),te.setAttribute("aria-checked","false"),te.setAttribute("aria-label",`Rating ${$} out of 10`),te.textContent=String($),te.dataset.rating=String($),$<=6?te.classList.add("persona-feedback-detractor"):$<=8?te.classList.add("persona-feedback-passive"):te.classList.add("persona-feedback-promoter"),te.addEventListener("click",()=>{h=$,R.forEach((Ae,ne)=>{Ae.classList.toggle("selected",ne===$),Ae.setAttribute("aria-checked",ne===$?"true":"false")})}),R.push(te),L.appendChild(te)}x.appendChild(S),x.appendChild(L),m.appendChild(x);let T=null;if(d){let $=document.createElement("div");$.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=o,T.rows=3,T.setAttribute("aria-label","Additional comments"),$.appendChild(T),m.appendChild($)}let Y=document.createElement("div");Y.className="persona-feedback-actions";let ue=document.createElement("button");ue.type="button",ue.className="persona-feedback-btn persona-feedback-btn-skip",ue.textContent=i,ue.addEventListener("click",()=>{t==null||t(),u.remove()});let se=document.createElement("button");return se.type="button",se.className="persona-feedback-btn persona-feedback-btn-submit",se.textContent=a,se.addEventListener("click",async()=>{if(h===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}se.disabled=!0,se.textContent="Submitting...";try{let $=(T==null?void 0:T.value.trim())||void 0;await r(h,$),u.remove()}catch($){se.disabled=!1,se.textContent=a,console.error("[NPS Feedback] Failed to submit:",$)}}),Y.appendChild(ue),Y.appendChild(se),m.appendChild(Y),u.appendChild(m),u}var Qr="persona-chat-history",Np=30*1e3,Op={"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 $p(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=Op[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 _p(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 jp(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Js=e=>!e||typeof e!="object"?{}:{...e},Rc=e=>e.map(r=>({...r,streaming:!1})),Hc=(e,r,t)=>{let n=e!=null&&e.markdown?jr(e.markdown):null,s=fo(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var c,p,u;let a=(c=o.text)!=null?c:"",i=(p=o.message.rawContent)!=null?p:null;if(r){let h=r.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});h!==null&&(a=h.text,h.persist||(o.message.__skipPersist=!0),h.resubmit&&!o.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(u=i!=null?i:o.text)!=null?u:""}):n?d=n(a):d=mo(a),s?s(d):d}},Ys=(e,r,t)=>{var sa,aa,ia,la,ca,da,pa,ua,ga,ma,fa,ha,ya,ba,xa,va,Ca,wa,Sa,Aa,Ea,Ta,Ma,ka,La,Ia,Pa,Wa,Ra,Ha,Ba,Da,Fa,Na,Oa,$a,_a,ja,za,Va;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=Ns(r),s=os.getForInstance(n.plugins);n.components&&vr.registerAll(n.components);let o=Pc(),a=(sa=n.storageAdapter)!=null?sa:$s(),i={},d=null,c=!1,p=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 p(y)});else{let g=l!=null?l:{messages:[],metadata:{}},y=p(g);y.metadata&&(i=Js(y.metadata)),(aa=y.messages)!=null&&aa.length&&(n={...n,initialMessages:y.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(n.onStateLoaded)try{let l=p({messages:[],metadata:{}});(ia=l.messages)!=null&&ia.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let u=()=>i,h=l=>{var y;i=(y=l({...i}))!=null?y:{},ro()},m=n.actionParsers&&n.actionParsers.length?n.actionParsers:[ss],C=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Zr.message,Zr.messageAndClick],M=as({parsers:m,handlers:C,getSessionMetadata:u,updateSessionMetadata:h,emit:o.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let b=(ca=(la=n.launcher)==null?void 0:la.enabled)!=null?ca:!0,x=(pa=(da=n.launcher)==null?void 0:da.autoExpand)!=null?pa:!1,S=(ua=n.autoFocusInput)!=null?ua:!1,F=x,w=b,L=(ma=(ga=n.layout)==null?void 0:ga.header)==null?void 0:ma.layout,R=!1,T=b?x:!0,Y=!1,ue=null,se=()=>{Y=!0,ue&&clearTimeout(ue),ue=setTimeout(()=>{Y&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Y=!1)},1e4)},$=Hc(n,M,se),te=(ha=(fa=n.features)==null?void 0:fa.showReasoning)!=null?ha:!0,Ae=(ba=(ya=n.features)==null?void 0:ya.showToolCalls)!=null?ba:!0,ne=(va=(xa=n.features)==null?void 0:xa.showEventStreamToggle)!=null?va:!1,Ce=(wa=(Ca=n.features)==null?void 0:Ca.scrollToBottom)!=null?wa:{},de=`${(Aa=typeof n.persistState=="object"?(Sa=n.persistState)==null?void 0:Sa.keyPrefix:void 0)!=null?Aa:"persona-"}event-stream`,fe=ne?new Po(de):null,Se=(Ma=(Ta=(Ea=n.features)==null?void 0:Ea.eventStream)==null?void 0:Ta.maxEvents)!=null?Ma:2e3,J=ne?new Io(Se,fe):null,ae=null,ge=!1,De=null,Le=0;fe==null||fe.open().then(()=>J==null?void 0:J.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Ie={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)}},Re=(ka=n.statusIndicator)!=null?ka:{},ot=l=>{var g,y,E,k;return l==="idle"?(g=Re.idleText)!=null?g:sn.idle:l==="connecting"?(y=Re.connectingText)!=null?y:sn.connecting:l==="connected"?(E=Re.connectedText)!=null?E:sn.connected:l==="error"?(k=Re.errorText)!=null?k:sn.error:sn[l]};function At(l,g,y,E){if(E==="idle"&&y.idleLink){l.textContent="";let k=document.createElement("a");k.href=y.idleLink,k.target="_blank",k.rel="noopener noreferrer",k.textContent=g,k.style.color="inherit",k.style.textDecoration="none",l.appendChild(k)}else l.textContent=g}let{wrapper:j,panel:U}=uc(n),re=gc(n,b),{container:_,body:z,messagesWrapper:Q,suggestions:lt,textarea:K,sendButton:X,sendButtonWrapper:wt,composerForm:st,statusText:Pt,introTitle:Jt,introSubtitle:Be,closeButton:ie,iconHolder:ke,headerTitle:Et,headerSubtitle:Tt,header:Qe,footer:et,actionsRow:en,leftActions:Zt,rightActions:tn}=re,O=re.micButton,Ee=re.micButtonWrapper,le=re.attachmentButton,dt=re.attachmentButtonWrapper,He=re.attachmentInput,G=re.attachmentPreviewsContainer;_.classList.add("persona-relative"),z.classList.add("persona-relative");let he=12,Pe=()=>{var l;return(l=Ce.label)!=null?l:""},mt=()=>{var l;return(l=Ce.iconName)!=null?l:"arrow-down"},Nt=()=>Ce.enabled!==!1,at=f("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");at.type="button",at.style.display="none",at.setAttribute("data-persona-scroll-to-bottom","true");let Ot=f("span","persona-flex persona-items-center"),pt=f("span","");at.append(Ot,pt),_.appendChild(at);let Je=()=>{let g=et.style.display==="none"?0:et.offsetHeight;at.style.bottom=`${g+he}px`};Je();let ut=()=>{let l=!!Pe();at.setAttribute("aria-label",Pe()||"Jump to latest"),at.title=Pe(),at.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),Ot.innerHTML="";let g=pe(mt(),"14px","currentColor",2);g?(Ot.appendChild(g),Ot.style.display=""):Ot.style.display="none",pt.textContent=Pe(),pt.style.display=l?"":"none"};ut();let Ne=null,$t=null,_n=s.find(l=>l.renderHeader);if(_n!=null&&_n.renderHeader){let l=_n.renderHeader({config:n,defaultRenderer:()=>{let g=xr({config:n,showClose:b});return Jr(_,g,n),g.header},onClose:()=>Mt(!1,"user")});if(l){let g=_.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),Qe=l)}}let Yn=()=>{var g,y,E,k;if(!J)return;if(ge=!0,!ae&&J&&(ae=vc({buffer:J,getFullHistory:()=>J.getAllFromStore(),onClose:()=>Rn(),config:n,plugins:s})),ae&&(z.style.display="none",(g=et.parentNode)==null||g.insertBefore(ae.element,et),ae.update()),Xe){Xe.style.boxShadow=`inset 0 0 0 1.5px ${bn.actionIconColor}`;let I=(k=(E=(y=n.features)==null?void 0:y.eventStream)==null?void 0:E.classNames)==null?void 0:k.toggleButtonActive;I&&I.split(/\s+/).forEach(P=>P&&Xe.classList.add(P))}let l=()=>{if(!ge)return;let I=Date.now();I-Le>=200&&(ae==null||ae.update(),Le=I),De=requestAnimationFrame(l)};Le=0,De=requestAnimationFrame(l),Zn(),o.emit("eventStream:opened",{timestamp:Date.now()})},Rn=()=>{var l,g,y;if(ge){if(ge=!1,ae&&ae.element.remove(),z.style.display="",Xe){Xe.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(k=>k&&Xe.classList.remove(k))}De!==null&&(cancelAnimationFrame(De),De=null),Zn(),o.emit("eventStream:closed",{timestamp:Date.now()})}},Xe=null;if(ne){let l=(Ia=(La=n.features)==null?void 0:La.eventStream)==null?void 0:Ia.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");Xe=f("button",g),Xe.style.width="28px",Xe.style.height="28px",Xe.style.color=bn.actionIconColor,Xe.type="button",Xe.setAttribute("aria-label","Event Stream"),Xe.title="Event Stream";let y=pe("activity","18px","currentColor",1.5);y&&Xe.appendChild(y);let E=re.clearChatButtonWrapper,k=re.closeButtonWrapper,I=E||k;I&&I.parentNode===Qe?Qe.insertBefore(Xe,I):Qe.appendChild(Xe),Xe.addEventListener("click",()=>{ge?Rn():Yn()})}let wr=l=>{var E,k,I;let g=n.attachments;if(!(g!=null&&g.enabled))return;let y=l.querySelector(".persona-attachment-previews");if(!y){y=f("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=f("input");P.type="file",P.accept=((E=g.allowedTypes)!=null?E:nr).join(","),P.multiple=((k=g.maxFiles)!=null?k:4)>1,P.style.display="none",P.setAttribute("aria-label",(I=g.buttonTooltipText)!=null?I:"Attach files"),l.appendChild(P)}},jn=s.find(l=>l.renderComposer);if(jn!=null&&jn.renderComposer){let l=n.composer,g=jn.renderComposer({config:n,defaultRenderer:()=>ko({config:n}).footer,onSubmit:y=>{H&&!H.isStreaming()&&H.sendMessage(y)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{He==null||He.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y}},onVoiceToggle:((Pa=n.voiceRecognition)==null?void 0:Pa.enabled)===!0?()=>{$t==null||$t()}:void 0});g&&(et.replaceWith(g),et=g)}let Sr=l=>{let g=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),E=l.querySelector("[data-persona-composer-submit]"),k=l.querySelector("[data-persona-composer-mic]"),I=l.querySelector("[data-persona-composer-status]");g&&(st=g),y&&(K=y),E&&(X=E),k&&(O=k,Ee=k.parentElement),I&&(Pt=I);let P=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");P&&(lt=P);let q=l.querySelector(".persona-attachment-button");q&&(le=q,dt=q.parentElement),He=l.querySelector('input[type="file"]'),G=l.querySelector(".persona-attachment-previews");let B=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");B&&(en=B)};wr(et),Sr(et);let zn=(Wa=n.layout)==null?void 0:Wa.contentMaxWidth;zn&&st&&(st.style.maxWidth=zn,st.style.marginLeft="auto",st.style.marginRight="auto"),zn&&G&&(G.style.maxWidth=zn,G.style.marginLeft="auto",G.style.marginRight="auto"),(Ra=n.attachments)!=null&&Ra.enabled&&He&&G&&(Ne=Ur.fromConfig(n.attachments),Ne.setPreviewsContainer(G),He.addEventListener("change",l=>{let g=l.target;Ne==null||Ne.handleFileSelect(g.files),g.value=""})),(()=>{var E,k;let l=(k=(E=n.layout)==null?void 0:E.slots)!=null?k:{},g=I=>{switch(I){case"body-top":return _.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Q;case"footer-top":return lt;case"composer":return st;case"footer-bottom":return Pt;default:return null}},y=(I,P)=>{var q;switch(I){case"header-left":case"header-center":case"header-right":if(I==="header-left")Qe.insertBefore(P,Qe.firstChild);else if(I==="header-right")Qe.appendChild(P);else{let B=Qe.querySelector(".persona-flex-col");B?(q=B.parentNode)==null||q.insertBefore(P,B.nextSibling):Qe.appendChild(P)}break;case"body-top":{let B=z.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(P):z.insertBefore(P,z.firstChild);break}case"body-bottom":z.appendChild(P);break;case"footer-top":lt.replaceWith(P);break;case"footer-bottom":Pt.replaceWith(P);break;default:break}};for(let[I,P]of Object.entries(l))if(P)try{let q=P({config:n,defaultContent:()=>g(I)});q&&y(I,q)}catch(q){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${I}":`,q)}})();let or=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let E=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!E)return;let k=E.getAttribute("data-message-id");if(!k)return;let I=y.getAttribute("data-bubble-type");I==="reasoning"?(Kr.has(k)?Kr.delete(k):Kr.add(k),yc(k,E)):I==="tool"&&(Xr.has(k)?Xr.delete(k):Xr.add(k),bc(k,E,n)),kn.delete(k)};Q.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),or(l))}),Q.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),or(l))});let Kn=new Map;Q.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 k=E.getAttribute("data-actions-for");if(!k)return;let I=y.getAttribute("data-action");if(I==="copy"){let B=H.getMessages().find(oe=>oe.id===k);if(B&&Ie.onCopy){let oe=B.content||"";navigator.clipboard.writeText(oe).then(()=>{y.classList.add("persona-message-action-success");let be=pe("check",14,"currentColor",2);be&&(y.innerHTML="",y.appendChild(be)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ve=pe("copy",14,"currentColor",2);ve&&(y.innerHTML="",y.appendChild(ve))},2e3)}).catch(be=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",be)}),Ie.onCopy(B)}}else if(I==="upvote"||I==="downvote")if(((P=Kn.get(k))!=null?P:null)===I)Kn.delete(k),y.classList.remove("persona-message-action-active");else{let oe=I==="upvote"?"downvote":"upvote",be=E.querySelector(`[data-action="${oe}"]`);be&&be.classList.remove("persona-message-action-active"),Kn.set(k,I),y.classList.add("persona-message-action-active");let ye=H.getMessages().find(je=>je.id===k);ye&&Ie.onFeedback&&Ie.onFeedback({type:I,messageId:ye.id,message:ye})}}),Q.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.closest(".persona-approval-bubble");if(!E)return;let k=E.getAttribute("data-message-id");if(!k)return;let I=y.getAttribute("data-approval-action");if(!I)return;let P=I==="approve"?"approved":"denied",B=H.getMessages().find(be=>be.id===k);if(!(B!=null&&B.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(B.approval,P)});let tt=null,xn=null,Hn={artifacts:[],selectedId:null},an=!1,sr={current:null};Q.addEventListener("click",l=>{var ve,ye,je,W,Fe;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.getAttribute("data-download-artifact");if(!E||((je=(ye=(ve=n.features)==null?void 0:ve.artifacts)==null?void 0:ye.onArtifactAction)==null?void 0:je.call(ye,{type:"download",artifactId:E}))===!0)return;let I=H.getArtifactById(E),P=I==null?void 0:I.markdown,q=(I==null?void 0:I.title)||"artifact";if(!P){let we=y.closest("[data-open-artifact]"),me=we==null?void 0:we.closest("[data-message-id]"),We=me==null?void 0:me.getAttribute("data-message-id");if(We){let Ke=H.getMessages().find(xe=>xe.id===We);if(Ke!=null&&Ke.rawContent)try{let xe=JSON.parse(Ke.rawContent);P=(W=xe==null?void 0:xe.props)==null?void 0:W.markdown,q=((Fe=xe==null?void 0:xe.props)==null?void 0:Fe.title)||q}catch{}}}if(!P)return;let B=new Blob([P],{type:"text/markdown"}),oe=URL.createObjectURL(B),be=document.createElement("a");be.href=oe,be.download=`${q}.md`,be.click(),URL.revokeObjectURL(oe)}),Q.addEventListener("click",l=>{var I,P,q;let y=l.target.closest("[data-open-artifact]");if(!y)return;let E=y.getAttribute("data-open-artifact");!E||((q=(P=(I=n.features)==null?void 0:I.artifacts)==null?void 0:P.onArtifactAction)==null?void 0:q.call(P,{type:"open",artifactId:E}))===!0||(l.preventDefault(),l.stopPropagation(),an=!1,H.selectArtifact(E),Cn())}),Q.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;g.hasAttribute("data-open-artifact")&&(l.preventDefault(),g.click())});let vn=null,bt=null,ln=null,Mn=null,ar=()=>{};function Xn(){Mn==null||Mn(),Mn=null}let ir=()=>{var P;if(!vn||!bt)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){bt.style.removeProperty("position"),bt.style.removeProperty("left"),bt.style.removeProperty("top"),bt.style.removeProperty("bottom"),bt.style.removeProperty("width"),bt.style.removeProperty("z-index");return}let E=vn.firstElementChild;if(!E||E===bt)return;let k=10;bt.style.position="absolute",bt.style.top="0",bt.style.bottom="0",bt.style.width=`${k}px`,bt.style.zIndex="5";let I=E.offsetWidth-k/2;bt.style.left=`${Math.max(0,I)}px`},Vn=()=>{},Cn=()=>{var y,E,k,I,P;if(!tt||!Wn(n))return;ns(e,n),rs(e,n),Vn();let l=(I=(k=(E=(y=n.features)==null?void 0:y.artifacts)==null?void 0:E.layout)==null?void 0:k.narrowHostMaxWidth)!=null?I:520,g=U.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l),tt.update(Hn),an?(tt.setMobileOpen(!1),tt.element.classList.add("persona-hidden"),(P=tt.backdrop)==null||P.classList.add("persona-hidden")):Hn.artifacts.length>0&&(tt.element.classList.remove("persona-hidden"),tt.setMobileOpen(!0)),ar()};if(Wn(n)){U.style.position="relative";let l=f("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=f("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(_),tt=Sc(n,{onSelect:y=>{var E;return(E=sr.current)==null?void 0:E.selectArtifact(y)},onDismiss:()=>{an=!0,Cn()}}),tt.element.classList.add("persona-hidden"),vn=g,g.appendChild(l),g.appendChild(tt.element),tt.backdrop&&U.appendChild(tt.backdrop),U.appendChild(g),ar=()=>{var E,k,I,P;if(!vn||!tt)return;if(!(((I=(k=(E=n.features)==null?void 0:E.artifacts)==null?void 0:k.layout)==null?void 0:I.resizable)===!0)){ln==null||ln(),ln=null,Xn(),bt&&(bt.remove(),bt=null),tt.element.style.removeProperty("width"),tt.element.style.removeProperty("maxWidth");return}if(!bt){let q=f("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");q.setAttribute("role","separator"),q.setAttribute("aria-orientation","vertical"),q.setAttribute("aria-label","Resize artifacts panel"),q.tabIndex=0;let B=e.ownerDocument,oe=(P=B.defaultView)!=null?P:window,be=ve=>{var me,We;if(!tt||ve.button!==0||e.classList.contains("persona-artifact-narrow-host")||oe.innerWidth<=640)return;ve.preventDefault(),Xn();let ye=ve.clientX,je=tt.element.getBoundingClientRect().width,W=(We=(me=n.features)==null?void 0:me.artifacts)==null?void 0:We.layout,Fe=gt=>{let Ke=vn.getBoundingClientRect().width,xe=e.classList.contains("persona-artifact-appearance-seamless"),Qt=xe?0:Mc(vn,oe),ht=xe?0:q.getBoundingClientRect().width||6,dn=je-(gt.clientX-ye),nn=kc(dn,Ke,Qt,ht,W==null?void 0:W.resizableMinWidth,W==null?void 0:W.resizableMaxWidth);tt.element.style.width=`${nn}px`,tt.element.style.maxWidth="none",ir()},we=()=>{B.removeEventListener("pointermove",Fe),B.removeEventListener("pointerup",we),B.removeEventListener("pointercancel",we),Mn=null;try{q.releasePointerCapture(ve.pointerId)}catch{}};Mn=we,B.addEventListener("pointermove",Fe),B.addEventListener("pointerup",we),B.addEventListener("pointercancel",we);try{q.setPointerCapture(ve.pointerId)}catch{}};q.addEventListener("pointerdown",be),bt=q,vn.insertBefore(q,tt.element),ln=()=>{q.removeEventListener("pointerdown",be)}}if(bt){let q=Hn.artifacts.length>0&&!an;bt.classList.toggle("persona-hidden",!q),ir()}},Vn=()=>{var oe,be,ve,ye,je,W,Fe,we,me,We,gt,Ke,xe,Qt;if(!b||!tt||((be=(oe=n.launcher)==null?void 0:oe.sidebarMode)!=null?be:!1)||Gt(n)&&On(n).reveal==="emerge")return;let E=(ve=e.ownerDocument.defaultView)!=null?ve:window,k=(je=(ye=n.launcher)==null?void 0:ye.mobileFullscreen)!=null?je:!0,I=(Fe=(W=n.launcher)==null?void 0:W.mobileBreakpoint)!=null?Fe:640;if(k&&E.innerWidth<=I||!Tc(n,b))return;let P=(We=(me=(we=n.launcher)==null?void 0:we.width)!=null?me:n.launcherWidth)!=null?We:"min(400px, calc(100vw - 24px))",q=(Qt=(xe=(Ke=(gt=n.features)==null?void 0:gt.artifacts)==null?void 0:Ke.layout)==null?void 0:xe.expandedPanelWidth)!=null?Qt:"min(720px, calc(100vw - 24px))";Hn.artifacts.length>0&&!an?(U.style.width=q,U.style.maxWidth=q):(U.style.width=P,U.style.maxWidth=P)},typeof ResizeObserver!="undefined"&&(xn=new ResizeObserver(()=>{Cn()}),xn.observe(U))}else U.appendChild(_);e.appendChild(j);let qn=()=>{var ht,dn,nn,rn,Dt,pn,Ve,yt,Pn,ur,er,gr,tr,Or,$r,Vt,Fo,co,po,_r,No,mr,Tr;let l=Gt(n),g=(dn=(ht=n.launcher)==null?void 0:ht.sidebarMode)!=null?dn:!1,y=l||g||((rn=(nn=n.launcher)==null?void 0:nn.fullHeight)!=null?rn:!1),E=((Dt=n.launcher)==null?void 0:Dt.enabled)===!1,k=(Ve=(pn=n.theme)==null?void 0:pn.components)==null?void 0:Ve.panel,I=Ko(n),P=(Kt,fn)=>{var fr;return Kt==null||Kt===""?fn:(fr=vo(I,Kt))!=null?fr:Kt},q=(yt=e.ownerDocument.defaultView)!=null?yt:window,B=(ur=(Pn=n.launcher)==null?void 0:Pn.mobileFullscreen)!=null?ur:!0,oe=(gr=(er=n.launcher)==null?void 0:er.mobileBreakpoint)!=null?gr:640,be=q.innerWidth<=oe,ve=B&&be&&b,ye=(Or=(tr=n.launcher)==null?void 0:tr.position)!=null?Or:"bottom-left",je=ye==="bottom-left"||ye==="top-left",W=(Vt=($r=n.launcher)==null?void 0:$r.zIndex)!=null?Vt:yn,Fe=g||ve?"none":"1px solid var(--persona-border)",we=ve?"none":g?je?"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&&(we="none",Fe="none");let me=g||ve?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",We=P(k==null?void 0:k.border,Fe),gt=P(k==null?void 0:k.shadow,we),Ke=P(k==null?void 0:k.borderRadius,me);if(e.style.cssText="",j.style.cssText="",U.style.cssText="",_.style.cssText="",z.style.cssText="",et.style.cssText="",ve){j.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),j.style.cssText=`
20
+ `,T.addEventListener("click",()=>{u=B,C.forEach((Y,ue)=>{let ce=ue<B;Y.classList.toggle("selected",ce),Y.setAttribute("aria-checked",ue===B-1?"true":"false")})}),C.push(T),b.appendChild(T)}f.appendChild(b);let S=null;if(d){let B=document.createElement("div");B.className="persona-feedback-comment-container",S=document.createElement("textarea"),S.className="persona-feedback-comment",S.placeholder=o,S.rows=3,S.setAttribute("aria-label","Additional comments"),B.appendChild(S),f.appendChild(B)}let R=document.createElement("div");R.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=i,w.addEventListener("click",()=>{t==null||t(),p.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(u===null){b.classList.add("persona-feedback-shake"),setTimeout(()=>b.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let B=(S==null?void 0:S.value.trim())||void 0;await r(u,B),p.remove()}catch(B){L.disabled=!1,L.textContent=a,console.error("[CSAT Feedback] Failed to submit:",B)}}),R.appendChild(w),R.appendChild(L),f.appendChild(R),p.appendChild(f),p}function Ks(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:p="Very likely"}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-nps",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let M=document.createElement("h3");M.className="persona-feedback-title",M.textContent=n,v.appendChild(M);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=s,v.appendChild(b),m.appendChild(v);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-nps",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="persona-feedback-labels";let R=document.createElement("span");R.className="persona-feedback-label-low",R.textContent=c;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=p,S.appendChild(R),S.appendChild(w);let L=document.createElement("div");L.className="persona-feedback-numbers";let B=[];for(let $=0;$<=10;$++){let te=document.createElement("button");te.type="button",te.className="persona-feedback-rating-btn persona-feedback-number-btn",te.setAttribute("role","radio"),te.setAttribute("aria-checked","false"),te.setAttribute("aria-label",`Rating ${$} out of 10`),te.textContent=String($),te.dataset.rating=String($),$<=6?te.classList.add("persona-feedback-detractor"):$<=8?te.classList.add("persona-feedback-passive"):te.classList.add("persona-feedback-promoter"),te.addEventListener("click",()=>{f=$,B.forEach((Te,ne)=>{Te.classList.toggle("selected",ne===$),Te.setAttribute("aria-checked",ne===$?"true":"false")})}),B.push(te),L.appendChild(te)}C.appendChild(S),C.appendChild(L),m.appendChild(C);let T=null;if(d){let $=document.createElement("div");$.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=o,T.rows=3,T.setAttribute("aria-label","Additional comments"),$.appendChild(T),m.appendChild($)}let Y=document.createElement("div");Y.className="persona-feedback-actions";let ue=document.createElement("button");ue.type="button",ue.className="persona-feedback-btn persona-feedback-btn-skip",ue.textContent=i,ue.addEventListener("click",()=>{t==null||t(),u.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){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}ce.disabled=!0,ce.textContent="Submitting...";try{let $=(T==null?void 0:T.value.trim())||void 0;await r(f,$),u.remove()}catch($){ce.disabled=!1,ce.textContent=a,console.error("[NPS Feedback] Failed to submit:",$)}}),Y.appendChild(ue),Y.appendChild(ce),m.appendChild(Y),u.appendChild(m),u}var no="persona-chat-history",$p=30*1e3,_p={"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 jp(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=_p[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 zp(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 Up(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Zs=e=>!e||typeof e!="object"?{}:{...e},Bc=e=>e.map(r=>({...r,streaming:!1})),Dc=(e,r,t)=>{let n=e!=null&&e.markdown?Vr(e.markdown):null,s=xo(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var c,p,u;let a=(c=o.text)!=null?c:"",i=(p=o.message.rawContent)!=null?p:null;if(r){let f=r.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&t&&t())}let d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(u=i!=null?i:o.text)!=null?u:""}):n?d=n(a):d=bo(a),s?s(d):d}},Qs=(e,r,t)=>{var bt,Dt,Pn,da,pa,ua,ga,ma,fa,ha,ya,ba,xa,va,Ca,wa,Sa,Aa,Ea,Ta,Ma,ka,La,Ia,Pa,Wa,Ra,Ha,Ba,Da,Fa,Na,Oa,$a,_a,ja,za,Ua,Va,qa;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=Ls(r),s=ls.getForInstance(n.plugins);n.components&&wr.registerAll(n.components);let o=Rc(),a=(bt=n.storageAdapter)!=null?bt:Vs(),i={},d=null,c=!1,p=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 p(y)});else{let g=l!=null?l:{messages:[],metadata:{}},y=p(g);y.metadata&&(i=Zs(y.metadata)),(Dt=y.messages)!=null&&Dt.length&&(n={...n,initialMessages:y.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(n.onStateLoaded)try{let l=p({messages:[],metadata:{}});(Pn=l.messages)!=null&&Pn.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let u=()=>i,f=l=>{var y;i=(y=l({...i}))!=null?y:{},ao()},m=n.actionParsers&&n.actionParsers.length?n.actionParsers:[cs],v=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[to.message,to.messageAndClick],M=ds({parsers:m,handlers:v,getSessionMetadata:u,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});M.syncFromMetadata();let b=(pa=(da=n.launcher)==null?void 0:da.enabled)!=null?pa:!0,C=(ga=(ua=n.launcher)==null?void 0:ua.autoExpand)!=null?ga:!1,S=(ma=n.autoFocusInput)!=null?ma:!1,R=C,w=b,L=(ha=(fa=n.layout)==null?void 0:fa.header)==null?void 0:ha.layout,B=!1,T=b?C:!0,Y=!1,ue=null,ce=()=>{Y=!0,ue&&clearTimeout(ue),ue=setTimeout(()=>{Y&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),Y=!1)},1e4)},$=Dc(n,M,ce),te=(ba=(ya=n.features)==null?void 0:ya.showReasoning)!=null?ba:!0,Te=(va=(xa=n.features)==null?void 0:xa.showToolCalls)!=null?va:!0,ne=(wa=(Ca=n.features)==null?void 0:Ca.showEventStreamToggle)!=null?wa:!1,Se=(Aa=(Sa=n.features)==null?void 0:Sa.scrollToBottom)!=null?Aa:{},he=`${(Ta=typeof n.persistState=="object"?(Ea=n.persistState)==null?void 0:Ea.keyPrefix:void 0)!=null?Ta:"persona-"}event-stream`,Me=ne?new Bo(he):null,ke=(La=(ka=(Ma=n.features)==null?void 0:Ma.eventStream)==null?void 0:ka.maxEvents)!=null?La:2e3,re=ne?new Ho(ke,Me):null,be=null,$e=!1,ge=null,de=0;Me==null||Me.open().then(()=>re==null?void 0:re.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let oe={onCopy:l=>{var g,y;o.emit("message:copy",l),D!=null&&D.isClientTokenMode()&&D.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),D!=null&&D.isClientTokenMode()&&D.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)}},De=(Ia=n.statusIndicator)!=null?Ia:{},ot=l=>{var g,y,E,k;return l==="idle"?(g=De.idleText)!=null?g:sn.idle:l==="connecting"?(y=De.connectingText)!=null?y:sn.connecting:l==="connected"?(E=De.connectedText)!=null?E:sn.connected:l==="error"?(k=De.errorText)!=null?k:sn.error:sn[l]};function wt(l,g,y,E){if(E==="idle"&&y.idleLink){l.textContent="";let k=document.createElement("a");k.href=y.idleLink,k.target="_blank",k.rel="noopener noreferrer",k.textContent=g,k.style.color="inherit",k.style.textDecoration="none",l.appendChild(k)}else l.textContent=g}let{wrapper:j,panel:q}=fc(n),se=hc(n,b),{container:_,body:z,messagesWrapper:Q,suggestions:Fe,textarea:J,sendButton:K,sendButtonWrapper:xt,composerForm:tt,statusText:Lt,introTitle:Ut,introSubtitle:Ne,closeButton:le,iconHolder:Ie,headerTitle:St,headerSubtitle:At,header:Ze,footer:Qe,actionsRow:Kt,leftActions:Gt,rightActions:Zt}=se,O=se.micButton,Le=se.micButtonWrapper,pe=se.attachmentButton,at=se.attachmentButtonWrapper,Be=se.attachmentInput,Z=se.attachmentPreviewsContainer;_.classList.add("persona-relative"),z.classList.add("persona-relative");let ye=12,Pe=()=>{var l;return(l=Se.label)!=null?l:""},dt=()=>{var l;return(l=Se.iconName)!=null?l:"arrow-down"},Ot=()=>Se.enabled!==!1,nt=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");nt.type="button",nt.style.display="none",nt.setAttribute("data-persona-scroll-to-bottom","true");let $t=h("span","persona-flex persona-items-center"),it=h("span","");nt.append($t,it),_.appendChild(nt);let qe=()=>{let g=Qe.style.display==="none"?0:Qe.offsetHeight;nt.style.bottom=`${g+ye}px`};qe();let lt=()=>{let l=!!Pe();nt.setAttribute("aria-label",Pe()||"Jump to latest"),nt.title=Pe(),nt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),$t.innerHTML="";let g=me(dt(),"14px","currentColor",2);g?($t.appendChild(g),$t.style.display=""):$t.style.display="none",it.textContent=Pe(),it.style.display=l?"":"none"};lt();let _e=null,_t=null,Un=s.find(l=>l.renderHeader);if(Un!=null&&Un.renderHeader){let l=Un.renderHeader({config:n,defaultRenderer:()=>{let g=Cr({config:n,showClose:b});return Xr(_,g,n),g.header},onClose:()=>Et(!1,"user")});if(l){let g=_.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),Ze=l)}}let Xn=()=>{var g,y,E,k;if(!re)return;if($e=!0,!be&&re&&(be=Sc({buffer:re,getFullHistory:()=>re.getAllFromStore(),onClose:()=>Bn(),config:n,plugins:s})),be&&(z.style.display="none",(g=Qe.parentNode)==null||g.insertBefore(be.element,Qe),be.update()),Xe){Xe.style.boxShadow=`inset 0 0 0 1.5px ${bn.actionIconColor}`;let P=(k=(E=(y=n.features)==null?void 0:y.eventStream)==null?void 0:E.classNames)==null?void 0:k.toggleButtonActive;P&&P.split(/\s+/).forEach(W=>W&&Xe.classList.add(W))}let l=()=>{if(!$e)return;let P=Date.now();P-de>=200&&(be==null||be.update(),de=P),ge=requestAnimationFrame(l)};de=0,ge=requestAnimationFrame(l),er(),o.emit("eventStream:opened",{timestamp:Date.now()})},Bn=()=>{var l,g,y;if($e){if($e=!1,be&&be.element.remove(),z.style.display="",Xe){Xe.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(k=>k&&Xe.classList.remove(k))}ge!==null&&(cancelAnimationFrame(ge),ge=null),er(),o.emit("eventStream:closed",{timestamp:Date.now()})}},Xe=null;if(ne){let l=(Wa=(Pa=n.features)==null?void 0:Pa.eventStream)==null?void 0:Wa.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");Xe=h("button",g),Xe.style.width="28px",Xe.style.height="28px",Xe.style.color=bn.actionIconColor,Xe.type="button",Xe.setAttribute("aria-label","Event Stream"),Xe.title="Event Stream";let y=me("activity","18px","currentColor",1.5);y&&Xe.appendChild(y);let E=se.clearChatButtonWrapper,k=se.closeButtonWrapper,P=E||k;P&&P.parentNode===Ze?Ze.insertBefore(Xe,P):Ze.appendChild(Xe),Xe.addEventListener("click",()=>{$e?Bn():Xn()})}let Ar=l=>{var E,k,P;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 W=l.querySelector("[data-persona-composer-form]");W!=null&&W.parentNode?W.parentNode.insertBefore(y,W):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let W=h("input");W.type="file",W.accept=((E=g.allowedTypes)!=null?E:sr).join(","),W.multiple=((k=g.maxFiles)!=null?k:4)>1,W.style.display="none",W.setAttribute("aria-label",(P=g.buttonTooltipText)!=null?P:"Attach files"),l.appendChild(W)}},Vn=s.find(l=>l.renderComposer);if(Vn!=null&&Vn.renderComposer){let l=n.composer,g=Vn.renderComposer({config:n,defaultRenderer:()=>Wo({config:n}).footer,onSubmit:y=>{D&&!D.isStreaming()&&D.sendMessage(y)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Be==null||Be.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y},n.agent&&(n.agent={...n.agent,model:y})},onVoiceToggle:((Ra=n.voiceRecognition)==null?void 0:Ra.enabled)===!0?()=>{_t==null||_t()}:void 0});g&&(Qe.replaceWith(g),Qe=g)}let Er=l=>{let g=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),E=l.querySelector("[data-persona-composer-submit]"),k=l.querySelector("[data-persona-composer-mic]"),P=l.querySelector("[data-persona-composer-status]");g&&(tt=g),y&&(J=y),E&&(K=E),k&&(O=k,Le=k.parentElement),P&&(Lt=P);let W=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");W&&(Fe=W);let V=l.querySelector(".persona-attachment-button");V&&(pe=V,at=V.parentElement),Be=l.querySelector('input[type="file"]'),Z=l.querySelector(".persona-attachment-previews");let F=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");F&&(Kt=F)};Ar(Qe),Er(Qe);let Mn=(Ha=n.layout)==null?void 0:Ha.contentMaxWidth;Mn&&tt&&(tt.style.maxWidth=Mn,tt.style.marginLeft="auto",tt.style.marginRight="auto"),Mn&&Fe&&(Fe.style.maxWidth=Mn,Fe.style.marginLeft="auto",Fe.style.marginRight="auto"),Mn&&Z&&(Z.style.maxWidth=Mn,Z.style.marginLeft="auto",Z.style.marginRight="auto"),(Ba=n.attachments)!=null&&Ba.enabled&&Be&&Z&&(_e=Gr.fromConfig(n.attachments),_e.setPreviewsContainer(Z),Be.addEventListener("change",l=>{let g=l.target;_e==null||_e.handleFileSelect(g.files),g.value=""})),(()=>{var E,k;let l=(k=(E=n.layout)==null?void 0:E.slots)!=null?k:{},g=P=>{switch(P){case"body-top":return _.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Q;case"footer-top":return Fe;case"composer":return tt;case"footer-bottom":return Lt;default:return null}},y=(P,W)=>{var V;switch(P){case"header-left":case"header-center":case"header-right":if(P==="header-left")Ze.insertBefore(W,Ze.firstChild);else if(P==="header-right")Ze.appendChild(W);else{let F=Ze.querySelector(".persona-flex-col");F?(V=F.parentNode)==null||V.insertBefore(W,F.nextSibling):Ze.appendChild(W)}break;case"body-top":{let F=z.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");F?F.replaceWith(W):z.insertBefore(W,z.firstChild);break}case"body-bottom":z.appendChild(W);break;case"footer-top":Fe.replaceWith(W);break;case"footer-bottom":Lt.replaceWith(W);break;default:break}};for(let[P,W]of Object.entries(l))if(W)try{let V=W({config:n,defaultContent:()=>g(P)});V&&y(P,V)}catch(V){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${P}":`,V)}})();let ir=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let E=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!E)return;let k=E.getAttribute("data-message-id");if(!k)return;let P=y.getAttribute("data-bubble-type");P==="reasoning"?(Zr.has(k)?Zr.delete(k):Zr.add(k),vc(k,E)):P==="tool"&&(Qr.has(k)?Qr.delete(k):Qr.add(k),Cc(k,E,n)),Ln.delete(k)};Q.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),ir(l))}),Q.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),ir(l))});let Kn=new Map;Q.addEventListener("click",l=>{var W;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 k=E.getAttribute("data-actions-for");if(!k)return;let P=y.getAttribute("data-action");if(P==="copy"){let F=D.getMessages().find(ae=>ae.id===k);if(F&&oe.onCopy){let ae=F.content||"";navigator.clipboard.writeText(ae).then(()=>{y.classList.add("persona-message-action-success");let ve=me("check",14,"currentColor",2);ve&&(y.innerHTML="",y.appendChild(ve)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let we=me("copy",14,"currentColor",2);we&&(y.innerHTML="",y.appendChild(we))},2e3)}).catch(ve=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ve)}),oe.onCopy(F)}}else if(P==="upvote"||P==="downvote")if(((W=Kn.get(k))!=null?W:null)===P)Kn.delete(k),y.classList.remove("persona-message-action-active");else{let ae=P==="upvote"?"downvote":"upvote",ve=E.querySelector(`[data-action="${ae}"]`);ve&&ve.classList.remove("persona-message-action-active"),Kn.set(k,P),y.classList.add("persona-message-action-active");let xe=D.getMessages().find(ze=>ze.id===k);xe&&oe.onFeedback&&oe.onFeedback({type:P,messageId:xe.id,message:xe})}}),Q.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.closest(".persona-approval-bubble");if(!E)return;let k=E.getAttribute("data-message-id");if(!k)return;let P=y.getAttribute("data-approval-action");if(!P)return;let W=P==="approve"?"approved":"denied",F=D.getMessages().find(ve=>ve.id===k);if(!(F!=null&&F.approval))return;let ae=E.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(we=>{we.disabled=!0,we.style.opacity="0.5",we.style.cursor="not-allowed"}),D.resolveApproval(F.approval,W)});let et=null,xn=null,Dn={artifacts:[],selectedId:null},an=!1,lr={current:null};Q.addEventListener("click",l=>{var we,xe,ze,H,Oe;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.getAttribute("data-download-artifact");if(!E||((ze=(xe=(we=n.features)==null?void 0:we.artifacts)==null?void 0:xe.onArtifactAction)==null?void 0:ze.call(xe,{type:"download",artifactId:E}))===!0)return;let P=D.getArtifactById(E),W=P==null?void 0:P.markdown,V=(P==null?void 0:P.title)||"artifact";if(!W){let Ee=y.closest("[data-open-artifact]"),fe=Ee==null?void 0:Ee.closest("[data-message-id]"),Re=fe==null?void 0:fe.getAttribute("data-message-id");if(Re){let Ge=D.getMessages().find(Ce=>Ce.id===Re);if(Ge!=null&&Ge.rawContent)try{let Ce=JSON.parse(Ge.rawContent);W=(H=Ce==null?void 0:Ce.props)==null?void 0:H.markdown,V=((Oe=Ce==null?void 0:Ce.props)==null?void 0:Oe.title)||V}catch{}}}if(!W)return;let F=new Blob([W],{type:"text/markdown"}),ae=URL.createObjectURL(F),ve=document.createElement("a");ve.href=ae,ve.download=`${V}.md`,ve.click(),URL.revokeObjectURL(ae)}),Q.addEventListener("click",l=>{var P,W,V;let y=l.target.closest("[data-open-artifact]");if(!y)return;let E=y.getAttribute("data-open-artifact");!E||((V=(W=(P=n.features)==null?void 0:P.artifacts)==null?void 0:W.onArtifactAction)==null?void 0:V.call(W,{type:"open",artifactId:E}))===!0||(l.preventDefault(),l.stopPropagation(),an=!1,D.selectArtifact(E),Cn())}),Q.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;g.hasAttribute("data-open-artifact")&&(l.preventDefault(),g.click())});let vn=null,ft=null,ln=null,kn=null,cr=()=>{};function Zn(){kn==null||kn(),kn=null}let dr=()=>{var W;if(!vn||!ft)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((W=e.ownerDocument.defaultView)!=null?W:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){ft.style.removeProperty("position"),ft.style.removeProperty("left"),ft.style.removeProperty("top"),ft.style.removeProperty("bottom"),ft.style.removeProperty("width"),ft.style.removeProperty("z-index");return}let E=vn.firstElementChild;if(!E||E===ft)return;let k=10;ft.style.position="absolute",ft.style.top="0",ft.style.bottom="0",ft.style.width=`${k}px`,ft.style.zIndex="5";let P=E.offsetWidth-k/2;ft.style.left=`${Math.max(0,P)}px`},qn=()=>{},Cn=()=>{var y,E,k,P,W;if(!et||!Hn(n))return;as(e,n),is(e,n),qn();let l=(P=(k=(E=(y=n.features)==null?void 0:y.artifacts)==null?void 0:E.layout)==null?void 0:k.narrowHostMaxWidth)!=null?P:520,g=q.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l),et.update(Dn),an?(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),(W=et.backdrop)==null||W.classList.add("persona-hidden")):Dn.artifacts.length>0&&(et.element.classList.remove("persona-hidden"),et.setMobileOpen(!0)),cr()};if(Hn(n)){q.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(_),et=Tc(n,{onSelect:y=>{var E;return(E=lr.current)==null?void 0:E.selectArtifact(y)},onDismiss:()=>{an=!0,Cn()}}),et.element.classList.add("persona-hidden"),vn=g,g.appendChild(l),g.appendChild(et.element),et.backdrop&&q.appendChild(et.backdrop),q.appendChild(g),cr=()=>{var E,k,P,W;if(!vn||!et)return;if(!(((P=(k=(E=n.features)==null?void 0:E.artifacts)==null?void 0:k.layout)==null?void 0:P.resizable)===!0)){ln==null||ln(),ln=null,Zn(),ft&&(ft.remove(),ft=null),et.element.style.removeProperty("width"),et.element.style.removeProperty("maxWidth");return}if(!ft){let V=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");V.setAttribute("role","separator"),V.setAttribute("aria-orientation","vertical"),V.setAttribute("aria-label","Resize artifacts panel"),V.tabIndex=0;let F=e.ownerDocument,ae=(W=F.defaultView)!=null?W:window,ve=we=>{var fe,Re;if(!et||we.button!==0||e.classList.contains("persona-artifact-narrow-host")||ae.innerWidth<=640)return;we.preventDefault(),Zn();let xe=we.clientX,ze=et.element.getBoundingClientRect().width,H=(Re=(fe=n.features)==null?void 0:fe.artifacts)==null?void 0:Re.layout,Oe=ct=>{let Ge=vn.getBoundingClientRect().width,Ce=e.classList.contains("persona-artifact-appearance-seamless"),Xt=Ce?0:Ic(vn,ae),gt=Ce?0:V.getBoundingClientRect().width||6,dn=ze-(ct.clientX-xe),nn=Pc(dn,Ge,Xt,gt,H==null?void 0:H.resizableMinWidth,H==null?void 0:H.resizableMaxWidth);et.element.style.width=`${nn}px`,et.element.style.maxWidth="none",dr()},Ee=()=>{F.removeEventListener("pointermove",Oe),F.removeEventListener("pointerup",Ee),F.removeEventListener("pointercancel",Ee),kn=null;try{V.releasePointerCapture(we.pointerId)}catch{}};kn=Ee,F.addEventListener("pointermove",Oe),F.addEventListener("pointerup",Ee),F.addEventListener("pointercancel",Ee);try{V.setPointerCapture(we.pointerId)}catch{}};V.addEventListener("pointerdown",ve),ft=V,vn.insertBefore(V,et.element),ln=()=>{V.removeEventListener("pointerdown",ve)}}if(ft){let V=Dn.artifacts.length>0&&!an;ft.classList.toggle("persona-hidden",!V),dr()}},qn=()=>{var ae,ve,we,xe,ze,H,Oe,Ee,fe,Re,ct,Ge,Ce,Xt;if(!b||!et||((ve=(ae=n.launcher)==null?void 0:ae.sidebarMode)!=null?ve:!1)||Yt(n)&&jn(n).reveal==="emerge")return;let E=(we=e.ownerDocument.defaultView)!=null?we:window,k=(ze=(xe=n.launcher)==null?void 0:xe.mobileFullscreen)!=null?ze:!0,P=(Oe=(H=n.launcher)==null?void 0:H.mobileBreakpoint)!=null?Oe:640;if(k&&E.innerWidth<=P||!Lc(n,b))return;let W=(Re=(fe=(Ee=n.launcher)==null?void 0:Ee.width)!=null?fe:n.launcherWidth)!=null?Re:Rn,V=(Xt=(Ce=(Ge=(ct=n.features)==null?void 0:ct.artifacts)==null?void 0:Ge.layout)==null?void 0:Ce.expandedPanelWidth)!=null?Xt:"min(720px, calc(100vw - 24px))";Dn.artifacts.length>0&&!an?(q.style.width=V,q.style.maxWidth=V):(q.style.width=W,q.style.maxWidth=W)},typeof ResizeObserver!="undefined"&&(xn=new ResizeObserver(()=>{Cn()}),xn.observe(q))}else q.appendChild(_);e.appendChild(j);let Jn=()=>{var gt,dn,nn,rn,Ft,pn,Ve,mt,Wn,fr,nr,hr,rr,jr,zr,jt,_o,mo,fo,Ur,jo,yr,Lr;let l=Yt(n),g=(dn=(gt=n.launcher)==null?void 0:gt.sidebarMode)!=null?dn:!1,y=l||g||((rn=(nn=n.launcher)==null?void 0:nn.fullHeight)!=null?rn:!1),E=((Ft=n.launcher)==null?void 0:Ft.enabled)===!1,k=(Ve=(pn=n.theme)==null?void 0:pn.components)==null?void 0:Ve.panel,P=Qo(n),W=(qt,fn)=>{var or;return qt==null||qt===""?fn:(or=Eo(P,qt))!=null?or:qt},V=(mt=e.ownerDocument.defaultView)!=null?mt:window,F=(fr=(Wn=n.launcher)==null?void 0:Wn.mobileFullscreen)!=null?fr:!0,ae=(hr=(nr=n.launcher)==null?void 0:nr.mobileBreakpoint)!=null?hr:640,ve=V.innerWidth<=ae,we=F&&ve&&b,xe=(jr=(rr=n.launcher)==null?void 0:rr.position)!=null?jr:"bottom-left",ze=xe==="bottom-left"||xe==="top-left",H=(jt=(zr=n.launcher)==null?void 0:zr.zIndex)!=null?jt:yn,Oe=g||we?"none":"1px solid var(--persona-border)",Ee=we?"none":g?ze?"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&&!we&&(Ee="none",Oe="none");let fe=g||we?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Re=W(k==null?void 0:k.border,Oe),ct=W(k==null?void 0:k.shadow,Ee),Ge=W(k==null?void 0:k.borderRadius,fe);if(e.style.cssText="",j.style.cssText="",q.style.cssText="",_.style.cssText="",z.style.cssText="",Qe.style.cssText="",we){j.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),j.style.cssText=`
21
21
  position: fixed !important;
22
22
  inset: 0 !important;
23
23
  width: 100% !important;
@@ -27,9 +27,9 @@ import{Marked as yd}from"marked";var bd=e=>{if(e)return e},Oo=e=>{var s,o;let r=
27
27
  padding: 0 !important;
28
28
  display: flex !important;
29
29
  flex-direction: column !important;
30
- z-index: ${W} !important;
30
+ z-index: ${H} !important;
31
31
  background-color: var(--persona-surface, #ffffff) !important;
32
- `,U.style.cssText=`
32
+ `,q.style.cssText=`
33
33
  position: relative !important;
34
34
  display: flex !important;
35
35
  flex-direction: column !important;
@@ -53,20 +53,20 @@ import{Marked as yd}from"marked";var bd=e=>{if(e)return e},Oo=e=>{var s,o;let r=
53
53
  overflow: hidden !important;
54
54
  border-radius: 0 !important;
55
55
  border: none !important;
56
- `,z.style.flex="1 1 0%",z.style.minHeight="0",z.style.overflowY="auto",et.style.flexShrink="0",R=!0;return}let xe=(co=(Fo=n==null?void 0:n.launcher)==null?void 0:Fo.width)!=null?co:n==null?void 0:n.launcherWidth,Qt=xe!=null?xe:"min(400px, calc(100vw - 24px))";if(!g&&!l)E&&y?(U.style.width="100%",U.style.maxWidth="100%"):(U.style.width=Qt,U.style.maxWidth=Qt);else if(l)if(On(n).reveal==="emerge"){let fn=On(n).width;U.style.width=fn,U.style.maxWidth=fn}else U.style.width="100%",U.style.maxWidth="100%";if(Vn(),U.style.boxShadow=gt,U.style.borderRadius=Ke,_.style.border=We,_.style.borderRadius=Ke,l&&!ve&&(k==null?void 0:k.border)===void 0&&(_.style.border="none",On(n).side==="right"?_.style.borderLeft="1px solid var(--persona-border)":_.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%"),j.style.display="flex",j.style.flexDirection="column",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.maxHeight="100%",j.style.height="100%",E&&(j.style.overflow="hidden"),U.style.display="flex",U.style.flexDirection="column",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.maxHeight="100%",U.style.height="100%",U.style.overflow="hidden",_.style.display="flex",_.style.flexDirection="column",_.style.flex="1 1 0%",_.style.minHeight="0",_.style.maxHeight="100%",_.style.overflow="hidden",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.overflowY="auto",et.style.flexShrink="0"),j.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!E&&!l&&((po=$n[ye])!=null?po:$n["bottom-right"]).split(" ").forEach(fn=>j.classList.add(fn)),g){let Kt=(No=(_r=n.launcher)==null?void 0:_r.sidebarWidth)!=null?No:"420px";j.style.cssText=`
56
+ `,z.style.flex="1 1 0%",z.style.minHeight="0",z.style.overflowY="auto",Qe.style.flexShrink="0",B=!0;return}let Ce=(mo=(_o=n==null?void 0:n.launcher)==null?void 0:_o.width)!=null?mo:n==null?void 0:n.launcherWidth,Xt=Ce!=null?Ce:Rn;if(!g&&!l)E&&y?(q.style.width="100%",q.style.maxWidth="100%"):(q.style.width=Xt,q.style.maxWidth=Xt);else if(l)if(jn(n).reveal==="emerge"){let fn=jn(n).width;q.style.width=fn,q.style.maxWidth=fn}else q.style.width="100%",q.style.maxWidth="100%";if(qn(),q.style.boxShadow=ct,q.style.borderRadius=Ge,_.style.border=Re,_.style.borderRadius=Ge,l&&!we&&(k==null?void 0:k.border)===void 0&&(_.style.border="none",jn(n).side==="right"?_.style.borderLeft="1px solid var(--persona-border)":_.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%"),j.style.display="flex",j.style.flexDirection="column",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.maxHeight="100%",j.style.height="100%",E&&(j.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.height="100%",q.style.overflow="hidden",_.style.display="flex",_.style.flexDirection="column",_.style.flex="1 1 0%",_.style.minHeight="0",_.style.maxHeight="100%",_.style.overflow="hidden",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.overflowY="auto",Qe.style.flexShrink="0"),j.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!g&&!E&&!l&&((fo=zn[xe])!=null?fo:zn["bottom-right"]).split(" ").forEach(fn=>j.classList.add(fn)),g){let qt=(jo=(Ur=n.launcher)==null?void 0:Ur.sidebarWidth)!=null?jo:"420px";j.style.cssText=`
57
57
  position: fixed !important;
58
58
  top: 0 !important;
59
59
  bottom: 0 !important;
60
- width: ${Kt} !important;
60
+ width: ${qt} !important;
61
61
  height: 100vh !important;
62
62
  max-height: 100vh !important;
63
63
  margin: 0 !important;
64
64
  padding: 0 !important;
65
65
  display: flex !important;
66
66
  flex-direction: column !important;
67
- z-index: ${W} !important;
68
- ${je?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
69
- `,U.style.cssText=`
67
+ z-index: ${H} !important;
68
+ ${ze?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
69
+ `,q.style.cssText=`
70
70
  position: relative !important;
71
71
  display: flex !important;
72
72
  flex-direction: column !important;
@@ -77,9 +77,9 @@ import{Marked as yd}from"marked";var bd=e=>{if(e)return e},Oo=e=>{var s,o;let r=
77
77
  min-height: 0 !important;
78
78
  margin: 0 !important;
79
79
  padding: 0 !important;
80
- box-shadow: ${gt} !important;
81
- border-radius: ${Ke} !important;
82
- `,U.style.setProperty("width","100%","important"),U.style.setProperty("max-width","100%","important"),_.style.cssText=`
80
+ box-shadow: ${ct} !important;
81
+ border-radius: ${Ge} !important;
82
+ `,q.style.setProperty("width","100%","important"),q.style.setProperty("max-width","100%","important"),_.style.cssText=`
83
83
  display: flex !important;
84
84
  flex-direction: column !important;
85
85
  flex: 1 1 0% !important;
@@ -88,29 +88,29 @@ import{Marked as yd}from"marked";var bd=e=>{if(e)return e},Oo=e=>{var s,o;let r=
88
88
  min-height: 0 !important;
89
89
  max-height: 100% !important;
90
90
  overflow: hidden !important;
91
- border-radius: ${Ke} !important;
92
- border: ${We} !important;
93
- `,et.style.cssText=`
91
+ border-radius: ${Ge} !important;
92
+ border: ${Re} !important;
93
+ `,Qe.style.cssText=`
94
94
  flex-shrink: 0 !important;
95
95
  border-top: none !important;
96
96
  padding: 8px 16px 12px 16px !important;
97
- `}if(!E&&!l){let Kt="max-height: -moz-available !important; max-height: stretch !important;",fn=g?"":"padding-top: 1.25em !important;",fr=g?"":`z-index: ${(Tr=(mr=n.launcher)==null?void 0:mr.zIndex)!=null?Tr:yn} !important;`;j.style.cssText+=Kt+fn+fr}};qn(),Ir(e,n),ns(e,n),rs(e,n);let xt=[],Wt=null,Rt=null;xt.push(()=>{Wt==null||Wt(),Wt=null,Rt==null||Rt(),Rt=null}),xn&&xt.push(()=>{xn==null||xn.disconnect(),xn=null}),xt.push(()=>{ln==null||ln(),ln=null,Xn(),bt&&(bt.remove(),bt=null),tt==null||tt.element.style.removeProperty("width"),tt==null||tt.element.style.removeProperty("maxWidth")}),ne&&xt.push(()=>{De!==null&&(cancelAnimationFrame(De),De=null),ae==null||ae.destroy(),ae=null,J==null||J.destroy(),J=null,fe=null});let wn=null,lr=()=>{wn&&(wn(),wn=null),n.colorScheme==="auto"&&(wn=Ts(()=>{Ir(e,n)}))};lr(),xt.push(()=>{wn&&(wn(),wn=null)});let Bn=xc(lt),Sn=null,H,Dn=!1,kn=sc(),cr=0,gn=Xo(),An=0,ee=null,Fn=!1,Rr=1,to=8,Hr=new Map,Ye={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},no=(Ba=(Ha=n.voiceRecognition)==null?void 0:Ha.autoResume)!=null?Ba:!1,Ln=l=>{o.emit("voice:state",{active:Ye.active,source:l,timestamp:Date.now()})},mn=()=>{h(l=>({...l,voiceState:{active:Ye.active,timestamp:Date.now(),manuallyDeactivated:Ye.manuallyDeactivated}}))},Wo=()=>{var E,k;if(((E=n.voiceRecognition)==null?void 0:E.enabled)===!1)return;let l=Js(i.voiceState),g=!!l.active,y=Number((k=l.timestamp)!=null?k:0);Ye.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-y<Np&&setTimeout(()=>{var I,P;Ye.active||(Ye.manuallyDeactivated=!1,((P=(I=n.voiceRecognition)==null?void 0:I.provider)==null?void 0:P.type)==="runtype"?H.toggleVoice().then(()=>{Ye.active=H.isVoiceActive(),Ln("restore"),H.isVoiceActive()&&v()}):qe("restore"))},1e3)},Ro=()=>H?Rc(H.getMessages()).filter(l=>!l.__skipPersist):[];function ro(l){if(!(a!=null&&a.save))return;let y={messages:l?Rc(l):H?Ro():[],metadata:i};try{let E=a.save(y);E instanceof Promise&&E.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",E)}}let Gn=null,Ho=()=>j.querySelector("#persona-scroll-container")||z,Br=()=>{Gn!==null&&(cancelAnimationFrame(Gn),Gn=null),Fn=!1},Dr=()=>{ee!==null&&(cancelAnimationFrame(ee),ee=null),Br()},Zn=()=>{if(!Nt()||ge){at.parentNode&&at.remove(),at.style.display="none";return}at.parentNode!==_&&_.appendChild(at),Je();let l=So(z)>0;at.style.display=gn.isFollowing()||!l?"none":""},oo=()=>{gn.pause()&&(Dr(),Zn())},dr=()=>{gn.resume(),Zn()},pr=(l=!1)=>{gn.isFollowing()&&(!l&&!Dn||(Dr(),ee=requestAnimationFrame(()=>{ee=null,gn.isFollowing()&&Bo(Ho(),l?220:140)})))},Bo=(l,g=500)=>{let y=l.scrollTop,E=So(l),k=E-y;if(Math.abs(k)<1){An=l.scrollTop;return}Br();let I=performance.now();Fn=!0;let P=B=>1-Math.pow(1-B,3),q=B=>{if(!gn.isFollowing()){Br();return}let oe=So(l);oe!==E&&(E=oe,k=E-y);let be=B-I,ve=Math.min(be/g,1),ye=P(ve),je=y+k*ye;l.scrollTop=je,An=l.scrollTop,ve<1?Gn=requestAnimationFrame(q):(l.scrollTop=E,An=l.scrollTop,Gn=null,Fn=!1)};Gn=requestAnimationFrame(q)},Do=l=>{let g=new Map;l.forEach(y=>{let E=Hr.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}))}),Hr.clear(),g.forEach((y,E)=>{Hr.set(E,y)})},Ar=(l,g,y)=>{var be,ve,ye,je;let E=document.createElement("div"),I=(()=>{var Fe;let W=s.find(we=>we.renderLoadingIndicator);if(W!=null&&W.renderLoadingIndicator)return W.renderLoadingIndicator;if((Fe=n.loadingIndicator)!=null&&Fe.render)return n.loadingIndicator.render})(),P=new Set;g.forEach(W=>{var xe,Qt;P.add(W.id);let Fe=oc(W,cr),we=ac(kn,W.id,Fe);if(we){E.appendChild(we.cloneNode(!0));return}let me=null,We=s.find(ht=>!!(W.variant==="reasoning"&&ht.renderReasoning||W.variant==="tool"&&ht.renderToolCall||W.variant==="approval"&&ht.renderApproval||!W.variant&&ht.renderMessage)),gt=(xe=n.layout)==null?void 0:xe.messages;if(We)if(W.variant==="reasoning"&&W.reasoning&&We.renderReasoning){if(!te)return;me=We.renderReasoning({message:W,defaultRenderer:()=>Ps(W),config:n})}else if(W.variant==="tool"&&W.toolCall&&We.renderToolCall){if(!Ae)return;me=We.renderToolCall({message:W,defaultRenderer:()=>Ws(W,n),config:n})}else if(W.variant==="approval"&&W.approval&&We.renderApproval){if(n.approval===!1)return;me=We.renderApproval({message:W,defaultRenderer:()=>Rs(W,n),config:n})}else We.renderMessage&&(me=We.renderMessage({message:W,defaultRenderer:()=>{let ht=Lo(W,y,gt,n.messageActions,Ie,{loadingIndicatorRenderer:I,widgetConfig:n});return W.role!=="user"&&Ds(ht,W,n,H),ht},config:n}));if(!me&&W.role==="assistant"&&!W.variant&&n.enableComponentStreaming!==!1&&zs(W)){let dn=Vs(W);if(dn){let nn=js(dn,{config:n,message:W,transform:y});if(nn)if(n.wrapComponentDirectiveInBubble!==!1){let Dt=document.createElement("div");if(Dt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Dt.id=`bubble-${W.id}`,Dt.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let pn=document.createElement("div");pn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",pn.innerHTML=y({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Dt.appendChild(pn)}Dt.appendChild(nn),me=Dt}else{let Dt=document.createElement("div");if(Dt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Dt.id=`bubble-${W.id}`,Dt.setAttribute("data-message-id",W.id),Dt.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let pn=document.createElement("div");pn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",pn.innerHTML=y({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),Dt.appendChild(pn)}Dt.appendChild(nn),me=Dt}}}if(!me)if(W.variant==="reasoning"&&W.reasoning){if(!te)return;me=Ps(W)}else if(W.variant==="tool"&&W.toolCall){if(!Ae)return;me=Ws(W,n)}else if(W.variant==="approval"&&W.approval){if(n.approval===!1)return;me=Rs(W,n)}else{let ht=(Qt=n.layout)==null?void 0:Qt.messages;ht!=null&&ht.renderUserMessage&&W.role==="user"?me=ht.renderUserMessage({message:W,config:n,streaming:!!W.streaming}):ht!=null&&ht.renderAssistantMessage&&W.role==="assistant"?me=ht.renderAssistantMessage({message:W,config:n,streaming:!!W.streaming}):me=Lo(W,y,ht,n.messageActions,Ie,{loadingIndicatorRenderer:I,widgetConfig:n}),W.role!=="user"&&me&&Ds(me,W,n,H)}let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id=`wrapper-${W.id}`,Ke.setAttribute("data-wrapper-id",W.id),W.role==="user"&&Ke.classList.add("persona-justify-end"),(me==null?void 0:me.getAttribute("data-persona-component-directive"))==="true"&&Ke.classList.add("persona-w-full"),Ke.appendChild(me),ic(kn,W.id,Fe,Ke),E.appendChild(Ke)}),lc(kn,P);let q=g.some(W=>W.role==="assistant"&&W.streaming),B=g[g.length-1],oe=(B==null?void 0:B.role)==="assistant"&&!B.streaming&&B.variant!=="approval";if(Dn&&g.some(W=>W.role==="user")&&!q&&!oe){let W={config:n,streaming:!0,location:"standalone",defaultRenderer:Yr},Fe=s.find(me=>me.renderLoadingIndicator),we=null;if(Fe!=null&&Fe.renderLoadingIndicator&&(we=Fe.renderLoadingIndicator(W)),we===null&&((be=n.loadingIndicator)!=null&&be.render)&&(we=n.loadingIndicator.render(W)),we===null&&(we=Yr()),we){let me=document.createElement("div"),We=((ve=n.loadingIndicator)==null?void 0:ve.showBubble)!==!1;me.className=We?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),me.setAttribute("data-typing-indicator","true"),me.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",me.appendChild(we);let gt=document.createElement("div");gt.className="persona-flex",gt.id="wrapper-typing-indicator",gt.setAttribute("data-wrapper-id","typing-indicator"),gt.appendChild(me),E.appendChild(gt)}}if(!Dn&&g.length>0){let W=g[g.length-1],Fe={config:n,lastMessage:W,messageCount:g.length},we=s.find(We=>We.renderIdleIndicator),me=null;if(we!=null&&we.renderIdleIndicator&&(me=we.renderIdleIndicator(Fe)),me===null&&((ye=n.loadingIndicator)!=null&&ye.renderIdle)&&(me=n.loadingIndicator.renderIdle(Fe)),me){let We=document.createElement("div"),gt=((je=n.loadingIndicator)==null?void 0:je.showBubble)!==!1;We.className=gt?["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(" "),We.setAttribute("data-idle-indicator","true"),We.appendChild(me);let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id="wrapper-idle-indicator",Ke.setAttribute("data-wrapper-id","idle-indicator"),Ke.appendChild(We),E.appendChild(Ke)}}rc(l,E)},Er=()=>{var B,oe,be,ve,ye;if(!b)return;let l=Gt(n),g=(B=e.ownerDocument.defaultView)!=null?B:window,y=(be=(oe=n.launcher)==null?void 0:oe.mobileBreakpoint)!=null?be:640,E=(ye=(ve=n.launcher)==null?void 0:ve.mobileFullscreen)!=null?ye:!0,k=g.innerWidth<=y,I=E&&k&&b,P=On(n).reveal;T?(j.style.removeProperty("display"),j.style.display=l?"flex":"",j.classList.remove("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-95","persona-opacity-0"),U.classList.add("persona-scale-100","persona-opacity-100"),Ue?Ue.element.style.display="none":$e&&($e.style.display="none")):(l?l&&(P==="overlay"||P==="push")&&!I?(j.style.removeProperty("display"),j.style.display="flex",j.classList.remove("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(j.style.setProperty("display","none","important"),j.classList.remove("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(j.style.display="",j.classList.add("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-100","persona-opacity-100"),U.classList.add("persona-scale-95","persona-opacity-0")),Ue?Ue.element.style.display=l?"none":"":$e&&($e.style.display=l?"none":""))},Mt=(l,g="user")=>{var I,P;if(!b||T===l)return;let y=T;T=l,Er();let E=(()=>{var je,W,Fe,we,me,We,gt;let q=(W=(je=n.launcher)==null?void 0:je.sidebarMode)!=null?W:!1,B=(Fe=e.ownerDocument.defaultView)!=null?Fe:window,oe=(me=(we=n.launcher)==null?void 0:we.mobileFullscreen)!=null?me:!0,be=(gt=(We=n.launcher)==null?void 0:We.mobileBreakpoint)!=null?gt:640,ve=B.innerWidth<=be,ye=Gt(n)&&oe&&ve;return q||oe&&ve&&b||ye})();if(T&&E){if(!Wt){let q=e.getRootNode(),B=q instanceof ShadowRoot?q.host:e.closest(".persona-host");B&&(Wt=Ms(B,(P=(I=n.launcher)==null?void 0:I.zIndex)!=null?P:yn))}Rt||(Rt=ks(e.ownerDocument))}else T||(Wt==null||Wt(),Wt=null,Rt==null||Rt(),Rt=null);T&&(Ht(),pr(!0));let k={open:T,source:g,timestamp:Date.now()};T&&!y?o.emit("widget:opened",k):!T&&y&&o.emit("widget:closed",k),o.emit("widget:state",{open:T,launcherEnabled:b,voiceActive:Ye.active,streaming:H.isStreaming()})},Fr=l=>{X.disabled=l,O&&(O.disabled=l),Bn.buttons.forEach(g=>{g.disabled=l}),et.dataset.personaComposerStreaming=l?"true":"false",et.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},Nr=()=>{Ye.active||K&&K.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Nr(),200)});let so=()=>{var y,E,k,I,P,q,B,oe,be,ve,ye;Jt.textContent=(E=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?E:"Hello \u{1F44B}",Be.textContent=(I=(k=n.copy)==null?void 0:k.welcomeSubtitle)!=null?I:"Ask anything about your account or products.",K.placeholder=(q=(P=n.copy)==null?void 0:P.inputPlaceholder)!=null?q:"How can I help...";let l=z.querySelector("[data-persona-intro-card]");if(l){let je=((B=n.copy)==null?void 0:B.showWelcomeCard)!==!1;l.style.display=je?"":"none",je?(z.classList.remove("persona-gap-3"),z.classList.add("persona-gap-6")):(z.classList.remove("persona-gap-6"),z.classList.add("persona-gap-3"))}(be=(oe=n.sendButton)==null?void 0:oe.useIcon)!=null&&be||(X.textContent=(ye=(ve=n.copy)==null?void 0:ve.sendButtonLabel)!=null?ye:"Send"),K.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',K.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=>{h(g=>({...g,sessionId:l}))}}),H=new xo(n,{onMessagesChanged(l){Ar(Q,l,$),H&&(l.some(k=>k.role==="user")?Bn.render([],H,K,l):Bn.render(n.suggestionChips,H,K,l,n.suggestionChipsConfig)),pr(!Dn),Do(l);let g=[...l].reverse().find(E=>E.role==="user"),y=Ye.lastUserMessageId;g&&g.id!==y&&(Ye.lastUserMessageId=g.id,o.emit("user:message",g)),Ye.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),ro(l)},onStatusChanged(l){var E;let g=(E=n.statusIndicator)!=null?E:{};At(Pt,(k=>{var I,P,q,B;return k==="idle"?(I=g.idleText)!=null?I:sn.idle:k==="connecting"?(P=g.connectingText)!=null?P:sn.connecting:k==="connected"?(q=g.connectedText)!=null?q:sn.connected:k==="error"?(B=g.errorText)!=null?B:sn.error:sn[k]})(l),g,l)},onStreamingChanged(l){Dn=l,Fr(l),H&&Ar(Q,H.getMessages(),$),l||pr(!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":A(),_e();break;case"speaking":A(),D();break;default:l==="idle"&&H.isBargeInActive()?(A(),v(),O==null||O.setAttribute("aria-label","End voice session")):(Ye.active=!1,A(),Ln("system"),mn());break}},onArtifactsState(l){Hn=l,Cn()}}),sr.current=H,((Fa=(Da=n.voiceRecognition)==null?void 0:Da.provider)==null?void 0:Fa.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)}),J&&H.setSSEEventCallback((l,g)=>{J==null||J.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=Js(l.metadata),M.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 ao=l=>{var k;l.preventDefault();let g=K.value.trim(),y=(k=Ne==null?void 0:Ne.hasAttachments())!=null?k:!1;if(!g&&!y)return;let E;y&&(E=[],E.push(...Ne.getContentParts()),g&&E.push(ws(g))),K.value="",K.style.height="auto",H.sendMessage(g,{contentParts:E}),y&&Ne.clearAttachments()},io=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),X.click())},lo=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!Ne)return;let g=$p(l.clipboardData);g.length!==0&&(l.preventDefault(),await Ne.handleFiles(g))},cn=null,En=!1,Qn=null,Oe=null,Z=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,qe=(l="user")=>{var I,P,q,B,oe,be,ve;if(En||H.isStreaming())return;let g=Z();if(!g)return;cn=new g;let E=(P=((I=n.voiceRecognition)!=null?I:{}).pauseDuration)!=null?P:2e3;cn.continuous=!0,cn.interimResults=!0,cn.lang="en-US";let k=K.value;cn.onresult=ye=>{let je="",W="";for(let we=0;we<ye.results.length;we++){let me=ye.results[we],We=me[0].transcript;me.isFinal?je+=We+" ":W=We}let Fe=k+je+W;K.value=Fe,Qn&&clearTimeout(Qn),(je||W)&&(Qn=window.setTimeout(()=>{let we=K.value.trim();we&&cn&&En&&(nt(),K.value="",K.style.height="auto",H.sendMessage(we,{viaVoice:!0}))},E))},cn.onerror=ye=>{ye.error!=="no-speech"&&nt()},cn.onend=()=>{if(En){let ye=K.value.trim();ye&&ye!==k.trim()&&(K.value="",K.style.height="auto",H.sendMessage(ye,{viaVoice:!0})),nt()}};try{if(cn.start(),En=!0,Ye.active=!0,l!=="system"&&(Ye.manuallyDeactivated=!1),Ln(l),mn(),O){let ye=(q=n.voiceRecognition)!=null?q:{};Oe={backgroundColor:O.style.backgroundColor,color:O.style.color,borderColor:O.style.borderColor,iconName:(B=ye.iconName)!=null?B:"mic",iconSize:parseFloat((ve=(be=ye.iconSize)!=null?be:(oe=n.sendButton)==null?void 0:oe.size)!=null?ve:"40")||24};let je=ye.recordingBackgroundColor,W=ye.recordingIconColor,Fe=ye.recordingBorderColor;if(O.classList.add("persona-voice-recording"),O.style.backgroundColor=je!=null?je:"var(--persona-voice-recording-bg, #ef4444)",O.style.color=W!=null?W:"var(--persona-voice-recording-indicator, #ffffff)",W){let we=O.querySelector("svg");we&&we.setAttribute("stroke",W)}Fe&&(O.style.borderColor=Fe),O.setAttribute("aria-label","Stop voice recognition")}}catch{nt("system")}},nt=(l="user")=>{if(En){if(En=!1,Qn&&(clearTimeout(Qn),Qn=null),cn){try{cn.stop()}catch{}cn=null}if(Ye.active=!1,Ln(l),mn(),O){if(O.classList.remove("persona-voice-recording"),Oe){O.style.backgroundColor=Oe.backgroundColor,O.style.color=Oe.color,O.style.borderColor=Oe.borderColor;let g=O.querySelector("svg");g&&g.setAttribute("stroke",Oe.color||"currentColor"),Oe=null}O.setAttribute("aria-label","Start voice recognition")}}},_t=(l,g)=>{var me,We,gt,Ke,xe,Qt,ht,dn;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),E=((me=l==null?void 0:l.provider)==null?void 0:me.type)==="runtype";if(!(y||E))return null;let I=f("div","persona-send-button-wrapper"),P=f("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 q=(We=l==null?void 0:l.iconName)!=null?We:"mic",B=(gt=g==null?void 0:g.size)!=null?gt:"40px",oe=(Ke=l==null?void 0:l.iconSize)!=null?Ke:B,be=parseFloat(oe)||24,ve=(xe=l==null?void 0:l.backgroundColor)!=null?xe:g==null?void 0:g.backgroundColor,ye=(Qt=l==null?void 0:l.iconColor)!=null?Qt: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",ye?P.style.color=ye:P.style.color="var(--persona-text, #111827)";let W=pe(q,be,ye||"currentColor",1.5);W?P.appendChild(W):P.textContent="\u{1F3A4}",ve?P.style.backgroundColor=ve:P.style.backgroundColor="",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 Fe=(ht=l==null?void 0:l.tooltipText)!=null?ht:"Start voice recognition";if(((dn=l==null?void 0:l.showTooltip)!=null?dn:!1)&&Fe){let nn=f("div","persona-send-button-tooltip");nn.textContent=Fe,I.appendChild(nn)}return{micButton:P,micButtonWrapper:I}},jt=()=>{var g,y,E,k,I;if(!O||Oe)return;let l=(g=n.voiceRecognition)!=null?g:{};Oe={backgroundColor:O.style.backgroundColor,color:O.style.color,borderColor:O.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((I=(k=l.iconSize)!=null?k:(E=n.sendButton)==null?void 0:E.size)!=null?I:"40")||24}},Yt=(l,g)=>{var I,P,q,B,oe;if(!O)return;let y=O.querySelector("svg");y&&y.remove();let E=(oe=Oe==null?void 0:Oe.iconSize)!=null?oe:parseFloat((B=(q=(I=n.voiceRecognition)==null?void 0:I.iconSize)!=null?q:(P=n.sendButton)==null?void 0:P.size)!=null?B:"40")||24,k=pe(l,E,g,1.5);k&&O.appendChild(k)},kt=()=>{O&&O.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},v=()=>{var k;if(!O)return;jt();let l=(k=n.voiceRecognition)!=null?k:{},g=l.recordingBackgroundColor,y=l.recordingIconColor,E=l.recordingBorderColor;if(kt(),O.classList.add("persona-voice-recording"),O.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",O.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let I=O.querySelector("svg");I&&I.setAttribute("stroke",y)}E&&(O.style.borderColor=E),O.setAttribute("aria-label","Stop voice recognition")},_e=()=>{var q,B,oe,be,ve,ye,je,W;if(!O)return;jt();let l=(q=n.voiceRecognition)!=null?q:{},g=H.getVoiceInterruptionMode(),y=(B=l.processingIconName)!=null?B:"loader",E=(be=(oe=l.processingIconColor)!=null?oe:Oe==null?void 0:Oe.color)!=null?be:"",k=(ye=(ve=l.processingBackgroundColor)!=null?ve:Oe==null?void 0:Oe.backgroundColor)!=null?ye:"",I=(W=(je=l.processingBorderColor)!=null?je:Oe==null?void 0:Oe.borderColor)!=null?W:"";kt(),O.classList.add("persona-voice-processing"),O.style.backgroundColor=k,O.style.borderColor=I;let P=E||"currentColor";O.style.color=P,Yt(y,P),O.setAttribute("aria-label","Processing voice input"),g==="none"&&(O.style.cursor="default")},D=()=>{var oe,be,ve,ye,je,W,Fe,we,me,We,gt,Ke;if(!O)return;jt();let l=(oe=n.voiceRecognition)!=null?oe:{},g=H.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",E=(be=l.speakingIconName)!=null?be:y,k=(W=l.speakingIconColor)!=null?W:g==="barge-in"?(ye=(ve=l.recordingIconColor)!=null?ve:Oe==null?void 0:Oe.color)!=null?ye:"":(je=Oe==null?void 0:Oe.color)!=null?je:"",I=(me=l.speakingBackgroundColor)!=null?me:g==="barge-in"?(Fe=l.recordingBackgroundColor)!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)":(we=Oe==null?void 0:Oe.backgroundColor)!=null?we:"",P=(Ke=l.speakingBorderColor)!=null?Ke:g==="barge-in"?(We=l.recordingBorderColor)!=null?We:"":(gt=Oe==null?void 0:Oe.borderColor)!=null?gt:"";kt(),O.classList.add("persona-voice-speaking"),O.style.backgroundColor=I,O.style.borderColor=P;let q=k||"currentColor";O.style.color=q,Yt(E,q);let B=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";O.setAttribute("aria-label",B),g==="none"&&(O.style.cursor="default"),g==="barge-in"&&O.classList.add("persona-voice-recording")},A=()=>{var l,g,y;O&&(kt(),Oe&&(O.style.backgroundColor=(l=Oe.backgroundColor)!=null?l:"",O.style.color=(g=Oe.color)!=null?g:"",O.style.borderColor=(y=Oe.borderColor)!=null?y:"",Yt(Oe.iconName,Oe.color||"currentColor"),Oe=null),O.style.cursor="",O.setAttribute("aria-label","Start voice recognition"))},N=()=>{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(()=>{Ye.active=!1,Ye.manuallyDeactivated=!0,mn(),Ln("user"),A()});return}H.toggleVoice().then(()=>{Ye.active=H.isVoiceActive(),Ye.manuallyDeactivated=!H.isVoiceActive(),mn(),Ln("user"),H.isVoiceActive()?v():A()});return}if(En){let y=K.value.trim();Ye.manuallyDeactivated=!0,mn(),nt("user"),y&&(K.value="",K.style.height="auto",H.sendMessage(y))}else Ye.manuallyDeactivated=!1,mn(),qe("user")};$t=N,O&&(O.addEventListener("click",N),xt.push(()=>{var l,g;((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?(H.isVoiceActive()&&H.toggleVoice(),A()):nt("system"),O&&O.removeEventListener("click",N)}));let ce=o.on("assistant:complete",()=>{no&&(Ye.active||Ye.manuallyDeactivated||no==="assistant"&&!Ye.lastUserMessageWasVoice||setTimeout(()=>{var l,g;!Ye.active&&!Ye.manuallyDeactivated&&(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?H.toggleVoice().then(()=>{Ye.active=H.isVoiceActive(),Ln("auto"),H.isVoiceActive()&&v()}):qe("auto"))},600))});xt.push(ce);let Te=o.on("action:resubmit",()=>{setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)});xt.push(Te);let rt=()=>{Mt(!T,"user")},Ue=null,$e=null;if(b){let l=s.find(g=>g.renderLauncher);if(l!=null&&l.renderLauncher){let g=l.renderLauncher({config:n,defaultRenderer:()=>To(n,rt).element,onToggle:rt});g&&($e=g)}$e||(Ue=To(n,rt))}Ue?e.appendChild(Ue.element):$e&&e.appendChild($e),Er(),Bn.render(n.suggestionChips,H,K,void 0,n.suggestionChipsConfig),so(),Fr(H.isStreaming()),pr(!0),Wo(),S&&(b?T&&setTimeout(()=>Nr(),200):setTimeout(()=>Nr(),0));let Ht=()=>{var B,oe,be,ve,ye,je,W,Fe,we,me,We,gt,Ke,xe,Qt,ht,dn,nn,rn,Dt,pn,Ve;let l=Gt(n),g=(oe=(B=n.launcher)==null?void 0:B.sidebarMode)!=null?oe:!1,y=l||g||((ve=(be=n.launcher)==null?void 0:be.fullHeight)!=null?ve:!1),E=(ye=e.ownerDocument.defaultView)!=null?ye:window,k=(W=(je=n.launcher)==null?void 0:je.mobileFullscreen)!=null?W:!0,I=(we=(Fe=n.launcher)==null?void 0:Fe.mobileBreakpoint)!=null?we:640,P=E.innerWidth<=I,q=k&&P&&b;try{if(q){qn(),Ir(e,n);return}if(R&&(R=!1,qn(),Ir(e,n)),!b&&!l){U.style.height="",U.style.width="";return}if(!g&&!l){let yt=(We=(me=n==null?void 0:n.launcher)==null?void 0:me.width)!=null?We:n==null?void 0:n.launcherWidth,Pn=yt!=null?yt:"min(400px, calc(100vw - 24px))";U.style.width=Pn,U.style.maxWidth=Pn}if(Vn(),!y){let yt=E.innerHeight,Pn=64,ur=(Ke=(gt=n.launcher)==null?void 0:gt.heightOffset)!=null?Ke:0,er=Math.max(200,yt-Pn),gr=Math.min(640,er),tr=Math.max(200,gr-ur);U.style.height=`${tr}px`}}finally{if(Je(),Er(),T&&b){let Pn=((xe=e.ownerDocument.defaultView)!=null?xe:window).innerWidth<=((ht=(Qt=n.launcher)==null?void 0:Qt.mobileBreakpoint)!=null?ht:640),ur=(nn=(dn=n.launcher)==null?void 0:dn.sidebarMode)!=null?nn:!1,er=(Dt=(rn=n.launcher)==null?void 0:rn.mobileFullscreen)!=null?Dt:!0,gr=Gt(n)&&er&&Pn,tr=ur||er&&Pn&&b||gr;if(tr&&!Rt){let Or=e.getRootNode(),$r=Or instanceof ShadowRoot?Or.host:e.closest(".persona-host");$r&&!Wt&&(Wt=Ms($r,(Ve=(pn=n.launcher)==null?void 0:pn.zIndex)!=null?Ve:yn)),Rt=ks(e.ownerDocument)}else tr||(Wt==null||Wt(),Wt=null,Rt==null||Rt(),Rt=null)}}};Ht();let qt=(Na=e.ownerDocument.defaultView)!=null?Na:window;if(qt.addEventListener("resize",Ht),xt.push(()=>qt.removeEventListener("resize",Ht)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Je()});l.observe(et),xt.push(()=>l.disconnect())}An=z.scrollTop;let ft=()=>{let l=z.scrollTop,{action:g,nextLastScrollTop:y}=Go({following:gn.isFollowing(),currentScrollTop:l,lastScrollTop:An,nearBottom:Ao(z,to),userScrollThreshold:Rr,isAutoScrolling:Fn,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(An=y,g==="resume"){dr();return}g==="pause"&&oo()};z.addEventListener("scroll",ft,{passive:!0}),xt.push(()=>z.removeEventListener("scroll",ft));let vt=l=>{let g=Zo({following:gn.isFollowing(),deltaY:l.deltaY,nearBottom:Ao(z,to),resumeWhenNearBottom:!0});g==="pause"?oo():g==="resume"&&dr()};z.addEventListener("wheel",vt,{passive:!0}),xt.push(()=>z.removeEventListener("wheel",vt)),at.addEventListener("click",()=>{z.scrollTop=z.scrollHeight,An=z.scrollTop,dr(),pr(!0)}),xt.push(()=>at.remove()),xt.push(()=>{Dr()});let zt=()=>{ie&&(Sn&&(ie.removeEventListener("click",Sn),Sn=null),b?(ie.style.display="",Sn=()=>{Mt(!1,"user")},ie.addEventListener("click",Sn)):ie.style.display="none")};zt(),(()=>{let{clearChatButton:l}=re;l&&l.addEventListener("click",()=>{H.clearMessages(),kn.clear(),dr();try{localStorage.removeItem(Qr),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Qr}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Qr)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={},M.syncFromMetadata(),J==null||J.clear(),ae==null||ae.update()})})(),st&&st.addEventListener("submit",ao),K==null||K.addEventListener("keydown",io),K==null||K.addEventListener("paste",lo),xt.push(()=>{st&&st.removeEventListener("submit",ao),K==null||K.removeEventListener("keydown",io),K==null||K.removeEventListener("paste",lo)}),xt.push(()=>{H.cancel()}),Ue?xt.push(()=>{Ue==null||Ue.destroy()}):$e&&xt.push(()=>{$e==null||$e.remove()});let Ze={update(l){var qa,Ua,Ja,Ya,Ka,Xa,Ga,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,Ii,Pi,Wi,Ri,Hi,Bi,Di,Fi,Ni,Oi,$i,_i,ji,zi,Vi,qi,Ui,Ji,Yi,Ki,Xi,Gi,Zi,Qi,el,tl,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,gl,ml,fl,hl,yl,bl,xl,vl,Cl,wl,Sl,Al,El,Tl,Ml,kl,Ll,Il,Pl,Wl,Rl,Hl;let g=n.toolCall,y=n.messageActions,E=(qa=n.layout)==null?void 0:qa.messages,k=n.colorScheme,I=n.loadingIndicator,P=n.iterationDisplay;n={...n,...l},qn(),Ir(e,n),ns(e,n),rs(e,n),Cn(),n.colorScheme!==k&&lr();let q=os.getForInstance(n.plugins);s.length=0,s.push(...q),b=(Ja=(Ua=n.launcher)==null?void 0:Ua.enabled)!=null?Ja:!0,x=(Ka=(Ya=n.launcher)==null?void 0:Ya.autoExpand)!=null?Ka:!1,te=(Ga=(Xa=n.features)==null?void 0:Xa.showReasoning)!=null?Ga:!0,Ae=(Qa=(Za=n.features)==null?void 0:Za.showToolCalls)!=null?Qa:!0,Ce=(ti=(ei=n.features)==null?void 0:ei.scrollToBottom)!=null?ti:{},ut(),Zn();let B=ne;if(ne=(ri=(ni=n.features)==null?void 0:ni.showEventStreamToggle)!=null?ri:!1,ne&&!B){if(J||(fe=new Po(de),J=new Io(Se,fe),fe.open().then(()=>J==null?void 0:J.restore()).catch(()=>{}),H.setSSEEventCallback((V,it)=>{J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:V,timestamp:Date.now(),payload:JSON.stringify(it)})})),!Xe&&Qe){let V=(si=(oi=n.features)==null?void 0:oi.eventStream)==null?void 0:si.classNames,it="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(V!=null&&V.toggleButton?" "+V.toggleButton:"");Xe=f("button",it),Xe.style.width="28px",Xe.style.height="28px",Xe.style.color=bn.actionIconColor,Xe.type="button",Xe.setAttribute("aria-label","Event Stream"),Xe.title="Event Stream";let Lt=pe("activity","18px","currentColor",1.5);Lt&&Xe.appendChild(Lt);let ze=re.clearChatButtonWrapper,ct=re.closeButtonWrapper,Ut=ze||ct;Ut&&Ut.parentNode===Qe?Qe.insertBefore(Xe,Ut):Qe.appendChild(Xe),Xe.addEventListener("click",()=>{ge?Rn():Yn()})}}else!ne&&B&&(Rn(),Xe&&(Xe.remove(),Xe=null),J==null||J.clear(),fe==null||fe.destroy(),J=null,fe=null);if(((ai=n.launcher)==null?void 0:ai.enabled)===!1&&Ue&&(Ue.destroy(),Ue=null),((ii=n.launcher)==null?void 0:ii.enabled)===!1&&$e&&($e.remove(),$e=null),((li=n.launcher)==null?void 0:li.enabled)!==!1&&!Ue&&!$e){let V=s.find(it=>it.renderLauncher);if(V!=null&&V.renderLauncher){let it=V.renderLauncher({config:n,defaultRenderer:()=>To(n,rt).element,onToggle:rt});it&&($e=it,e.appendChild($e))}$e||(Ue=To(n,rt),e.appendChild(Ue.element))}Ue&&Ue.update(n),Et&&((ci=n.launcher)==null?void 0:ci.title)!==void 0&&(Et.textContent=n.launcher.title),Tt&&((di=n.launcher)==null?void 0:di.subtitle)!==void 0&&(Tt.textContent=n.launcher.subtitle);let oe=(pi=n.layout)==null?void 0:pi.header;if((oe==null?void 0:oe.layout)!==L&&Qe){let V=oe?Mo(n,oe,{showClose:b,onClose:()=>Mt(!1,"user")}):xr({config:n,showClose:b,onClose:()=>Mt(!1,"user")});Qe.replaceWith(V.header),Qe=V.header,ke=V.iconHolder,Et=V.headerTitle,Tt=V.headerSubtitle,ie=V.closeButton,L=oe==null?void 0:oe.layout}else if(oe&&(ke&&(ke.style.display=oe.showIcon===!1?"none":""),Et&&(Et.style.display=oe.showTitle===!1?"none":""),Tt&&(Tt.style.display=oe.showSubtitle===!1?"none":""),ie&&(ie.style.display=oe.showCloseButton===!1?"none":""),re.clearChatButtonWrapper)){let V=oe.showClearChat;if(V!==void 0){re.clearChatButtonWrapper.style.display=V?"":"none";let{closeButtonWrapper:it}=re;it&&!it.classList.contains("persona-absolute")&&(V?it.classList.remove("persona-ml-auto"):it.classList.add("persona-ml-auto"))}}let ve=((ui=n.layout)==null?void 0:ui.showHeader)!==!1;Qe&&(Qe.style.display=ve?"":"none");let ye=((gi=n.layout)==null?void 0:gi.showFooter)!==!1;et&&(et.style.display=ye?"":"none"),Je(),Zn(),b!==w?b?Mt(x,"auto"):(T=!0,Er()):x!==F&&Mt(x,"auto"),F=x,w=b,Ht(),zt();let Fe=JSON.stringify(l.toolCall)!==JSON.stringify(g),we=JSON.stringify(n.messageActions)!==JSON.stringify(y),me=JSON.stringify((mi=n.layout)==null?void 0:mi.messages)!==JSON.stringify(E),We=((fi=n.loadingIndicator)==null?void 0:fi.render)!==(I==null?void 0:I.render)||((hi=n.loadingIndicator)==null?void 0:hi.renderIdle)!==(I==null?void 0:I.renderIdle)||((yi=n.loadingIndicator)==null?void 0:yi.showBubble)!==(I==null?void 0:I.showBubble),gt=n.iterationDisplay!==P;(Fe||we||me||We||gt)&&H&&(cr++,Ar(Q,H.getMessages(),$));let xe=(bi=n.launcher)!=null?bi:{},Qt=(xi=xe.headerIconHidden)!=null?xi:!1,ht=(Ci=(vi=n.layout)==null?void 0:vi.header)==null?void 0:Ci.showIcon,dn=Qt||ht===!1,nn=xe.headerIconName,rn=(wi=xe.headerIconSize)!=null?wi:"48px";if(ke){let V=_.querySelector(".persona-border-b-persona-divider"),it=V==null?void 0:V.querySelector(".persona-flex-col");if(dn)ke.style.display="none",V&&it&&!V.contains(it)&&V.insertBefore(it,V.firstChild);else{if(ke.style.display="",ke.style.height=rn,ke.style.width=rn,V&&it&&(V.contains(ke)?ke.nextSibling!==it&&(ke.remove(),V.insertBefore(ke,it)):V.insertBefore(ke,it)),nn){let ze=parseFloat(rn)||24,ct=pe(nn,ze*.6,"#ffffff",2);ct?ke.replaceChildren(ct):ke.textContent=(Si=xe.agentIconText)!=null?Si:"\u{1F4AC}"}else if(xe.iconUrl){let ze=ke.querySelector("img");if(ze)ze.src=xe.iconUrl,ze.style.height=rn,ze.style.width=rn;else{let ct=document.createElement("img");ct.src=xe.iconUrl,ct.alt="",ct.className="persona-rounded-xl persona-object-cover",ct.style.height=rn,ct.style.width=rn,ke.replaceChildren(ct)}}else{let ze=ke.querySelector("svg"),ct=ke.querySelector("img");(ze||ct)&&ke.replaceChildren(),ke.textContent=(Ai=xe.agentIconText)!=null?Ai:"\u{1F4AC}"}let Lt=ke.querySelector("img");Lt&&(Lt.style.height=rn,Lt.style.width=rn)}}let Dt=(Ti=(Ei=n.layout)==null?void 0:Ei.header)==null?void 0:Ti.showTitle,pn=(ki=(Mi=n.layout)==null?void 0:Mi.header)==null?void 0:ki.showSubtitle;if(Et&&(Et.style.display=Dt===!1?"none":""),Tt&&(Tt.style.display=pn===!1?"none":""),ie){((Ii=(Li=n.layout)==null?void 0:Li.header)==null?void 0:Ii.showCloseButton)===!1?ie.style.display="none":ie.style.display="";let it=(Pi=xe.closeButtonSize)!=null?Pi:"32px",Lt=(Wi=xe.closeButtonPlacement)!=null?Wi:"inline";ie.style.height=it,ie.style.width=it;let{closeButtonWrapper:ze}=re,ct=Lt==="top-right",Ut=ze==null?void 0:ze.classList.contains("persona-absolute");if(ze&&ct!==Ut)if(ze.remove(),ct)ze.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",_.style.position="relative",_.appendChild(ze);else{let Ge=(Hi=(Ri=xe.clearChat)==null?void 0:Ri.placement)!=null?Hi:"inline",Xt=(Di=(Bi=xe.clearChat)==null?void 0:Bi.enabled)!=null?Di:!0;ze.className=Xt&&Ge==="inline"?"":"persona-ml-auto";let hn=_.querySelector(".persona-border-b-persona-divider");hn&&hn.appendChild(ze)}if(ie.style.color=xe.closeButtonColor||bn.actionIconColor,xe.closeButtonBackgroundColor?(ie.style.backgroundColor=xe.closeButtonBackgroundColor,ie.classList.remove("hover:persona-bg-gray-100")):(ie.style.backgroundColor="",ie.classList.add("hover:persona-bg-gray-100")),xe.closeButtonBorderWidth||xe.closeButtonBorderColor){let Ge=xe.closeButtonBorderWidth||"0px",Xt=xe.closeButtonBorderColor||"transparent";ie.style.border=`${Ge} solid ${Xt}`,ie.classList.remove("persona-border-none")}else ie.style.border="",ie.classList.add("persona-border-none");xe.closeButtonBorderRadius?(ie.style.borderRadius=xe.closeButtonBorderRadius,ie.classList.remove("persona-rounded-full")):(ie.style.borderRadius="",ie.classList.add("persona-rounded-full")),xe.closeButtonPaddingX?(ie.style.paddingLeft=xe.closeButtonPaddingX,ie.style.paddingRight=xe.closeButtonPaddingX):(ie.style.paddingLeft="",ie.style.paddingRight=""),xe.closeButtonPaddingY?(ie.style.paddingTop=xe.closeButtonPaddingY,ie.style.paddingBottom=xe.closeButtonPaddingY):(ie.style.paddingTop="",ie.style.paddingBottom="");let on=(Fi=xe.closeButtonIconName)!=null?Fi:"x",Nn=(Ni=xe.closeButtonIconText)!=null?Ni:"\xD7";ie.innerHTML="";let un=pe(on,"20px","currentColor",2);un?ie.appendChild(un):ie.textContent=Nn;let Ft=(Oi=xe.closeButtonTooltipText)!=null?Oi:"Close chat",Tn=($i=xe.closeButtonShowTooltip)!=null?$i:!0;if(ie.setAttribute("aria-label",Ft),ze&&(ze._cleanupTooltip&&(ze._cleanupTooltip(),delete ze._cleanupTooltip),Tn&&Ft)){let Ge=null,Xt=()=>{if(Ge||!ie)return;let Mr=ie.ownerDocument,uo=Mr.body;if(!uo)return;Ge=Un(Mr,"div","persona-clear-chat-tooltip"),Ge.textContent=Ft;let go=Un(Mr,"div");go.className="persona-clear-chat-tooltip-arrow",Ge.appendChild(go);let kr=ie.getBoundingClientRect();Ge.style.position="fixed",Ge.style.zIndex=String(yr),Ge.style.left=`${kr.left+kr.width/2}px`,Ge.style.top=`${kr.top-8}px`,Ge.style.transform="translate(-50%, -100%)",uo.appendChild(Ge)},hn=()=>{Ge&&Ge.parentNode&&(Ge.parentNode.removeChild(Ge),Ge=null)};ze.addEventListener("mouseenter",Xt),ze.addEventListener("mouseleave",hn),ie.addEventListener("focus",Xt),ie.addEventListener("blur",hn),ze._cleanupTooltip=()=>{hn(),ze&&(ze.removeEventListener("mouseenter",Xt),ze.removeEventListener("mouseleave",hn)),ie&&(ie.removeEventListener("focus",Xt),ie.removeEventListener("blur",hn))}}}let{clearChatButton:Ve,clearChatButtonWrapper:yt}=re;if(Ve){let V=(_i=xe.clearChat)!=null?_i:{},it=(ji=V.enabled)!=null?ji:!0,Lt=(Vi=(zi=n.layout)==null?void 0:zi.header)==null?void 0:Vi.showClearChat,ze=Lt!==void 0?Lt:it,ct=(qi=V.placement)!=null?qi:"inline";if(yt){yt.style.display=ze?"":"none";let{closeButtonWrapper:Ut}=re;Ut&&!Ut.classList.contains("persona-absolute")&&(ze?Ut.classList.remove("persona-ml-auto"):Ut.classList.add("persona-ml-auto"));let on=ct==="top-right",Nn=yt.classList.contains("persona-absolute");if(on!==Nn&&ze){if(yt.remove(),on)yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px",_.style.position="relative",_.appendChild(yt);else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let Ft=_.querySelector(".persona-border-b-persona-divider"),Tn=re.closeButtonWrapper;Ft&&Tn&&Tn.parentElement===Ft?Ft.insertBefore(yt,Tn):Ft&&Ft.appendChild(yt)}let un=re.closeButtonWrapper;un&&!un.classList.contains("persona-absolute")&&(on?un.classList.add("persona-ml-auto"):un.classList.remove("persona-ml-auto"))}}if(ze){let Ut=(Ui=V.size)!=null?Ui:"32px";Ve.style.height=Ut,Ve.style.width=Ut;let on=(Ji=V.iconName)!=null?Ji:"refresh-cw",Nn=(Yi=V.iconColor)!=null?Yi:"";Ve.style.color=Nn||bn.actionIconColor,Ve.innerHTML="";let un=pe(on,"20px","currentColor",2);if(un&&Ve.appendChild(un),V.backgroundColor?(Ve.style.backgroundColor=V.backgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),V.borderWidth||V.borderColor){let Ge=V.borderWidth||"0px",Xt=V.borderColor||"transparent";Ve.style.border=`${Ge} solid ${Xt}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");V.borderRadius?(Ve.style.borderRadius=V.borderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),V.paddingX?(Ve.style.paddingLeft=V.paddingX,Ve.style.paddingRight=V.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),V.paddingY?(Ve.style.paddingTop=V.paddingY,Ve.style.paddingBottom=V.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let Ft=(Ki=V.tooltipText)!=null?Ki:"Clear chat",Tn=(Xi=V.showTooltip)!=null?Xi:!0;if(Ve.setAttribute("aria-label",Ft),yt&&(yt._cleanupTooltip&&(yt._cleanupTooltip(),delete yt._cleanupTooltip),Tn&&Ft)){let Ge=null,Xt=()=>{if(Ge||!Ve)return;let Mr=Ve.ownerDocument,uo=Mr.body;if(!uo)return;Ge=Un(Mr,"div","persona-clear-chat-tooltip"),Ge.textContent=Ft;let go=Un(Mr,"div");go.className="persona-clear-chat-tooltip-arrow",Ge.appendChild(go);let kr=Ve.getBoundingClientRect();Ge.style.position="fixed",Ge.style.zIndex=String(yr),Ge.style.left=`${kr.left+kr.width/2}px`,Ge.style.top=`${kr.top-8}px`,Ge.style.transform="translate(-50%, -100%)",uo.appendChild(Ge)},hn=()=>{Ge&&Ge.parentNode&&(Ge.parentNode.removeChild(Ge),Ge=null)};yt.addEventListener("mouseenter",Xt),yt.addEventListener("mouseleave",hn),Ve.addEventListener("focus",Xt),Ve.addEventListener("blur",hn),yt._cleanupTooltip=()=>{hn(),yt&&(yt.removeEventListener("mouseenter",Xt),yt.removeEventListener("mouseleave",hn)),Ve&&(Ve.removeEventListener("focus",Xt),Ve.removeEventListener("blur",hn))}}}}let Pn=n.actionParsers&&n.actionParsers.length?n.actionParsers:[ss],ur=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Zr.message,Zr.messageAndClick];M=as({parsers:Pn,handlers:ur,getSessionMetadata:u,updateSessionMetadata:h,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),$=Hc(n,M,se),H.updateConfig(n),Ar(Q,H.getMessages(),$),Bn.render(n.suggestionChips,H,K,void 0,n.suggestionChipsConfig),so(),Fr(H.isStreaming());let er=((Gi=n.voiceRecognition)==null?void 0:Gi.enabled)===!0,gr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),tr=((Qi=(Zi=n.voiceRecognition)==null?void 0:Zi.provider)==null?void 0:Qi.type)==="runtype";if(er&&(gr||tr))if(!O||!Ee){let V=_t(n.voiceRecognition,n.sendButton);V&&(O=V.micButton,Ee=V.micButtonWrapper,tn.insertBefore(Ee,wt),O.addEventListener("click",N),O.disabled=H.isStreaming())}else{let V=(el=n.voiceRecognition)!=null?el:{},it=(tl=n.sendButton)!=null?tl:{},Lt=(nl=V.iconName)!=null?nl:"mic",ze=(rl=it.size)!=null?rl:"40px",ct=(ol=V.iconSize)!=null?ol:ze,Ut=parseFloat(ct)||24;O.style.width=ct,O.style.height=ct,O.style.minWidth=ct,O.style.minHeight=ct;let on=(al=(sl=V.iconColor)!=null?sl:it.textColor)!=null?al:"currentColor";O.innerHTML="";let Nn=pe(Lt,Ut,on,2);Nn?O.appendChild(Nn):O.textContent="\u{1F3A4}";let un=(il=V.backgroundColor)!=null?il:it.backgroundColor;un?O.style.backgroundColor=un:O.style.backgroundColor="",on?O.style.color=on:O.style.color="var(--persona-text, #111827)",V.borderWidth?(O.style.borderWidth=V.borderWidth,O.style.borderStyle="solid"):(O.style.borderWidth="",O.style.borderStyle=""),V.borderColor?O.style.borderColor=V.borderColor:O.style.borderColor="",V.paddingX?(O.style.paddingLeft=V.paddingX,O.style.paddingRight=V.paddingX):(O.style.paddingLeft="",O.style.paddingRight=""),V.paddingY?(O.style.paddingTop=V.paddingY,O.style.paddingBottom=V.paddingY):(O.style.paddingTop="",O.style.paddingBottom="");let Ft=Ee==null?void 0:Ee.querySelector(".persona-send-button-tooltip"),Tn=(ll=V.tooltipText)!=null?ll:"Start voice recognition";if(((cl=V.showTooltip)!=null?cl:!1)&&Tn)if(Ft)Ft.textContent=Tn,Ft.style.display="";else{let Xt=document.createElement("div");Xt.className="persona-send-button-tooltip",Xt.textContent=Tn,Ee==null||Ee.insertBefore(Xt,O)}else Ft&&(Ft.style.display="none");Ee.style.display="",O.disabled=H.isStreaming()}else O&&Ee&&(Ee.style.display="none",((pl=(dl=n.voiceRecognition)==null?void 0:dl.provider)==null?void 0:pl.type)==="runtype"?H.isVoiceActive()&&H.toggleVoice():En&&nt());if(((ul=n.attachments)==null?void 0:ul.enabled)===!0)if(!dt||!le){let V=(gl=n.attachments)!=null?gl:{},Lt=(fl=((ml=n.sendButton)!=null?ml:{}).size)!=null?fl:"40px";G||(G=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),G.style.display="none",st.insertBefore(G,K)),He||(He=document.createElement("input"),He.type="file",He.accept=((hl=V.allowedTypes)!=null?hl:nr).join(","),He.multiple=((yl=V.maxFiles)!=null?yl:4)>1,He.style.display="none",He.setAttribute("aria-label","Attach files"),st.insertBefore(He,K)),dt=f("div","persona-send-button-wrapper"),le=f("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",(bl=V.buttonTooltipText)!=null?bl:"Attach file");let ze=(xl=V.buttonIconName)!=null?xl:"paperclip",ct=Lt,Ut=parseFloat(ct)||40,on=Math.round(Ut*.6);le.style.width=ct,le.style.height=ct,le.style.minWidth=ct,le.style.minHeight=ct,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 Nn=pe(ze,on,"currentColor",1.5);Nn?le.appendChild(Nn):le.textContent="\u{1F4CE}",le.addEventListener("click",Tn=>{Tn.preventDefault(),He==null||He.click()}),dt.appendChild(le);let un=(vl=V.buttonTooltipText)!=null?vl:"Attach file",Ft=f("div","persona-send-button-tooltip");Ft.textContent=un,dt.appendChild(Ft),Zt.append(dt),!Ne&&He&&G&&(Ne=Ur.fromConfig(V),Ne.setPreviewsContainer(G),He.addEventListener("change",async()=>{Ne&&(He!=null&&He.files)&&(await Ne.handleFileSelect(He.files),He.value="")}))}else{dt.style.display="";let V=(Cl=n.attachments)!=null?Cl:{};He&&(He.accept=((wl=V.allowedTypes)!=null?wl:nr).join(","),He.multiple=((Sl=V.maxFiles)!=null?Sl:4)>1),Ne&&Ne.updateConfig({allowedTypes:V.allowedTypes,maxFileSize:V.maxFileSize,maxFiles:V.maxFiles})}else dt&&(dt.style.display="none"),Ne&&Ne.clearAttachments();let Vt=(Al=n.sendButton)!=null?Al:{},Fo=(El=Vt.useIcon)!=null?El:!1,co=(Tl=Vt.iconText)!=null?Tl:"\u2191",po=Vt.iconName,_r=(Ml=Vt.tooltipText)!=null?Ml:"Send message",No=(kl=Vt.showTooltip)!=null?kl:!1,mr=(Ll=Vt.size)!=null?Ll:"40px",Tr=Vt.backgroundColor,Kt=Vt.textColor;if(Fo){if(X.style.width=mr,X.style.height=mr,X.style.minWidth=mr,X.style.minHeight=mr,X.style.fontSize="18px",X.style.lineHeight="1",X.innerHTML="",Kt?X.style.color=Kt:X.style.color="var(--persona-button-primary-fg, #ffffff)",po){let V=parseFloat(mr)||24,it=(Kt==null?void 0:Kt.trim())||"currentColor",Lt=pe(po,V,it,2);Lt?X.appendChild(Lt):X.textContent=co}else X.textContent=co;X.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Tr?(X.style.backgroundColor=Tr,X.classList.remove("persona-bg-persona-primary")):(X.style.backgroundColor="",X.classList.add("persona-bg-persona-primary"))}else X.textContent=(Pl=(Il=n.copy)==null?void 0:Il.sendButtonLabel)!=null?Pl:"Send",X.style.width="",X.style.height="",X.style.minWidth="",X.style.minHeight="",X.style.fontSize="",X.style.lineHeight="",X.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",Tr?(X.style.backgroundColor=Tr,X.classList.remove("persona-bg-persona-accent")):X.classList.add("persona-bg-persona-accent"),Kt?X.style.color=Kt:X.classList.add("persona-text-white");Vt.borderWidth?(X.style.borderWidth=Vt.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),Vt.borderColor?X.style.borderColor=Vt.borderColor:X.style.borderColor="",Vt.paddingX?(X.style.paddingLeft=Vt.paddingX,X.style.paddingRight=Vt.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),Vt.paddingY?(X.style.paddingTop=Vt.paddingY,X.style.paddingBottom=Vt.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let fn=wt==null?void 0:wt.querySelector(".persona-send-button-tooltip");if(No&&_r)if(fn)fn.textContent=_r,fn.style.display="";else{let V=document.createElement("div");V.className="persona-send-button-tooltip",V.textContent=_r,wt==null||wt.insertBefore(V,X)}else fn&&(fn.style.display="none");let fr=(Wl=n.layout)==null?void 0:Wl.contentMaxWidth;fr?(Q.style.maxWidth=fr,Q.style.marginLeft="auto",Q.style.marginRight="auto",Q.style.width="100%",st&&(st.style.maxWidth=fr,st.style.marginLeft="auto",st.style.marginRight="auto")):(Q.style.maxWidth="",Q.style.marginLeft="",Q.style.marginRight="",Q.style.width="",st&&(st.style.maxWidth="",st.style.marginLeft="",st.style.marginRight=""));let hr=(Rl=n.statusIndicator)!=null?Rl:{},fd=(Hl=hr.visible)!=null?Hl:!0;if(Pt.style.display=fd?"":"none",H){let V=H.getStatus();At(Pt,(Lt=>{var ze,ct,Ut,on;return Lt==="idle"?(ze=hr.idleText)!=null?ze:sn.idle:Lt==="connecting"?(ct=hr.connectingText)!=null?ct:sn.connecting:Lt==="connected"?(Ut=hr.connectedText)!=null?Ut:sn.connected:Lt==="error"?(on=hr.errorText)!=null?on:sn.error:sn[Lt]})(V),hr,V)}Pt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let hd=hr.align==="left"?"persona-text-left":hr.align==="center"?"persona-text-center":"persona-text-right";Pt.classList.add(hd)},open(){b&&Mt(!0,"api")},close(){b&&Mt(!1,"api")},toggle(){b&&Mt(!T,"api")},clearChat(){an=!1,H.clearMessages(),kn.clear(),dr();try{localStorage.removeItem(Qr),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Qr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Qr)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={},M.syncFromMetadata(),J==null||J.clear(),ae==null||ae.update()},setMessage(l){return!K||H.isStreaming()?!1:(!T&&b&&Mt(!0,"system"),K.value=l,K.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(H.isStreaming())return!1;let g=(l==null?void 0:l.trim())||K.value.trim();return g?(!T&&b&&Mt(!0,"system"),K.value="",K.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()||(!T&&b&&Mt(!0,"system"),Ye.manuallyDeactivated=!1,mn(),H.toggleVoice().then(()=>{Ye.active=H.isVoiceActive(),Ln("user"),H.isVoiceActive()&&v()})),!0):En?!0:Z()?(!T&&b&&Mt(!0,"system"),Ye.manuallyDeactivated=!1,mn(),qe("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(()=>{Ye.active=!1,Ye.manuallyDeactivated=!0,mn(),Ln("user"),A()}),!0):!1:En?(Ye.manuallyDeactivated=!0,mn(),nt("user"),!0):!1},injectMessage(l){return!T&&b&&Mt(!0,"system"),H.injectMessage(l)},injectAssistantMessage(l){!T&&b&&Mt(!0,"system");let g=H.injectAssistantMessage(l);return Y&&(Y=!1,ue&&(clearTimeout(ue),ue=null),setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)),g},injectUserMessage(l){return!T&&b&&Mt(!0,"system"),H.injectUserMessage(l)},injectSystemMessage(l){return!T&&b&&Mt(!0,"system"),H.injectSystemMessage(l)},injectMessageBatch(l){return!T&&b&&Mt(!0,"system"),H.injectMessageBatch(l)},injectTestMessage(l){!T&&b&&Mt(!0,"system"),H.injectTestEvent(l)},async connectStream(l,g){return H.connectStream(l,g)},__pushEventStreamEvent(l){J&&J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!ne||!J||Yn()},hideEventStream(){ge&&Rn()},isEventStreamVisible(){return ge},showArtifacts(){Wn(n)&&(an=!1,Cn(),tt==null||tt.setMobileOpen(!0))},hideArtifacts(){Wn(n)&&(an=!0,Cn())},upsertArtifact(l){return Wn(n)?(an=!1,H.upsertArtifact(l)):null},selectArtifact(l){Wn(n)&&H.selectArtifact(l)},clearArtifacts(){Wn(n)&&H.clearArtifacts()},focusInput(){return b&&!T||!K?!1:(K.focus(),!0)},async resolveApproval(l,g){let E=H.getMessages().find(k=>{var I;return k.variant==="approval"&&((I=k.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){h(l)},on(l,g){return o.on(l,g)},off(l,g){o.off(l,g)},isOpen(){return b&&T},isVoiceActive(){return Ye.active},getState(){return{open:b&&T,launcherEnabled:b,voiceActive:Ye.active,streaming:H.isStreaming()}},showCSATFeedback(l){!T&&b&&Mt(!0,"system");let g=Q.querySelector(".persona-feedback-container");g&&g.remove();let y=qs({onSubmit:async(E,k)=>{var I;H.isClientTokenMode()&&await H.submitCSATFeedback(E,k),(I=l==null?void 0:l.onSubmit)==null||I.call(l,E,k)},onDismiss:l==null?void 0:l.onDismiss,...l});Q.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!T&&b&&Mt(!0,"system");let g=Q.querySelector(".persona-feedback-container");g&&g.remove();let y=Us({onSubmit:async(E,k)=>{var I;H.isClientTokenMode()&&await H.submitNPSFeedback(E,k),(I=l==null?void 0:l.onSubmit)==null||I.call(l,E,k)},onDismiss:l==null?void 0:l.onDismiss,...l});Q.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(){xt.forEach(l=>l()),j.remove(),Ue==null||Ue.destroy(),$e==null||$e.remove(),Sn&&ie.removeEventListener("click",Sn)}};if((((Oa=t==null?void 0:t.debugTools)!=null?Oa:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,g={controller:Ze,getMessages:Ze.getMessages,getStatus:Ze.getStatus,getMetadata:Ze.getPersistentMetadata,updateMetadata:Ze.updatePersistentMetadata,clearHistory:()=>Ze.clearChat(),setVoiceActive:y=>y?Ze.startVoiceRecognition():Ze.stopVoiceRecognition()};window.AgentWidgetBrowser=g,xt.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=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&Ze.focusInput()};if(window.addEventListener("persona:focusInput",g),xt.push(()=>{window.removeEventListener("persona:focusInput",g)}),ne){let q=oe=>{let be=oe.detail;(!(be!=null&&be.instanceId)||be.instanceId===l)&&Ze.showEventStream()},B=oe=>{let be=oe.detail;(!(be!=null&&be.instanceId)||be.instanceId===l)&&Ze.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",B),xt.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",B)})}let y=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&Ze.showArtifacts()},E=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&Ze.hideArtifacts()},k=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==l||B!=null&&B.artifact&&Ze.upsertArtifact(B.artifact)},I=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==l||typeof(B==null?void 0:B.id)=="string"&&Ze.selectArtifact(B.id)},P=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&Ze.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",E),window.addEventListener("persona:upsertArtifact",k),window.addEventListener("persona:selectArtifact",I),window.addEventListener("persona:clearArtifacts",P),xt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",E),window.removeEventListener("persona:upsertArtifact",k),window.removeEventListener("persona:selectArtifact",I),window.removeEventListener("persona:clearArtifacts",P)})}let Bt=_p(n.persistState);if(Bt&&b){let l=jp(Bt.storage),g=`${Bt.keyPrefix}widget-open`,y=`${Bt.keyPrefix}widget-voice`,E=`${Bt.keyPrefix}widget-voice-mode`;if(l){let k=(($a=Bt.persist)==null?void 0:$a.openState)&&l.getItem(g)==="true",I=((_a=Bt.persist)==null?void 0:_a.voiceState)&&l.getItem(y)==="true",P=((ja=Bt.persist)==null?void 0:ja.voiceState)&&l.getItem(E)==="true";if(k&&setTimeout(()=>{Ze.open(),setTimeout(()=>{var q;if(I||P)Ze.startVoiceRecognition();else if((q=Bt.persist)!=null&&q.focusInput){let B=e.querySelector("textarea");B&&B.focus()}},100)},0),(za=Bt.persist)!=null&&za.openState&&(o.on("widget:opened",()=>{l.setItem(g,"true")}),o.on("widget:closed",()=>{l.setItem(g,"false")})),(Va=Bt.persist)!=null&&Va.voiceState&&(o.on("voice:state",q=>{l.setItem(y,q.active?"true":"false")}),o.on("user:message",q=>{l.setItem(E,q.viaVoice?"true":"false")})),Bt.clearOnChatClear){let q=()=>{l.removeItem(g),l.removeItem(y),l.removeItem(E)},B=()=>q();window.addEventListener("persona:clear-chat",B),xt.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return c&&b&&setTimeout(()=>{Ze.open()},0),Ze};var zp=(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},Bc=(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"},Zs=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=""},Dc=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Zs(e)},Ks=e=>{e.style.transition=""},Xs=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=""},Gs=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},is=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},Vp=(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))},qp=(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)},Fc=(e,r,t,n,s,o,a)=>{var C,M,b,x,S,F;let i=On(o),d=i.reveal==="push";Vp(e,r,t,n,d),qp(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,p=(M=(C=o==null?void 0:o.launcher)==null?void 0:C.mobileFullscreen)!=null?M:!0,u=(x=(b=o==null?void 0:o.launcher)==null?void 0:b.mobileBreakpoint)!=null?x:640,h=c!=null?c.innerWidth<=u:!1;if(p&&h&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Xs(r),Ks(n),Dc(n),Gs(t),is(s,n),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((F=(S=o==null?void 0:o.launcher)==null?void 0:S.zIndex)!=null?F:yn),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"),Dc(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Xs(r),Ks(n),Gs(t),is(s,n);let w=i.animate?"transform 180ms ease":"none",L=i.side==="right"?"translateX(100%)":"translateX(-100%)",R=a?"translateX(0)":L;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=w,n.style.transform=R,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",Ks(n),Zs(n),is(s,n);let w=zp(i.width,e.clientWidth),L=Math.max(0,e.clientWidth),R=i.animate?"transform 180ms ease":"none",T=i.side==="right"?a?`translateX(-${w}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${w}px)`;r.style.display="flex",r.style.flexDirection="row",r.style.flex="0 0 auto",r.style.minHeight="0",r.style.minWidth="0",r.style.alignItems="stretch",r.style.height="100%",r.style.width=`${L+w}px`,r.style.transition=R,r.style.transform=T,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${L}px`,t.style.maxWidth=`${L}px`,t.style.minWidth=`${L}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Xs(r),Zs(n),Gs(t),is(s,n);let w=i.reveal==="emerge";w?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let L=a?i.width:"0px",R=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",T=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${L}`,n.style.width=L,n.style.maxWidth=L,n.style.minWidth=L,n.style.minHeight="0",n.style.position="relative",n.style.overflow=w||T?"hidden":"visible",n.style.transition=R,w&&(n.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},Up=(e,r)=>{let t=e.ownerDocument.createElement("div");return Bc(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){Bc(t,n)},destroy(){t.remove()}}},Jp=(e,r)=>{var S,F,w,L;let{ownerDocument:t}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),c=t.createElement("aside"),p=t.createElement("div"),u=(F=(S=r==null?void 0:r.launcher)==null?void 0:S.enabled)==null||F?(L=(w=r==null?void 0:r.launcher)==null?void 0:w.autoExpand)!=null?L:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),n.insertBefore(a,e),d.appendChild(e);let h=null,m=()=>{h==null||h.disconnect(),h=null},C=()=>{m(),On(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(h=new ResizeObserver(()=>{Fc(a,i,d,c,p,r,u)}),h.observe(a))},M=()=>{Fc(a,i,d,c,p,r,u),C()},b=a.ownerDocument.defaultView,x=()=>{M()};return b==null||b.addEventListener("resize",x),On(r).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),M(),{mode:"docked",host:p,shell:a,syncWidgetState(R){let T=R.launcherEnabled?R.open:!0;u!==T&&(u=T,M())},updateConfig(R){var T,Y;r=R,((Y=(T=r==null?void 0:r.launcher)==null?void 0:T.enabled)!=null?Y:!0)===!1&&(u=!0),M()},destroy(){b==null||b.removeEventListener("resize",x),m(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},ls=(e,r)=>Gt(r)?Jp(e,r):Up(e,r);var Qs={},Yp=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},Kp=()=>{try{if(typeof Qs!="undefined"&&Qs.url)return new URL("../widget.css",Qs.url).href}catch{}return null},Nc=(e,r)=>{let t=Kp(),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)}},Oc=e=>{var b;let r=Yp(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=ls(r,s),a,i=[],d=(x,S)=>{var R,T;let w=!((T=(R=S==null?void 0:S.launcher)==null?void 0:R.enabled)!=null?T:!0)||Gt(S),L=n.createElement("div");if(L.setAttribute("data-persona-root","true"),w&&(L.style.height="100%",L.style.display="flex",L.style.flexDirection="column",L.style.flex="1",L.style.minHeight="0"),t){let Y=x.attachShadow({mode:"open"});Y.appendChild(L),Nc(Y,n)}else x.appendChild(L),Nc(x,n);return r.id&&L.setAttribute("data-persona-instance",r.id),L},c=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(x=>x()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},u=()=>{let x=d(o.host,s);a=Ys(x,s,{debugTools:e.debugTools}),p()},h=()=>{i.forEach(x=>x()),i=[],a.destroy()};u(),(b=e.onReady)==null||b.call(e);let m=x=>{h(),o.destroy(),o=ls(r,x),s=x,u()},C={update(x){var L,R,T,Y,ue,se;let S={...s,...x,launcher:{...(L=s==null?void 0:s.launcher)!=null?L:{},...(R=x==null?void 0:x.launcher)!=null?R:{},dock:{...(Y=(T=s==null?void 0:s.launcher)==null?void 0:T.dock)!=null?Y:{},...(se=(ue=x==null?void 0:x.launcher)==null?void 0:ue.dock)!=null?se:{}}}},F=Gt(s),w=Gt(S);if(F!==w){m(S);return}s=S,o.updateConfig(s),a.update(x),c()},destroy(){h(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},M=new Proxy(C,{get(x,S,F){if(S==="host")return o.host;if(S in x)return Reflect.get(x,S,F);let w=a[S];return typeof w=="function"?w.bind(a):w}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=M),M};var Vc=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Xp=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"]),ea=/\b(product|card|item|listing|result)\b/i,na=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Zp=3e3,Qp=100;function qc(e){let r=typeof e.className=="string"?e.className:"";if(ea.test(r)||e.id&&ea.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&ea.test(n.value))return!0}return!1}function Uc(e){var r;return na.test(((r=e.textContent)!=null?r:"").trim())}function Jc(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 eu(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function $c(e){let r=e.match(na);return r?r[0]:null}function _c(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 tu(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 nu="commerce-card",ru="result-card";function jc(e){return!qc(e)||!Uc(e)||!Jc(e)&&!eu(e)?0:5200}function zc(e){var n;return!qc(e)||Uc(e)||!Jc(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 Yc=[{id:nu,scoreElement(e){return jc(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||na.test(n)&&n.length<32)}return!0},formatSummary(e,r){var d,c,p;if(jc(e)===0)return null;let{title:t,href:n}=_c(e),s=(p=(c=$c(((d=e.textContent)!=null?d:"").trim()))!=null?c:$c(r.text))!=null?p:"",o=tu(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(`
98
- `)}},{id:ru,scoreElement(e){return zc(e)},formatSummary(e,r){if(zc(e)===0)return null;let{title:t,href:n}=_c(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
99
- `)}}];function ou(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function su(e){var p,u,h,m,C,M,b,x,S,F,w,L,R;let r=(p=e.options)!=null?p:{},t=(h=(u=r.maxElements)!=null?u:e.maxElements)!=null?h:80,n=(C=(m=r.excludeSelector)!=null?m:e.excludeSelector)!=null?C:".persona-host",s=(b=(M=r.maxTextLength)!=null?M:e.maxTextLength)!=null?b:200,o=(S=(x=r.visibleOnly)!=null?x:e.visibleOnly)!=null?S:!0,a=(F=r.root)!=null?F:e.root,i=(w=r.mode)!=null?w:"structured",d=(L=r.maxCandidates)!=null?L:Math.max(500,t*10),c=(R=e.rules)!=null?R:Yc;return i==="simple"&&e.rules&&e.rules.length>0?(ou(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:n,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function ta(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var au=["data-testid","data-product","data-action","data-id","data-name","data-type"];function iu(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"||Xp.has(r)||t&&Gp.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Kc(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 lu(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 p=e.attributes[c];p.name.startsWith("data-")&&(r[p.name]=p.value)}return r}function Xc(e){let r=e.tagName.toLowerCase();if(e.id){let s=`#${ta(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of au){let o=e.getAttribute(s);if(o){let a=`${r}[${s}="${ta(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=>ta(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 cu(e){return e==="static"?Qp:Zp}function Gc(e,r){var s;let t=e.tagName.toLowerCase(),n=((s=e.textContent)!=null?s:"").trim().substring(0,r);return{selector:Xc(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:iu(e),attributes:lu(e)}}function du(e,r,t,n){let s=cu(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 pu(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 uu(e,r){let t={doc:r.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,s=[],o=0,a=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,p=c.tagName.toLowerCase();if(Vc.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Kc(c)){i=a.nextNode();continue}let u=Gc(c,e.maxTextLength),h=u.text.length>0,m=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(b=>b==="role");if(!h&&!m){i=a.nextNode();continue}if(n.has(u.selector)){i=a.nextNode();continue}n.add(u.selector);let{score:C,formattingRule:M}=du(c,u,e.rules,t);s.push({el:c,domIndex:o,enriched:u,score:C,formattingRule:M}),o+=1}i=a.nextNode()}s.sort((c,p)=>{let u=c.enriched.interactivity==="static"?1:0,h=p.enriched.interactivity==="static"?1:0;return u!==h?u-h:p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex});let d=[];for(let c of s){if(d.length>=e.maxElements)break;pu(d,c)||d.push(c)}return d.sort((c,p)=>{let u=c.enriched.interactivity==="static"?1:0,h=p.enriched.interactivity==="static"?1:0;return u!==h?u-h:u===1&&p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex}),d.map(c=>{var h;let p;if((h=c.formattingRule)!=null&&h.formatSummary){let m=c.formattingRule.formatSummary(c.el,c.enriched,t);m&&(p=m)}let u={...c.enriched};return p&&(u.formattedSummary=p),u})}function gu(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(Vc.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Kc(d)){o=s.nextNode();continue}let p=Gc(d,e.maxTextLength),u=p.text.length>0,h=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(m=>m==="role");if(!u&&!h){o=s.nextNode();continue}n.has(p.selector)||(n.add(p.selector),t.push(p))}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 mu(e={}){var n;let r=su(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?gu(r,t):uu(r,t):[]}var cs=100;function fu(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:
97
+ `}if(!E&&!l){let qt="max-height: -moz-available !important; max-height: stretch !important;",fn=g?"":"padding-top: 1.25em !important;",or=g?"":`z-index: ${(Lr=(yr=n.launcher)==null?void 0:yr.zIndex)!=null?Lr:yn} !important;`;j.style.cssText+=qt+fn+or}};Jn(),Rr(e,n),as(e,n),is(e,n);let ht=[],Wt=null,Rt=null;ht.push(()=>{Wt==null||Wt(),Wt=null,Rt==null||Rt(),Rt=null}),xn&&ht.push(()=>{xn==null||xn.disconnect(),xn=null}),ht.push(()=>{ln==null||ln(),ln=null,Zn(),ft&&(ft.remove(),ft=null),et==null||et.element.style.removeProperty("width"),et==null||et.element.style.removeProperty("maxWidth")}),ne&&ht.push(()=>{ge!==null&&(cancelAnimationFrame(ge),ge=null),be==null||be.destroy(),be=null,re==null||re.destroy(),re=null,Me=null});let wn=null,pr=()=>{wn&&(wn(),wn=null),n.colorScheme==="auto"&&(wn=Ws(()=>{Rr(e,n)}))};pr(),ht.push(()=>{wn&&(wn(),wn=null)});let Fn=wc(Fe),Sn=null,D,Nn=!1,Ln=lc(),ur=0,gn=es(),An=0,ee=null,On=!1,Dr=1,oo=8,Fr=new Map,Je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},so=(Fa=(Da=n.voiceRecognition)==null?void 0:Da.autoResume)!=null?Fa:!1,In=l=>{o.emit("voice:state",{active:Je.active,source:l,timestamp:Date.now()})},mn=()=>{f(l=>({...l,voiceState:{active:Je.active,timestamp:Date.now(),manuallyDeactivated:Je.manuallyDeactivated}}))},Do=()=>{var E,k;if(((E=n.voiceRecognition)==null?void 0:E.enabled)===!1)return;let l=Zs(i.voiceState),g=!!l.active,y=Number((k=l.timestamp)!=null?k:0);Je.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-y<$p&&setTimeout(()=>{var P,W;Je.active||(Je.manuallyDeactivated=!1,((W=(P=n.voiceRecognition)==null?void 0:P.provider)==null?void 0:W.type)==="runtype"?D.toggleVoice().then(()=>{Je.active=D.isVoiceActive(),In("restore"),D.isVoiceActive()&&Pt()}):kr("restore"))},1e3)},Fo=()=>D?Bc(D.getMessages()).filter(l=>!l.__skipPersist):[];function ao(l){if(!(a!=null&&a.save))return;let y={messages:l?Bc(l):D?Fo():[],metadata:i};try{let E=a.save(y);E instanceof Promise&&E.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",E)}}let Qn=null,No=()=>j.querySelector("#persona-scroll-container")||z,Nr=()=>{Qn!==null&&(cancelAnimationFrame(Qn),Qn=null),On=!1},Or=()=>{ee!==null&&(cancelAnimationFrame(ee),ee=null),Nr()},er=()=>{if(!Ot()||$e){nt.parentNode&&nt.remove(),nt.style.display="none";return}nt.parentNode!==_&&_.appendChild(nt),qe();let l=Mo(z)>0;nt.style.display=gn.isFollowing()||!l?"none":""},io=()=>{gn.pause()&&(Or(),er())},gr=()=>{gn.resume(),er()},mr=(l=!1)=>{gn.isFollowing()&&(!l&&!Nn||(Or(),ee=requestAnimationFrame(()=>{ee=null,gn.isFollowing()&&Oo(No(),l?220:140)})))},Oo=(l,g=500)=>{let y=l.scrollTop,E=Mo(l),k=E-y;if(Math.abs(k)<1){An=l.scrollTop;return}Nr();let P=performance.now();On=!0;let W=F=>1-Math.pow(1-F,3),V=F=>{if(!gn.isFollowing()){Nr();return}let ae=Mo(l);ae!==E&&(E=ae,k=E-y);let ve=F-P,we=Math.min(ve/g,1),xe=W(we),ze=y+k*xe;l.scrollTop=ze,An=l.scrollTop,we<1?Qn=requestAnimationFrame(V):(l.scrollTop=E,An=l.scrollTop,Qn=null,On=!1)};Qn=requestAnimationFrame(V)},$o=l=>{let g=new Map;l.forEach(y=>{let E=Fr.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}))}),Fr.clear(),g.forEach((y,E)=>{Fr.set(E,y)})},Tr=(l,g,y)=>{var ve,we,xe,ze;let E=document.createElement("div"),P=(()=>{var Oe;let H=s.find(Ee=>Ee.renderLoadingIndicator);if(H!=null&&H.renderLoadingIndicator)return H.renderLoadingIndicator;if((Oe=n.loadingIndicator)!=null&&Oe.render)return n.loadingIndicator.render})(),W=new Set;g.forEach(H=>{var Ce,Xt;W.add(H.id);let Oe=ic(H,ur),Ee=cc(Ln,H.id,Oe);if(Ee){E.appendChild(Ee.cloneNode(!0));return}let fe=null,Re=s.find(gt=>!!(H.variant==="reasoning"&&gt.renderReasoning||H.variant==="tool"&&gt.renderToolCall||H.variant==="approval"&&gt.renderApproval||!H.variant&&gt.renderMessage)),ct=(Ce=n.layout)==null?void 0:Ce.messages;if(Re)if(H.variant==="reasoning"&&H.reasoning&&Re.renderReasoning){if(!te)return;fe=Re.renderReasoning({message:H,defaultRenderer:()=>Fs(H),config:n})}else if(H.variant==="tool"&&H.toolCall&&Re.renderToolCall){if(!Te)return;fe=Re.renderToolCall({message:H,defaultRenderer:()=>Ns(H,n),config:n})}else if(H.variant==="approval"&&H.approval&&Re.renderApproval){if(n.approval===!1)return;fe=Re.renderApproval({message:H,defaultRenderer:()=>Os(H,n),config:n})}else Re.renderMessage&&(fe=Re.renderMessage({message:H,defaultRenderer:()=>{let gt=Ro(H,y,ct,n.messageActions,oe,{loadingIndicatorRenderer:P,widgetConfig:n});return H.role!=="user"&&js(gt,H,n,D),gt},config:n}));if(!fe&&H.role==="assistant"&&!H.variant&&n.enableComponentStreaming!==!1&&Ys(H)){let dn=Gs(H);if(dn){let nn=Js(dn,{config:n,message:H,transform:y});if(nn)if(n.wrapComponentDirectiveInBubble!==!1){let Ft=document.createElement("div");if(Ft.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ft.id=`bubble-${H.id}`,Ft.setAttribute("data-message-id",H.id),H.content&&H.content.trim()){let pn=document.createElement("div");pn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",pn.innerHTML=y({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),Ft.appendChild(pn)}Ft.appendChild(nn),fe=Ft}else{let Ft=document.createElement("div");if(Ft.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ft.id=`bubble-${H.id}`,Ft.setAttribute("data-message-id",H.id),Ft.setAttribute("data-persona-component-directive","true"),H.content&&H.content.trim()){let pn=document.createElement("div");pn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",pn.innerHTML=y({text:H.content,message:H,streaming:!!H.streaming,raw:H.rawContent}),Ft.appendChild(pn)}Ft.appendChild(nn),fe=Ft}}}if(!fe)if(H.variant==="reasoning"&&H.reasoning){if(!te)return;fe=Fs(H)}else if(H.variant==="tool"&&H.toolCall){if(!Te)return;fe=Ns(H,n)}else if(H.variant==="approval"&&H.approval){if(n.approval===!1)return;fe=Os(H,n)}else{let gt=(Xt=n.layout)==null?void 0:Xt.messages;gt!=null&&gt.renderUserMessage&&H.role==="user"?fe=gt.renderUserMessage({message:H,config:n,streaming:!!H.streaming}):gt!=null&&gt.renderAssistantMessage&&H.role==="assistant"?fe=gt.renderAssistantMessage({message:H,config:n,streaming:!!H.streaming}):fe=Ro(H,y,gt,n.messageActions,oe,{loadingIndicatorRenderer:P,widgetConfig:n}),H.role!=="user"&&fe&&js(fe,H,n,D)}let Ge=document.createElement("div");Ge.className="persona-flex",Ge.id=`wrapper-${H.id}`,Ge.setAttribute("data-wrapper-id",H.id),H.role==="user"&&Ge.classList.add("persona-justify-end"),(fe==null?void 0:fe.getAttribute("data-persona-component-directive"))==="true"&&Ge.classList.add("persona-w-full"),Ge.appendChild(fe),dc(Ln,H.id,Oe,Ge),E.appendChild(Ge)}),pc(Ln,W);let V=g.some(H=>H.role==="assistant"&&H.streaming),F=g[g.length-1],ae=(F==null?void 0:F.role)==="assistant"&&!F.streaming&&F.variant!=="approval";if(Nn&&g.some(H=>H.role==="user")&&!V&&!ae){let H={config:n,streaming:!0,location:"standalone",defaultRenderer:Kr},Oe=s.find(fe=>fe.renderLoadingIndicator),Ee=null;if(Oe!=null&&Oe.renderLoadingIndicator&&(Ee=Oe.renderLoadingIndicator(H)),Ee===null&&((ve=n.loadingIndicator)!=null&&ve.render)&&(Ee=n.loadingIndicator.render(H)),Ee===null&&(Ee=Kr()),Ee){let fe=document.createElement("div"),Re=((we=n.loadingIndicator)==null?void 0:we.showBubble)!==!1;fe.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-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),fe.setAttribute("data-typing-indicator","true"),fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",fe.appendChild(Ee);let ct=document.createElement("div");ct.className="persona-flex",ct.id="wrapper-typing-indicator",ct.setAttribute("data-wrapper-id","typing-indicator"),ct.appendChild(fe),E.appendChild(ct)}}if(!Nn&&g.length>0){let H=g[g.length-1],Oe={config:n,lastMessage:H,messageCount:g.length},Ee=s.find(Re=>Re.renderIdleIndicator),fe=null;if(Ee!=null&&Ee.renderIdleIndicator&&(fe=Ee.renderIdleIndicator(Oe)),fe===null&&((xe=n.loadingIndicator)!=null&&xe.renderIdle)&&(fe=n.loadingIndicator.renderIdle(Oe)),fe){let Re=document.createElement("div"),ct=((ze=n.loadingIndicator)==null?void 0:ze.showBubble)!==!1;Re.className=ct?["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(fe);let Ge=document.createElement("div");Ge.className="persona-flex",Ge.id="wrapper-idle-indicator",Ge.setAttribute("data-wrapper-id","idle-indicator"),Ge.appendChild(Re),E.appendChild(Ge)}}ac(l,E)},Mr=()=>{var F,ae,ve,we,xe;if(!b)return;let l=Yt(n),g=(F=e.ownerDocument.defaultView)!=null?F:window,y=(ve=(ae=n.launcher)==null?void 0:ae.mobileBreakpoint)!=null?ve:640,E=(xe=(we=n.launcher)==null?void 0:we.mobileFullscreen)!=null?xe:!0,k=g.innerWidth<=y,P=E&&k&&b,W=jn(n).reveal;T?(j.style.removeProperty("display"),j.style.display=l?"flex":"",j.classList.remove("persona-pointer-events-none","persona-opacity-0"),q.classList.remove("persona-scale-95","persona-opacity-0"),q.classList.add("persona-scale-100","persona-opacity-100"),N?N.element.style.display="none":ie&&(ie.style.display="none")):(l?l&&(W==="overlay"||W==="push")&&!P?(j.style.removeProperty("display"),j.style.display="flex",j.classList.remove("persona-pointer-events-none","persona-opacity-0"),q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(j.style.setProperty("display","none","important"),j.classList.remove("persona-pointer-events-none","persona-opacity-0"),q.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(j.style.display="",j.classList.add("persona-pointer-events-none","persona-opacity-0"),q.classList.remove("persona-scale-100","persona-opacity-100"),q.classList.add("persona-scale-95","persona-opacity-0")),N?N.element.style.display=l?"none":"":ie&&(ie.style.display=l?"none":""))},Et=(l,g="user")=>{var P,W;if(!b||T===l)return;let y=T;T=l,Mr();let E=(()=>{var ze,H,Oe,Ee,fe,Re,ct;let V=(H=(ze=n.launcher)==null?void 0:ze.sidebarMode)!=null?H:!1,F=(Oe=e.ownerDocument.defaultView)!=null?Oe:window,ae=(fe=(Ee=n.launcher)==null?void 0:Ee.mobileFullscreen)!=null?fe:!0,ve=(ct=(Re=n.launcher)==null?void 0:Re.mobileBreakpoint)!=null?ct:640,we=F.innerWidth<=ve,xe=Yt(n)&&ae&&we;return V||ae&&we&&b||xe})();if(T&&E){if(!Wt){let V=e.getRootNode(),F=V instanceof ShadowRoot?V.host:e.closest(".persona-host");F&&(Wt=Rs(F,(W=(P=n.launcher)==null?void 0:P.zIndex)!=null?W:yn))}Rt||(Rt=Hs(e.ownerDocument))}else T||(Wt==null||Wt(),Wt=null,Rt==null||Rt(),Rt=null);T&&(ut(),mr(!0));let k={open:T,source:g,timestamp:Date.now()};T&&!y?o.emit("widget:opened",k):!T&&y&&o.emit("widget:closed",k),o.emit("widget:state",{open:T,launcherEnabled:b,voiceActive:Je.active,streaming:D.isStreaming()})},$r=l=>{K.disabled=l,O&&(O.disabled=l),Fn.buttons.forEach(g=>{g.disabled=l}),Qe.dataset.personaComposerStreaming=l?"true":"false",Qe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},_r=()=>{Je.active||J&&J.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>_r(),200)});let lo=()=>{var y,E,k,P,W,V,F,ae,ve,we,xe;Ut.textContent=(E=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?E:"Hello \u{1F44B}",Ne.textContent=(P=(k=n.copy)==null?void 0:k.welcomeSubtitle)!=null?P:"Ask anything about your account or products.",J.placeholder=(V=(W=n.copy)==null?void 0:W.inputPlaceholder)!=null?V:"How can I help...";let l=z.querySelector("[data-persona-intro-card]");if(l){let ze=((F=n.copy)==null?void 0:F.showWelcomeCard)!==!1;l.style.display=ze?"":"none",ze?(z.classList.remove("persona-gap-3"),z.classList.add("persona-gap-6")):(z.classList.remove("persona-gap-6"),z.classList.add("persona-gap-3"))}(ve=(ae=n.sendButton)==null?void 0:ae.useIcon)!=null&&ve||(K.textContent=(xe=(we=n.copy)==null?void 0:we.sendButtonLabel)!=null?xe:"Send"),J.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',J.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}))}}),D=new So(n,{onMessagesChanged(l){Tr(Q,l,$),D&&(l.some(k=>k.role==="user")?Fn.render([],D,J,l):Fn.render(n.suggestionChips,D,J,l,n.suggestionChipsConfig)),mr(!Nn),$o(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),ao(l)},onStatusChanged(l){var E;let g=(E=n.statusIndicator)!=null?E:{};wt(Lt,(k=>{var P,W,V,F;return k==="idle"?(P=g.idleText)!=null?P:sn.idle:k==="connecting"?(W=g.connectingText)!=null?W:sn.connecting:k==="connected"?(V=g.connectedText)!=null?V:sn.connected:k==="error"?(F=g.errorText)!=null?F:sn.error:sn[k]})(l),g,l)},onStreamingChanged(l){Nn=l,$r(l),D&&Tr(Q,D.getMessages(),$),l||mr(!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":x(),Qt();break;case"speaking":x(),Ht();break;default:l==="idle"&&D.isBargeInActive()?(x(),Pt(),O==null||O.setAttribute("aria-label","End voice session")):(Je.active=!1,x(),In("system"),mn());break}},onArtifactsState(l){Dn=l,Cn()}}),lr.current=D,((Oa=(Na=n.voiceRecognition)==null?void 0:Na.provider)==null?void 0:Oa.type)==="runtype")try{D.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&D.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),re&&D.setSSEEventCallback((l,g)=>{re==null||re.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=Zs(l.metadata),M.syncFromMetadata()),(g=l.messages)!=null&&g.length&&D.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let co=l=>{var k;l.preventDefault();let g=J.value.trim(),y=(k=_e==null?void 0:_e.hasAttachments())!=null?k:!1;if(!g&&!y)return;let E;y&&(E=[],E.push(..._e.getContentParts()),g&&E.push(Ts(g))),J.value="",J.style.height="auto",D.sendMessage(g,{contentParts:E}),y&&_e.clearAttachments()},po=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),K.click())},uo=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!_e)return;let g=jp(l.clipboardData);g.length!==0&&(l.preventDefault(),await _e.handleFiles(g))},cn=null,En=!1,tr=null,je=null,go=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,kr=(l="user")=>{var P,W,V,F,ae,ve,we;if(En||D.isStreaming())return;let g=go();if(!g)return;cn=new g;let E=(W=((P=n.voiceRecognition)!=null?P:{}).pauseDuration)!=null?W:2e3;cn.continuous=!0,cn.interimResults=!0,cn.lang="en-US";let k=J.value;cn.onresult=xe=>{let ze="",H="";for(let Ee=0;Ee<xe.results.length;Ee++){let fe=xe.results[Ee],Re=fe[0].transcript;fe.isFinal?ze+=Re+" ":H=Re}let Oe=k+ze+H;J.value=Oe,tr&&clearTimeout(tr),(ze||H)&&(tr=window.setTimeout(()=>{let Ee=J.value.trim();Ee&&cn&&En&&($n(),J.value="",J.style.height="auto",D.sendMessage(Ee,{viaVoice:!0}))},E))},cn.onerror=xe=>{xe.error!=="no-speech"&&$n()},cn.onend=()=>{if(En){let xe=J.value.trim();xe&&xe!==k.trim()&&(J.value="",J.style.height="auto",D.sendMessage(xe,{viaVoice:!0})),$n()}};try{if(cn.start(),En=!0,Je.active=!0,l!=="system"&&(Je.manuallyDeactivated=!1),In(l),mn(),O){let xe=(V=n.voiceRecognition)!=null?V:{};je={backgroundColor:O.style.backgroundColor,color:O.style.color,borderColor:O.style.borderColor,iconName:(F=xe.iconName)!=null?F:"mic",iconSize:parseFloat((we=(ve=xe.iconSize)!=null?ve:(ae=n.sendButton)==null?void 0:ae.size)!=null?we:"40")||24};let ze=xe.recordingBackgroundColor,H=xe.recordingIconColor,Oe=xe.recordingBorderColor;if(O.classList.add("persona-voice-recording"),O.style.backgroundColor=ze!=null?ze:"var(--persona-voice-recording-bg, #ef4444)",O.style.color=H!=null?H:"var(--persona-voice-recording-indicator, #ffffff)",H){let Ee=O.querySelector("svg");Ee&&Ee.setAttribute("stroke",H)}Oe&&(O.style.borderColor=Oe),O.setAttribute("aria-label","Stop voice recognition")}}catch{$n("system")}},$n=(l="user")=>{if(En){if(En=!1,tr&&(clearTimeout(tr),tr=null),cn){try{cn.stop()}catch{}cn=null}if(Je.active=!1,In(l),mn(),O){if(O.classList.remove("persona-voice-recording"),je){O.style.backgroundColor=je.backgroundColor,O.style.color=je.color,O.style.borderColor=je.borderColor;let g=O.querySelector("svg");g&&g.setAttribute("stroke",je.color||"currentColor"),je=null}O.setAttribute("aria-label","Start voice recognition")}}},X=(l,g)=>{var fe,Re,ct,Ge,Ce,Xt,gt,dn;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),E=((fe=l==null?void 0:l.provider)==null?void 0:fe.type)==="runtype";if(!(y||E))return null;let P=h("div","persona-send-button-wrapper"),W=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");W.type="button",W.setAttribute("aria-label","Start voice recognition");let V=(Re=l==null?void 0:l.iconName)!=null?Re:"mic",F=(ct=g==null?void 0:g.size)!=null?ct:"40px",ae=(Ge=l==null?void 0:l.iconSize)!=null?Ge:F,ve=parseFloat(ae)||24,we=(Ce=l==null?void 0:l.backgroundColor)!=null?Ce:g==null?void 0:g.backgroundColor,xe=(Xt=l==null?void 0:l.iconColor)!=null?Xt:g==null?void 0:g.textColor;W.style.width=ae,W.style.height=ae,W.style.minWidth=ae,W.style.minHeight=ae,W.style.fontSize="18px",W.style.lineHeight="1",xe?W.style.color=xe:W.style.color="var(--persona-text, #111827)";let H=me(V,ve,xe||"currentColor",1.5);H?W.appendChild(H):W.textContent="\u{1F3A4}",we?W.style.backgroundColor=we:W.style.backgroundColor="",l!=null&&l.borderWidth&&(W.style.borderWidth=l.borderWidth,W.style.borderStyle="solid"),l!=null&&l.borderColor&&(W.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(W.style.paddingLeft=l.paddingX,W.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(W.style.paddingTop=l.paddingY,W.style.paddingBottom=l.paddingY),P.appendChild(W);let Oe=(gt=l==null?void 0:l.tooltipText)!=null?gt:"Start voice recognition";if(((dn=l==null?void 0:l.showTooltip)!=null?dn:!1)&&Oe){let nn=h("div","persona-send-button-tooltip");nn.textContent=Oe,P.appendChild(nn)}return{micButton:W,micButtonWrapper:P}},Ye=()=>{var g,y,E,k,P;if(!O||je)return;let l=(g=n.voiceRecognition)!=null?g:{};je={backgroundColor:O.style.backgroundColor,color:O.style.color,borderColor:O.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((P=(k=l.iconSize)!=null?k:(E=n.sendButton)==null?void 0:E.size)!=null?P:"40")||24}},pt=(l,g)=>{var P,W,V,F,ae;if(!O)return;let y=O.querySelector("svg");y&&y.remove();let E=(ae=je==null?void 0:je.iconSize)!=null?ae:parseFloat((F=(V=(P=n.voiceRecognition)==null?void 0:P.iconSize)!=null?V:(W=n.sendButton)==null?void 0:W.size)!=null?F:"40")||24,k=me(l,E,g,1.5);k&&O.appendChild(k)},It=()=>{O&&O.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Pt=()=>{var k;if(!O)return;Ye();let l=(k=n.voiceRecognition)!=null?k:{},g=l.recordingBackgroundColor,y=l.recordingIconColor,E=l.recordingBorderColor;if(It(),O.classList.add("persona-voice-recording"),O.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",O.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let P=O.querySelector("svg");P&&P.setAttribute("stroke",y)}E&&(O.style.borderColor=E),O.setAttribute("aria-label","Stop voice recognition")},Qt=()=>{var V,F,ae,ve,we,xe,ze,H;if(!O)return;Ye();let l=(V=n.voiceRecognition)!=null?V:{},g=D.getVoiceInterruptionMode(),y=(F=l.processingIconName)!=null?F:"loader",E=(ve=(ae=l.processingIconColor)!=null?ae:je==null?void 0:je.color)!=null?ve:"",k=(xe=(we=l.processingBackgroundColor)!=null?we:je==null?void 0:je.backgroundColor)!=null?xe:"",P=(H=(ze=l.processingBorderColor)!=null?ze:je==null?void 0:je.borderColor)!=null?H:"";It(),O.classList.add("persona-voice-processing"),O.style.backgroundColor=k,O.style.borderColor=P;let W=E||"currentColor";O.style.color=W,pt(y,W),O.setAttribute("aria-label","Processing voice input"),g==="none"&&(O.style.cursor="default")},Ht=()=>{var ae,ve,we,xe,ze,H,Oe,Ee,fe,Re,ct,Ge;if(!O)return;Ye();let l=(ae=n.voiceRecognition)!=null?ae:{},g=D.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",E=(ve=l.speakingIconName)!=null?ve:y,k=(H=l.speakingIconColor)!=null?H:g==="barge-in"?(xe=(we=l.recordingIconColor)!=null?we:je==null?void 0:je.color)!=null?xe:"":(ze=je==null?void 0:je.color)!=null?ze:"",P=(fe=l.speakingBackgroundColor)!=null?fe:g==="barge-in"?(Oe=l.recordingBackgroundColor)!=null?Oe:"var(--persona-voice-recording-bg, #ef4444)":(Ee=je==null?void 0:je.backgroundColor)!=null?Ee:"",W=(Ge=l.speakingBorderColor)!=null?Ge:g==="barge-in"?(Re=l.recordingBorderColor)!=null?Re:"":(ct=je==null?void 0:je.borderColor)!=null?ct:"";It(),O.classList.add("persona-voice-speaking"),O.style.backgroundColor=P,O.style.borderColor=W;let V=k||"currentColor";O.style.color=V,pt(E,V);let F=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";O.setAttribute("aria-label",F),g==="none"&&(O.style.cursor="default"),g==="barge-in"&&O.classList.add("persona-voice-recording")},x=()=>{var l,g,y;O&&(It(),je&&(O.style.backgroundColor=(l=je.backgroundColor)!=null?l:"",O.style.color=(g=je.color)!=null?g:"",O.style.borderColor=(y=je.borderColor)!=null?y:"",pt(je.iconName,je.color||"currentColor"),je=null),O.style.cursor="",O.setAttribute("aria-label","Start voice recognition"))},We=()=>{var l,g;if(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"){let y=D.getVoiceStatus(),E=D.getVoiceInterruptionMode();if(E==="none"&&(y==="processing"||y==="speaking"))return;if(E==="cancel"&&(y==="processing"||y==="speaking")){D.stopVoicePlayback();return}if(D.isBargeInActive()){D.stopVoicePlayback(),D.deactivateBargeIn().then(()=>{Je.active=!1,Je.manuallyDeactivated=!0,mn(),In("user"),x()});return}D.toggleVoice().then(()=>{Je.active=D.isVoiceActive(),Je.manuallyDeactivated=!D.isVoiceActive(),mn(),In("user"),D.isVoiceActive()?Pt():x()});return}if(En){let y=J.value.trim();Je.manuallyDeactivated=!0,mn(),$n("user"),y&&(J.value="",J.style.height="auto",D.sendMessage(y))}else Je.manuallyDeactivated=!1,mn(),kr("user")};_t=We,O&&(O.addEventListener("click",We),ht.push(()=>{var l,g;((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?(D.isVoiceActive()&&D.toggleVoice(),x()):$n("system"),O&&O.removeEventListener("click",We)}));let I=o.on("assistant:complete",()=>{so&&(Je.active||Je.manuallyDeactivated||so==="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"?D.toggleVoice().then(()=>{Je.active=D.isVoiceActive(),In("auto"),D.isVoiceActive()&&Pt()}):kr("auto"))},600))});ht.push(I);let A=o.on("action:resubmit",()=>{setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)});ht.push(A);let G=()=>{Et(!T,"user")},N=null,ie=null;if(b){let l=s.find(g=>g.renderLauncher);if(l!=null&&l.renderLauncher){let g=l.renderLauncher({config:n,defaultRenderer:()=>Io(n,G).element,onToggle:G});g&&(ie=g)}ie||(N=Io(n,G))}N?e.appendChild(N.element):ie&&e.appendChild(ie),Mr(),Fn.render(n.suggestionChips,D,J,void 0,n.suggestionChipsConfig),lo(),$r(D.isStreaming()),mr(!0),Do(),S&&(b?T&&setTimeout(()=>_r(),200):setTimeout(()=>_r(),0));let ut=()=>{var F,ae,ve,we,xe,ze,H,Oe,Ee,fe,Re,ct,Ge,Ce,Xt,gt,dn,nn,rn,Ft,pn,Ve;let l=Yt(n),g=(ae=(F=n.launcher)==null?void 0:F.sidebarMode)!=null?ae:!1,y=l||g||((we=(ve=n.launcher)==null?void 0:ve.fullHeight)!=null?we:!1),E=(xe=e.ownerDocument.defaultView)!=null?xe:window,k=(H=(ze=n.launcher)==null?void 0:ze.mobileFullscreen)!=null?H:!0,P=(Ee=(Oe=n.launcher)==null?void 0:Oe.mobileBreakpoint)!=null?Ee:640,W=E.innerWidth<=P,V=k&&W&&b;try{if(V){Jn(),Rr(e,n);return}if(B&&(B=!1,Jn(),Rr(e,n)),!b&&!l){q.style.height="",q.style.width="";return}if(!g&&!l){let mt=(Re=(fe=n==null?void 0:n.launcher)==null?void 0:fe.width)!=null?Re:n==null?void 0:n.launcherWidth,Wn=mt!=null?mt:Rn;q.style.width=Wn,q.style.maxWidth=Wn}if(qn(),!y){let mt=E.innerHeight,Wn=64,fr=(Ge=(ct=n.launcher)==null?void 0:ct.heightOffset)!=null?Ge:0,nr=Math.max(200,mt-Wn),hr=Math.min(640,nr),rr=Math.max(200,hr-fr);q.style.height=`${rr}px`}}finally{if(qe(),Mr(),T&&b){let Wn=((Ce=e.ownerDocument.defaultView)!=null?Ce:window).innerWidth<=((gt=(Xt=n.launcher)==null?void 0:Xt.mobileBreakpoint)!=null?gt:640),fr=(nn=(dn=n.launcher)==null?void 0:dn.sidebarMode)!=null?nn:!1,nr=(Ft=(rn=n.launcher)==null?void 0:rn.mobileFullscreen)!=null?Ft:!0,hr=Yt(n)&&nr&&Wn,rr=fr||nr&&Wn&&b||hr;if(rr&&!Rt){let jr=e.getRootNode(),zr=jr instanceof ShadowRoot?jr.host:e.closest(".persona-host");zr&&!Wt&&(Wt=Rs(zr,(Ve=(pn=n.launcher)==null?void 0:pn.zIndex)!=null?Ve:yn)),Rt=Hs(e.ownerDocument)}else rr||(Wt==null||Wt(),Wt=null,Rt==null||Rt(),Rt=null)}}};ut();let Tt=($a=e.ownerDocument.defaultView)!=null?$a:window;if(Tt.addEventListener("resize",ut),ht.push(()=>Tt.removeEventListener("resize",ut)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{qe()});l.observe(Qe),ht.push(()=>l.disconnect())}An=z.scrollTop;let Bt=()=>{let l=z.scrollTop,{action:g,nextLastScrollTop:y}=ts({following:gn.isFollowing(),currentScrollTop:l,lastScrollTop:An,nearBottom:ko(z,oo),userScrollThreshold:Dr,isAutoScrolling:On,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(An=y,g==="resume"){gr();return}g==="pause"&&io()};z.addEventListener("scroll",Bt,{passive:!0}),ht.push(()=>z.removeEventListener("scroll",Bt));let en=l=>{let g=ns({following:gn.isFollowing(),deltaY:l.deltaY,nearBottom:ko(z,oo),resumeWhenNearBottom:!0});g==="pause"?io():g==="resume"&&gr()};z.addEventListener("wheel",en,{passive:!0}),ht.push(()=>z.removeEventListener("wheel",en)),nt.addEventListener("click",()=>{z.scrollTop=z.scrollHeight,An=z.scrollTop,gr(),mr(!0)}),ht.push(()=>nt.remove()),ht.push(()=>{Or()});let Vt=()=>{le&&(Sn&&(le.removeEventListener("click",Sn),Sn=null),b?(le.style.display="",Sn=()=>{Et(!1,"user")},le.addEventListener("click",Sn)):le.style.display="none")};Vt(),(()=>{let{clearChatButton:l}=se;l&&l.addEventListener("click",()=>{D.clearMessages(),Ln.clear(),gr();try{localStorage.removeItem(no),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${no}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==no)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={},M.syncFromMetadata(),re==null||re.clear(),be==null||be.update()})})(),tt&&tt.addEventListener("submit",co),J==null||J.addEventListener("keydown",po),J==null||J.addEventListener("paste",uo),ht.push(()=>{tt&&tt.removeEventListener("submit",co),J==null||J.removeEventListener("keydown",po),J==null||J.removeEventListener("paste",uo)}),ht.push(()=>{D.cancel()}),N?ht.push(()=>{N==null||N.destroy()}):ie&&ht.push(()=>{ie==null||ie.remove()});let Ae={update(l){var Ja,Ya,Ga,Xa,Ka,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,Ii,Pi,Wi,Ri,Hi,Bi,Di,Fi,Ni,Oi,$i,_i,ji,zi,Ui,Vi,qi,Ji,Yi,Gi,Xi,Ki,Zi,Qi,el,tl,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,gl,ml,fl,hl,yl,bl,xl,vl,Cl,wl,Sl,Al,El,Tl,Ml,kl,Ll,Il,Pl,Wl,Rl,Hl,Bl,Dl;let g=n.toolCall,y=n.messageActions,E=(Ja=n.layout)==null?void 0:Ja.messages,k=n.colorScheme,P=n.loadingIndicator,W=n.iterationDisplay;n={...n,...l},Jn(),Rr(e,n),as(e,n),is(e,n),Cn(),n.colorScheme!==k&&pr();let V=ls.getForInstance(n.plugins);s.length=0,s.push(...V),b=(Ga=(Ya=n.launcher)==null?void 0:Ya.enabled)!=null?Ga:!0,C=(Ka=(Xa=n.launcher)==null?void 0:Xa.autoExpand)!=null?Ka:!1,te=(Qa=(Za=n.features)==null?void 0:Za.showReasoning)!=null?Qa:!0,Te=(ti=(ei=n.features)==null?void 0:ei.showToolCalls)!=null?ti:!0,Se=(ri=(ni=n.features)==null?void 0:ni.scrollToBottom)!=null?ri:{},lt(),er();let F=ne;if(ne=(si=(oi=n.features)==null?void 0:oi.showEventStreamToggle)!=null?si:!1,ne&&!F){if(re||(Me=new Bo(he),re=new Ho(ke,Me),Me.open().then(()=>re==null?void 0:re.restore()).catch(()=>{}),D.setSSEEventCallback((U,rt)=>{re.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:U,timestamp:Date.now(),payload:JSON.stringify(rt)})})),!Xe&&Ze){let U=(ii=(ai=n.features)==null?void 0:ai.eventStream)==null?void 0:ii.classNames,rt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(U!=null&&U.toggleButton?" "+U.toggleButton:"");Xe=h("button",rt),Xe.style.width="28px",Xe.style.height="28px",Xe.style.color=bn.actionIconColor,Xe.type="button",Xe.setAttribute("aria-label","Event Stream"),Xe.title="Event Stream";let Mt=me("activity","18px","currentColor",1.5);Mt&&Xe.appendChild(Mt);let Ue=se.clearChatButtonWrapper,st=se.closeButtonWrapper,zt=Ue||st;zt&&zt.parentNode===Ze?Ze.insertBefore(Xe,zt):Ze.appendChild(Xe),Xe.addEventListener("click",()=>{$e?Bn():Xn()})}}else!ne&&F&&(Bn(),Xe&&(Xe.remove(),Xe=null),re==null||re.clear(),Me==null||Me.destroy(),re=null,Me=null);if(((li=n.launcher)==null?void 0:li.enabled)===!1&&N&&(N.destroy(),N=null),((ci=n.launcher)==null?void 0:ci.enabled)===!1&&ie&&(ie.remove(),ie=null),((di=n.launcher)==null?void 0:di.enabled)!==!1&&!N&&!ie){let U=s.find(rt=>rt.renderLauncher);if(U!=null&&U.renderLauncher){let rt=U.renderLauncher({config:n,defaultRenderer:()=>Io(n,G).element,onToggle:G});rt&&(ie=rt,e.appendChild(ie))}ie||(N=Io(n,G),e.appendChild(N.element))}N&&N.update(n),St&&((pi=n.launcher)==null?void 0:pi.title)!==void 0&&(St.textContent=n.launcher.title),At&&((ui=n.launcher)==null?void 0:ui.subtitle)!==void 0&&(At.textContent=n.launcher.subtitle);let ae=(gi=n.layout)==null?void 0:gi.header;if((ae==null?void 0:ae.layout)!==L&&Ze){let U=ae?Po(n,ae,{showClose:b,onClose:()=>Et(!1,"user")}):Cr({config:n,showClose:b,onClose:()=>Et(!1,"user")});Ze.replaceWith(U.header),Ze=U.header,Ie=U.iconHolder,St=U.headerTitle,At=U.headerSubtitle,le=U.closeButton,L=ae==null?void 0:ae.layout}else if(ae&&(Ie&&(Ie.style.display=ae.showIcon===!1?"none":""),St&&(St.style.display=ae.showTitle===!1?"none":""),At&&(At.style.display=ae.showSubtitle===!1?"none":""),le&&(le.style.display=ae.showCloseButton===!1?"none":""),se.clearChatButtonWrapper)){let U=ae.showClearChat;if(U!==void 0){se.clearChatButtonWrapper.style.display=U?"":"none";let{closeButtonWrapper:rt}=se;rt&&!rt.classList.contains("persona-absolute")&&(U?rt.classList.remove("persona-ml-auto"):rt.classList.add("persona-ml-auto"))}}let we=((mi=n.layout)==null?void 0:mi.showHeader)!==!1;Ze&&(Ze.style.display=we?"":"none");let xe=((fi=n.layout)==null?void 0:fi.showFooter)!==!1;Qe&&(Qe.style.display=xe?"":"none"),qe(),er(),b!==w?b?Et(C,"auto"):(T=!0,Mr()):C!==R&&Et(C,"auto"),R=C,w=b,ut(),Vt();let Oe=JSON.stringify(l.toolCall)!==JSON.stringify(g),Ee=JSON.stringify(n.messageActions)!==JSON.stringify(y),fe=JSON.stringify((hi=n.layout)==null?void 0:hi.messages)!==JSON.stringify(E),Re=((yi=n.loadingIndicator)==null?void 0:yi.render)!==(P==null?void 0:P.render)||((bi=n.loadingIndicator)==null?void 0:bi.renderIdle)!==(P==null?void 0:P.renderIdle)||((xi=n.loadingIndicator)==null?void 0:xi.showBubble)!==(P==null?void 0:P.showBubble),ct=n.iterationDisplay!==W;(Oe||Ee||fe||Re||ct)&&D&&(ur++,Tr(Q,D.getMessages(),$));let Ce=(vi=n.launcher)!=null?vi:{},Xt=(Ci=Ce.headerIconHidden)!=null?Ci:!1,gt=(Si=(wi=n.layout)==null?void 0:wi.header)==null?void 0:Si.showIcon,dn=Xt||gt===!1,nn=Ce.headerIconName,rn=(Ai=Ce.headerIconSize)!=null?Ai:"48px";if(Ie){let U=_.querySelector(".persona-border-b-persona-divider"),rt=U==null?void 0:U.querySelector(".persona-flex-col");if(dn)Ie.style.display="none",U&&rt&&!U.contains(rt)&&U.insertBefore(rt,U.firstChild);else{if(Ie.style.display="",Ie.style.height=rn,Ie.style.width=rn,U&&rt&&(U.contains(Ie)?Ie.nextSibling!==rt&&(Ie.remove(),U.insertBefore(Ie,rt)):U.insertBefore(Ie,rt)),nn){let Ue=parseFloat(rn)||24,st=me(nn,Ue*.6,"#ffffff",2);st?Ie.replaceChildren(st):Ie.textContent=(Ei=Ce.agentIconText)!=null?Ei:"\u{1F4AC}"}else if(Ce.iconUrl){let Ue=Ie.querySelector("img");if(Ue)Ue.src=Ce.iconUrl,Ue.style.height=rn,Ue.style.width=rn;else{let st=document.createElement("img");st.src=Ce.iconUrl,st.alt="",st.className="persona-rounded-xl persona-object-cover",st.style.height=rn,st.style.width=rn,Ie.replaceChildren(st)}}else{let Ue=Ie.querySelector("svg"),st=Ie.querySelector("img");(Ue||st)&&Ie.replaceChildren(),Ie.textContent=(Ti=Ce.agentIconText)!=null?Ti:"\u{1F4AC}"}let Mt=Ie.querySelector("img");Mt&&(Mt.style.height=rn,Mt.style.width=rn)}}let Ft=(ki=(Mi=n.layout)==null?void 0:Mi.header)==null?void 0:ki.showTitle,pn=(Ii=(Li=n.layout)==null?void 0:Li.header)==null?void 0:Ii.showSubtitle;if(St&&(St.style.display=Ft===!1?"none":""),At&&(At.style.display=pn===!1?"none":""),le){((Wi=(Pi=n.layout)==null?void 0:Pi.header)==null?void 0:Wi.showCloseButton)===!1?le.style.display="none":le.style.display="";let rt=(Ri=Ce.closeButtonSize)!=null?Ri:"32px",Mt=(Hi=Ce.closeButtonPlacement)!=null?Hi:"inline";le.style.height=rt,le.style.width=rt;let{closeButtonWrapper:Ue}=se,st=Mt==="top-right",zt=Ue==null?void 0:Ue.classList.contains("persona-absolute");if(Ue&&st!==zt)if(Ue.remove(),st)Ue.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",_.style.position="relative",_.appendChild(Ue);else{let Ke=(Di=(Bi=Ce.clearChat)==null?void 0:Bi.placement)!=null?Di:"inline",Jt=(Ni=(Fi=Ce.clearChat)==null?void 0:Fi.enabled)!=null?Ni:!0;Ue.className=Jt&&Ke==="inline"?"":"persona-ml-auto";let hn=_.querySelector(".persona-border-b-persona-divider");hn&&hn.appendChild(Ue)}if(le.style.color=Ce.closeButtonColor||bn.actionIconColor,Ce.closeButtonBackgroundColor?(le.style.backgroundColor=Ce.closeButtonBackgroundColor,le.classList.remove("hover:persona-bg-gray-100")):(le.style.backgroundColor="",le.classList.add("hover:persona-bg-gray-100")),Ce.closeButtonBorderWidth||Ce.closeButtonBorderColor){let Ke=Ce.closeButtonBorderWidth||"0px",Jt=Ce.closeButtonBorderColor||"transparent";le.style.border=`${Ke} solid ${Jt}`,le.classList.remove("persona-border-none")}else le.style.border="",le.classList.add("persona-border-none");Ce.closeButtonBorderRadius?(le.style.borderRadius=Ce.closeButtonBorderRadius,le.classList.remove("persona-rounded-full")):(le.style.borderRadius="",le.classList.add("persona-rounded-full")),Ce.closeButtonPaddingX?(le.style.paddingLeft=Ce.closeButtonPaddingX,le.style.paddingRight=Ce.closeButtonPaddingX):(le.style.paddingLeft="",le.style.paddingRight=""),Ce.closeButtonPaddingY?(le.style.paddingTop=Ce.closeButtonPaddingY,le.style.paddingBottom=Ce.closeButtonPaddingY):(le.style.paddingTop="",le.style.paddingBottom="");let on=(Oi=Ce.closeButtonIconName)!=null?Oi:"x",_n=($i=Ce.closeButtonIconText)!=null?$i:"\xD7";le.innerHTML="";let un=me(on,"20px","currentColor",2);un?le.appendChild(un):le.textContent=_n;let Nt=(_i=Ce.closeButtonTooltipText)!=null?_i:"Close chat",Tn=(ji=Ce.closeButtonShowTooltip)!=null?ji:!0;if(le.setAttribute("aria-label",Nt),Ue&&(Ue._cleanupTooltip&&(Ue._cleanupTooltip(),delete Ue._cleanupTooltip),Tn&&Nt)){let Ke=null,Jt=()=>{if(Ke||!le)return;let Ir=le.ownerDocument,ho=Ir.body;if(!ho)return;Ke=Yn(Ir,"div","persona-clear-chat-tooltip"),Ke.textContent=Nt;let yo=Yn(Ir,"div");yo.className="persona-clear-chat-tooltip-arrow",Ke.appendChild(yo);let Pr=le.getBoundingClientRect();Ke.style.position="fixed",Ke.style.zIndex=String(xr),Ke.style.left=`${Pr.left+Pr.width/2}px`,Ke.style.top=`${Pr.top-8}px`,Ke.style.transform="translate(-50%, -100%)",ho.appendChild(Ke)},hn=()=>{Ke&&Ke.parentNode&&(Ke.parentNode.removeChild(Ke),Ke=null)};Ue.addEventListener("mouseenter",Jt),Ue.addEventListener("mouseleave",hn),le.addEventListener("focus",Jt),le.addEventListener("blur",hn),Ue._cleanupTooltip=()=>{hn(),Ue&&(Ue.removeEventListener("mouseenter",Jt),Ue.removeEventListener("mouseleave",hn)),le&&(le.removeEventListener("focus",Jt),le.removeEventListener("blur",hn))}}}let{clearChatButton:Ve,clearChatButtonWrapper:mt}=se;if(Ve){let U=(zi=Ce.clearChat)!=null?zi:{},rt=(Ui=U.enabled)!=null?Ui:!0,Mt=(qi=(Vi=n.layout)==null?void 0:Vi.header)==null?void 0:qi.showClearChat,Ue=Mt!==void 0?Mt:rt,st=(Ji=U.placement)!=null?Ji:"inline";if(mt){mt.style.display=Ue?"":"none";let{closeButtonWrapper:zt}=se;zt&&!zt.classList.contains("persona-absolute")&&(Ue?zt.classList.remove("persona-ml-auto"):zt.classList.add("persona-ml-auto"));let on=st==="top-right",_n=mt.classList.contains("persona-absolute");if(on!==_n&&Ue){if(mt.remove(),on)mt.className="persona-absolute persona-top-4 persona-z-50",mt.style.right="48px",_.style.position="relative",_.appendChild(mt);else{mt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",mt.style.right="";let Nt=_.querySelector(".persona-border-b-persona-divider"),Tn=se.closeButtonWrapper;Nt&&Tn&&Tn.parentElement===Nt?Nt.insertBefore(mt,Tn):Nt&&Nt.appendChild(mt)}let un=se.closeButtonWrapper;un&&!un.classList.contains("persona-absolute")&&(on?un.classList.add("persona-ml-auto"):un.classList.remove("persona-ml-auto"))}}if(Ue){let zt=(Yi=U.size)!=null?Yi:"32px";Ve.style.height=zt,Ve.style.width=zt;let on=(Gi=U.iconName)!=null?Gi:"refresh-cw",_n=(Xi=U.iconColor)!=null?Xi:"";Ve.style.color=_n||bn.actionIconColor,Ve.innerHTML="";let un=me(on,"20px","currentColor",2);if(un&&Ve.appendChild(un),U.backgroundColor?(Ve.style.backgroundColor=U.backgroundColor,Ve.classList.remove("hover:persona-bg-gray-100")):(Ve.style.backgroundColor="",Ve.classList.add("hover:persona-bg-gray-100")),U.borderWidth||U.borderColor){let Ke=U.borderWidth||"0px",Jt=U.borderColor||"transparent";Ve.style.border=`${Ke} solid ${Jt}`,Ve.classList.remove("persona-border-none")}else Ve.style.border="",Ve.classList.add("persona-border-none");U.borderRadius?(Ve.style.borderRadius=U.borderRadius,Ve.classList.remove("persona-rounded-full")):(Ve.style.borderRadius="",Ve.classList.add("persona-rounded-full")),U.paddingX?(Ve.style.paddingLeft=U.paddingX,Ve.style.paddingRight=U.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),U.paddingY?(Ve.style.paddingTop=U.paddingY,Ve.style.paddingBottom=U.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let Nt=(Ki=U.tooltipText)!=null?Ki:"Clear chat",Tn=(Zi=U.showTooltip)!=null?Zi:!0;if(Ve.setAttribute("aria-label",Nt),mt&&(mt._cleanupTooltip&&(mt._cleanupTooltip(),delete mt._cleanupTooltip),Tn&&Nt)){let Ke=null,Jt=()=>{if(Ke||!Ve)return;let Ir=Ve.ownerDocument,ho=Ir.body;if(!ho)return;Ke=Yn(Ir,"div","persona-clear-chat-tooltip"),Ke.textContent=Nt;let yo=Yn(Ir,"div");yo.className="persona-clear-chat-tooltip-arrow",Ke.appendChild(yo);let Pr=Ve.getBoundingClientRect();Ke.style.position="fixed",Ke.style.zIndex=String(xr),Ke.style.left=`${Pr.left+Pr.width/2}px`,Ke.style.top=`${Pr.top-8}px`,Ke.style.transform="translate(-50%, -100%)",ho.appendChild(Ke)},hn=()=>{Ke&&Ke.parentNode&&(Ke.parentNode.removeChild(Ke),Ke=null)};mt.addEventListener("mouseenter",Jt),mt.addEventListener("mouseleave",hn),Ve.addEventListener("focus",Jt),Ve.addEventListener("blur",hn),mt._cleanupTooltip=()=>{hn(),mt&&(mt.removeEventListener("mouseenter",Jt),mt.removeEventListener("mouseleave",hn)),Ve&&(Ve.removeEventListener("focus",Jt),Ve.removeEventListener("blur",hn))}}}}let Wn=n.actionParsers&&n.actionParsers.length?n.actionParsers:[cs],fr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[to.message,to.messageAndClick];M=ds({parsers:Wn,handlers:fr,getSessionMetadata:u,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),$=Dc(n,M,ce),D.updateConfig(n),Tr(Q,D.getMessages(),$),Fn.render(n.suggestionChips,D,J,void 0,n.suggestionChipsConfig),lo(),$r(D.isStreaming());let nr=((Qi=n.voiceRecognition)==null?void 0:Qi.enabled)===!0,hr=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),rr=((tl=(el=n.voiceRecognition)==null?void 0:el.provider)==null?void 0:tl.type)==="runtype";if(nr&&(hr||rr))if(!O||!Le){let U=X(n.voiceRecognition,n.sendButton);U&&(O=U.micButton,Le=U.micButtonWrapper,Zt.insertBefore(Le,xt),O.addEventListener("click",We),O.disabled=D.isStreaming())}else{let U=(nl=n.voiceRecognition)!=null?nl:{},rt=(rl=n.sendButton)!=null?rl:{},Mt=(ol=U.iconName)!=null?ol:"mic",Ue=(sl=rt.size)!=null?sl:"40px",st=(al=U.iconSize)!=null?al:Ue,zt=parseFloat(st)||24;O.style.width=st,O.style.height=st,O.style.minWidth=st,O.style.minHeight=st;let on=(ll=(il=U.iconColor)!=null?il:rt.textColor)!=null?ll:"currentColor";O.innerHTML="";let _n=me(Mt,zt,on,2);_n?O.appendChild(_n):O.textContent="\u{1F3A4}";let un=(cl=U.backgroundColor)!=null?cl:rt.backgroundColor;un?O.style.backgroundColor=un:O.style.backgroundColor="",on?O.style.color=on:O.style.color="var(--persona-text, #111827)",U.borderWidth?(O.style.borderWidth=U.borderWidth,O.style.borderStyle="solid"):(O.style.borderWidth="",O.style.borderStyle=""),U.borderColor?O.style.borderColor=U.borderColor:O.style.borderColor="",U.paddingX?(O.style.paddingLeft=U.paddingX,O.style.paddingRight=U.paddingX):(O.style.paddingLeft="",O.style.paddingRight=""),U.paddingY?(O.style.paddingTop=U.paddingY,O.style.paddingBottom=U.paddingY):(O.style.paddingTop="",O.style.paddingBottom="");let Nt=Le==null?void 0:Le.querySelector(".persona-send-button-tooltip"),Tn=(dl=U.tooltipText)!=null?dl:"Start voice recognition";if(((pl=U.showTooltip)!=null?pl:!1)&&Tn)if(Nt)Nt.textContent=Tn,Nt.style.display="";else{let Jt=document.createElement("div");Jt.className="persona-send-button-tooltip",Jt.textContent=Tn,Le==null||Le.insertBefore(Jt,O)}else Nt&&(Nt.style.display="none");Le.style.display="",O.disabled=D.isStreaming()}else O&&Le&&(Le.style.display="none",((gl=(ul=n.voiceRecognition)==null?void 0:ul.provider)==null?void 0:gl.type)==="runtype"?D.isVoiceActive()&&D.toggleVoice():En&&$n());if(((ml=n.attachments)==null?void 0:ml.enabled)===!0)if(!at||!pe){let U=(fl=n.attachments)!=null?fl:{},Mt=(yl=((hl=n.sendButton)!=null?hl:{}).size)!=null?yl:"40px";Z||(Z=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Z.style.display="none",tt.insertBefore(Z,J)),Be||(Be=document.createElement("input"),Be.type="file",Be.accept=((bl=U.allowedTypes)!=null?bl:sr).join(","),Be.multiple=((xl=U.maxFiles)!=null?xl:4)>1,Be.style.display="none",Be.setAttribute("aria-label","Attach files"),tt.insertBefore(Be,J)),at=h("div","persona-send-button-wrapper"),pe=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),pe.type="button",pe.setAttribute("aria-label",(vl=U.buttonTooltipText)!=null?vl:"Attach file");let Ue=(Cl=U.buttonIconName)!=null?Cl:"paperclip",st=Mt,zt=parseFloat(st)||40,on=Math.round(zt*.6);pe.style.width=st,pe.style.height=st,pe.style.minWidth=st,pe.style.minHeight=st,pe.style.fontSize="18px",pe.style.lineHeight="1",pe.style.backgroundColor="transparent",pe.style.color="var(--persona-primary, #111827)",pe.style.border="none",pe.style.borderRadius="6px",pe.style.transition="background-color 0.15s ease",pe.addEventListener("mouseenter",()=>{pe.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),pe.addEventListener("mouseleave",()=>{pe.style.backgroundColor="transparent"});let _n=me(Ue,on,"currentColor",1.5);_n?pe.appendChild(_n):pe.textContent="\u{1F4CE}",pe.addEventListener("click",Tn=>{Tn.preventDefault(),Be==null||Be.click()}),at.appendChild(pe);let un=(wl=U.buttonTooltipText)!=null?wl:"Attach file",Nt=h("div","persona-send-button-tooltip");Nt.textContent=un,at.appendChild(Nt),Gt.append(at),!_e&&Be&&Z&&(_e=Gr.fromConfig(U),_e.setPreviewsContainer(Z),Be.addEventListener("change",async()=>{_e&&(Be!=null&&Be.files)&&(await _e.handleFileSelect(Be.files),Be.value="")}))}else{at.style.display="";let U=(Sl=n.attachments)!=null?Sl:{};Be&&(Be.accept=((Al=U.allowedTypes)!=null?Al:sr).join(","),Be.multiple=((El=U.maxFiles)!=null?El:4)>1),_e&&_e.updateConfig({allowedTypes:U.allowedTypes,maxFileSize:U.maxFileSize,maxFiles:U.maxFiles})}else at&&(at.style.display="none"),_e&&_e.clearAttachments();let jt=(Tl=n.sendButton)!=null?Tl:{},_o=(Ml=jt.useIcon)!=null?Ml:!1,mo=(kl=jt.iconText)!=null?kl:"\u2191",fo=jt.iconName,Ur=(Ll=jt.tooltipText)!=null?Ll:"Send message",jo=(Il=jt.showTooltip)!=null?Il:!1,yr=(Pl=jt.size)!=null?Pl:"40px",Lr=jt.backgroundColor,qt=jt.textColor;if(_o){if(K.style.width=yr,K.style.height=yr,K.style.minWidth=yr,K.style.minHeight=yr,K.style.fontSize="18px",K.style.lineHeight="1",K.innerHTML="",qt?K.style.color=qt:K.style.color="var(--persona-button-primary-fg, #ffffff)",fo){let U=parseFloat(yr)||24,rt=(qt==null?void 0:qt.trim())||"currentColor",Mt=me(fo,U,rt,2);Mt?K.appendChild(Mt):K.textContent=mo}else K.textContent=mo;K.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Lr?(K.style.backgroundColor=Lr,K.classList.remove("persona-bg-persona-primary")):(K.style.backgroundColor="",K.classList.add("persona-bg-persona-primary"))}else K.textContent=(Rl=(Wl=n.copy)==null?void 0:Wl.sendButtonLabel)!=null?Rl:"Send",K.style.width="",K.style.height="",K.style.minWidth="",K.style.minHeight="",K.style.fontSize="",K.style.lineHeight="",K.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Lr?(K.style.backgroundColor=Lr,K.classList.remove("persona-bg-persona-accent")):K.classList.add("persona-bg-persona-accent"),qt?K.style.color=qt:K.classList.add("persona-text-white");jt.borderWidth?(K.style.borderWidth=jt.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),jt.borderColor?K.style.borderColor=jt.borderColor:K.style.borderColor="",jt.paddingX?(K.style.paddingLeft=jt.paddingX,K.style.paddingRight=jt.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),jt.paddingY?(K.style.paddingTop=jt.paddingY,K.style.paddingBottom=jt.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let fn=xt==null?void 0:xt.querySelector(".persona-send-button-tooltip");if(jo&&Ur)if(fn)fn.textContent=Ur,fn.style.display="";else{let U=document.createElement("div");U.className="persona-send-button-tooltip",U.textContent=Ur,xt==null||xt.insertBefore(U,K)}else fn&&(fn.style.display="none");let or=(Hl=n.layout)==null?void 0:Hl.contentMaxWidth;or?(Q.style.maxWidth=or,Q.style.marginLeft="auto",Q.style.marginRight="auto",Q.style.width="100%",tt&&(tt.style.maxWidth=or,tt.style.marginLeft="auto",tt.style.marginRight="auto"),Fe&&(Fe.style.maxWidth=or,Fe.style.marginLeft="auto",Fe.style.marginRight="auto")):(Q.style.maxWidth="",Q.style.marginLeft="",Q.style.marginRight="",Q.style.width="",tt&&(tt.style.maxWidth="",tt.style.marginLeft="",tt.style.marginRight=""),Fe&&(Fe.style.maxWidth="",Fe.style.marginLeft="",Fe.style.marginRight=""));let br=(Bl=n.statusIndicator)!=null?Bl:{},yd=(Dl=br.visible)!=null?Dl:!0;if(Lt.style.display=yd?"":"none",D){let U=D.getStatus();wt(Lt,(Mt=>{var Ue,st,zt,on;return Mt==="idle"?(Ue=br.idleText)!=null?Ue:sn.idle:Mt==="connecting"?(st=br.connectingText)!=null?st:sn.connecting:Mt==="connected"?(zt=br.connectedText)!=null?zt:sn.connected:Mt==="error"?(on=br.errorText)!=null?on:sn.error:sn[Mt]})(U),br,U)}Lt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let bd=br.align==="left"?"persona-text-left":br.align==="center"?"persona-text-center":"persona-text-right";Lt.classList.add(bd)},open(){b&&Et(!0,"api")},close(){b&&Et(!1,"api")},toggle(){b&&Et(!T,"api")},clearChat(){an=!1,D.clearMessages(),Ln.clear(),gr();try{localStorage.removeItem(no),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${no}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==no)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={},M.syncFromMetadata(),re==null||re.clear(),be==null||be.update()},setMessage(l){return!J||D.isStreaming()?!1:(!T&&b&&Et(!0,"system"),J.value=l,J.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(D.isStreaming())return!1;let g=(l==null?void 0:l.trim())||J.value.trim();return g?(!T&&b&&Et(!0,"system"),J.value="",J.style.height="auto",D.sendMessage(g),!0):!1},startVoiceRecognition(){var g,y;return D.isStreaming()?!1:((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype"?(D.isVoiceActive()||(!T&&b&&Et(!0,"system"),Je.manuallyDeactivated=!1,mn(),D.toggleVoice().then(()=>{Je.active=D.isVoiceActive(),In("user"),D.isVoiceActive()&&Pt()})),!0):En?!0:go()?(!T&&b&&Et(!0,"system"),Je.manuallyDeactivated=!1,mn(),kr("user"),!0):!1},stopVoiceRecognition(){var l,g;return((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?D.isVoiceActive()?(D.toggleVoice().then(()=>{Je.active=!1,Je.manuallyDeactivated=!0,mn(),In("user"),x()}),!0):!1:En?(Je.manuallyDeactivated=!0,mn(),$n("user"),!0):!1},injectMessage(l){return!T&&b&&Et(!0,"system"),D.injectMessage(l)},injectAssistantMessage(l){!T&&b&&Et(!0,"system");let g=D.injectAssistantMessage(l);return Y&&(Y=!1,ue&&(clearTimeout(ue),ue=null),setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)),g},injectUserMessage(l){return!T&&b&&Et(!0,"system"),D.injectUserMessage(l)},injectSystemMessage(l){return!T&&b&&Et(!0,"system"),D.injectSystemMessage(l)},injectMessageBatch(l){return!T&&b&&Et(!0,"system"),D.injectMessageBatch(l)},injectTestMessage(l){!T&&b&&Et(!0,"system"),D.injectTestEvent(l)},async connectStream(l,g){return D.connectStream(l,g)},__pushEventStreamEvent(l){re&&re.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!ne||!re||Xn()},hideEventStream(){$e&&Bn()},isEventStreamVisible(){return $e},showArtifacts(){Hn(n)&&(an=!1,Cn(),et==null||et.setMobileOpen(!0))},hideArtifacts(){Hn(n)&&(an=!0,Cn())},upsertArtifact(l){return Hn(n)?(an=!1,D.upsertArtifact(l)):null},selectArtifact(l){Hn(n)&&D.selectArtifact(l)},clearArtifacts(){Hn(n)&&D.clearArtifacts()},focusInput(){return b&&!T||!J?!1:(J.focus(),!0)},async resolveApproval(l,g){let E=D.getMessages().find(k=>{var P;return k.variant==="approval"&&((P=k.approval)==null?void 0:P.id)===l});if(!(E!=null&&E.approval))throw new Error(`Approval not found: ${l}`);return D.resolveApproval(E.approval,g)},getMessages(){return D.getMessages()},getStatus(){return D.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&&T},isVoiceActive(){return Je.active},getState(){return{open:b&&T,launcherEnabled:b,voiceActive:Je.active,streaming:D.isStreaming()}},showCSATFeedback(l){!T&&b&&Et(!0,"system");let g=Q.querySelector(".persona-feedback-container");g&&g.remove();let y=Xs({onSubmit:async(E,k)=>{var P;D.isClientTokenMode()&&await D.submitCSATFeedback(E,k),(P=l==null?void 0:l.onSubmit)==null||P.call(l,E,k)},onDismiss:l==null?void 0:l.onDismiss,...l});Q.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!T&&b&&Et(!0,"system");let g=Q.querySelector(".persona-feedback-container");g&&g.remove();let y=Ks({onSubmit:async(E,k)=>{var P;D.isClientTokenMode()&&await D.submitNPSFeedback(E,k),(P=l==null?void 0:l.onSubmit)==null||P.call(l,E,k)},onDismiss:l==null?void 0:l.onDismiss,...l});Q.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return D.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return D.submitNPSFeedback(l,g)},destroy(){ht.forEach(l=>l()),j.remove(),N==null||N.destroy(),ie==null||ie.remove(),Sn&&le.removeEventListener("click",Sn)}};if((((_a=t==null?void 0:t.debugTools)!=null?_a:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,g={controller:Ae,getMessages:Ae.getMessages,getStatus:Ae.getStatus,getMetadata:Ae.getPersistentMetadata,updateMetadata:Ae.updatePersistentMetadata,clearHistory:()=>Ae.clearChat(),setVoiceActive:y=>y?Ae.startVoiceRecognition():Ae.stopVoiceRecognition()};window.AgentWidgetBrowser=g,ht.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=V=>{let F=V.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&Ae.focusInput()};if(window.addEventListener("persona:focusInput",g),ht.push(()=>{window.removeEventListener("persona:focusInput",g)}),ne){let V=ae=>{let ve=ae.detail;(!(ve!=null&&ve.instanceId)||ve.instanceId===l)&&Ae.showEventStream()},F=ae=>{let ve=ae.detail;(!(ve!=null&&ve.instanceId)||ve.instanceId===l)&&Ae.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",F),ht.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",F)})}let y=V=>{let F=V.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&Ae.showArtifacts()},E=V=>{let F=V.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&Ae.hideArtifacts()},k=V=>{let F=V.detail;F!=null&&F.instanceId&&F.instanceId!==l||F!=null&&F.artifact&&Ae.upsertArtifact(F.artifact)},P=V=>{let F=V.detail;F!=null&&F.instanceId&&F.instanceId!==l||typeof(F==null?void 0:F.id)=="string"&&Ae.selectArtifact(F.id)},W=V=>{let F=V.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&Ae.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",E),window.addEventListener("persona:upsertArtifact",k),window.addEventListener("persona:selectArtifact",P),window.addEventListener("persona:clearArtifacts",W),ht.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",E),window.removeEventListener("persona:upsertArtifact",k),window.removeEventListener("persona:selectArtifact",P),window.removeEventListener("persona:clearArtifacts",W)})}let yt=zp(n.persistState);if(yt&&b){let l=Up(yt.storage),g=`${yt.keyPrefix}widget-open`,y=`${yt.keyPrefix}widget-voice`,E=`${yt.keyPrefix}widget-voice-mode`;if(l){let k=((ja=yt.persist)==null?void 0:ja.openState)&&l.getItem(g)==="true",P=((za=yt.persist)==null?void 0:za.voiceState)&&l.getItem(y)==="true",W=((Ua=yt.persist)==null?void 0:Ua.voiceState)&&l.getItem(E)==="true";if(k&&setTimeout(()=>{Ae.open(),setTimeout(()=>{var V;if(P||W)Ae.startVoiceRecognition();else if((V=yt.persist)!=null&&V.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),(Va=yt.persist)!=null&&Va.openState&&(o.on("widget:opened",()=>{l.setItem(g,"true")}),o.on("widget:closed",()=>{l.setItem(g,"false")})),(qa=yt.persist)!=null&&qa.voiceState&&(o.on("voice:state",V=>{l.setItem(y,V.active?"true":"false")}),o.on("user:message",V=>{l.setItem(E,V.viaVoice?"true":"false")})),yt.clearOnChatClear){let V=()=>{l.removeItem(g),l.removeItem(y),l.removeItem(E)},F=()=>V();window.addEventListener("persona:clear-chat",F),ht.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}return c&&b&&setTimeout(()=>{Ae.open()},0),Ae};var Vp=(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},Fc=(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"},ra=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=""},Nc=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",ra(e)},ea=e=>{e.style.transition=""},ta=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=""},na=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ps=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},qp=(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))},Jp=(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 v,M,b,C,S,R;let i=jn(o),d=i.reveal==="push";qp(e,r,t,n,d),Jp(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,p=(M=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?M:!0,u=(C=(b=o==null?void 0:o.launcher)==null?void 0:b.mobileBreakpoint)!=null?C:640,f=c!=null?c.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),ta(r),ea(n),Nc(n),na(t),ps(s,n),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((R=(S=o==null?void 0:o.launcher)==null?void 0:S.zIndex)!=null?R:yn),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"),Nc(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",ta(r),ea(n),na(t),ps(s,n);let w=i.animate?"transform 180ms ease":"none",L=i.side==="right"?"translateX(100%)":"translateX(-100%)",B=a?"translateX(0)":L;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=w,n.style.transform=B,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",ea(n),ra(n),ps(s,n);let w=Vp(i.width,e.clientWidth),L=Math.max(0,e.clientWidth),B=i.animate?"transform 180ms ease":"none",T=i.side==="right"?a?`translateX(-${w}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${w}px)`;r.style.display="flex",r.style.flexDirection="row",r.style.flex="0 0 auto",r.style.minHeight="0",r.style.minWidth="0",r.style.alignItems="stretch",r.style.height="100%",r.style.width=`${L+w}px`,r.style.transition=B,r.style.transform=T,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${L}px`,t.style.maxWidth=`${L}px`,t.style.minWidth=`${L}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",ta(r),ra(n),na(t),ps(s,n);let w=i.reveal==="emerge";w?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let L=a?i.width:"0px",B=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",T=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${L}`,n.style.width=L,n.style.maxWidth=L,n.style.minWidth=L,n.style.minHeight="0",n.style.position="relative",n.style.overflow=w||T?"hidden":"visible",n.style.transition=B,w&&(n.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},Yp=(e,r)=>{let t=e.ownerDocument.createElement("div");return Fc(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){Fc(t,n)},destroy(){t.remove()}}},Gp=(e,r)=>{var S,R,w,L;let{ownerDocument:t}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("div"),c=t.createElement("aside"),p=t.createElement("div"),u=(R=(S=r==null?void 0:r.launcher)==null?void 0:S.enabled)==null||R?(L=(w=r==null?void 0:r.launcher)==null?void 0:w.autoExpand)!=null?L:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),n.insertBefore(a,e),d.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},v=()=>{m(),jn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Oc(a,i,d,c,p,r,u)}),f.observe(a))},M=()=>{Oc(a,i,d,c,p,r,u),v()},b=a.ownerDocument.defaultView,C=()=>{M()};return b==null||b.addEventListener("resize",C),jn(r).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),M(),{mode:"docked",host:p,shell:a,syncWidgetState(B){let T=B.launcherEnabled?B.open:!0;u!==T&&(u=T,M())},updateConfig(B){var T,Y;r=B,((Y=(T=r==null?void 0:r.launcher)==null?void 0:T.enabled)!=null?Y:!0)===!1&&(u=!0),M()},destroy(){b==null||b.removeEventListener("resize",C),m(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},us=(e,r)=>Yt(r)?Gp(e,r):Yp(e,r);var oa={},Xp=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},Kp=()=>{try{if(typeof oa!="undefined"&&oa.url)return new URL("../widget.css",oa.url).href}catch{}return null},$c=(e,r)=>{let t=Kp(),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)}},_c=e=>{var b;let r=Xp(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=us(r,s),a,i=[],d=(C,S)=>{var B,T;let w=!((T=(B=S==null?void 0:S.launcher)==null?void 0:B.enabled)!=null?T:!0)||Yt(S),L=n.createElement("div");if(L.setAttribute("data-persona-root","true"),w&&(L.style.height="100%",L.style.display="flex",L.style.flexDirection="column",L.style.flex="1",L.style.minHeight="0"),t){let Y=C.attachShadow({mode:"open"});Y.appendChild(L),$c(Y,n)}else C.appendChild(L),$c(C,n);return r.id&&L.setAttribute("data-persona-instance",r.id),L},c=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(C=>C()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},u=()=>{let C=d(o.host,s);a=Qs(C,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(C=>C()),i=[],a.destroy()};u(),(b=e.onReady)==null||b.call(e);let m=C=>{f(),o.destroy(),o=us(r,C),s=C,u()},v={update(C){var L,B,T,Y,ue,ce;let S={...s,...C,launcher:{...(L=s==null?void 0:s.launcher)!=null?L:{},...(B=C==null?void 0:C.launcher)!=null?B:{},dock:{...(Y=(T=s==null?void 0:s.launcher)==null?void 0:T.dock)!=null?Y:{},...(ce=(ue=C==null?void 0:C.launcher)==null?void 0:ue.dock)!=null?ce:{}}}},R=Yt(s),w=Yt(S);if(R!==w){m(S);return}s=S,o.updateConfig(s),a.update(C),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},M=new Proxy(v,{get(C,S,R){if(S==="host")return o.host;if(S in C)return Reflect.get(C,S,R);let w=a[S];return typeof w=="function"?w.bind(a):w}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=M),M};var qc=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),Zp=new Set(["button","a","input","select","textarea","details","summary"]),Qp=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),sa=/\b(product|card|item|listing|result)\b/i,ia=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,eu=3e3,tu=100;function Jc(e){let r=typeof e.className=="string"?e.className:"";if(sa.test(r)||e.id&&sa.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&sa.test(n.value))return!0}return!1}function Yc(e){var r;return ia.test(((r=e.textContent)!=null?r:"").trim())}function Gc(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 nu(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function jc(e){let r=e.match(ia);return r?r[0]:null}function zc(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 ru(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 ou="commerce-card",su="result-card";function Uc(e){return!Jc(e)||!Yc(e)||!Gc(e)&&!nu(e)?0:5200}function Vc(e){var n;return!Jc(e)||Yc(e)||!Gc(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 Xc=[{id:ou,scoreElement(e){return Uc(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||ia.test(n)&&n.length<32)}return!0},formatSummary(e,r){var d,c,p;if(Uc(e)===0)return null;let{title:t,href:n}=zc(e),s=(p=(c=jc(((d=e.textContent)!=null?d:"").trim()))!=null?c:jc(r.text))!=null?p:"",o=ru(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(`
98
+ `)}},{id:su,scoreElement(e){return Vc(e)},formatSummary(e,r){if(Vc(e)===0)return null;let{title:t,href:n}=zc(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
99
+ `)}}];function au(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function iu(e){var p,u,f,m,v,M,b,C,S,R,w,L,B;let r=(p=e.options)!=null?p:{},t=(f=(u=r.maxElements)!=null?u:e.maxElements)!=null?f:80,n=(v=(m=r.excludeSelector)!=null?m:e.excludeSelector)!=null?v:".persona-host",s=(b=(M=r.maxTextLength)!=null?M:e.maxTextLength)!=null?b:200,o=(S=(C=r.visibleOnly)!=null?C:e.visibleOnly)!=null?S:!0,a=(R=r.root)!=null?R:e.root,i=(w=r.mode)!=null?w:"structured",d=(L=r.maxCandidates)!=null?L:Math.max(500,t*10),c=(B=e.rules)!=null?B:Xc;return i==="simple"&&e.rules&&e.rules.length>0?(au(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:n,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function aa(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var lu=["data-testid","data-product","data-action","data-id","data-name","data-type"];function cu(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"||Zp.has(r)||t&&Qp.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Kc(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 du(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 p=e.attributes[c];p.name.startsWith("data-")&&(r[p.name]=p.value)}return r}function Zc(e){let r=e.tagName.toLowerCase();if(e.id){let s=`#${aa(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of lu){let o=e.getAttribute(s);if(o){let a=`${r}[${s}="${aa(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=>aa(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 pu(e){return e==="static"?tu:eu}function Qc(e,r){var s;let t=e.tagName.toLowerCase(),n=((s=e.textContent)!=null?s:"").trim().substring(0,r);return{selector:Zc(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:cu(e),attributes:du(e)}}function uu(e,r,t,n){let s=pu(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 gu(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 mu(e,r){let t={doc:r.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,s=[],o=0,a=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,p=c.tagName.toLowerCase();if(qc.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Kc(c)){i=a.nextNode();continue}let u=Qc(c,e.maxTextLength),f=u.text.length>0,m=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(b=>b==="role");if(!f&&!m){i=a.nextNode();continue}if(n.has(u.selector)){i=a.nextNode();continue}n.add(u.selector);let{score:v,formattingRule:M}=uu(c,u,e.rules,t);s.push({el:c,domIndex:o,enriched:u,score:v,formattingRule:M}),o+=1}i=a.nextNode()}s.sort((c,p)=>{let u=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex});let d=[];for(let c of s){if(d.length>=e.maxElements)break;gu(d,c)||d.push(c)}return d.sort((c,p)=>{let u=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:u===1&&p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex}),d.map(c=>{var f;let p;if((f=c.formattingRule)!=null&&f.formatSummary){let m=c.formattingRule.formatSummary(c.el,c.enriched,t);m&&(p=m)}let u={...c.enriched};return p&&(u.formattedSummary=p),u})}function fu(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(qc.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Kc(d)){o=s.nextNode();continue}let p=Qc(d,e.maxTextLength),u=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(m=>m==="role");if(!u&&!f){o=s.nextNode();continue}n.has(p.selector)||(n.add(p.selector),t.push(p))}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 hu(e={}){var n;let r=iu(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?fu(r,t):mu(r,t):[]}var gs=100;function yu(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:
100
100
  ${a.map(i=>`- ${i.split(`
101
101
  `).join(`
102
102
  `)}`).join(`
103
- `)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)t==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,cs)}" (clickable)`);n.push(`Interactive elements:
103
+ `)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)t==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,gs)}" (clickable)`);n.push(`Interactive elements:
104
104
  ${a.join(`
105
- `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,cs)}" (navigable)`);n.push(`Navigation links:
105
+ `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,gs)}" (navigable)`);n.push(`Navigation links:
106
106
  ${a.join(`
107
- `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,cs)}" (input)`);n.push(`Form inputs:
107
+ `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,gs)}" (input)`);n.push(`Form inputs:
108
108
  ${a.join(`
109
- `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,cs)}"`);n.push(`Content:
109
+ `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,gs)}"`);n.push(`Content:
110
110
  ${a.join(`
111
111
  `)}`)}return n.join(`
112
112
 
113
- `)}var Zc={name:"@runtypelabs/persona",version:"3.8.2",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var eo=Zc.version;function rr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function yu(e){if(e)return{getHeaders:rr(e.getHeaders),onFeedback:rr(e.onFeedback),onCopy:rr(e.onCopy),requestMiddleware:rr(e.requestMiddleware),actionHandlers:rr(e.actionHandlers),actionParsers:rr(e.actionParsers),postprocessMessage:rr(e.postprocessMessage),contextProviders:rr(e.contextProviders),streamParser:rr(e.streamParser)}}var Qc=`({ text, message }: any) => {
113
+ `)}var ed={name:"@runtypelabs/persona",version:"3.9.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var ro=ed.version;function ar(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function xu(e){if(e)return{getHeaders:ar(e.getHeaders),onFeedback:ar(e.onFeedback),onCopy:ar(e.onCopy),requestMiddleware:ar(e.requestMiddleware),actionHandlers:ar(e.actionHandlers),actionParsers:ar(e.actionParsers),postprocessMessage:ar(e.postprocessMessage),contextProviders:ar(e.contextProviders),streamParser:ar(e.streamParser)}}var td=`({ text, message }: any) => {
114
114
  const jsonSource = (message as any).rawContent || text || message.content;
115
115
  if (!jsonSource || typeof jsonSource !== 'string') return null;
116
116
  let cleanJson = jsonSource
@@ -123,7 +123,7 @@ ${a.join(`
123
123
  if (parsed.action) return { type: parsed.action, payload: parsed };
124
124
  } catch (e) { return null; }
125
125
  return null;
126
- }`,ed=`function(ctx) {
126
+ }`,nd=`function(ctx) {
127
127
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
128
128
  if (!jsonSource || typeof jsonSource !== 'string') return null;
129
129
  var cleanJson = jsonSource
@@ -136,7 +136,7 @@ ${a.join(`
136
136
  if (parsed.action) return { type: parsed.action, payload: parsed };
137
137
  } catch (e) { return null; }
138
138
  return null;
139
- }`,td=`(action: any, context: any) => {
139
+ }`,rd=`(action: any, context: any) => {
140
140
  if (action.type !== 'nav_then_click') return;
141
141
  const payload = action.payload || action.raw || {};
142
142
  const url = payload?.page;
@@ -153,7 +153,7 @@ ${a.join(`
153
153
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
154
154
  window.location.href = targetUrl;
155
155
  return { handled: true, displayText: text };
156
- }`,nd=`function(action, context) {
156
+ }`,od=`function(action, context) {
157
157
  if (action.type !== 'nav_then_click') return;
158
158
  var payload = action.payload || action.raw || {};
159
159
  var url = payload.page;
@@ -170,26 +170,26 @@ ${a.join(`
170
170
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
171
171
  window.location.href = targetUrl;
172
172
  return { handled: true, displayText: text };
173
- }`,bu=`(parsed: any) => {
173
+ }`,vu=`(parsed: any) => {
174
174
  if (!parsed || typeof parsed !== 'object') return null;
175
175
  if (parsed.action === 'nav_then_click') return 'Navigating...';
176
176
  if (parsed.action === 'message') return parsed.text || '';
177
177
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
178
178
  return parsed.text || null;
179
- }`,xu=`function(parsed) {
179
+ }`,Cu=`function(parsed) {
180
180
  if (!parsed || typeof parsed !== 'object') return null;
181
181
  if (parsed.action === 'nav_then_click') return 'Navigating...';
182
182
  if (parsed.action === 'message') return parsed.text || '';
183
183
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
184
184
  return parsed.text || null;
185
- }`;function vu(e){if(!e)return null;let r=e.toString();return r.includes("createJsonStreamParser")||r.includes("partial-json")?"json":r.includes("createRegexJsonParser")||r.includes("regex")?"regex-json":r.includes("createXmlParser")||r.includes("<text>")?"xml":null}function ds(e){var r,t;return(t=(r=e.parserType)!=null?r:vu(e.streamParser))!=null?t:"plain"}function ps(e,r){let t=[];return e.toolCall&&(t.push(`${r}toolCall: {`),Object.entries(e.toolCall).forEach(([n,s])=>{typeof s=="string"&&t.push(`${r} ${n}: "${s}",`)}),t.push(`${r}},`)),t}function us(e,r,t){let n=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(t==null?void 0:t.onFeedback)||(t==null?void 0:t.onCopy);return(s||o)&&(n.push(`${r}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?n.push(`${r} ${a}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${a}: ${i},`))}),t!=null&&t.onFeedback&&n.push(`${r} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&n.push(`${r} onCopy: ${t.onCopy},`),n.push(`${r}},`)),n}function gs(e,r){let t=[];if(e.markdown){let n=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(n||s)&&(t.push(`${r}markdown: {`),n&&(t.push(`${r} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`)}),t.push(`${r} },`)),s&&t.push(`${r} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${r}},`))}return t}function ms(e,r){let t=[];if(e.layout){let n=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(n||s)&&(t.push(`${r}layout: {`),n&&(t.push(`${r} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`))}),t.push(`${r} },`)),s&&(t.push(`${r} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${r} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?t.push(`${r} ${i}: "${d}",`):typeof d=="boolean"&&t.push(`${r} ${i}: ${d},`)}),t.push(`${r} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(t.push(`${r} timestamp: {`),Object.entries(a).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?t.push(`${r} ${d}: "${c}",`):typeof c=="boolean"&&t.push(`${r} ${d}: ${c},`))}),t.push(`${r} },`)):typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`))}),t.push(`${r} },`)),t.push(`${r}},`))}return t}function ra(e,r){let t=[];return e&&(e.getHeaders&&t.push(`${r}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${r}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${r}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${r}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${r}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${r}streamParser: ${e.streamParser},`)),t}function rd(e,r,t){Object.entries(r).forEach(([n,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${t}${n}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${t}${n}: {`),rd(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${n}: ${JSON.stringify(s)},`)}})}function Cr(e,r,t,n){t&&(e.push(`${n}${r}: {`),rd(e,t,`${n} `),e.push(`${n}},`))}function Cu(e,r="esm",t){let n={...e};delete n.postprocessMessage,delete n.initialMessages;let s=t?{...t,hooks:yu(t.hooks)}:void 0;return r==="esm"?wu(n,s):r==="script-installer"?Eu(n):r==="script-advanced"?Mu(n,s):r==="react-component"?Su(n,s):r==="react-advanced"?Au(n,s):Tu(n,s)}function wu(e,r){let t=r==null?void 0:r.hooks,n=ds(e),s=n!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Cr(o,"theme",e.theme," "),e.launcher&&Cr(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...ps(e," ")),o.push(...us(e," ",t)),o.push(...gs(e," ")),o.push(...ms(e," ")),o.push(...ra(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
186
- `)}function Su(e,r){let t=r==null?void 0:r.hooks,n=ds(e),s=n!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Cr(o,"theme",e.theme," "),e.launcher&&Cr(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...ps(e," ")),o.push(...us(e," ",t)),o.push(...gs(e," ")),o.push(...ms(e," ")),o.push(...ra(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
187
- `)}function Au(e,r){let t=r==null?void 0:r.hooks,n=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Cr(n,"theme",e.theme," "),e.launcher&&Cr(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{n.push(` ${s}: "${o}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"?n.push(` ${s}: ${o},`):typeof o=="number"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{n.push(` ${s}: ${o},`)}),n.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{n.push(` "${s}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...ps(e," ")),n.push(...us(e," ",t)),n.push(...gs(e," ")),n.push(...ms(e," ")),t!=null&&t.getHeaders&&n.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&n.push(` contextProviders: ${t.contextProviders},`),e.debug&&n.push(` debug: ${e.debug},`),n.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?n.push(` streamParser: ${t.streamParser},`):(n.push(" // Flexible JSON stream parser for handling structured actions"),n.push(` streamParser: () => createFlexibleJsonStreamParser(${bu}),`)),t!=null&&t.actionParsers?(n.push(" // Action parsers (custom merged with defaults)"),n.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),n.push(" // Built-in parser for markdown-wrapped JSON"),n.push(` ${Qc}`),n.push(" ],")):(n.push(" // Action parsers to detect JSON actions in responses"),n.push(" actionParsers: ["),n.push(" defaultJsonActionParser,"),n.push(" // Parser for markdown-wrapped JSON"),n.push(` ${Qc}`),n.push(" ],")),t!=null&&t.actionHandlers?(n.push(" // Action handlers (custom merged with defaults)"),n.push(` actionHandlers: [...(${t.actionHandlers}),`),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Built-in handler for nav_then_click action"),n.push(` ${td}`),n.push(" ],")):(n.push(" // Action handlers for navigation and other actions"),n.push(" actionHandlers: ["),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Handler for nav_then_click action"),n.push(` ${td}`),n.push(" ],")),t!=null&&t.postprocessMessage?n.push(` postprocessMessage: ${t.postprocessMessage},`):n.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(n.push(" // Request middleware (custom merged with DOM context)"),n.push(" requestMiddleware: ({ payload, config }) => {"),n.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),n.push(" const merged = customResult || payload;"),n.push(" return {"),n.push(" ...merged,"),n.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),n.push(" };"),n.push(" }")):(n.push(" requestMiddleware: ({ payload }) => {"),n.push(" return {"),n.push(" ...payload,"),n.push(" metadata: collectDOMContext()"),n.push(" };"),n.push(" }")),n.push(" }"),n.push(" });"),n.push(""),n.push(" // Save state on message events"),n.push(" const handleMessage = () => {"),n.push(" const session = handle?.getSession?.();"),n.push(" if (session) {"),n.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),n.push(" messages: session.messages,"),n.push(" timestamp: new Date().toISOString()"),n.push(" }));"),n.push(" }"),n.push(" };"),n.push(""),n.push(" // Clear state on clear chat"),n.push(" const handleClearChat = () => {"),n.push(" localStorage.removeItem(STORAGE_KEY);"),n.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),n.push(" };"),n.push(""),n.push(" window.addEventListener('persona:message', handleMessage);"),n.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),n.push(""),n.push(" // Cleanup on unmount"),n.push(" return () => {"),n.push(" window.removeEventListener('persona:message', handleMessage);"),n.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),n.push(" if (handle) {"),n.push(" handle.destroy();"),n.push(" }"),n.push(" };"),n.push(" }, []);"),n.push(""),n.push(" return null; // Widget injects itself into the DOM"),n.push("}"),n.push(""),n.push("// Usage: Collects DOM context for AI-powered navigation"),n.push("// Features:"),n.push("// - Extracts page elements (products, buttons, links)"),n.push("// - Persists chat history across page loads"),n.push("// - Handles navigation actions (nav_then_click)"),n.push("// - Processes structured JSON actions from AI"),n.push("//"),n.push("// Example usage in Next.js:"),n.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),n.push("//"),n.push("// export default function RootLayout({ children }) {"),n.push("// return ("),n.push('// <html lang="en">'),n.push("// <body>"),n.push("// {children}"),n.push("// <ChatWidgetAdvanced />"),n.push("// </body>"),n.push("// </html>"),n.push("// );"),n.push("// }"),n.join(`
188
- `)}function od(e){var s;let r=ds(e),t=r!=="plain",n={};if(e.apiUrl&&(n.apiUrl=e.apiUrl),e.clientToken&&(n.clientToken=e.clientToken),e.flowId&&(n.flowId=e.flowId),t&&(n.parserType=r),e.theme&&(n.theme=e.theme),e.launcher&&(n.launcher=e.launcher),e.copy&&(n.copy=e.copy),e.sendButton&&(n.sendButton=e.sendButton),e.voiceRecognition&&(n.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(n.statusIndicator=e.statusIndicator),e.features&&(n.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(n.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(n.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(n.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(n.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(n.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(n.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([p,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(c[p]=u)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(n.layout=o)}return n}function Eu(e){let r=od(e),t=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${eo}/dist/install.global.js" data-config='${t}'></script>`}function Tu(e,r){let t=r==null?void 0:r.hooks,n=ds(e),s=n!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${eo}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${eo}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Cr(o,"theme",e.theme," "),e.launcher&&Cr(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...ps(e," ")),o.push(...us(e," ",t)),o.push(...gs(e," ")),o.push(...ms(e," ")),o.push(...ra(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
189
- `)}function Mu(e,r){let t=r==null?void 0:r.hooks,n=od(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(n,null,2).split(`
185
+ }`;function wu(e){if(!e)return null;let r=e.toString();return r.includes("createJsonStreamParser")||r.includes("partial-json")?"json":r.includes("createRegexJsonParser")||r.includes("regex")?"regex-json":r.includes("createXmlParser")||r.includes("<text>")?"xml":null}function ms(e){var r,t;return(t=(r=e.parserType)!=null?r:wu(e.streamParser))!=null?t:"plain"}function fs(e,r){let t=[];return e.toolCall&&(t.push(`${r}toolCall: {`),Object.entries(e.toolCall).forEach(([n,s])=>{typeof s=="string"&&t.push(`${r} ${n}: "${s}",`)}),t.push(`${r}},`)),t}function hs(e,r,t){let n=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(t==null?void 0:t.onFeedback)||(t==null?void 0:t.onCopy);return(s||o)&&(n.push(`${r}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?n.push(`${r} ${a}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${a}: ${i},`))}),t!=null&&t.onFeedback&&n.push(`${r} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&n.push(`${r} onCopy: ${t.onCopy},`),n.push(`${r}},`)),n}function ys(e,r){let t=[];if(e.markdown){let n=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(n||s)&&(t.push(`${r}markdown: {`),n&&(t.push(`${r} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`)}),t.push(`${r} },`)),s&&t.push(`${r} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${r}},`))}return t}function bs(e,r){let t=[];if(e.layout){let n=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(n||s)&&(t.push(`${r}layout: {`),n&&(t.push(`${r} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`))}),t.push(`${r} },`)),s&&(t.push(`${r} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${r} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?t.push(`${r} ${i}: "${d}",`):typeof d=="boolean"&&t.push(`${r} ${i}: ${d},`)}),t.push(`${r} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(t.push(`${r} timestamp: {`),Object.entries(a).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?t.push(`${r} ${d}: "${c}",`):typeof c=="boolean"&&t.push(`${r} ${d}: ${c},`))}),t.push(`${r} },`)):typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`))}),t.push(`${r} },`)),t.push(`${r}},`))}return t}function la(e,r){let t=[];return e&&(e.getHeaders&&t.push(`${r}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${r}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${r}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${r}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${r}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${r}streamParser: ${e.streamParser},`)),t}function sd(e,r,t){Object.entries(r).forEach(([n,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${t}${n}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${t}${n}: {`),sd(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${n}: ${JSON.stringify(s)},`)}})}function Sr(e,r,t,n){t&&(e.push(`${n}${r}: {`),sd(e,t,`${n} `),e.push(`${n}},`))}function Su(e,r="esm",t){let n={...e};delete n.postprocessMessage,delete n.initialMessages;let s=t?{...t,hooks:xu(t.hooks)}:void 0;return r==="esm"?Au(n,s):r==="script-installer"?Mu(n):r==="script-advanced"?Lu(n,s):r==="react-component"?Eu(n,s):r==="react-advanced"?Tu(n,s):ku(n,s)}function Au(e,r){let t=r==null?void 0:r.hooks,n=ms(e),s=n!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Sr(o,"theme",e.theme," "),e.launcher&&Sr(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...fs(e," ")),o.push(...hs(e," ",t)),o.push(...ys(e," ")),o.push(...bs(e," ")),o.push(...la(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
186
+ `)}function Eu(e,r){let t=r==null?void 0:r.hooks,n=ms(e),s=n!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Sr(o,"theme",e.theme," "),e.launcher&&Sr(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...fs(e," ")),o.push(...hs(e," ",t)),o.push(...ys(e," ")),o.push(...bs(e," ")),o.push(...la(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
187
+ `)}function Tu(e,r){let t=r==null?void 0:r.hooks,n=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Sr(n,"theme",e.theme," "),e.launcher&&Sr(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{n.push(` ${s}: "${o}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"?n.push(` ${s}: ${o},`):typeof o=="number"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{n.push(` ${s}: ${o},`)}),n.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{n.push(` "${s}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...fs(e," ")),n.push(...hs(e," ",t)),n.push(...ys(e," ")),n.push(...bs(e," ")),t!=null&&t.getHeaders&&n.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&n.push(` contextProviders: ${t.contextProviders},`),e.debug&&n.push(` debug: ${e.debug},`),n.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?n.push(` streamParser: ${t.streamParser},`):(n.push(" // Flexible JSON stream parser for handling structured actions"),n.push(` streamParser: () => createFlexibleJsonStreamParser(${vu}),`)),t!=null&&t.actionParsers?(n.push(" // Action parsers (custom merged with defaults)"),n.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),n.push(" // Built-in parser for markdown-wrapped JSON"),n.push(` ${td}`),n.push(" ],")):(n.push(" // Action parsers to detect JSON actions in responses"),n.push(" actionParsers: ["),n.push(" defaultJsonActionParser,"),n.push(" // Parser for markdown-wrapped JSON"),n.push(` ${td}`),n.push(" ],")),t!=null&&t.actionHandlers?(n.push(" // Action handlers (custom merged with defaults)"),n.push(` actionHandlers: [...(${t.actionHandlers}),`),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Built-in handler for nav_then_click action"),n.push(` ${rd}`),n.push(" ],")):(n.push(" // Action handlers for navigation and other actions"),n.push(" actionHandlers: ["),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Handler for nav_then_click action"),n.push(` ${rd}`),n.push(" ],")),t!=null&&t.postprocessMessage?n.push(` postprocessMessage: ${t.postprocessMessage},`):n.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(n.push(" // Request middleware (custom merged with DOM context)"),n.push(" requestMiddleware: ({ payload, config }) => {"),n.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),n.push(" const merged = customResult || payload;"),n.push(" return {"),n.push(" ...merged,"),n.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),n.push(" };"),n.push(" }")):(n.push(" requestMiddleware: ({ payload }) => {"),n.push(" return {"),n.push(" ...payload,"),n.push(" metadata: collectDOMContext()"),n.push(" };"),n.push(" }")),n.push(" }"),n.push(" });"),n.push(""),n.push(" // Save state on message events"),n.push(" const handleMessage = () => {"),n.push(" const session = handle?.getSession?.();"),n.push(" if (session) {"),n.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),n.push(" messages: session.messages,"),n.push(" timestamp: new Date().toISOString()"),n.push(" }));"),n.push(" }"),n.push(" };"),n.push(""),n.push(" // Clear state on clear chat"),n.push(" const handleClearChat = () => {"),n.push(" localStorage.removeItem(STORAGE_KEY);"),n.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),n.push(" };"),n.push(""),n.push(" window.addEventListener('persona:message', handleMessage);"),n.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),n.push(""),n.push(" // Cleanup on unmount"),n.push(" return () => {"),n.push(" window.removeEventListener('persona:message', handleMessage);"),n.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),n.push(" if (handle) {"),n.push(" handle.destroy();"),n.push(" }"),n.push(" };"),n.push(" }, []);"),n.push(""),n.push(" return null; // Widget injects itself into the DOM"),n.push("}"),n.push(""),n.push("// Usage: Collects DOM context for AI-powered navigation"),n.push("// Features:"),n.push("// - Extracts page elements (products, buttons, links)"),n.push("// - Persists chat history across page loads"),n.push("// - Handles navigation actions (nav_then_click)"),n.push("// - Processes structured JSON actions from AI"),n.push("//"),n.push("// Example usage in Next.js:"),n.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),n.push("//"),n.push("// export default function RootLayout({ children }) {"),n.push("// return ("),n.push('// <html lang="en">'),n.push("// <body>"),n.push("// {children}"),n.push("// <ChatWidgetAdvanced />"),n.push("// </body>"),n.push("// </html>"),n.push("// );"),n.push("// }"),n.join(`
188
+ `)}function ad(e){var s;let r=ms(e),t=r!=="plain",n={};if(e.apiUrl&&(n.apiUrl=e.apiUrl),e.clientToken&&(n.clientToken=e.clientToken),e.flowId&&(n.flowId=e.flowId),t&&(n.parserType=r),e.theme&&(n.theme=e.theme),e.launcher&&(n.launcher=e.launcher),e.copy&&(n.copy=e.copy),e.sendButton&&(n.sendButton=e.sendButton),e.voiceRecognition&&(n.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(n.statusIndicator=e.statusIndicator),e.features&&(n.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(n.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(n.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(n.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(n.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(n.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(n.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([p,u])=>{p!=="format"&&(typeof u=="string"||typeof u=="boolean")&&(c[p]=u)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(n.layout=o)}return n}function Mu(e){let r=ad(e),t=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ro}/dist/install.global.js" data-config='${t}'></script>`}function ku(e,r){let t=r==null?void 0:r.hooks,n=ms(e),s=n!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ro}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ro}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Sr(o,"theme",e.theme," "),e.launcher&&Sr(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...fs(e," ")),o.push(...hs(e," ",t)),o.push(...ys(e," ")),o.push(...bs(e," ")),o.push(...la(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
189
+ `)}function Lu(e,r){let t=r==null?void 0:r.hooks,n=ad(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(n,null,2).split(`
190
190
  `).map((a,i)=>i===0?a:" "+a).join(`
191
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${eo}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return t!=null&&t.getHeaders&&(o.push(` widgetConfig.getHeaders = ${t.getHeaders};`),o.push("")),t!=null&&t.contextProviders&&(o.push(` widgetConfig.contextProviders = ${t.contextProviders};`),o.push("")),t!=null&&t.streamParser?o.push(` widgetConfig.streamParser = ${t.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${xu});`),o.push(" };")),o.push(""),t!=null&&t.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${t.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${ed}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${ed}`),o.push(" ];")),o.push(""),t!=null&&t.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${t.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${nd}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${nd}`),o.push(" ];")),o.push(""),t!=null&&t.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${t.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),t!=null&&t.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${t.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(t!=null&&t.onFeedback||t!=null&&t.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),t!=null&&t.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${t.onFeedback};`),t!=null&&t.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${t.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
192
- `)}var sd={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ad=.1,id=.15,ld=1.5,oa=24,cd=40,ku=`
191
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${ro}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return t!=null&&t.getHeaders&&(o.push(` widgetConfig.getHeaders = ${t.getHeaders};`),o.push("")),t!=null&&t.contextProviders&&(o.push(` widgetConfig.contextProviders = ${t.contextProviders};`),o.push("")),t!=null&&t.streamParser?o.push(` widgetConfig.streamParser = ${t.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${Cu});`),o.push(" };")),o.push(""),t!=null&&t.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${t.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${nd}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${nd}`),o.push(" ];")),o.push(""),t!=null&&t.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${t.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${od}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${od}`),o.push(" ];")),o.push(""),t!=null&&t.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${t.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),t!=null&&t.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${t.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(t!=null&&t.onFeedback||t!=null&&t.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),t!=null&&t.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${t.onFeedback};`),t!=null&&t.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${t.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
192
+ `)}var id={desktop:{w:1280,h:800},mobile:{w:390,h:844}},ld=.1,cd=.15,dd=1.5,ca=24,pd=40,Iu=`
193
193
  /* \u2500\u2500 Root \u2500\u2500 */
194
194
  .persona-dc-root {
195
195
  display: flex;
@@ -340,7 +340,7 @@ ${a.join(`
340
340
  .persona-dc-stage {
341
341
  height: 550px;
342
342
  min-height: 400px;
343
- padding: ${oa}px;
343
+ padding: ${ca}px;
344
344
  overflow: auto;
345
345
  background: #f0f1f3;
346
346
  background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
@@ -430,5 +430,5 @@ ${a.join(`
430
430
  min-height: 300px;
431
431
  }
432
432
  }
433
- `;function Lu(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=ku,document.head.appendChild(e)}function Iu(e,r){let t=e.clientWidth-oa*2-cd,n=e.clientHeight-oa*2-cd;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function Pu(e,r,t,n,s){e.style.width=`${t.w*n}px`,e.style.height=`${t.h*n}px`,e.style.borderRadius=s==="mobile"?`${32*n}px`:"10px",r.style.width=`${t.w}px`,r.style.height=`${t.h}px`,r.style.transformOrigin="top left",r.style.transform=`scale(${n})`}function Wu(e,r){let{items:t,initialIndex:n=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:c}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");Lu();let p=Math.max(0,Math.min(n,t.length-1)),u=s,h=o,m=null,C=1,M=!1,b=f("div","persona-dc-root"),x=f("div","persona-dc-toolbar"),S=f("div","persona-dc-toolbar-lead"),F=f("div","persona-dc-toolbar-trail"),w=It({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>ot(-1)}),L=f("div");L.style.position="relative";let R=f("button","persona-dc-title-btn");R.type="button",R.setAttribute("aria-expanded","false"),R.setAttribute("aria-haspopup","listbox");let T=f("span","persona-dc-title-text"),Y=f("span","persona-dc-title-chevron"),ue=pe("chevron-down",12,"currentColor",2);ue&&Y.appendChild(ue),R.append(T,Y);let se=f("div","persona-dc-dropdown");se.setAttribute("role","listbox"),se.style.display="none";let $=!1;function te(){se.innerHTML="";for(let _=0;_<t.length;_++){let z=t[_],Q=f("button","persona-dc-dropdown-item");Q.type="button",Q.setAttribute("role","option"),Q.setAttribute("aria-current",_===p?"true":"false");let lt=f("span");if(lt.textContent=z.title,Q.appendChild(lt),z.description){let K=f("span","persona-dc-dropdown-desc");K.textContent=z.description,Q.appendChild(K)}Q.addEventListener("click",()=>{ne(),At(_)}),se.appendChild(Q)}}function Ae(){$=!$,se.style.display=$?"":"none",R.setAttribute("aria-expanded",$?"true":"false"),$&&te()}function ne(){$&&($=!1,se.style.display="none",R.setAttribute("aria-expanded","false"))}R.addEventListener("click",_=>{_.stopPropagation(),Ae()});let Ce=()=>ne();document.addEventListener("click",Ce),L.append(R,se);let Me=It({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>ot(1)}),de=f("span","persona-dc-counter");S.append(w,L,Me,de);let fe=null;i&&(fe=ts({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:_=>{u=_,De.dataset.device=u,m=null,j()}}),F.appendChild(fe.element));let Se=null;if(a){let _=f("div","persona-dc-zoom-controls"),z=It({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let K=m!=null?m:C;m=Math.max(id,K-ad),j()}});Se=f("span","persona-dc-zoom-level"),Se.title="Reset to 100%",Se.style.cursor="pointer",Se.addEventListener("click",()=>{m=1,j()});let Q=It({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let K=m!=null?m:C;m=Math.min(ld,K+ad),j()}}),lt=It({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,j()}});_.append(z,Se,Q,lt),F.appendChild(_)}if(d){let _=f("div","persona-dc-separator");F.appendChild(_);let z=ts({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:h,onSelect:Q=>{h=Q,De.dataset.colorScheme=h,Ie()}});F.appendChild(z.element)}let J=f("div","persona-dc-separator");F.appendChild(J);let ae=It({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[p].url,"_blank")}});F.appendChild(ae),x.append(S,F);let ge=f("div","persona-dc-stage"),De=f("div","persona-dc-iframe-wrapper");De.dataset.device=u,De.dataset.colorScheme=h;let Le=f("iframe","persona-dc-iframe");Le.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),Le.setAttribute("loading","lazy"),Le.title=t[p].title,De.appendChild(Le),ge.appendChild(De),b.append(x,ge),e.appendChild(b);function Ie(){var _;try{let z=(_=Le.contentDocument)==null?void 0:_.body;if(!z)return;h==="dark"?z.classList.add("theme-dark"):z.classList.remove("theme-dark")}catch{}}Le.addEventListener("load",()=>Ie());function Re(){let _=t[p];T.textContent=_.title,de.textContent=`${p+1} / ${t.length}`,Le.title=_.title}function ot(_){let z=((p+_)%t.length+t.length)%t.length;At(z)}function At(_){_<0||_>=t.length||(p=_,Le.src=t[p].url,Re(),c==null||c(p,t[p]))}function j(){var Q;if(M)return;let _=(Q=sd[u])!=null?Q:sd.desktop;C=Iu(ge,_);let z=Math.max(id,Math.min(ld,m!=null?m:C));Pu(De,Le,_,z,u),Se&&(Se.textContent=`${Math.round(z*100)}%`)}let U=new ResizeObserver(()=>j());U.observe(ge),Re(),Le.src=t[p].url,requestAnimationFrame(()=>j());function re(){M||(M=!0,U.disconnect(),document.removeEventListener("click",Ce),b.remove())}return{element:b,goTo:At,next:()=>ot(1),prev:()=>ot(-1),getIndex:()=>p,setDevice(_){u=_,De.dataset.device=_,fe==null||fe.setSelected(_),m=null,j()},setColorScheme(_){h=_,De.dataset.colorScheme=_},setZoom(_){m=_,j()},destroy:re}}function Ru(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function Hu(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Bu(e){return{name:"@persona/brand",version:"1.0.0",transform(r){var n;let t={...r.palette};return(n=e.colors)!=null&&n.primary&&(t.colors={...t.colors,primary:{50:Jn(e.colors.primary,.95),100:Jn(e.colors.primary,.9),200:Jn(e.colors.primary,.8),300:Jn(e.colors.primary,.7),400:Jn(e.colors.primary,.6),500:e.colors.primary,600:Jn(e.colors.primary,.8),700:Jn(e.colors.primary,.7),800:Jn(e.colors.primary,.6),900:Jn(e.colors.primary,.5),950:Jn(e.colors.primary,.45)}}),{...r,palette:t}}}}function Du(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Fu(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Jn(e,r){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-r)),a=Math.round(n+(255-n)*(1-r)),i=Math.round(s+(255-s)*(1-r));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Nu(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Ou={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},dd={components:{panel:{borderRadius:"0",shadow:"none"}}},pd={id:"shop",label:"Shopping Assistant",config:{theme:Ou,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:"min(400px, calc(100vw - 24px))"},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},ud={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:dd}},gd={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:dd}},md={shop:pd,minimal:ud,fullscreen:gd};function $u(e){return md[e]}var Rh=Oc;export{zr as AgentWidgetClient,xo as AgentWidgetSession,Ur as AttachmentManager,Gl as DEFAULT_COMPONENTS,Kl as DEFAULT_PALETTE,Xl as DEFAULT_SEMANTIC,St as DEFAULT_WIDGET_CONFIG,md as PRESETS,gd as PRESET_FULLSCREEN,ud as PRESET_MINIMAL,pd as PRESET_SHOP,Jd as THEME_ZONES,eo as VERSION,Ru as accessibilityPlugin,Hu as animationsPlugin,Ir as applyThemeVariables,Jr as attachHeaderToContainer,Bu as brandPlugin,ko as buildComposer,cc as buildDefaultHeader,xr as buildHeader,Mo as buildHeaderWithLayout,dc as buildMinimalHeader,mu as collectEnrichedPageContext,vr as componentRegistry,as as createActionManager,Ys as createAgentExperience,Ss as createBestAvailableVoiceProvider,lp as createBubbleWithLayout,qs as createCSATFeedback,Ls as createComboButton,Dp as createComponentMiddleware,_s as createComponentStreamParser,Ol as createDefaultSanitizer,Wu as createDemoCarousel,vd as createDirectivePostprocessor,Pr as createDropdownMenu,kd as createFlexibleJsonStreamParser,It as createIconButton,Dd as createImagePart,bs as createJsonStreamParser,es as createLabelButton,$s as createLocalStorageAdapter,Oo as createMarkdownProcessor,jr as createMarkdownProcessorFromConfig,hc as createMessageActions,Us as createNPSFeedback,hs as createPlainTextParser,Nu as createPlugin,ys as createRegexJsonParser,Lo as createStandardBubble,ws as createTextPart,Co as createTheme,Ts as createThemeObserver,ts as createToggleGroup,Yr as createTypingIndicator,qr as createVoiceProvider,ls as createWidgetHostLayout,xs as createXmlParser,Rh as default,Zr as defaultActionHandlers,ss as defaultJsonActionParser,Yc as defaultParseRules,Yo as detectColorScheme,Cd as directivePostprocessor,mo as escapeHtml,Vs as extractComponentDirectiveFromMessage,Fd as fileToImagePart,fu as formatEnrichedContext,Vr as generateAssistantMessageId,Cu as generateCodeSnippet,Pd as generateMessageId,Xc as generateStableSelector,yo as generateUserMessageId,Ko as getActiveTheme,nc as getColorScheme,Rd as getDisplayText,pc as getHeaderLayout,Bd as getImageParts,$u as getPreset,zs as hasComponentDirective,Hd as hasImages,Is as headerLayouts,Fu as highContrastPlugin,Oc as initAgentWidget,Bp as isComponentDirectiveType,Gt as isDockedMountMode,Uo as isVoiceSupported,Dl as markdownPostprocessor,Ns as mergeWithDefaults,Wd as normalizeContent,os as pluginRegistry,Du as reducedMotionPlugin,js as renderComponentDirective,fc as renderLoadingIndicatorWithFallback,On as resolveDockConfig,fo as resolveSanitizer,As as resolveTokens,Es as themeToCssVariables,Nd as validateImageFile,Zl as validateTheme};
433
+ `;function Pu(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Iu,document.head.appendChild(e)}function Wu(e,r){let t=e.clientWidth-ca*2-pd,n=e.clientHeight-ca*2-pd;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function Ru(e,r,t,n,s){e.style.width=`${t.w*n}px`,e.style.height=`${t.h*n}px`,e.style.borderRadius=s==="mobile"?`${32*n}px`:"10px",r.style.width=`${t.w}px`,r.style.height=`${t.h}px`,r.style.transformOrigin="top left",r.style.transform=`scale(${n})`}function Hu(e,r){let{items:t,initialIndex:n=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:d=!0,onChange:c}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");Pu();let p=Math.max(0,Math.min(n,t.length-1)),u=s,f=o,m=null,v=1,M=!1,b=h("div","persona-dc-root"),C=h("div","persona-dc-toolbar"),S=h("div","persona-dc-toolbar-lead"),R=h("div","persona-dc-toolbar-trail"),w=kt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>ot(-1)}),L=h("div");L.style.position="relative";let B=h("button","persona-dc-title-btn");B.type="button",B.setAttribute("aria-expanded","false"),B.setAttribute("aria-haspopup","listbox");let T=h("span","persona-dc-title-text"),Y=h("span","persona-dc-title-chevron"),ue=me("chevron-down",12,"currentColor",2);ue&&Y.appendChild(ue),B.append(T,Y);let ce=h("div","persona-dc-dropdown");ce.setAttribute("role","listbox"),ce.style.display="none";let $=!1;function te(){ce.innerHTML="";for(let _=0;_<t.length;_++){let z=t[_],Q=h("button","persona-dc-dropdown-item");Q.type="button",Q.setAttribute("role","option"),Q.setAttribute("aria-current",_===p?"true":"false");let Fe=h("span");if(Fe.textContent=z.title,Q.appendChild(Fe),z.description){let J=h("span","persona-dc-dropdown-desc");J.textContent=z.description,Q.appendChild(J)}Q.addEventListener("click",()=>{ne(),wt(_)}),ce.appendChild(Q)}}function Te(){$=!$,ce.style.display=$?"":"none",B.setAttribute("aria-expanded",$?"true":"false"),$&&te()}function ne(){$&&($=!1,ce.style.display="none",B.setAttribute("aria-expanded","false"))}B.addEventListener("click",_=>{_.stopPropagation(),Te()});let Se=()=>ne();document.addEventListener("click",Se),L.append(B,ce);let He=kt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>ot(1)}),he=h("span","persona-dc-counter");S.append(w,L,He,he);let Me=null;i&&(Me=ss({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:u,onSelect:_=>{u=_,ge.dataset.device=u,m=null,j()}}),R.appendChild(Me.element));let ke=null;if(a){let _=h("div","persona-dc-zoom-controls"),z=kt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let J=m!=null?m:v;m=Math.max(cd,J-ld),j()}});ke=h("span","persona-dc-zoom-level"),ke.title="Reset to 100%",ke.style.cursor="pointer",ke.addEventListener("click",()=>{m=1,j()});let Q=kt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let J=m!=null?m:v;m=Math.min(dd,J+ld),j()}}),Fe=kt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,j()}});_.append(z,ke,Q,Fe),R.appendChild(_)}if(d){let _=h("div","persona-dc-separator");R.appendChild(_);let z=ss({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:Q=>{f=Q,ge.dataset.colorScheme=f,oe()}});R.appendChild(z.element)}let re=h("div","persona-dc-separator");R.appendChild(re);let be=kt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[p].url,"_blank")}});R.appendChild(be),C.append(S,R);let $e=h("div","persona-dc-stage"),ge=h("div","persona-dc-iframe-wrapper");ge.dataset.device=u,ge.dataset.colorScheme=f;let de=h("iframe","persona-dc-iframe");de.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),de.setAttribute("loading","lazy"),de.title=t[p].title,ge.appendChild(de),$e.appendChild(ge),b.append(C,$e),e.appendChild(b);function oe(){var _;try{let z=(_=de.contentDocument)==null?void 0:_.body;if(!z)return;f==="dark"?z.classList.add("theme-dark"):z.classList.remove("theme-dark")}catch{}}de.addEventListener("load",()=>oe());function De(){let _=t[p];T.textContent=_.title,he.textContent=`${p+1} / ${t.length}`,de.title=_.title}function ot(_){let z=((p+_)%t.length+t.length)%t.length;wt(z)}function wt(_){_<0||_>=t.length||(p=_,de.src=t[p].url,De(),c==null||c(p,t[p]))}function j(){var Q;if(M)return;let _=(Q=id[u])!=null?Q:id.desktop;v=Wu($e,_);let z=Math.max(cd,Math.min(dd,m!=null?m:v));Ru(ge,de,_,z,u),ke&&(ke.textContent=`${Math.round(z*100)}%`)}let q=new ResizeObserver(()=>j());q.observe($e),De(),de.src=t[p].url,requestAnimationFrame(()=>j());function se(){M||(M=!0,q.disconnect(),document.removeEventListener("click",Se),b.remove())}return{element:b,goTo:wt,next:()=>ot(1),prev:()=>ot(-1),getIndex:()=>p,setDevice(_){u=_,ge.dataset.device=_,Me==null||Me.setSelected(_),m=null,j()},setColorScheme(_){f=_,ge.dataset.colorScheme=_},setZoom(_){m=_,j()},destroy:se}}function Bu(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function Du(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Fu(e){return{name:"@persona/brand",version:"1.0.0",transform(r){var n;let t={...r.palette};return(n=e.colors)!=null&&n.primary&&(t.colors={...t.colors,primary:{50:Gn(e.colors.primary,.95),100:Gn(e.colors.primary,.9),200:Gn(e.colors.primary,.8),300:Gn(e.colors.primary,.7),400:Gn(e.colors.primary,.6),500:e.colors.primary,600:Gn(e.colors.primary,.8),700:Gn(e.colors.primary,.7),800:Gn(e.colors.primary,.6),900:Gn(e.colors.primary,.5),950:Gn(e.colors.primary,.45)}}),{...r,palette:t}}}}function Nu(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Ou(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Gn(e,r){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-r)),a=Math.round(n+(255-n)*(1-r)),i=Math.round(s+(255-s)*(1-r));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function $u(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var _u={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},ud={components:{panel:{borderRadius:"0",shadow:"none"}}},gd={id:"shop",label:"Shopping Assistant",config:{theme:_u,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Rn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},md={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:ud}},fd={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:ud}},hd={shop:gd,minimal:md,fullscreen:fd};function ju(e){return hd[e]}var Nh=_c;export{qr as AgentWidgetClient,So as AgentWidgetSession,Gr as AttachmentManager,tc as DEFAULT_COMPONENTS,ks as DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,Rn as DEFAULT_FLOATING_LAUNCHER_WIDTH,Ql as DEFAULT_PALETTE,ec as DEFAULT_SEMANTIC,Ct as DEFAULT_WIDGET_CONFIG,hd as PRESETS,fd as PRESET_FULLSCREEN,md as PRESET_MINIMAL,gd as PRESET_SHOP,Gd as THEME_ZONES,ro as VERSION,Bu as accessibilityPlugin,Du as animationsPlugin,Rr as applyThemeVariables,Xr as attachHeaderToContainer,Fu as brandPlugin,Wo as buildComposer,uc as buildDefaultHeader,Cr as buildHeader,Po as buildHeaderWithLayout,gc as buildMinimalHeader,hu as collectEnrichedPageContext,wr as componentRegistry,ds as createActionManager,Qs as createAgentExperience,Ms as createBestAvailableVoiceProvider,dp as createBubbleWithLayout,Xs as createCSATFeedback,Bs as createComboButton,Np as createComponentMiddleware,qs as createComponentStreamParser,_l as createDefaultSanitizer,Hu as createDemoCarousel,wd as createDirectivePostprocessor,Hr as createDropdownMenu,Id as createFlexibleJsonStreamParser,kt as createIconButton,Nd as createImagePart,ws as createJsonStreamParser,os as createLabelButton,Vs as createLocalStorageAdapter,zo as createMarkdownProcessor,Vr as createMarkdownProcessorFromConfig,xc as createMessageActions,Ks as createNPSFeedback,vs as createPlainTextParser,$u as createPlugin,Cs as createRegexJsonParser,Ro as createStandardBubble,Ts as createTextPart,To as createTheme,Ws as createThemeObserver,ss as createToggleGroup,Kr as createTypingIndicator,Yr as createVoiceProvider,us as createWidgetHostLayout,Ss as createXmlParser,Nh as default,to as defaultActionHandlers,cs as defaultJsonActionParser,Xc as defaultParseRules,Zo as detectColorScheme,Sd as directivePostprocessor,bo as escapeHtml,Gs as extractComponentDirectiveFromMessage,Od as fileToImagePart,yu as formatEnrichedContext,Jr as generateAssistantMessageId,Su as generateCodeSnippet,Rd as generateMessageId,Zc as generateStableSelector,Co as generateUserMessageId,Qo as getActiveTheme,sc as getColorScheme,Bd as getDisplayText,mc as getHeaderLayout,Fd as getImageParts,ju as getPreset,Ys as hasComponentDirective,Dd as hasImages,Ds as headerLayouts,Ou as highContrastPlugin,_c as initAgentWidget,Fp as isComponentDirectiveType,Yt as isDockedMountMode,Xo as isVoiceSupported,Nl as markdownPostprocessor,Ls as mergeWithDefaults,Hd as normalizeContent,ls as pluginRegistry,Nu as reducedMotionPlugin,Js as renderComponentDirective,bc as renderLoadingIndicatorWithFallback,jn as resolveDockConfig,xo as resolveSanitizer,Is as resolveTokens,Ps as themeToCssVariables,$d as validateImageFile,nc as validateTheme};
434
434
  //# sourceMappingURL=index.js.map